Debian Codegraph @

hypothesis-python/tests/cover/test_lookup_py38.py

raw
1 # This file is part of Hypothesis, which may be found at
2 # https://github.com/HypothesisWorks/hypothesis/
3 #
4 # Copyright the Hypothesis Authors.
5 # Individual contributors are listed in AUTHORS.rst and the git log.
6 #
7 # This Source Code Form is subject to the terms of the Mozilla Public License,
8 # v. 2.0. If a copy of the MPL was not distributed with this file, You can
9 # obtain one at https://mozilla.org/MPL/2.0/.
10
11 import dataclasses
12 import re
13 import typing
14 from types import SimpleNamespace
15
16 import pytest
17
18 from hypothesis import example, given, settings, strategies as st
19 from hypothesis.errors import InvalidArgument
20 from hypothesis.internal.reflection import (
21 convert_positional_arguments,
22 get_pretty_function_description,
23 )
24 from hypothesis.strategies import from_type
25
26 from tests.common.debug import (
27 assert_simple_property,
28 check_can_generate_examples,
29 find_any,
30 )
31 from tests.common.utils import fails_with, temp_registered
32
33
34 @given(st.data())
35 def test_typing_Final(data):
36 value = data.draw(from_type(typing.Final[int]))
37 assert isinstance(value, int)
38
39
40 @pytest.mark.parametrize("value", ["dog", b"goldfish", 42, 63.4, -80.5, False])
41 def test_typing_Literal(value):
42 assert_simple_property(from_type(typing.Literal[value]), lambda v: v == value)
43
44
45 @given(st.data())
46 def test_typing_Literal_nested(data):
47 lit = typing.Literal
48 values = [
49 (lit["hamster", 0], ("hamster", 0)),
50 (lit[26, False, "bunny", 130], (26, False, "bunny", 130)),
51 (lit[lit[1]], {1}),
52 (lit[lit[1], 2], {1, 2}),
53 (lit[1, lit[2], 3], {1, 2, 3}),
54 (lit[lit[lit[1], lit[2]], lit[lit[3], lit[4]]], {1, 2, 3, 4}),
55 ]
56 literal_type, flattened_literals = data.draw(st.sampled_from(values))
57 assert data.draw(st.from_type(literal_type)) in flattened_literals
58
59
60 class A(typing.TypedDict):
61 a: int
62
63
64 @given(from_type(A))
65 def test_simple_typeddict(value):
66 assert type(value) == dict
67 assert set(value) == {"a"}
68 assert isinstance(value["a"], int)
69
70
71 class B(A, total=False):
72 # a is required, b is optional
73 b: bool
74
75
76 @given(from_type(B))
77 def test_typeddict_with_optional(value):
78 assert type(value) == dict
79 assert set(value).issubset({"a", "b"})
80 assert isinstance(value["a"], int)
81 if "b" in value:
82 assert isinstance(value["b"], bool)
83
84
85 def test_simple_optional_key_is_optional():
86 # Optional keys are not currently supported, as PEP-589 leaves no traces
87 # at runtime. See https://github.com/python/cpython/pull/17214
88 find_any(from_type(B), lambda d: "b" not in d)
89
90
91 class C(B):
92 # a is required, b is optional, c is required again
93 c: str
94
95
96 @given(from_type(C))
97 def test_typeddict_with_optional_then_required_again(value):
98 assert type(value) == dict
99 assert set(value).issubset({"a", "b", "c"})
100 assert isinstance(value["a"], int)
101 if "b" in value:
102 assert isinstance(value["b"], bool)
103 assert isinstance(value["c"], str)
104
105
106 class NestedDict(typing.TypedDict):
107 inner: A
108
109
110 @given(from_type(NestedDict))
111 def test_typeddict_with_nested_value(value):
112 assert type(value) == dict
113 assert set(value) == {"inner"}
114 assert isinstance(value["inner"]["a"], int)
115
116
117 def test_layered_optional_key_is_optional():
118 # Optional keys are not currently supported, as PEP-589 leaves no traces
119 # at runtime. See https://github.com/python/cpython/pull/17214
120 find_any(from_type(C), lambda d: "b" not in d)
121
122
123 @dataclasses.dataclass(slots=False, frozen=False)
124 class Node:
125 left: typing.Union["Node", int]
126 right: typing.Union["Node", int]
127
128
129 @pytest.mark.skipif(
130 settings.get_current_profile_name() == "crosshair",
131 reason="takes ~11 mins; datastructure explosion: https://github.com/pschanely/hypothesis-crosshair/issues/27",
132 )
133 @given(st.builds(Node))
134 def test_can_resolve_recursive_dataclass(val):
135 assert isinstance(val, Node)
136
137
138 def test_can_register_new_type_for_typeddicts():
139 sentinel = object()
140 with temp_registered(C, st.just(sentinel)):
141 assert_simple_property(st.from_type(C), lambda v: v is sentinel)
142
143
144 @pytest.mark.parametrize(
145 "lam,source",
146 [
147 ((lambda a, /, b: a), "lambda a, /, b: a"),
148 ((lambda a=None, /, b=None: a), "lambda a=None, /, b=None: a"),
149 ],
150 )
151 def test_posonly_lambda_formatting(lam, source):
152 # Testing posonly lambdas, with and without default values
153 assert get_pretty_function_description(lam) == source
154
155
156 def test_does_not_convert_posonly_to_keyword():
157 args, kws = convert_positional_arguments(lambda x, /: None, (1,), {})
158 assert args
159 assert not kws
160
161
162 @given(x=st.booleans())
163 def test_given_works_with_keyword_only_params(*, x):
164 pass
165
166
167 def test_given_works_with_keyword_only_params_some_unbound():
168 @given(x=st.booleans())
169 def test(*, x, y):
170 assert y is None
171
172 test(y=None)
173
174
175 def test_given_works_with_positional_only_params():
176 @given(y=st.booleans())
177 def test(x, /, y):
178 pass
179
180 test(None)
181
182
183 def test_cannot_pass_strategies_by_position_if_there_are_posonly_args():
184 @given(st.booleans())
185 def test(x, /, y):
186 pass
187
188 with pytest.raises(InvalidArgument):
189 test(None)
190
191
192 @fails_with(InvalidArgument)
193 @given(st.booleans())
194 def test_cannot_pass_strategies_for_posonly_args(x, /):
195 pass
196
197
198 @given(y=st.booleans())
199 def has_posonly_args(x, /, y):
200 pass
201
202
203 @pytest.mark.xfail(
204 settings.get_current_profile_name() == "threading",
205 reason=(
206 "dynamic @example applications modify the shared "
207 "has_posonly_args.hypothesis._given_kwargs."
208 ),
209 strict=False,
210 )
211 def test_example_argument_validation():
212 example(y=None)(has_posonly_args)(1) # Basic case is OK
213
214 with pytest.raises(
215 InvalidArgument,
216 match=re.escape(
217 "Cannot pass positional arguments to @example() when decorating "
218 "a test function which has positional-only parameters."
219 ),
220 ):
221 example(None)(has_posonly_args)(1)
222
223 with pytest.raises(
224 InvalidArgument,
225 match=re.escape(
226 "Inconsistent args: @given() got strategies for 'y', "
227 "but @example() got arguments for 'x'"
228 ),
229 ):
230 example(x=None)(has_posonly_args)(1)
231
232
233 class FooProtocol(typing.Protocol):
234 def frozzle(self, x):
235 pass
236
237
238 class BarProtocol(typing.Protocol):
239 def bazzle(self, y):
240 pass
241
242
243 @given(st.data())
244 def test_can_resolve_registered_protocol(data):
245 with temp_registered(
246 FooProtocol,
247 st.builds(SimpleNamespace, frozzle=st.functions(like=lambda x: ...)),
248 ):
249 obj = data.draw(st.from_type(FooProtocol))
250 assert obj.frozzle(x=1) is None
251
252
253 def test_cannot_resolve_un_registered_protocol():
254 msg = "Instance and class checks can only be used with @runtime_checkable protocols"
255 with pytest.raises(TypeError, match=msg):
256 check_can_generate_examples(st.from_type(BarProtocol))