瀏覽代碼

use local files for testing `ui.interactive_image` (#3118)

Falko Schindler 1 年之前
父節點
當前提交
061242c2b2
共有 6 個文件被更改,包括 51 次插入26 次删除
  1. 0 1
      .gitignore
  2. 25 7
      nicegui/testing/screen.py
  3. 1 0
      tests/media/.gitignore
  4. 二進制
      tests/media/test1.jpg
  5. 二進制
      tests/media/test2.jpg
  6. 25 18
      tests/test_interactive_image.py

+ 0 - 1
.gitignore

@@ -5,7 +5,6 @@ dist
 /test.py
 *.pickle
 screenshots/
-tests/media/
 venv
 .idea
 .nicegui/

+ 25 - 7
nicegui/testing/screen.py

@@ -4,7 +4,7 @@ import threading
 import time
 from contextlib import contextmanager
 from pathlib import Path
-from typing import Generator, List, Optional, Union
+from typing import Callable, Generator, List, Optional, Union, overload
 
 import pytest
 from selenium import webdriver
@@ -102,17 +102,35 @@ class Screen:
             return
         self.find(text)
 
-    def wait_for(self, text: str) -> None:
+    @overload
+    def wait_for(self, target: str) -> None:
         """Wait until the page contains the given text."""
-        self.should_contain(text)
+
+    @overload
+    def wait_for(self, target: Callable[..., bool]) -> None:
+        """Wait until the given condition is met."""
+
+    def wait_for(self, target: Union[str, Callable[..., bool]]) -> None:
+        """Wait until the page contains the given text or the given condition is met."""
+        if isinstance(target, str):
+            self.should_contain(target)
+        if callable(target):
+            deadline = time.time() + self.IMPLICIT_WAIT
+            while time.time() < deadline:
+                if target():
+                    return
+                self.wait(0.1)
+            raise AssertionError('Condition not met')
 
     def should_not_contain(self, text: str, wait: float = 0.5) -> None:
         """Assert that the page does not contain the given text."""
         assert self.selenium.title != text
-        self.selenium.implicitly_wait(wait)
-        with pytest.raises(AssertionError):
-            self.find(text)
-        self.selenium.implicitly_wait(self.IMPLICIT_WAIT)
+        try:
+            self.selenium.implicitly_wait(wait)
+            with pytest.raises(AssertionError):
+                self.find(text)
+        finally:
+            self.selenium.implicitly_wait(self.IMPLICIT_WAIT)
 
     def should_contain_input(self, text: str) -> None:
         """Assert that the page contains an input with the given value."""

+ 1 - 0
tests/media/.gitignore

@@ -0,0 +1 @@
+test.mp4

二進制
tests/media/test1.jpg


二進制
tests/media/test2.jpg


+ 25 - 18
tests/test_interactive_image.py

@@ -1,11 +1,21 @@
+from pathlib import Path
 from typing import List
 
 import pytest
 from selenium.webdriver.common.action_chains import ActionChains
 
-from nicegui import ui
+from nicegui import app, ui
 from nicegui.testing import Screen
 
+URL_PATH1 = '/test1.jpg'
+URL_PATH2 = '/test2.jpg'
+
+
+@pytest.fixture(autouse=True)
+def provide_image_files():
+    app.add_static_file(local_file=Path(__file__).parent / 'media' / 'test1.jpg', url_path=URL_PATH1)
+    app.add_static_file(local_file=Path(__file__).parent / 'media' / 'test2.jpg', url_path=URL_PATH2)
+
 
 def test_set_source_in_tab(screen: Screen):
     """https://github.com/zauberzeug/nicegui/issues/488"""
@@ -21,21 +31,20 @@ def test_set_source_in_tab(screen: Screen):
             with ui.tab_panel('B'):
                 ui.label('Tab B')
         await ui.context.client.connected()
-        img.set_source('https://picsum.photos/id/29/640/360')
+        img.set_source(URL_PATH1)
 
     screen.open('/')
     screen.wait(0.5)
-    assert screen.find_by_tag('img').get_attribute('src') == 'https://picsum.photos/id/29/640/360'
+    assert screen.find_by_tag('img').get_attribute('src').endswith(URL_PATH1)
     screen.click('B')
     screen.wait(0.5)
     screen.click('A')
-    assert screen.find_by_tag('img').get_attribute('src') == 'https://picsum.photos/id/29/640/360'
+    assert screen.find_by_tag('img').get_attribute('src').endswith(URL_PATH1)
 
 
 @pytest.mark.parametrize('cross', [True, False])
 def test_with_cross(screen: Screen, cross: bool):
-    ui.interactive_image('https://picsum.photos/id/29/640/360',
-                         content='<circle cx="100" cy="100" r="15" />', cross=cross)
+    ui.interactive_image(URL_PATH1, content='<circle cx="100" cy="100" r="15" />', cross=cross)
 
     screen.open('/')
     screen.find_by_tag('svg')
@@ -46,25 +55,25 @@ def test_with_cross(screen: Screen, cross: bool):
 
 def test_replace_interactive_image(screen: Screen):
     with ui.row() as container:
-        ui.interactive_image('https://picsum.photos/id/29/640/360')
+        ui.interactive_image(URL_PATH1)
 
     def replace():
         container.clear()
         with container:
-            ui.interactive_image('https://picsum.photos/id/30/640/360')
+            ui.interactive_image(URL_PATH2)
     ui.button('Replace', on_click=replace)
 
     screen.open('/')
-    assert (screen.find_by_tag('img').get_attribute('src') or '').endswith('id/29/640/360')
+    assert (screen.find_by_tag('img').get_attribute('src') or '').endswith(URL_PATH1)
     screen.click('Replace')
     screen.wait(0.5)
-    assert (screen.find_by_tag('img').get_attribute('src') or '').endswith('id/30/640/360')
+    assert (screen.find_by_tag('img').get_attribute('src') or '').endswith(URL_PATH2)
 
 
 @pytest.mark.parametrize('cross', [True, False])
 def test_mousemove_event(screen: Screen, cross: bool):
     counter = {'value': 0}
-    ii = ui.interactive_image('https://picsum.photos/id/29/640/360', cross=cross, events=['mousemove'],
+    ii = ui.interactive_image(URL_PATH1, cross=cross, events=['mousemove'],
                               on_mouse=lambda: counter.update(value=counter['value'] + 1))
 
     screen.open('/')
@@ -80,15 +89,13 @@ def test_mousemove_event(screen: Screen, cross: bool):
 
 def test_loaded_event(screen: Screen):
     sources: List[str] = []
-    ii = ui.interactive_image('https://picsum.photos/id/29/640/360')
+    ii = ui.interactive_image(URL_PATH1)
     ii.on('loaded', lambda e: sources.append(e.args['source']))
-    ui.button('Change Source', on_click=lambda: ii.set_source('https://picsum.photos/id/30/640/360'))
+    ui.button('Change Source', on_click=lambda: ii.set_source(URL_PATH2))
 
     screen.open('/')
-    screen.wait(0.5)
-    assert len(sources) == 1
+    screen.wait_for(lambda: len(sources) == 1)
     screen.click('Change Source')
-    screen.wait(1.5)
-    assert len(sources) == 2
-    assert sources[1].endswith('id/30/640/360')
+    screen.wait_for(lambda: len(sources) == 2)
+    assert sources[1].endswith(URL_PATH2)
     assert screen.find_by_tag('img').get_attribute('src') == sources[1]