|
| 1 | +from functools import wraps |
| 2 | + |
| 3 | +import pytest |
| 4 | +from IPython.display import display |
| 5 | + |
| 6 | +try: |
| 7 | + import solara # noqa |
| 8 | + import playwright # noqa |
| 9 | + import pytest_mpl # noqa |
| 10 | + import pytest_playwright # noqa |
| 11 | +except ImportError: |
| 12 | + HAS_VISUAL_TEST_DEPS = False |
| 13 | +else: |
| 14 | + HAS_VISUAL_TEST_DEPS = True |
| 15 | + |
| 16 | +__all__ = ['visual_widget_test'] |
| 17 | + |
| 18 | + |
| 19 | +class DummyFigure: |
| 20 | + |
| 21 | + def __init__(self, png_bytes): |
| 22 | + self._png_bytes = png_bytes |
| 23 | + |
| 24 | + def savefig(self, filename_or_fileobj, *args, **kwargs): |
| 25 | + if isinstance(filename_or_fileobj, str): |
| 26 | + with open(filename_or_fileobj, 'wb') as f: |
| 27 | + f.write(self._png_bytes) |
| 28 | + else: |
| 29 | + filename_or_fileobj.write(self._png_bytes) |
| 30 | + |
| 31 | + |
| 32 | +def visual_widget_test(*args, **kwargs): |
| 33 | + |
| 34 | + tolerance = kwargs.pop("tolerance", 0) |
| 35 | + |
| 36 | + def decorator(test_function): |
| 37 | + @pytest.mark.skipif("not HAS_VISUAL_TEST_DEPS") |
| 38 | + @pytest.mark.mpl_image_compare( |
| 39 | + tolerance=tolerance, **kwargs |
| 40 | + ) |
| 41 | + @wraps(test_function) |
| 42 | + def test_wrapper(tmp_path, page_session, *args, **kwargs): |
| 43 | + layout = test_function(tmp_path, page_session, *args, **kwargs) |
| 44 | + |
| 45 | + layout.add_class("test-viewer") |
| 46 | + |
| 47 | + display(layout) |
| 48 | + |
| 49 | + viewer = page_session.locator(".test-viewer") |
| 50 | + viewer.wait_for() |
| 51 | + |
| 52 | + screenshot = viewer.screenshot() |
| 53 | + |
| 54 | + return DummyFigure(screenshot) |
| 55 | + |
| 56 | + return test_wrapper |
| 57 | + |
| 58 | + # If the decorator was used without any arguments, the only positional |
| 59 | + # argument will be the test to decorate so we do the following: |
| 60 | + if len(args) == 1: |
| 61 | + return decorator(*args) |
| 62 | + |
| 63 | + return decorator |
0 commit comments