瀏覽代碼

pytest: renaming User to Screen

Rodja Trappe 2 年之前
父節點
當前提交
ba63bd224b
共有 8 個文件被更改,包括 107 次插入106 次删除
  1. 5 5
      tests/conftest.py
  2. 7 7
      tests/screen.py
  3. 6 6
      tests/test_3d_scene.py
  4. 12 12
      tests/test_auto_context.py
  5. 17 16
      tests/test_element.py
  6. 11 11
      tests/test_javascript.py
  7. 44 44
      tests/test_pages.py
  8. 5 5
      tests/test_user.py

+ 5 - 5
tests/conftest.py

@@ -10,7 +10,7 @@ from justpy.htmlcomponents import JustpyBaseComponent, WebPage
 from nicegui import globals
 from selenium import webdriver
 
-from .user import User
+from .screen import Screen
 
 icecream.install()
 
@@ -42,10 +42,10 @@ def reset_globals() -> Generator[None, None, None]:
 
 
 @pytest.fixture()
-def user(selenium: webdriver.Chrome) -> Generator[User, None, None]:
-    user = User(selenium)
-    yield user
-    user.stop_server()
+def screen(selenium: webdriver.Chrome) -> Generator[Screen, None, None]:
+    screen = Screen(selenium)
+    yield screen
+    screen.stop_server()
 
 
 @pytest.fixture

+ 7 - 7
tests/user.py → tests/screen.py

@@ -12,7 +12,7 @@ PORT = 3392
 IGNORED_CLASSES = ['row', 'column', 'q-card', 'q-field', 'q-field__label', 'q-input']
 
 
-class User():
+class Screen():
 
     def __init__(self, selenium: webdriver.Chrome) -> None:
         self.selenium = selenium
@@ -44,11 +44,11 @@ class User():
                 if not self.server_thread.is_alive():
                     raise RuntimeError('The NiceGUI server has stopped running')
 
-    def should_see(self, text: str) -> None:
+    def should_contain(self, text: str) -> None:
         assert self.selenium.title == text or self.find(text), \
-            f'could not find "{text}" on:\n{self.page()}'
+            f'could not find "{text}" on:\n{self.render_content()}'
 
-    def should_not_see(self, text: str) -> None:
+    def should_not_contain(self, text: str) -> None:
         assert self.selenium.title != text
         with pytest.raises(AssertionError):
             element = self.find(text)
@@ -61,9 +61,9 @@ class User():
         try:
             return self.selenium.find_element_by_xpath(f'//*[contains(text(),"{text}")]')
         except NoSuchElementException:
-            raise AssertionError(f'Could not find "{text}" on:\n{self.page()}')
+            raise AssertionError(f'Could not find "{text}" on:\n{self.render_content()}')
 
-    def page(self, with_extras: bool = False) -> str:
+    def render_content(self, with_extras: bool = False) -> str:
         body = self.selenium.find_element_by_tag_name('body').get_attribute('innerHTML')
         soup = BeautifulSoup(body, 'html.parser')
         self.simplify_input_tags(soup)
@@ -112,5 +112,5 @@ class User():
     def get_attributes(self, tag: str, attribute: str) -> list[str]:
         return [t.get_attribute(attribute) for t in self.get_tags(tag)]
 
-    def sleep(self, t: float) -> None:
+    def wait(self, t: float) -> None:
         time.sleep(t)

+ 6 - 6
tests/test_3d_scene.py

@@ -1,16 +1,16 @@
 from nicegui import ui
 
-from .user import User
+from .screen import Screen
 
 
-def test_moving_sphere_with_timer(user: User):
+def test_moving_sphere_with_timer(screen: Screen):
     with ui.scene() as scene:
         sphere = scene.sphere().move(0, -5, 2)
         ui.timer(0.03, lambda: sphere.move(sphere.x, sphere.y + 0.05, sphere.z))
 
-    user.open('/')
-    user.sleep(0.1)
-    def position(): return user.selenium.execute_script('return scene.children[4].position.y')
+    screen.open('/')
+    screen.wait(0.1)
+    def position(): return screen.selenium.execute_script('return scene.children[4].position.y')
     pos = position()
