screen.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. import os
  2. import threading
  3. import time
  4. from typing import List
  5. import pytest
  6. from bs4 import BeautifulSoup
  7. from nicegui import globals, ui
  8. from selenium import webdriver
  9. from selenium.common.exceptions import ElementNotInteractableException, NoSuchElementException
  10. from selenium.webdriver import ActionChains
  11. from selenium.webdriver.common.by import By
  12. from selenium.webdriver.remote.webelement import WebElement
  13. from .helper import remove_prefix
  14. PORT = 3392
  15. IGNORED_CLASSES = ['row', 'column', 'q-card', 'q-field', 'q-field__label', 'q-input']
  16. class Screen:
  17. SCREENSHOT_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'screenshots')
  18. def __init__(self, selenium: webdriver.Chrome) -> None:
  19. self.selenium = selenium
  20. self.server_thread = None
  21. def start_server(self) -> None:
  22. '''Start the webserver in a separate thread. This is the equivalent of `ui.run()` in a normal script.'''
  23. self.server_thread = threading.Thread(target=ui.run, kwargs={'port': PORT, 'show': False, 'reload': False})
  24. self.server_thread.start()
  25. def stop_server(self) -> None:
  26. '''Stop the webserver.'''
  27. self.selenium.close()
  28. globals.server.should_exit = True
  29. self.server_thread.join()
  30. def open(self, path: str) -> None:
  31. if self.server_thread is None:
  32. self.start_server()
  33. start = time.time()
  34. while True:
  35. try:
  36. self.selenium.get(f'http://localhost:{PORT}{path}')
  37. break
  38. except Exception:
  39. if time.time() - start > 3:
  40. raise
  41. time.sleep(0.1)
  42. if not self.server_thread.is_alive():
  43. raise RuntimeError('The NiceGUI server has stopped running')
  44. def should_contain(self, text: str) -> None:
  45. assert self.selenium.title == text or self.find(text), \
  46. f'could not find "{text}" on:\n{self.render_content()}'
  47. def should_not_contain(self, text: str) -> None:
  48. assert self.selenium.title != text
  49. with pytest.raises(AssertionError):
  50. self.find(text)
  51. def click(self, target_text: str) -> WebElement:
  52. element = self.find(target_text)
  53. try:
  54. element.click()
  55. except ElementNotInteractableException:
  56. raise AssertionError(f'Could not click on "{target_text}" on:\n{element.get_attribute("outerHTML")}')
  57. return element
  58. def click_at_position(self, element: WebElement, x: int, y: int) -> None:
  59. action = ActionChains(self.selenium)
  60. action.move_to_element_with_offset(element, x, y).click().perform()
  61. def find(self, text: str) -> WebElement:
  62. try:
  63. query = f'//*[not(self::script) and not(self::style) and contains(text(), "{text}")]'
  64. return self.selenium.find_element(By.XPATH, query)
  65. except NoSuchElementException:
  66. raise AssertionError(f'Could not find "{text}" on:\n{self.render_content()}')
  67. def render_content(self, with_extras: bool = False) -> str:
  68. body = self.selenium.find_element(By.TAG_NAME, 'body').get_attribute('innerHTML')
  69. soup = BeautifulSoup(body, 'html.parser')
  70. self.simplify_input_tags(soup)
  71. content = ''
  72. for child in soup.find_all():
  73. is_element = False
  74. if child is None or child.name == 'script':
  75. continue
  76. depth = (len(list(child.parents)) - 3) * ' '
  77. if not child.find_all() and child.text:
  78. content += depth + child.getText()
  79. is_element = True
  80. classes = child.get('class', '')
  81. if classes:
  82. if classes[0] in ['row', 'column', 'q-card']:
  83. content += depth + remove_prefix(classes[0], 'q-')
  84. is_element = True
  85. if classes[0] == 'q-field':
  86. pass
  87. [classes.remove(c) for c in IGNORED_CLASSES if c in classes]
  88. for i, c in enumerate(classes):
  89. classes[i] = remove_prefix(c, 'q-field--')
  90. if is_element and with_extras:
  91. content += f' [class: {" ".join(classes)}]'
  92. if is_element:
  93. content += '\n'
  94. return f'Title: {self.selenium.title}\n\n{content}'
  95. def render_html(self) -> str:
  96. body = self.selenium.page_source
  97. soup = BeautifulSoup(body, 'html.parser')
  98. for element in soup.find_all():
  99. if element.name in ['script', 'style'] and len(element.text) > 10:
  100. element.string = '... removed lengthy content ...'
  101. return soup.prettify()
  102. def render_logs(self) -> str:
  103. console = '\n'.join(l['message'] for l in self.selenium.get_log('browser'))
  104. return f'-- console logs ---\n{console}\n---------------------'
  105. @staticmethod
  106. def simplify_input_tags(soup: BeautifulSoup) -> None:
  107. for element in soup.find_all(class_='q-field'):
  108. new = soup.new_tag('simple_input')
  109. name = element.find(class_='q-field__label').text
  110. placeholder = element.find(class_='q-field__native').get('placeholder')
  111. messages = element.find(class_='q-field__messages')
  112. value = element.find(class_='q-field__native').get('value')
  113. new.string = (f'{name}: ' if name else '') + (value or placeholder or '') + \
  114. (f' \u002A{messages.text}' if messages else '')
  115. new['class'] = element['class']
  116. element.replace_with(new)
  117. def get_tags(self, name: str) -> List[WebElement]:
  118. return self.selenium.find_elements(By.TAG_NAME, name)
  119. def get_attributes(self, tag: str, attribute: str) -> List[str]:
  120. return [t.get_attribute(attribute) for t in self.get_tags(tag)]
  121. def wait(self, t: float) -> None:
  122. time.sleep(t)
  123. def shot(self, name: str) -> None:
  124. os.makedirs(self.SCREENSHOT_DIR, exist_ok=True)
  125. filename = f'{self.SCREENSHOT_DIR}/{name}.png'
  126. print(f'Storing screenshot to {filename}')
  127. self.selenium.get_screenshot_as_file(filename)