user.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import logging
  2. import threading
  3. import time
  4. from nicegui import globals as nicegui_globals
  5. from nicegui import ui
  6. from selenium import webdriver
  7. from selenium.common.exceptions import NoSuchElementException
  8. from selenium.webdriver.common.by import By
  9. from selenium.webdriver.remote.webelement import WebElement
  10. class User():
  11. def __init__(self, selenium: webdriver.Chrome) -> None:
  12. self.selenium = selenium
  13. self.thread = None
  14. def start_server(self) -> None:
  15. '''Start the webserver in a separate thread. This is the equivalent of `ui.run()` in a normal script.'''
  16. self.thread = threading.Thread(target=ui.run, kwargs={'port': 3392, 'show': False, 'reload': False})
  17. self.thread.start()
  18. def stop_server(self) -> None:
  19. '''Stop the webserver.'''
  20. self.selenium.close()
  21. nicegui_globals.server.should_exit = True
  22. self.thread.join()
  23. def open(self, path: str) -> None:
  24. if self.thread is None:
  25. self.start_server()
  26. start = time.time()
  27. while True:
  28. try:
  29. self.selenium.get(f'http://localhost:3392{path}')
  30. break
  31. except Exception:
  32. if time.time() - start > 3:
  33. raise
  34. time.sleep(0.1)
  35. if not self.thread.is_alive():
  36. raise RuntimeError('The NiceGUI server has stopped running')
  37. logging.warning(f'Failed to open page at {path}, retrying...')
  38. def should_see(self, text: str) -> None:
  39. assert self.selenium.title == text or self.find(text).text == text
  40. def click(self, target_text: str) -> None:
  41. self.find(target_text).click()
  42. def find(self, text: str) -> WebElement:
  43. try:
  44. return self.selenium.find_element(By.XPATH, f'//*[contains(text(),"{text}")]')
  45. except NoSuchElementException:
  46. raise AssertionError(f'Could not find "{text}" on:\n{self.get_body()}')
  47. def get_body(self) -> str:
  48. return self.selenium.find_element(By.TAG_NAME, 'body').text