screen.py 6.6 KB

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