forked from pyapp-kit/magicgui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_types.py
75 lines (53 loc) · 1.95 KB
/
test_types.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import pytest
from magicgui import magicgui, register_type, types, widgets
def test_forward_refs():
"""Test that forward refs parameter annotations get resolved."""
@magicgui
def testA(x: "tests.MyInt" = "1"): # type: ignore # noqa
pass
@magicgui
def testB(x="1"):
pass
# because tests.MyInt is a subclass of int, it will be shown as a SpinBox
assert isinstance(testA.x, widgets.SpinBox)
# whereas without the forward ref type annotation, it would have been a LineEdit
assert isinstance(testB.x, widgets.LineEdit)
with pytest.raises(ImportError) as err:
# bad forward ref
@magicgui
def testA(x: "testsd.MyInt" = "1"): # type: ignore # noqa
pass
assert "Could not resolve the magicgui forward reference" in str(err.value)
def test_forward_refs_return_annotation():
"""Test that forward refs return annotations get resolved."""
@magicgui
def testA() -> int:
return 1
@magicgui
def testB() -> "tests.MyInt": # type: ignore # noqa
return 1
from tests import MyInt
results = []
register_type(MyInt, return_callback=lambda *x: results.append(x))
testA()
assert not results
testB()
gui, result, return_annotation = results[0]
assert isinstance(gui, widgets.FunctionGui)
assert result == 1
# the forward ref has been resolved
assert return_annotation is MyInt
def test_pathlike_annotation():
import pathlib
from typing import Union
@magicgui(fn={"mode": "r"})
def widget(fn: types.PathLike):
print(fn)
assert isinstance(widget.fn, widgets.FileEdit)
assert widget.fn.mode is types.FileDialogMode.EXISTING_FILE
# an equivalent union also works
@magicgui(fn={"mode": "rm"})
def widget2(fn: Union[bytes, pathlib.Path, str]):
print(fn)
assert isinstance(widget2.fn, widgets.FileEdit)
assert widget2.fn.mode is types.FileDialogMode.EXISTING_FILES