screen.py 4.5 KB

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