1
0

screen.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  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, caplog: pytest.LogCaptureFixture) -> None:
  20. self.selenium = selenium
  21. self.caplog = caplog
  22. self.server_thread = None
  23. def start_server(self) -> None:
  24. '''Start the webserver in a separate thread. This is the equivalent of `ui.run()` in a normal script.'''
  25. self.server_thread = threading.Thread(target=ui.run, kwargs=self.UI_RUN_KWARGS)
  26. self.server_thread.start()
  27. @property
  28. def is_open(self) -> None:
  29. # https://stackoverflow.com/a/66150779/3419103
  30. try:
  31. self.selenium.current_url
  32. return True
  33. except:
  34. return False
  35. def stop_server(self) -> None:
  36. '''Stop the webserver.'''
  37. self.close()
  38. globals.server.should_exit = True
  39. self.server_thread.join()
  40. def open(self, path: str) -> None:
  41. if self.server_thread is None:
  42. self.start_server()
  43. start = time.time()
  44. while True:
  45. try:
  46. self.selenium.get(f'http://localhost:{PORT}{path}')
  47. break
  48. except Exception:
  49. if time.time() - start > 3:
  50. raise
  51. time.sleep(0.1)
  52. if not self.server_thread.is_alive():
  53. raise RuntimeError('The NiceGUI server has stopped running')
  54. def close(self) -> None:
  55. if self.is_open:
  56. self.selenium.close()
  57. def should_contain(self, text: str) -> None:
  58. assert self.selenium.title == text or self.find(text), \
  59. f'could not find "{text}" on:\n{self.render_content()}'
  60. def should_not_contain(self, text: str) -> None:
  61. assert self.selenium.title != text
  62. with pytest.raises(AssertionError):
  63. self.find(text)
  64. def click(self, target_text: str) -> WebElement:
  65. element = self.find(target_text)
  66. try:
  67. element.click()
  68. except ElementNotInteractableException:
  69. raise AssertionError(f'Could not click on "{target_text}" on:\n{element.get_attribute("outerHTML")}')
  70. return element
  71. def click_at_position(self, element: WebElement, x: int, y: int) -> None:
  72. action = ActionChains(self.selenium)
  73. action.move_to_element_with_offset(element, x, y).click().perform()
  74. def find(self, text: str) -> WebElement:
  75. try:
  76. query = f'//*[not(self::script) and not(self::style) and contains(text(), "{text}")]'
  77. return self.selenium.find_element(By.XPATH, query)
  78. except NoSuchElementException:
  79. raise AssertionError(f'Could not find "{text}" on:\n{self.render_content()}')
  80. def render_content(self, with_extras: bool = False) -> str:
  81. body = self.selenium.find_element(By.TAG_NAME, 'body').get_attribute('innerHTML')
  82. soup = BeautifulSoup(body, 'html.parser')
  83. self.simplify_input_tags(soup)
  84. content = ''
  85. for child in soup.find_all():
  86. is_element = False
  87. if child is None or child.name == 'script':
  88. continue
  89. depth = (len(list(child.parents)) - 3) * ' '
  90. if not child.find_all() and child.text:
  91. content += depth + child.getText()
  92. is_element = True
  93. classes = child.get('class', '')
  94. if classes:
  95. if classes[0] in ['row', 'column', 'q-card']:
  96. content += depth + remove_prefix(classes[0], 'q-')
  97. is_element = True
  98. if classes[0] == 'q-field':
  99. pass
  100. [classes.remove(c) for c in IGNORED_CLASSES if c in classes]
  101. for i, c in enumerate(classes):
  102. classes[i] = remove_prefix(c, 'q-field--')
  103. if is_element and with_extras:
  104. content += f' [class: {" ".join(classes)}]'
  105. if is_element:
  106. content += '\n'
  107. return f'Title: {self.selenium.title}\n\n{content}'
  108. def render_html(self) -> str:
  109. body = self.selenium.page_source
  110. soup = BeautifulSoup(body, 'html.parser')
  111. for element in soup.find_all():
  112. if element.name in ['script', 'style'] and len(element.text) > 10:
  113. element.string = '... removed lengthy content ...'
  114. return soup.prettify()
  115. def render_js_logs(self) -> str:
  116. console = '\n'.join(l['message'] for l in self.selenium.get_log('browser'))
  117. return f'-- console logs ---\n{console}\n---------------------'
  118. @staticmethod
  119. def simplify_input_tags(soup: BeautifulSoup) -> None:
  120. for element in soup.find_all(class_='q-field'):
  121. new = soup.new_tag('simple_input')
  122. name = element.find(class_='q-field__label').text
  123. placeholder = element.find(class_='q-field__native').get('placeholder')
  124. messages = element.find(class_='q-field__messages')
  125. value = element.find(class_='q-field__native').get('value')
  126. new.string = (f'{name}: ' if name else '') + (value or placeholder or '') + \
  127. (f' \u002A{messages.text}' if messages else '')
  128. new['class'] = element['class']
  129. element.replace_with(new)
  130. def get_tags(self, name: str) -> List[WebElement]:
  131. return self.selenium.find_elements(By.TAG_NAME, name)
  132. def get_attributes(self, tag: str, attribute: str) -> List[str]:
  133. return [t.get_attribute(attribute) for t in self.get_tags(tag)]
  134. def wait(self, t: float) -> None:
  135. time.sleep(t)
  136. def wait_for(self, text: str, *, timeout: float = 1.0) -> None:
  137. deadline = time.time() + timeout
  138. while time.time() < deadline:
  139. try:
  140. self.find(text)
  141. return
  142. except:
  143. self.wait(0.1)
  144. raise TimeoutError()
  145. def shot(self, name: str) -> None:
  146. os.makedirs(self.SCREENSHOT_DIR, exist_ok=True)
  147. filename = f'{self.SCREENSHOT_DIR}/{name}.png'
  148. print(f'Storing screenshot to {filename}')
  149. self.selenium.get_screenshot_as_file(filename)
  150. def assert_py_logger(self, name: str, message: str) -> None:
  151. assert len(self.caplog.records) == 1, 'Expected exactly one log message'
  152. record = self.caplog.records[0]
  153. print('---------------', record.levelname, record.message)
  154. assert record.levelname == name, f'Expected "{name}" but got "{record.levelname}"'
  155. assert record.message == message, f'Expected "{message}" but got "{record.message}"'
  156. self.caplog.records.clear()