-    user.sleep(0.1)
+    screen.wait(0.1)
     assert position() > pos

+ 12 - 12
tests/test_auto_context.py

@@ -2,28 +2,28 @@ import asyncio
 
 from nicegui import ui
 
-from .user import User
+from .screen import Screen
 
 
-def test_adding_element_to_shared_index_page(user: User):
+def test_adding_element_to_shared_index_page(screen: Screen):
     ui.button('add label', on_click=lambda: ui.label('added'))
 
-    user.open('/')
-    user.click('add label')
-    user.should_see('added')
+    screen.open('/')
+    screen.click('add label')
+    screen.should_contain('added')
 
 
-def test_adding_element_to_private_page(user: User):
+def test_adding_element_to_private_page(screen: Screen):
     @ui.page('/')
     def page():
         ui.button('add label', on_click=lambda: ui.label('added'))
 
-    user.open('/')
-    user.click('add label')
-    user.should_see('added')
+    screen.open('/')
+    screen.click('add label')
+    screen.should_contain('added')
 
 
-def test_adding_elements_with_async_await(user: User):
+def test_adding_elements_with_async_await(screen: Screen):
     async def add_a():
         await asyncio.sleep(0.1)
         ui.label('A')
@@ -37,10 +37,10 @@ def test_adding_elements_with_async_await(user: User):
     with ui.card():
         ui.timer(1.1, add_b, once=True)
 
