screen.py 8.7 KB

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