screen.py 7.1 KB

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