-    user.open('/')
+    screen.open('/')
     assert '''
 card
   A
 card
   B
-''' in user.page(), f'{user.page()} should show cards with "A" and "B"'
+''' in screen.render_content(), f'{screen.render_content()} should show cards with "A" and "B"'

+ 17 - 16
tests/test_element.py

@@ -2,27 +2,28 @@
 from nicegui import ui
 from selenium.webdriver.common.action_chains import ActionChains
 
-from .user import User
+from .screen import Screen
 
 
-def test_keyboard(user: User):
+def test_keyboard(screen: Screen):
     result = ui.label('')
     ui.keyboard(on_key=lambda e: result.set_text(f'{e.key, e.action}'))
 
-    user.open('/')
-    assert any(s.endswith('keyboard.js') for s in user.get_attributes('script', 'src'))
-    assert user.selenium.find_element_by_tag_name('span')  # NOTE keyboard dom element is a span
-    ActionChains(user.selenium).send_keys('t').perform()
-    user.should_see('t, KeyboardAction(keydown=False, keyup=True, repeat=False)')
+    screen.open('/')
+    assert any(s.endswith('keyboard.js') for s in screen.get_attributes('script', 'src'))
+    assert screen.selenium.find_element_by_tag_name('span')  # NOTE keyboard dom element is a span
+    ActionChains(screen.selenium).send_keys('t').perform()
+    screen.should_contain('t, KeyboardAction(keydown=False, keyup=True, repeat=False)')
 
 
-def test_classes(user: User):
+def test_classes(screen: Screen):
     label = ui.label('Some label')
 
     def assert_classes(classes: str) -> None:
-        assert user.selenium.find_element_by_xpath(f'//*[normalize-space(@class)="{classes}" and text()="Some label"]')
+        assert screen.selenium.find_element_by_xpath(
+            f'//*[normalize-space(@class)="{classes}" and text()="Some label"]')
 
-    user.open('/')
+    screen.open('/')
     assert_classes('')
 
     label.classes('one')
@@ -41,13 +42,13 @@ def test_classes(user: User):
     assert_classes('four')
 
 
-def test_style(user: User):
+def test_style(screen: Screen):
     label = ui.label('Some label')
 
     def assert_style(style: str) -> None:
-        assert user.selenium.find_element_by_xpath(f'//*[normalize-space(@style)="{style}" and text()="Some label"]')
+        assert screen.selenium.find_element_by_xpath(f'//*[normalize-space(@style)="{style}" and text()="Some label"]')
 
-    user.open('/')
+    screen.open('/')
     assert_style('')
 
     label.style('color: red')
@@ -72,14 +73,14 @@ def test_style(user: User):
     assert_style('text-decoration: underline; color: blue;')
 
 
-def test_props(user: User):
+def test_props(screen: Screen):
     input = ui.input()
 
     def assert_props(*props: str) -> None:
         class_conditions = [f'contains(@class, "q-field--{prop}")' for prop in props]
-        assert user.selenium.find_element_by_xpath(f'//label[{" and ".join(class_conditions)}]')
+        assert screen.selenium.find_element_by_xpath(f'//label[{" and ".join(class_conditions)}]')
 
-    user.open('/')
+    screen.open('/')
     assert_props('standard', 'labeled')
 
     input.props('dark')

+ 11 - 11
tests/test_javascript.py

@@ -2,30 +2,30 @@ from datetime import datetime
 
 from nicegui import ui
 
-from .user import User
+from .screen import Screen
 
 
-def test_executing_javascript(user: User):
+def test_executing_javascript(screen: Screen):
     async def set_title():
         await ui.run_javascript('document.title = "A New Title"')
     ui.button('change title', on_click=set_title)
 
-    user.open('/')
-    user.selenium.title == 'NiceGUI'
-    user.click('change title')
-    user.selenium.title == 'A New Title'
-    user.selenium.title != 'NiceGUI'
+    screen.open('/')
+    screen.selenium.title == 'NiceGUI'
+    screen.click('change title')
+    screen.selenium.title == 'A New Title'
+    screen.selenium.title != 'NiceGUI'
 
 
-def test_retrieving_content_from_javascript(user: User):
+def test_retrieving_content_from_javascript(screen: Screen):
     async def write_time():
         response = await ui.await_javascript('Date.now()')
         ui.label(f'Browser time: {response}')
 
     ui.button('write time', on_click=write_time)
 
-    user.open('/')
-    user.click('write time')
-    label = user.find('Browser time').text
+    screen.open('/')
+    screen.click('write time')
+    label = screen.find('Browser time').text
     jstime = datetime.fromtimestamp(int(label.split(': ')[1])/1000)
     assert abs((datetime.now() - jstime).total_seconds()) < 1, f'{jstime} should be close to now'

+ 44 - 44
tests/test_pages.py

@@ -3,92 +3,92 @@ from uuid import uuid4
 
 from nicegui import task_logger, ui
 
-from .user import User
+from .screen import Screen
 
 
-def test_page(user: User):
+def test_page(screen: Screen):
     @ui.page('/')
     def page():
         ui.label('Hello, world!')
 
-    user.open('/')
-    user.should_see('NiceGUI')
-    user.should_see('Hello, world!')
+    screen.open('/')
+    screen.should_contain('NiceGUI')
+    screen.should_contain('Hello, world!')
 
 
-def test_shared_page(user: User):
+def test_shared_page(screen: Screen):
     @ui.page('/', shared=True)
     def page():
         ui.label('Hello, world!')
 
-    user.open('/')
-    user.should_see('NiceGUI')
-    user.should_see('Hello, world!')
+    screen.open('/')
+    screen.should_contain('NiceGUI')
+    screen.should_contain('Hello, world!')
 
 
-def test_auto_index_page(user: User):
+def test_auto_index_page(screen: Screen):
     ui.label('Hello, world!')
 
-    user.open('/')
-    user.should_see('NiceGUI')
-    user.should_see('Hello, world!')
+    screen.open('/')
+    screen.should_contain('NiceGUI')
+    screen.should_contain('Hello, world!')
 
 
-def test_custom_title(user: User):
+def test_custom_title(screen: Screen):
     @ui.page('/', title='My Custom Title')
     def page():
         ui.label('Hello, world!')
 
-    user.open('/')
-    user.should_see('My Custom Title')
-    user.should_see('Hello, world!')
+    screen.open('/')
+    screen.should_contain('My Custom Title')
+    screen.should_contain('Hello, world!')
 
 
-def test_route_with_custom_path(user: User):
+def test_route_with_custom_path(screen: Screen):
     @ui.page('/test_route')
     def page():
         ui.label('page with custom path')
 
-    user.open('/test_route')
-    user.should_see('page with custom path')
+    screen.open('/test_route')
+    screen.should_contain('page with custom path')
 
 
-def test_auto_index_page_with_link_to_subpage(user: User):
+def test_auto_index_page_with_link_to_subpage(screen: Screen):
     ui.link('link to subpage', '/subpage')
 
     @ui.page('/subpage')
     def page():
         ui.label('the subpage')
 
-    user.open('/')
-    user.click('link to subpage')
-    user.should_see('the subpage')
+    screen.open('/')
+    screen.click('link to subpage')
+    screen.should_contain('the subpage')
 
 
-def test_link_to_page_by_passing_function(user: User):
+def test_link_to_page_by_passing_function(screen: Screen):
     @ui.page('/subpage')
     def page():
         ui.label('the subpage')
 
     ui.link('link to subpage', page)
 
-    user.open('/')
-    user.click('link to subpage')
-    user.should_see('the subpage')
+    screen.open('/')
+    screen.click('link to subpage')
+    screen.should_contain('the subpage')
 
 
-def test_creating_new_page_after_startup(user: User):
-    user.start_server()
+def test_creating_new_page_after_startup(screen: Screen):
+    screen.start_server()
 
     @ui.page('/late_page')
     def page():
         ui.label('page created after startup')
 
-    user.open('/late_page')
-    user.should_see('page created after startup')
+    screen.open('/late_page')
+    screen.should_contain('page created after startup')
 
 
-def test_shared_and_individual_pages(user: User):
+def test_shared_and_individual_pages(screen: Screen):
     @ui.page('/individual_page')
     def individual_page():
         ui.label(f'individual page with uuid {uuid4()}')
@@ -97,20 +97,20 @@ def test_shared_and_individual_pages(user: User):
     def shared_page():
         ui.label(f'shared page with uuid {uuid4()}')
 
-    user.open('/shared_page')
-    uuid1 = user.find('shared page').text.split()[-1]
-    user.open('/shared_page')
-    uuid2 = user.find('shared page').text.split()[-1]
+    screen.open('/shared_page')
+    uuid1 = screen.find('shared page').text.split()[-1]
+    screen.open('/shared_page')
+    uuid2 = screen.find('shared page').text.split()[-1]
     assert uuid1 == uuid2
 
-    user.open('/individual_page')
-    uuid1 = user.find('individual page').text.split()[-1]
-    user.open('/individual_page')
-    uuid2 = user.find('individual page').text.split()[-1]
+    screen.open('/individual_page')
+    uuid1 = screen.find('individual page').text.split()[-1]
+    screen.open('/individual_page')
+    uuid2 = screen.find('individual page').text.split()[-1]
     assert uuid1 != uuid2
 
 
-def test_on_page_ready_event(user: User):
+def test_on_page_ready_event(screen: Screen):
     '''This feature was introduced to fix #50; see https://github.com/zauberzeug/nicegui/issues/50#issuecomment-1210962617.'''
 
     async def load():
@@ -127,5 +127,5 @@ def test_on_page_ready_event(user: User):
         global label
         label = ui.label()
 
-    user.open('/')
-    user.should_see('delayed data has been loaded')
+    screen.open('/')
+    screen.should_contain('delayed data has been loaded')

+ 5 - 5
tests/test_user.py

@@ -1,9 +1,9 @@
 from nicegui import ui
 
-from .user import User
+from .screen import Screen
 
 
-def test_rendering_page(user: User):
+def test_rendering_page(screen: Screen):
     ui.label('test label')
     with ui.row().classes('positive'):
         ui.input('test input', placeholder='some placeholder')
@@ -14,8 +14,8 @@ def test_rendering_page(user: User):
     with ui.card():
         ui.label('some text')
 
-    user.open('/')
-    assert user.page() == '''Title: NiceGUI
+    screen.open('/')
+    assert screen.render_content() == '''Title: NiceGUI
 
 test label
 row
@@ -28,7 +28,7 @@ card
   some text
 '''
 
-    assert user.page(with_extras=True) == '''Title: NiceGUI
+    assert screen.render_content(with_extras=True) == '''Title: NiceGUI
 
 test label
 row [class: items-start positive]