user.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import threading
  2. import time
  3. from asyncio import start_server
  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):
  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. time.sleep(1)
  19. def stop_server(self) -> None:
  20. '''Stop the webserver.'''
  21. self.selenium.close()
  22. nicegui_globals.server.should_exit = True
  23. self.thread.join()
  24. def open(self, path: str = '/') -> None:
  25. if self.thread is None:
  26. self.start_server()
  27. self.selenium.get('http://localhost:3392' + path)
  28. def should_see(self, text: str) -> None:
  29. if text == self.selenium.title:
  30. return
  31. assert self.find(text).text == text
  32. def click(self, target_text: str) -> None:
  33. self.find(target_text).click()
  34. def find(self, text: str) -> WebElement:
  35. try:
  36. return self.selenium.find_element(By.XPATH, f'//*[contains(text(),"{text}")]')
  37. except NoSuchElementException:
  38. raise AssertionError(f'Could not find "{text}" on:\n{self.get_body()}')
  39. def get_body(self) -> str:
  40. return self.selenium.find_element(By.TAG_NAME, 'body').text