Debian Codegraph @

mypyc/test-data/run-signatures.test

raw
1 [case testSignaturesBasic]
2 def f1(): pass
3 def f2(x): pass
4 def f3(x, /): pass
5 def f4(*, x): pass
6 def f5(*x): pass
7 def f6(**x): pass
8 def f7(x=None): pass
9 def f8(x=None, /): pass
10 def f9(*, x=None): pass
11 def f10(a, /, b, c=None, *args, d=None, **h): pass
12
13 [file driver.py]
14 import inspect
15 from native import *
16
17 assert str(inspect.signature(f1)) == "()"
18 assert str(inspect.signature(f2)) == "(x)"
19 assert str(inspect.signature(f3)) == "(x, /)"
20 assert str(inspect.signature(f4)) == "(*, x)"
21 assert str(inspect.signature(f5)) == "(*x)"
22 assert str(inspect.signature(f6)) == "(**x)"
23 assert str(inspect.signature(f7)) == "(x=None)"
24 assert str(inspect.signature(f8)) == "(x=None, /)"
25 assert str(inspect.signature(f9)) == "(*, x=None)"
26 assert str(inspect.signature(f10)) == "(a, /, b, c=None, *args, d=None, **h)"
27
28 for fn in [f1, f2, f3, f4, f5, f6, f7, f8, f9, f10]:
29 assert getattr(fn, "__doc__") is None
30
31 [case testSignaturesValidDefaults]
32 from typing import Final
33 A: Final = 1
34
35 def default_int(x=1): pass
36 def default_str(x="a"): pass
37 def default_float(x=1.0): pass
38 def default_true(x=True): pass
39 def default_false(x=False): pass
40 def default_none(x=None): pass
41 def default_tuple_empty(x=()): pass
42 def default_tuple_literals(x=(1, "a", 1.0, False, True, None, (), (1,2,(3,4)))): pass
43 def default_tuple_singleton(x=(1,)): pass
44 def default_named_constant(x=A): pass
45
46 [file driver.py]
47 import inspect
48 from native import *
49
50 assert str(inspect.signature(default_int)) == "(x=1)"
51 assert str(inspect.signature(default_str)) == "(x='a')"
52 assert str(inspect.signature(default_float)) == "(x=1.0)"
53 assert str(inspect.signature(default_true)) == "(x=True)"
54 assert str(inspect.signature(default_false)) == "(x=False)"
55 assert str(inspect.signature(default_none)) == "(x=None)"
56 assert str(inspect.signature(default_tuple_empty)) == "(x=())"
57 assert str(inspect.signature(default_tuple_literals)) == "(x=(1, 'a', 1.0, False, True, None, (), (1, 2, (3, 4))))"
58 assert str(inspect.signature(default_named_constant)) == "(x=1)"
59
60 # Check __text_signature__ directly since inspect.signature produces
61 # an incorrect signature for 1-tuple default arguments prior to
62 # Python 3.12 (cpython#102379).
63 # assert str(inspect.signature(default_tuple_singleton)) == "(x=(1,))"
64 assert getattr(default_tuple_singleton, "__text_signature__") == "(x=(1,))"
65
66 [case testSignaturesStringDefaults]
67 def f1(x="'foo"): pass
68 def f2(x='"foo'): pass
69 def f3(x=""""Isn\'t," they said."""): pass
70 def f4(x="\\ \a \b \f \n \r \t \v \x00"): pass
71 def f5(x="\N{BANANA}sv"): pass
72
73 [file driver.py]
74 import inspect
75 from native import *
76
77 assert str(inspect.signature(f1)) == """(x="'foo")"""
78 assert str(inspect.signature(f2)) == """(x='"foo')"""
79 assert str(inspect.signature(f3)) == r"""(x='"Isn\'t," they said.')"""
80 assert str(inspect.signature(f4)) == r"""(x='\\ \x07 \x08 \x0c \n \r \t \x0b \x00')"""
81 assert str(inspect.signature(f5)) == """(x='\N{BANANA}sv')"""
82
83 [case testSignaturesIrrepresentableDefaults]
84 import enum
85 class Color(enum.Enum):
86 RED = 1
87 misc = object()
88
89 # Default arguments that cannot be represented in a __text_signature__
90 def bad_object(x=misc): pass
91 def bad_list_nonliteral(x=[misc]): pass
92 def bad_dict_nonliteral(x={'a': misc}): pass
93 def bad_set_nonliteral(x={misc}): pass
94 def bad_set_empty(x=set()): pass # supported by ast.literal_eval, but not by inspect._signature_fromstr
95 def bad_nan(x=float("nan")): pass
96 def bad_enum(x=Color.RED): pass
97
98 # TODO: Default arguments that could potentially be represented in a
99 # __text_signature__, but which are not currently supported.
100 # See 'inspect._signature_fromstr' for what default values are supported at runtime.
101 def bad_complex(x=1+2j): pass
102 def bad_list_empty(x=[]): pass
103 def bad_list_literals(x=[1, 2, 3]): pass
104 def bad_dict_empty(x={}): pass
105 def bad_dict_literals(x={'a': 1}): pass
106 def bad_set_literals(x={1, 2, 3}): pass
107 def bad_tuple_literals(x=([1, 2, 3], {'a': 1}, {1, 2, 3})): pass
108 def bad_ellipsis(x=...): pass
109 def bad_literal_fold(x=1+2): pass
110
111 [file driver.py]
112 import inspect
113 from testutil import assertRaises
114 import native
115
116 all_bad = [fn for name, fn in vars(native).items() if name.startswith("bad_")]
117 assert all_bad
118
119 for bad in all_bad:
120 assert bad.__text_signature__ is None, f"{bad.__name__} has unexpected __text_signature__"
121 with assertRaises(ValueError, "no signature found for builtin"):
122 inspect.signature(bad)
123
124 [case testSignaturesMethods]
125 class Foo:
126 def f1(self, x): pass
127 @classmethod
128 def f2(cls, x): pass
129 @staticmethod
130 def f3(x): pass
131 def __eq__(self, x: object): pass
132
133 [file driver.py]
134 import inspect
135 from native import *
136
137 assert str(inspect.signature(Foo.f1)) == "(self, /, x)"
138 assert str(inspect.signature(Foo().f1)) == "(x)"
139
140 assert str(inspect.signature(Foo.f2)) == "(x)"
141 assert str(inspect.signature(Foo().f2)) == "(x)"
142
143 assert str(inspect.signature(Foo.f3)) == "(x)"
144 assert str(inspect.signature(Foo().f3)) == "(x)"
145
146 assert str(inspect.signature(Foo.__eq__)) == "(self, value, /)"
147 assert str(inspect.signature(Foo().__eq__)) == "(value, /)"
148
149 [case testSignaturesConstructors]
150 class Empty: pass
151
152 class HasInit:
153 def __init__(self, x) -> None: pass
154
155 class InheritedInit(HasInit): pass
156
157 class HasInitBad:
158 def __init__(self, x=[]) -> None: pass
159
160 [file driver.py]
161 import inspect
162 from testutil import assertRaises
163 from native import *
164
165 assert str(inspect.signature(Empty)) == "()"
166 assert str(inspect.signature(Empty.__init__)) == "(self, /, *args, **kwargs)"
167
168 assert str(inspect.signature(HasInit)) == "(x)"
169 assert str(inspect.signature(HasInit.__init__)) == "(self, /, *args, **kwargs)"
170
171 assert str(inspect.signature(InheritedInit)) == "(x)"
172 assert str(inspect.signature(InheritedInit.__init__)) == "(self, /, *args, **kwargs)"
173
174 assert getattr(HasInitBad, "__text_signature__") is None
175 with assertRaises(ValueError, "no signature found for builtin"):
176 inspect.signature(HasInitBad)
177
178 # CPython detail note: type objects whose tp_doc contains only a text signature behave
179 # differently from method objects whose ml_doc contains only a test signature: type
180 # objects will have __doc__="" whereas method objects will have __doc__=None. This
181 # difference stems from the former using _PyType_GetDocFromInternalDoc(...) and the
182 # latter using PyUnicode_FromString(_PyType_DocWithoutSignature(...)).
183 for cls in [Empty, HasInit, InheritedInit]:
184 assert getattr(cls, "__doc__") == ""
185 assert getattr(HasInitBad, "__doc__") is None
186
187 [case testSignaturesConstructorsNonExt]
188 from mypy_extensions import mypyc_attr
189
190 @mypyc_attr(native_class=False)
191 class NonExt:
192 def __init__(self, x) -> None: pass
193
194 [file driver.py]
195 import inspect
196 from testutil import assertRaises
197 from native import *
198
199 # TODO: support constructor signatures for non-extension classes
200 with assertRaises(ValueError, "no signature found for builtin"):
201 inspect.signature(NonExt)
202
203 [case testSignaturesHistoricalPositionalOnly]
204 import inspect
205
206 def f1(__x): pass
207 def f2(__x, y): pass
208 def f3(*, __y): pass
209 def f4(x, *, __y): pass
210 def f5(__x, *, __y): pass
211
212 class A:
213 def func(self, __x): pass
214
215 def test_historical_positional_only() -> None:
216 assert str(inspect.signature(f1)) == "(__x, /)"
217 assert str(inspect.signature(f2)) == "(__x, /, y)"
218 assert str(inspect.signature(f3)) == "(*, __y)"
219 assert str(inspect.signature(f4)) == "(x, *, __y)"
220 assert str(inspect.signature(f5)) == "(__x, /, *, __y)"
221
222 assert str(inspect.signature(A.func)) == "(self, __x, /)"
223 assert str(inspect.signature(A().func)) == "(__x, /)"