screen.py 5.2 KB

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