screen.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. import os
  2. import threading
  3. import time
  4. from contextlib import contextmanager
  5. from typing import List, Optional
  6. import pytest
  7. from selenium import webdriver
  8. from selenium.common.exceptions import (ElementNotInteractableException, NoSuchElementException,
  9. StaleElementReferenceException)
  10. from selenium.webdriver import ActionChains
  11. from selenium.webdriver.common.by import By
  12. from selenium.webdriver.remote.webelement import WebElement
  13. from nicegui import app, ui
  14. from nicegui.server import Server
  15. from .test_helpers import TEST_DIR
  16. class Screen:
  17. PORT = 3392
  18. IMPLICIT_WAIT = 4
  19. SCREENSHOT_DIR = TEST_DIR / 'screenshots'
  20. def __init__(self, selenium: webdriver.Chrome, caplog: pytest.LogCaptureFixture) -> None:
  21. self.selenium = selenium
  22. self.caplog = caplog
  23. self.server_thread: Optional[threading.Thread] = None
  24. self.ui_run_kwargs = {'port': self.PORT, 'show': False, 'reload': False}
  25. self.connected = threading.Event()
  26. app.on_connect(self.connected.set)
  27. def start_server(self) -> None:
  28. """Start the webserver in a separate thread. This is the equivalent of `ui.run()` in a normal script."""
  29. self.server_thread = threading.Thread(target=ui.run, kwargs=self.ui_run_kwargs)
  30. self.server_thread.start()
  31. @property
  32. def is_open(self) -> None:
  33. # https://stackoverflow.com/a/66150779/3419103
  34. try:
  35. self.selenium.current_url # pylint: disable=pointless-statement
  36. return True
  37. except Exception as e:
  38. print(e)
  39. return False
  40. def stop_server(self) -> None:
  41. """Stop the webserver."""
  42. self.close()
  43. self.caplog.clear()
  44. Server.instance.should_exit = True
  45. if self.server_thread:
  46. self.server_thread.join()
  47. def open(self, path: str, timeout: float = 3.0) -> None:
  48. """Try to open the page until the server is ready or we time out.
  49. If the server is not yet running, start it.
  50. """
  51. if self.server_thread is None:
  52. self.start_server()
  53. deadline = time.time() + timeout
  54. self.connected.clear()
  55. while True:
  56. try:
  57. self.selenium.get(f'http://localhost:{self.PORT}{path}')
  58. self.selenium.find_element(By.XPATH, '//body') # ensure page and JS are loaded
  59. self.connected.wait(1) # Ensure that the client has connected to the API
  60. break
  61. except Exception as e:
  62. if time.time() > deadline:
  63. raise
  64. time.sleep(0.1)
  65. if not self.server_thread.is_alive():
  66. raise RuntimeError('The NiceGUI server has stopped running') from e
  67. def close(self) -> None:
  68. if self.is_open:
  69. self.selenium.close()
  70. def switch_to(self, tab_id: int) -> None:
  71. window_count = len(self.selenium.window_handles)
  72. if tab_id > window_count:
  73. raise IndexError(f'Could not go to or create tab {tab_id}, there are only {window_count} tabs')
  74. elif tab_id == window_count:
  75. self.selenium.switch_to.new_window('tab')
  76. else:
  77. self.selenium.switch_to.window(self.selenium.window_handles[tab_id])
  78. def should_contain(self, text: str) -> None:
  79. if self.selenium.title == text:
  80. return
  81. self.find(text)
  82. def wait_for(self, text: str) -> None:
  83. self.should_contain(text)
  84. def should_not_contain(self, text: str, wait: float = 0.5) -> None:
  85. assert self.selenium.title != text
  86. self.selenium.implicitly_wait(wait)
  87. with pytest.raises(AssertionError):
  88. self.find(text)
  89. self.selenium.implicitly_wait(self.IMPLICIT_WAIT)
  90. def should_contain_input(self, text: str) -> None:
  91. deadline = time.time() + self.IMPLICIT_WAIT
  92. while time.time() < deadline:
  93. for input_element in self.find_all_by_tag('input'):
  94. if input_element.get_attribute('value') == text:
  95. return
  96. self.wait(0.1)
  97. raise AssertionError(f'Could not find input with value "{text}"')
  98. def should_load_image(self, image: WebElement, *, timeout: float = 2.0) -> None:
  99. deadline = time.time() + timeout
  100. while time.time() < deadline:
  101. js = 'return arguments[0].naturalWidth > 0 && arguments[0].naturalHeight > 0'
  102. if self.selenium.execute_script(js, image):
  103. return
  104. raise AssertionError(f'Image not loaded: {image.get_attribute("outerHTML")}')
  105. def click(self, target_text: str) -> WebElement:
  106. element = self.find(target_text)
  107. try:
  108. element.click()
  109. except ElementNotInteractableException as e:
  110. raise AssertionError(f'Could not click on "{target_text}" on:\n{element.get_attribute("outerHTML")}') from e
  111. return element
  112. def context_click(self, target_text: str) -> WebElement:
  113. element = self.find(target_text)
  114. action = ActionChains(self.selenium)
  115. action.context_click(element).perform()
  116. return element
  117. def click_at_position(self, element: WebElement, x: int, y: int) -> None:
  118. action = ActionChains(self.selenium)
  119. action.move_to_element_with_offset(element, x, y).click().perform()
  120. def type(self, text: str) -> None:
  121. self.selenium.execute_script("window.focus();")
  122. self.wait(0.2)
  123. self.selenium.switch_to.active_element.send_keys(text)
  124. def find(self, text: str) -> WebElement:
  125. try:
  126. query = f'//*[not(self::script) and not(self::style) and text()[contains(., "{text}")]]'
  127. element = self.selenium.find_element(By.XPATH, query)
  128. try:
  129. if not element.is_displayed():
  130. self.wait(0.1) # HACK: repeat check after a short delay to avoid timing issue on fast machines
  131. if not element.is_displayed():
  132. raise AssertionError(f'Found "{text}" but it is hidden')
  133. except StaleElementReferenceException as e:
  134. raise AssertionError(f'Found "{text}" but it is hidden') from e
  135. return element
  136. except NoSuchElementException as e:
  137. raise AssertionError(f'Could not find "{text}"') from e
  138. def find_element(self, element: ui.element) -> WebElement:
  139. return self.selenium.find_element(By.ID, f'c{element.id}')
  140. def find_by_class(self, name: str) -> WebElement:
  141. return self.selenium.find_element(By.CLASS_NAME, name)
  142. def find_all_by_class(self, name: str) -> WebElement:
  143. return self.selenium.find_elements(By.CLASS_NAME, name)
  144. def find_by_tag(self, name: str) -> WebElement:
  145. return self.selenium.find_element(By.TAG_NAME, name)
  146. def find_all_by_tag(self, name: str) -> List[WebElement]:
  147. return self.selenium.find_elements(By.TAG_NAME, name)
  148. def render_js_logs(self) -> str:
  149. console = '\n'.join(l['message'] for l in self.selenium.get_log('browser'))
  150. return f'-- console logs ---\n{console}\n---------------------'
  151. def get_attributes(self, tag: str, attribute: str) -> List[str]:
  152. return [t.get_attribute(attribute) for t in self.find_all_by_tag(tag)]
  153. def wait(self, t: float) -> None:
  154. time.sleep(t)
  155. def shot(self, name: str) -> None:
  156. os.makedirs(self.SCREENSHOT_DIR, exist_ok=True)
  157. filename = f'{self.SCREENSHOT_DIR}/{name}.png'
  158. print(f'Storing screenshot to {filename}')
  159. self.selenium.get_screenshot_as_file(filename)
  160. def assert_py_logger(self, level: str, message: str) -> None:
  161. """Assert that the Python logger has received a message with the given level and text."""
  162. try:
  163. assert self.caplog.records, 'Expected a log message'
  164. record = self.caplog.records[0]
  165. print(record.levelname, record.message)
  166. assert record.levelname.strip() == level, f'Expected "{level}" but got "{record.levelname}"'
  167. assert record.message.strip() == message, f'Expected "{message}" but got "{record.message}"'
  168. finally:
  169. self.caplog.records.clear()
  170. @contextmanager
  171. def implicitly_wait(self, t: float) -> None:
  172. self.selenium.implicitly_wait(t)
  173. yield
  174. self.selenium.implicitly_wait(self.IMPLICIT_WAIT)