user.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import threading
  2. import time
  3. from nicegui import globals, ui
  4. from selenium import webdriver
  5. from selenium.common.exceptions import NoSuchElementException
  6. from selenium.webdriver.remote.webelement import WebElement
  7. PORT = 3392
  8. class User():
  9. def __init__(self, selenium: webdriver.Chrome) -> None:
  10. self.selenium = selenium
  11. self.server_thread = None
  12. def start_server(self) -> None:
  13. '''Start the webserver in a separate thread. This is the equivalent of `ui.run()` in a normal script.'''
  14. self.server_thread = threading.Thread(target=ui.run, kwargs={'port': PORT, 'show': False, 'reload': False})
  15. self.server_thread.start()
  16. def stop_server(self) -> None:
  17. '''Stop the webserver.'''
  18. self.selenium.close()
  19. globals.server.should_exit = True
  20. self.server_thread.join()
  21. def open(self, path: str) -> None:
  22. if self.server_thread is None:
  23. self.start_server()
  24. start = time.time()
  25. while True:
  26. try:
  27. self.selenium.get(f'http://localhost:{PORT}{path}')
  28. break
  29. except Exception:
  30. if time.time() - start > 3:
  31. raise
  32. time.sleep(0.1)
  33. if not self.server_thread.is_alive():
  34. raise RuntimeError('The NiceGUI server has stopped running')
  35. def should_see(self, text: str) -> None:
  36. assert text in self.page(), f'Could not find "{text}" on:\n{self.page()}'
  37. def click(self, target_text: str) -> None:
  38. self.find(target_text).click()
  39. def find(self, text: str) -> WebElement:
  40. try:
  41. return self.selenium.find_element_by_xpath(f'//*[contains(text(),"{text}")]')
  42. except NoSuchElementException:
  43. raise AssertionError(f'Could not find "{text}" on:\n{self.page()}')
  44. def page(self) -> str:
  45. return f'Title: {self.selenium.title}\n\n' + self.content(self.selenium.find_element_by_tag_name('body'))
  46. def content(self, element: WebElement, indent: str = '') -> str:
  47. content = ''
  48. is_group = False
  49. for child in element.find_elements_by_xpath('./*'):
  50. assert isinstance(child, WebElement)
  51. classes = child.get_attribute('class').split(' ')
  52. if not child.find_elements_by_xpath('./*') and child.text:
  53. content += f'{indent}{child.text}\n'
  54. if classes and classes[0] in ['row', 'column']:
  55. content += f'{classes[0]}\n'
  56. is_group = True
  57. if classes and classes[0] == 'q-field':
  58. try:
  59. name = child.find_element_by_class_name('q-field__label').text
  60. except NoSuchElementException:
  61. name = ''
  62. input = child.find_element_by_tag_name('input')
  63. value = input.get_attribute('value') or input.get_attribute('placeholder')
  64. content += f'{indent}{name}: {value}\n'
  65. else:
  66. content += self.content(child, indent + (' ' if is_group else ''))
  67. return content
  68. def get_tags(self, name: str) -> list[WebElement]:
  69. return self.selenium.find_elements_by_tag_name(name)
  70. def get_attributes(self, tag: str, attribute: str) -> list[str]:
  71. return [t.get_attribute(attribute) for t in self.get_tags(tag)]
  72. def sleep(self, t: float) -> None:
  73. time.sleep(t)