Debian Codegraph @

hypothesis-python/tests/cover/test_type_lookup.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 abc
12 import enum
13 import typing
14 from collections.abc import Callable, Sequence
15 from inspect import Parameter as P, Signature
16 from typing import Generic, List as _List, TypeVar, Union
17
18 import pytest
19
20 from hypothesis import given, infer, settings, strategies as st
21 from hypothesis.errors import InvalidArgument, ResolutionFailed
22 from hypothesis.internal.compat import get_type_hints
23 from hypothesis.internal.reflection import get_pretty_function_description
24 from hypothesis.strategies._internal import types
25 from hypothesis.strategies._internal.lazy import LazyStrategy
26 from hypothesis.strategies._internal.types import _global_type_lookup
27 from hypothesis.strategies._internal.utils import _all_strategies
28
29 from tests.common.debug import (
30 assert_all_examples,
31 assert_simple_property,
32 check_can_generate_examples,
33 find_any,
34 )
35 from tests.common.utils import (
36 Why,
37 fails_with,
38 skipif_threading,
39 temp_registered,
40 xfail_on_crosshair,
41 )
42
43 # we'll continue testing the typing variants until their removal from the stdlib
44 # ruff: noqa: UP006, UP035, UP007
45
46 types_with_core_strat = {
47 type_
48 for type_, strat in _global_type_lookup.items()
49 if isinstance(strat, LazyStrategy) and strat.function in vars(st).values()
50 }
51
52
53 def test_generic_sequence_of_integers_may_be_lists_or_bytes():
54 strat = st.from_type(Sequence[int])
55 find_any(strat, lambda x: isinstance(x, bytes))
56 find_any(strat, lambda x: isinstance(x, list))
57
58
59 @pytest.mark.parametrize("typ", sorted(types_with_core_strat, key=str))
60 def test_resolve_core_strategies(typ):
61 @given(st.from_type(typ))
62 def inner(ex):
63 assert isinstance(ex, typ)
64
65 inner()
66
67
68 def test_lookup_knows_about_all_core_strategies():
69 # Build a set of all types output by core strategies
70 blocklist = {
71 "builds",
72 "data",
73 "deferred",
74 "from_regex",
75 "from_type",
76 "ip_addresses",
77 "iterables",
78 "just",
79 "nothing",
80 "one_of",
81 "permutations",
82 "random_module",
83 "randoms",
84 "recursive",
85 "runner",
86 "sampled_from",
87 "shared",
88 "timezone_keys",
89 "timezones",
90 }
91 assert set(_all_strategies).issuperset(blocklist), blocklist.difference(
92 _all_strategies
93 )
94 found = set()
95 for thing in (
96 getattr(st, name)
97 for name in sorted(_all_strategies)
98 if name in dir(st) and name not in blocklist
99 ):
100 for n in range(3):
101 try:
102 ex = find_any(thing(*([st.nothing()] * n)))
103 found.add(type(ex))
104 break
105 except Exception:
106 continue
107
108 cannot_lookup = found - set(types._global_type_lookup)
109 assert not cannot_lookup
110
111
112 def test_lookup_keys_are_types():
113 with pytest.raises(InvalidArgument):
114 st.register_type_strategy("int", st.integers())
115 assert "int" not in types._global_type_lookup
116
117
118 @pytest.mark.parametrize(
119 "typ, not_a_strategy",
120 [
121 (int, 42), # Values must be strategies
122 # Can't register NotImplemented directly, even though strategy functions
123 # can return it.
124 (int, NotImplemented),
125 ],
126 )
127 def test_lookup_values_are_strategies(typ, not_a_strategy):
128 with pytest.raises(InvalidArgument):
129 st.register_type_strategy(typ, not_a_strategy)
130 assert not_a_strategy not in types._global_type_lookup.values()
131
132
133 @pytest.mark.parametrize("typ", sorted(types_with_core_strat, key=str))
134 def test_lookup_overrides_defaults(typ):
135 sentinel = object()
136 with temp_registered(typ, st.just(sentinel)):
137 assert_simple_property(st.from_type(typ), lambda v: v is sentinel)
138 assert_simple_property(st.from_type(typ), lambda v: v is not sentinel)
139
140
141 class ParentUnknownType:
142 pass
143
144
145 class UnknownType(ParentUnknownType):
146 def __init__(self, arg):
147 pass
148
149
150 def test_custom_type_resolution_fails_without_registering():
151 fails = st.from_type(UnknownType)
152 with pytest.raises(ResolutionFailed):
153 check_can_generate_examples(fails)
154
155
156 def test_custom_type_resolution():
157 sentinel = object()
158 with temp_registered(UnknownType, st.just(sentinel)):
159 assert_simple_property(st.from_type(UnknownType), lambda v: v is sentinel)
160 # Also covered by registration of child class
161 assert_simple_property(st.from_type(ParentUnknownType), lambda v: v is sentinel)
162
163
164 def test_custom_type_resolution_with_function():
165 sentinel = object()
166 with temp_registered(UnknownType, lambda _: st.just(sentinel)):
167 assert_simple_property(st.from_type(UnknownType), lambda v: v is sentinel)
168 assert_simple_property(st.from_type(ParentUnknownType), lambda v: v is sentinel)
169
170
171 def test_custom_type_resolution_with_function_non_strategy():
172 with temp_registered(UnknownType, lambda _: None):
173 with pytest.raises(ResolutionFailed):
174 check_can_generate_examples(st.from_type(UnknownType))
175 with pytest.raises(ResolutionFailed):
176 check_can_generate_examples(st.from_type(ParentUnknownType))
177
178
179 @pytest.mark.parametrize("strategy_returned", [True, False])
180 def test_conditional_type_resolution_with_function(strategy_returned):
181 sentinel = object()
182
183 def resolve_strategy(thing):
184 assert thing == UnknownType
185 if strategy_returned:
186 return st.just(sentinel)
187 return NotImplemented
188
189 with temp_registered(UnknownType, resolve_strategy):
190 if strategy_returned:
191 assert_simple_property(st.from_type(UnknownType), lambda v: v is sentinel)
192 else:
193 with pytest.raises(ResolutionFailed):
194 check_can_generate_examples(st.from_type(UnknownType))
195
196
197 def test_errors_if_generic_resolves_empty():
198 with temp_registered(UnknownType, lambda _: st.nothing()):
199 fails_1 = st.from_type(UnknownType)
200 with pytest.raises(ResolutionFailed):
201 check_can_generate_examples(fails_1)
202 fails_2 = st.from_type(ParentUnknownType)
203 with pytest.raises(ResolutionFailed):
204 check_can_generate_examples(fails_2)
205
206
207 @skipif_threading
208 def test_cannot_register_empty():
209 # Cannot register and did not register
210 with pytest.raises(InvalidArgument):
211 st.register_type_strategy(UnknownType, st.nothing())
212 fails = st.from_type(UnknownType)
213 with pytest.raises(ResolutionFailed):
214 check_can_generate_examples(fails)
215 assert UnknownType not in types._global_type_lookup
216
217
218 def test_pulic_interface_works():
219 check_can_generate_examples(st.from_type(int))
220 fails = st.from_type("not a type or annotated function")
221 with pytest.raises(InvalidArgument):
222 check_can_generate_examples(fails)
223
224
225 @pytest.mark.parametrize("infer_token", [infer, ...])
226 def test_given_can_infer_from_manual_annotations(infer_token):
227 # Editing annotations before decorating is hilariously awkward, but works!
228 def inner(a):
229 assert isinstance(a, int)
230
231 inner.__annotations__ = {"a": int}
232 given(a=infer_token)(inner)()
233
234
235 class EmptyEnum(enum.Enum):
236 pass
237
238
239 @fails_with(InvalidArgument)
240 @given(st.from_type(EmptyEnum))
241 def test_error_if_enum_is_empty(x):
242 pass
243
244
245 class BrokenClass:
246 __init__ = "Hello!"
247
248
249 def test_uninspectable_builds():
250 with pytest.raises(TypeError, match="object is not callable"):
251 check_can_generate_examples(st.builds(BrokenClass))
252
253
254 def test_uninspectable_from_type():
255 with pytest.raises(TypeError, match="object is not callable"):
256 check_can_generate_examples(st.from_type(BrokenClass))
257
258
259 def _check_instances(t):
260 # See https://github.com/samuelcolvin/pydantic/discussions/2508
261 return (
262 t.__module__ != "typing"
263 and t.__name__ != "ByteString"
264 and not t.__module__.startswith("pydantic")
265 and t.__module__ != "typing_extensions"
266 )
267
268
269 def maybe_mark(x):
270 if x.__name__ in "Match Decimal IPv4Address":
271 marks = xfail_on_crosshair(Why.other, as_marks=True, strict=False)
272 return pytest.param(x, marks=marks)
273 return x
274
275
276 @pytest.mark.parametrize(
277 "typ",
278 sorted(
279 (maybe_mark(x) for x in _global_type_lookup if _check_instances(x)),
280 key=str,
281 ),
282 )
283 @given(data=st.data())
284 def test_can_generate_from_all_registered_types(data, typ):
285 value = data.draw(st.from_type(typ), label="value")
286 assert isinstance(value, typ)
287
288
289 T = TypeVar("T")
290
291
292 class MyGeneric(Generic[T]):
293 def __init__(self, arg: T) -> None:
294 self.arg = arg
295
296
297 class Lines(Sequence[str]):
298 """Represent a sequence of text lines.
299
300 It turns out that resolving a class which inherits from a parametrised generic
301 type is... tricky. See https://github.com/HypothesisWorks/hypothesis/issues/2951
302 """
303
304
305 class SpecificDict(dict[int, int]):
306 pass
307
308
309 def using_generic(instance: MyGeneric[T]) -> T:
310 return instance.arg
311
312
313 def using_concrete_generic(instance: MyGeneric[int]) -> int:
314 return instance.arg
315
316
317 def test_generic_origin_empty():
318 with pytest.raises(ResolutionFailed):
319 check_can_generate_examples(st.builds(using_generic))
320
321
322 def test_issue_2951_regression():
323 lines_strat = st.builds(Lines, lines=st.lists(st.text()))
324 prev_seq_int_repr = repr(st.from_type(Sequence[int]))
325 with temp_registered(Lines, lines_strat):
326 assert st.from_type(Lines) == lines_strat
327 # Now let's test that the strategy for ``Sequence[int]`` did not
328 # change just because we registered a strategy for ``Lines``:
329 assert repr(st.from_type(Sequence[int])) == prev_seq_int_repr
330
331
332 def test_issue_2951_regression_two_params():
333 map_strat = st.builds(SpecificDict, st.dictionaries(st.integers(), st.integers()))
334 expected = repr(st.from_type(dict[int, int]))
335 with temp_registered(SpecificDict, map_strat):
336 assert st.from_type(SpecificDict) == map_strat
337 assert expected == repr(st.from_type(dict[int, int]))
338
339
340 @pytest.mark.parametrize(
341 "generic",
342 (
343 Union[str, int],
344 str | int,
345 Sequence[Sequence[int]],
346 MyGeneric[str],
347 Callable[..., str],
348 Callable[[int], str],
349 ),
350 ids=repr,
351 )
352 @pytest.mark.parametrize("strategy", [st.none(), lambda _: st.none()])
353 def test_generic_origin_with_type_args(generic, strategy):
354 with pytest.raises(InvalidArgument):
355 st.register_type_strategy(generic, strategy)
356 assert generic not in types._global_type_lookup
357
358
359 @pytest.mark.parametrize(
360 "generic",
361 (
362 Callable,
363 list,
364 Sequence,
365 # you can register types with all generic parameters
366 _List[T],
367 getattr(typing, "Sequence", None)[T], # pyupgrade workaround
368 list[T],
369 Sequence[T],
370 # User-defined generics should also work
371 MyGeneric,
372 MyGeneric[T],
373 ),
374 )
375 def test_generic_origin_without_type_args(generic):
376 with temp_registered(generic, st.just("example")):
377 pass
378
379
380 @pytest.mark.parametrize(
381 "strat, type_",
382 [
383 (st.from_type, MyGeneric[T]),
384 (st.from_type, MyGeneric[int]),
385 (st.from_type, MyGeneric),
386 (st.builds, using_generic),
387 (st.builds, using_concrete_generic),
388 ],
389 ids=get_pretty_function_description,
390 )
391 def test_generic_origin_from_type(strat, type_):
392 with temp_registered(MyGeneric, st.builds(MyGeneric)):
393 check_can_generate_examples(strat(type_))
394
395
396 def test_generic_origin_concrete_builds():
397 with temp_registered(MyGeneric, st.builds(MyGeneric, st.integers())):
398 assert_all_examples(
399 st.builds(using_generic), lambda example: isinstance(example, int)
400 )
401
402
403 class AbstractFoo(abc.ABC):
404 def __init__(self, x): # noqa: B027
405 pass
406
407 @abc.abstractmethod
408 def qux(self):
409 pass
410
411
412 class ConcreteFoo1(AbstractFoo):
413 # Can't resolve this one due to unannotated `x` param
414 def qux(self):
415 pass
416
417
418 class ConcreteFoo2(AbstractFoo):
419 def __init__(self, x: int):
420 pass
421
422 def qux(self):
423 pass
424
425
426 @given(st.from_type(AbstractFoo))
427 def test_gen_abstract(foo):
428 # This requires that we correctly checked which of the subclasses
429 # could be resolved, rather than unconditionally using all of them.
430 assert isinstance(foo, ConcreteFoo2)
431
432
433 class AbstractBar(abc.ABC):
434 def __init__(self, x): # noqa: B027
435 pass
436
437 @abc.abstractmethod
438 def qux(self):
439 pass
440
441
442 class ConcreteBar(AbstractBar):
443 def qux(self):
444 pass
445
446
447 def test_abstract_resolver_fallback():
448 # We create our distinct strategies for abstract and concrete types
449 gen_abstractbar = st.from_type(AbstractBar)
450 gen_concretebar = st.builds(ConcreteBar, x=st.none())
451 assert gen_abstractbar != gen_concretebar
452
453 # And trying to generate an instance of the abstract type fails,
454 # UNLESS the concrete type is currently resolvable
455 with pytest.raises(ResolutionFailed):
456 check_can_generate_examples(gen_abstractbar)
457 with temp_registered(ConcreteBar, gen_concretebar):
458 # which in turn means we resolve to the concrete subtype.
459 assert_simple_property(
460 gen_abstractbar, lambda gen: isinstance(gen, ConcreteBar)
461 )
462 with pytest.raises(ResolutionFailed):
463 check_can_generate_examples(gen_abstractbar)
464
465
466 def _one_arg(x: int):
467 assert isinstance(x, int)
468
469
470 def _multi_arg(x: int, y: str):
471 assert isinstance(x, int)
472 assert isinstance(y, str)
473
474
475 def _kwd_only(*, y: str):
476 assert isinstance(y, str)
477
478
479 def _pos_and_kwd_only(x: int, *, y: str):
480 assert isinstance(x, int)
481 assert isinstance(y, str)
482
483
484 @pytest.mark.parametrize("func", [_one_arg, _multi_arg, _kwd_only, _pos_and_kwd_only])
485 def test_infer_all(func):
486 # tests @given(...) against various signatures
487 settings(max_examples=1)(given(...))(func)()
488
489
490 def test_does_not_add_param_empty_to_type_hints():
491 def f(x):
492 pass
493
494 f.__signature__ = Signature([P("y", P.KEYWORD_ONLY)], return_annotation=None)
495 assert get_type_hints(f) == {}