screen.py 7.6 KB

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