1
0

screen.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. import os
  2. import threading
  3. import time
  4. from typing import List
  5. import pytest
  6. from bs4 import BeautifulSoup
  7. from nicegui import globals, ui
  8. from selenium import webdriver
  9. from selenium.common.exceptions import ElementNotInteractableException, NoSuchElementException
  10. from selenium.webdriver import ActionChains
  11. from selenium.webdriver.common.by import By
  12. from selenium.webdriver.remote.webelement import WebElement
  13. from .helper import remove_prefix
  14. PORT = 3392
  15. IGNORED_CLASSES = ['row', 'column', 'q-card', 'q-field', 'q-field__label', 'q-input']
  16. class Screen:
  17. SCREENSHOT_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'screenshots')
  18. UI_RUN_KWARGS = {'port': PORT, 'show': False, 'reload': False}
  19. def __init__(self, selenium: webdriver.Chrome) -> None:
  20. self.selenium = selenium
  21. self.server_thread = None
  22. def start_server(self) -> None:
  23. '''Start the webserver in a separate thread. This is the equivalent of `ui.run()` in a normal script.'''
  24. self.server_thread = threading.Thread(target=ui.run, kwargs=self.UI_RUN_KWARGS)
  25. self.server_thread.start()
  26. def stop_server(self) -> None:
  27. '''Stop the webserver.'''
  28. self.selenium.close()
  29. globals.server.should_exit = True
  30. self.server_thread.join()
  31. def open(self, path: str) -> None:
  32. if self.server_thread is None:
  33. self.start_server()
  34. start = time.time()
  35. while True:
  36. try:
  37. self.selenium.get(f'http://localhost:{PORT}{path}')
  38. break
  39. except Exception:
  40. if time.time() - start > 3:
  41. raise
  42. time.sleep(0.1)
  43. if not self.server_thread.is_alive():
  44. raise RuntimeError('The NiceGUI server has stopped running')
  45. def should_contain(self, text: str) -> None:
  46. assert self.selenium.title == text or self.find(text), \
  47. f'could not find "{text}" on:\n{self.render_content()}'
  48. def should_not_contain(self, text: str) -> None:
  49. assert self.selenium.title != text
  50. with pytest.raises(AssertionError):
  51. self.find(text)
  52. def click(self, target_text: str) -> WebElement:
  53. element = self.find(target_text)
  54. try:
  55. element.click()
  56. except ElementNotInteractableException:
  57. raise AssertionError(f'Could not click on "{target_text}" on:\n{element.get_attribute("outerHTML")}')
  58. return element
  59. def click_at_position(self, element: WebElement, x: int, y: int) -> None:
  60. action = ActionChains(self.selenium)
  61. action.move_to_element_with_offset(element, x, y).click().perform()
  62. def find(self, text: str) -> WebElement:
  63. try:
  64. query = f'//*[not(self::script) and not(self::style) and contains(text(), "{text}")]'
  65. return self.selenium.find_element(By.XPATH, query)
  66. except NoSuchElementException:
  67. raise AssertionError(f'Could not find "{text}" on:\n{self.render_content()}')
  68. def render_content(self, with_extras: bool = False) -> str:
  69. body = self.selenium.find_element(By.TAG_NAME, 'body').get_attribute('innerHTML')
  70. soup = BeautifulSoup(body, 'html.parser')
  71. self.simplify_input_tags(soup)
  72. content = ''
  73. for child in soup.find_all():
  74. is_element = False
  75. if child is None or child.name == 'script':
  76. continue
  77. depth = (len(list(child.parents)) - 3) * ' '
  78. if not child.find_all() and child.text:
  79. content += depth + child.getText()
  80. is_element = True
  81. classes = child.get('class', '')
  82. if classes:
  83. if classes[0] in ['row', 'column', 'q-card']:
  84. content += depth + remove_prefix(classes[0], 'q-')
  85. is_element = True
  86. if classes[0] == 'q-field':
  87. pass
  88. [classes.remove(c) for c in IGNORED_CLASSES if c in classes]
  89. for i, c in enumerate(classes):
  90. classes[i] = remove_prefix(c, 'q-field--')
  91. if is_element and with_extras:
  92. content += f' [class: {" ".join(classes)}]'
  93. if is_element:
  94. content += '\n'
  95. return f'Title: {self.selenium.title}\n\n{content}'
  96. def render_html(self) -> str:
  97. body = self.selenium.page_source
  98. soup = BeautifulSoup(body, 'html.parser')
  99. for element in soup.find_all():
  100. if element.name in ['script', 'style'] and len(element.text) > 10:
  101. element.string = '... removed lengthy content ...'
  102. return soup.prettify()
  103. def render_logs(self) -> str:
  104. console = '\n'.join(l['message'] for l in self.selenium.get_log('browser'))
  105. return f'-- console logs ---\n{console}\n---------------------'
  106. @staticmethod
  107. def simplify_input_tags(soup: BeautifulSoup) -> None:
  108. for element in soup.find_all(class_='q-field'):
  109. new = soup.new_tag('simple_input')
  110. name = element.find(class_='q-field__label').text
  111. placeholder = element.find(class_='q-field__native').get('placeholder')
  112. messages = element.find(class_='q-field__messages')
  113. value = element.find(class_='q-field__native').get('value')
  114. new.string = (f'{name}: ' if name else '') + (value or placeholder or '') + \
  115. (f' \u002A{messages.text}' if messages else '')
  116. new['class'] = element['class']
  117. element.replace_with(new)
  118. def get_tags(self, name: str) -> List[WebElement]:
  119. return self.selenium.find_elements(By.TAG_NAME, name)
  120. def get_attributes(self, tag: str, attribute: str) -> List[str]:
  121. return [t.get_attribute(attribute) for t in self.get_tags(tag)]
  122. def wait(self, t: float) -> None:
  123. time.sleep(t)
  124. def shot(self, name: str) -> None:
  125. os.makedirs(self.SCREENSHOT_DIR, exist_ok=True)
  126. filename = f'{self.SCREENSHOT_DIR}/{name}.png'
  127. print(f'Storing screenshot to {filename}')
  128. self.selenium.get_screenshot_as_file(filename)