screen.py 7.0 KB

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