Debian Codegraph @

hypothesis-python/tests/cover/test_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 builtins
13 import collections
14 import contextlib
15 import datetime
16 import enum
17 import inspect
18 import io
19 import random
20 import re
21 import string
22 import sys
23 import typing
24 import warnings
25 from dataclasses import dataclass
26 from inspect import signature
27 from numbers import Real
28 from typing import (
29 Dict as _Dict,
30 FrozenSet as _FrozenSet,
31 List as _List,
32 Set as _Set,
33 Tuple as _Tuple,
34 Type as _Type,
35 )
36
37 import pytest
38
39 from hypothesis import HealthCheck, assume, given, settings, strategies as st
40 from hypothesis.errors import InvalidArgument, ResolutionFailed, SmallSearchSpaceWarning
41 from hypothesis.internal.compat import get_type_hints
42 from hypothesis.internal.conjecture.junkdrawer import stack_depth_of_caller
43 from hypothesis.internal.reflection import get_pretty_function_description
44 from hypothesis.strategies import from_type
45 from hypothesis.strategies._internal import types
46
47 from tests.common.debug import (
48 assert_all_examples,
49 assert_no_examples,
50 assert_simple_property,
51 check_can_generate_examples,
52 find_any,
53 minimal,
54 )
55 from tests.common.utils import fails_with, temp_registered
56
57 # we'll continue testing the typing variants until their removal from the stdlib
58 # ruff: noqa: UP006, UP035, UP045, UP007
59
60 sentinel = object()
61 BUILTIN_TYPES = tuple(
62 v
63 for v in vars(builtins).values()
64 if isinstance(v, type) and v.__name__ != "BuiltinImporter"
65 )
66 generics = sorted(
67 (
68 t
69 for t in types._global_type_lookup
70 # We ignore TypeVar, because it is not a Generic type:
71 if isinstance(t, types.typing_root_type)
72 and t != typing.TypeVar
73 and (
74 sys.version_info[:2] <= (3, 11)
75 or t != getattr(typing, "ByteString", object())
76 )
77 ),
78 key=str,
79 )
80
81
82 @pytest.mark.parametrize("typ", generics, ids=repr)
83 @settings(
84 suppress_health_check=[HealthCheck.too_slow, HealthCheck.filter_too_much],
85 database=None,
86 )
87 @given(data=st.data())
88 def test_resolve_typing_module(data, typ):
89 ex = data.draw(from_type(typ))
90
91 if typ in (typing.BinaryIO, typing.TextIO):
92 assert isinstance(ex, io.IOBase)
93 elif isinstance(typ, typing._ProtocolMeta):
94 pass
95 elif (typing.get_origin(typ) or typ) is type and not isinstance(type, type):
96 assert ex is type or isinstance(ex, typing.TypeVar)
97 else:
98 assert isinstance(ex, typ)
99
100
101 @pytest.mark.parametrize("typ", [typing.Any, typing.Union])
102 def test_does_not_resolve_special_cases(typ):
103 with pytest.raises(InvalidArgument):
104 check_can_generate_examples(from_type(typ))
105
106
107 @pytest.mark.parametrize(
108 "typ,instance_of",
109 [
110 (typing.Union[int, str], (int, str)),
111 (int | str, (int, str)),
112 (typing.Optional[int], (int, type(None))),
113 (int | None, (int, type(None))),
114 ],
115 )
116 @given(data=st.data())
117 def test_specialised_scalar_types(data, typ, instance_of):
118 ex = data.draw(from_type(typ))
119 assert isinstance(ex, instance_of)
120
121
122 def test_typing_Type_int():
123 for t in (type[int], type["int"], _Type[int], _Type["int"]):
124 assert_simple_property(from_type(t), lambda x: x is int)
125
126
127 @given(from_type(type[str | list]) | from_type(_Type[str | list]))
128 def test_typing_Type_Union(ex):
129 assert ex in (str, list)
130
131
132 @pytest.mark.parametrize(
133 "typ",
134 [
135 pytest.param(
136 getattr(collections.abc, "ByteString", ...),
137 marks=pytest.mark.skipif(sys.version_info[:2] >= (3, 14), reason="removed"),
138 ),
139 typing.Match,
140 typing.Pattern,
141 re.Match,
142 re.Pattern,
143 ],
144 ids=repr,
145 )
146 @given(data=st.data())
147 def test_rare_types(data, typ):
148 ex = data.draw(from_type(typ))
149 with warnings.catch_warnings():
150 if sys.version_info[:2] >= (3, 12):
151 warnings.simplefilter("ignore", DeprecationWarning)
152 # ByteString is deprecated in Python 3.12
153 assert isinstance(ex, typ)
154
155
156 class Elem:
157 pass
158
159
160 @pytest.mark.parametrize(
161 "typ,coll_type",
162 [
163 (_Set[Elem], set),
164 (_FrozenSet[Elem], frozenset),
165 (_Dict[Elem, None], dict),
166 (set[Elem], set),
167 (frozenset[Elem], frozenset),
168 # (dict[Elem, None], dict), # FIXME this should work
169 (typing.DefaultDict[Elem, None], collections.defaultdict),
170 (typing.KeysView[Elem], type({}.keys())),
171 (typing.ValuesView[Elem], type({}.values())),
172 (_List[Elem], list),
173 (_Tuple[Elem], tuple),
174 (_Tuple[Elem, ...], tuple),
175 (list[Elem], list),
176 (tuple[Elem], tuple),
177 (tuple[Elem, ...], tuple),
178 (typing.Iterator[Elem], typing.Iterator),
179 (typing.Sequence[Elem], typing.Sequence),
180 (typing.Iterable[Elem], typing.Iterable),
181 (typing.Mapping[Elem, None], typing.Mapping),
182 (typing.Container[Elem], typing.Container),
183 (typing.NamedTuple("A_NamedTuple", (("elem", Elem),)), tuple),
184 (typing.Counter[Elem], typing.Counter),
185 (typing.Deque[Elem], typing.Deque),
186 ],
187 ids=repr,
188 )
189 @given(data=st.data())
190 def test_specialised_collection_types(data, typ, coll_type):
191 ex = data.draw(from_type(typ))
192 assert isinstance(ex, coll_type)
193 instances = [isinstance(elem, Elem) for elem in ex]
194 assert all(instances)
195 assume(instances) # non-empty collections without calling len(iterator)
196
197
198 class ElemValue:
199 pass
200
201
202 @pytest.mark.parametrize(
203 "typ,coll_type",
204 [
205 (typing.ChainMap[Elem, ElemValue], typing.ChainMap),
206 (typing.DefaultDict[Elem, ElemValue], typing.DefaultDict),
207 (typing.OrderedDict[Elem, ElemValue], typing.OrderedDict),
208 ],
209 ids=repr,
210 )
211 @given(data=st.data())
212 def test_specialised_mapping_types(data, typ, coll_type):
213 ex = data.draw(from_type(typ).filter(len))
214 assert isinstance(ex, coll_type)
215 instances = [isinstance(elem, Elem) for elem in ex]
216 assert all(instances)
217 assert all(isinstance(elem, ElemValue) for elem in ex.values())
218
219
220 @given(from_type(typing.ItemsView[Elem, Elem]).filter(len))
221 def test_ItemsView(ex):
222 # See https://github.com/python/typing/issues/177
223 assert isinstance(ex, type({}.items()))
224 assert all(isinstance(elem, tuple) and len(elem) == 2 for elem in ex)
225 assert all(all(isinstance(e, Elem) for e in elem) for elem in ex)
226
227
228 @pytest.mark.parametrize("generic", [typing.Match, typing.Pattern])
229 @pytest.mark.parametrize("typ", [bytes, str])
230 @given(data=st.data())
231 def test_regex_types(data, generic, typ):
232 x = data.draw(from_type(generic[typ]))
233 assert isinstance(x[0] if generic is typing.Match else x.pattern, typ)
234
235
236 @given(x=...)
237 def test_Generator(x: typing.Generator[Elem, None, ElemValue]):
238 assert isinstance(x, typing.Generator)
239 try:
240 while True:
241 e = next(x)
242 assert isinstance(e, Elem)
243 x.send(None) # The generators we create don't check the send type
244 except StopIteration as stop:
245 assert isinstance(stop.value, ElemValue)
246
247
248 def test_Optional_minimises_to_None():
249 assert minimal(from_type(typing.Optional[int]), lambda ex: True) is None
250
251
252 @pytest.mark.parametrize("n", [0, 1, 5])
253 @pytest.mark.parametrize("t", [tuple, _Tuple])
254 def test_variable_length_tuples(t, n):
255 type_ = t[int, ...]
256 check_can_generate_examples(from_type(type_).filter(lambda ex: len(ex) == n))
257
258
259 def test_lookup_overrides_defaults():
260 sentinel = object()
261 with temp_registered(int, st.just(sentinel)):
262
263 @given(from_type(list[int]))
264 def inner_1(ex):
265 assert all(elem is sentinel for elem in ex)
266
267 inner_1()
268
269 @given(from_type(list[int]))
270 def inner_2(ex):
271 assert all(isinstance(elem, int) for elem in ex)
272
273 inner_2()
274
275
276 def test_register_generic_typing_strats():
277 # I don't expect anyone to do this, but good to check it works as expected
278 with temp_registered(
279 typing.Sequence,
280 types._global_type_lookup[set],
281 ):
282 # We register sets for the abstract sequence type, which masks subtypes
283 # from supertype resolution but not direct resolution
284 assert_all_examples(
285 from_type(typing.Sequence[int]), lambda ex: isinstance(ex, set)
286 )
287 assert_all_examples(
288 from_type(typing.Container[int]),
289 lambda ex: not isinstance(ex, typing.Sequence),
290 )
291 assert_all_examples(from_type(list[int]), lambda ex: isinstance(ex, list))
292
293
294 def if_available(name):
295 try:
296 return getattr(typing, name)
297 except AttributeError:
298 return pytest.param(name, marks=[pytest.mark.skip])
299
300
301 @pytest.mark.parametrize(
302 "typ",
303 [
304 typing.Sequence,
305 typing.Container,
306 typing.Mapping,
307 typing.Reversible,
308 typing.SupportsBytes,
309 typing.SupportsAbs,
310 typing.SupportsComplex,
311 typing.SupportsFloat,
312 typing.SupportsInt,
313 typing.SupportsRound,
314 if_available("SupportsIndex"),
315 ],
316 ids=get_pretty_function_description,
317 )
318 def test_resolves_weird_types(typ):
319 check_can_generate_examples(from_type(typ))
320
321
322 class Foo:
323 def __init__(self, x):
324 pass
325
326
327 class Bar(Foo):
328 pass
329
330
331 class Baz(Foo):
332 pass
333
334
335 st.register_type_strategy(Bar, st.builds(Bar, st.integers()))
336 st.register_type_strategy(Baz, st.builds(Baz, st.integers()))
337
338
339 @pytest.mark.parametrize(
340 "var,expected",
341 [
342 (typing.TypeVar("V"), object),
343 (typing.TypeVar("V", bound=int), int),
344 (typing.TypeVar("V", bound=Foo), (Bar, Baz)),
345 (typing.TypeVar("V", bound=int | str), (int, str)),
346 (typing.TypeVar("V", int, str), (int, str)),
347 ],
348 )
349 @settings(suppress_health_check=[HealthCheck.too_slow])
350 @given(data=st.data())
351 def test_typevar_type_is_consistent(data, var, expected):
352 strat = st.from_type(var)
353 v1 = data.draw(strat)
354 v2 = data.draw(strat)
355 assume(v1 != v2) # Values may vary, just not types
356 assert type(v1) == type(v2)
357 assert isinstance(v1, expected)
358
359
360 def test_distinct_typevars_same_constraint():
361 A = typing.TypeVar("A", int, str)
362 B = typing.TypeVar("B", int, str)
363 find_any(
364 st.tuples(st.from_type(A), st.from_type(B)),
365 lambda ab: type(ab[0]) != type(ab[1]),
366 )
367
368
369 def test_distinct_typevars_distinct_type():
370 """Ensures that two different type vars have at least one different type in their strategies."""
371 A = typing.TypeVar("A")
372 B = typing.TypeVar("B")
373 find_any(
374 st.tuples(st.from_type(A), st.from_type(B)),
375 lambda ab: type(ab[0]) != type(ab[1]),
376 )
377
378
379 A = typing.TypeVar("A")
380
381
382 def same_type_args(a: A, b: A):
383 assert type(a) == type(b)
384
385
386 @given(st.builds(same_type_args))
387 def test_same_typevars_same_type(_):
388 """Ensures that single type argument will always have the same type in a single context."""
389
390
391 def test_typevars_can_be_redefined():
392 """We test that one can register a custom strategy for all type vars."""
393 A = typing.TypeVar("A")
394
395 with temp_registered(typing.TypeVar, st.just(1)):
396 assert_all_examples(st.from_type(A), lambda obj: obj == 1)
397
398
399 def test_typevars_can_be_redefine_with_factory():
400 """We test that one can register a custom strategy for all type vars."""
401 A = typing.TypeVar("A")
402
403 with temp_registered(typing.TypeVar, lambda thing: st.just(thing.__name__)):
404 assert_all_examples(st.from_type(A), lambda obj: obj == "A")
405
406
407 def test_typevars_can_be_resolved_conditionally():
408 sentinel = object()
409 A = typing.TypeVar("A")
410 B = typing.TypeVar("B")
411
412 def resolve_type_var(thing):
413 assert thing in (A, B)
414 if thing == A:
415 return st.just(sentinel)
416 return NotImplemented
417
418 with temp_registered(typing.TypeVar, resolve_type_var):
419 assert_simple_property(st.from_type(A), lambda x: x is sentinel)
420 # We've re-defined the default TypeVar resolver, so there is no fallback.
421 # This causes the lookup to fail.
422 with pytest.raises(InvalidArgument):
423 check_can_generate_examples(st.from_type(B))
424
425
426 def annotated_func(a: int, b: int = 2, *, c: int, d: int = 4):
427 return a + b + c + d
428
429
430 def test_issue_946_regression():
431 # Turned type hints into kwargs even if the required posarg was passed
432 check_can_generate_examples(st.builds(annotated_func, st.integers()))
433
434
435 @pytest.mark.parametrize(
436 "thing",
437 [
438 annotated_func, # Works via typing.get_type_hints
439 typing.NamedTuple("N", [("a", int)]), # Falls back to inspection
440 int, # Fails; returns empty dict
441 ],
442 )
443 def test_can_get_type_hints(thing):
444 assert isinstance(get_type_hints(thing), dict)
445
446
447 def test_force_builds_to_infer_strategies_for_default_args():
448 # By default, leaves args with defaults and minimises to 2+4=6
449 assert minimal(st.builds(annotated_func), lambda ex: True) == 6
450 # Inferring integers() for args makes it minimise to zero
451 assert minimal(st.builds(annotated_func, b=..., d=...), lambda ex: True) == 0
452
453
454 def non_annotated_func(a, b=2, *, c, d=4):
455 pass
456
457
458 def test_cannot_pass_infer_as_posarg():
459 with pytest.raises(InvalidArgument):
460 check_can_generate_examples(st.builds(annotated_func, ...))
461
462
463 def test_cannot_force_inference_for_unannotated_arg():
464 with pytest.raises(InvalidArgument):
465 check_can_generate_examples(st.builds(non_annotated_func, a=..., c=st.none()))
466 with pytest.raises(InvalidArgument):
467 check_can_generate_examples(st.builds(non_annotated_func, a=st.none(), c=...))
468
469
470 class UnknownType:
471 def __init__(self, arg):
472 pass
473
474
475 class UnknownAnnotatedType:
476 def __init__(self, arg: int):
477 pass
478
479
480 @given(st.from_type(UnknownAnnotatedType))
481 def test_builds_for_unknown_annotated_type(ex):
482 assert isinstance(ex, UnknownAnnotatedType)
483
484
485 def unknown_annotated_func(a: UnknownType, b=2, *, c: UnknownType, d=4):
486 pass
487
488
489 def test_raises_for_arg_with_unresolvable_annotation():
490 with pytest.raises(ResolutionFailed):
491 check_can_generate_examples(st.builds(unknown_annotated_func))
492 with pytest.raises(ResolutionFailed):
493 check_can_generate_examples(
494 st.builds(unknown_annotated_func, a=st.none(), c=...)
495 )
496
497
498 @given(a=..., b=...)
499 def test_can_use_type_hints(a: int, b: float):
500 assert isinstance(a, int)
501 assert isinstance(b, float)
502
503
504 def test_error_if_has_unresolvable_hints():
505 @given(a=...)
506 def inner(a: UnknownType):
507 pass
508
509 with pytest.raises(InvalidArgument):
510 inner()
511
512
513 def test_resolves_NewType():
514 typ = typing.NewType("T", int)
515 nested = typing.NewType("NestedT", typ)
516 uni = typing.NewType("UnionT", int | None)
517 assert_simple_property(from_type(typ), lambda x: isinstance(x, int))
518 assert_simple_property(from_type(nested), lambda x: isinstance(x, int))
519 assert_simple_property(from_type(uni), lambda x: isinstance(x, (int, type(None))))
520 find_any(from_type(uni), lambda x: isinstance(x, int))
521 find_any(from_type(uni), lambda x: isinstance(x, type(None)))
522
523
524 @pytest.mark.parametrize("is_handled", [True, False])
525 def test_resolves_NewType_conditionally(is_handled):
526 sentinel = object()
527 typ = typing.NewType("T", int)
528
529 def resolve_custom_strategy(thing):
530 assert thing is typ
531 if is_handled:
532 return st.just(sentinel)
533 return NotImplemented
534
535 with temp_registered(typ, resolve_custom_strategy):
536 if is_handled:
537 assert_simple_property(st.from_type(typ), lambda x: x is sentinel)
538 else:
539 assert_simple_property(st.from_type(typ), lambda x: isinstance(x, int))
540
541
542 E = enum.Enum("E", "a b c")
543
544
545 @given(from_type(E))
546 def test_resolves_enum(ex):
547 assert isinstance(ex, E)
548
549
550 @pytest.mark.parametrize("resolver", [from_type, st.sampled_from])
551 def test_resolves_flag_enum(resolver):
552 # Storing all combinations takes O(2^n) memory. Using an enum of 52
553 # members in this test ensures that we won't try!
554 F = enum.Flag("F", " ".join(string.ascii_letters))
555
556 # Checks for combination coverage are found in nocover/test_sampled_from
557 @given(resolver(F))
558 def inner(ex):
559 assert isinstance(ex, F)
560
561 inner()
562
563
564 class AnnotatedTarget:
565 def __init__(self, a: int, b: int):
566 pass
567
568 def method(self, a: int, b: int):
569 pass
570
571
572 @pytest.mark.parametrize("target", [AnnotatedTarget, AnnotatedTarget(1, 2).method])
573 @pytest.mark.parametrize(
574 "args,kwargs",
575 [
576 ((), {}),
577 ((1,), {}),
578 ((1, 2), {}),
579 ((), {"a": 1}),
580 ((), {"b": 2}),
581 ((), {"a": 1, "b": 2}),
582 ],
583 )
584 def test_required_args(target, args, kwargs):
585 # Mostly checking that `self` (and only self) is correctly excluded
586 check_can_generate_examples(
587 st.builds(
588 target, *map(st.just, args), **{k: st.just(v) for k, v in kwargs.items()}
589 )
590 )
591
592
593 class AnnotatedNamedTuple(typing.NamedTuple):
594 a: str
595
596
597 @given(st.builds(AnnotatedNamedTuple))
598 def test_infers_args_for_namedtuple_builds(thing):
599 assert isinstance(thing.a, str)
600
601
602 @given(st.from_type(AnnotatedNamedTuple))
603 def test_infers_args_for_namedtuple_from_type(thing):
604 assert isinstance(thing.a, str)
605
606
607 @given(st.builds(AnnotatedNamedTuple, a=st.none()))
608 def test_override_args_for_namedtuple(thing):
609 assert thing.a is None
610
611
612 @pytest.mark.parametrize("thing", [typing.Optional, list, type, _List, _Type])
613 def test_cannot_resolve_bare_forward_reference(thing):
614 t = thing["ConcreteFoo"]
615 with pytest.raises(InvalidArgument):
616 check_can_generate_examples(st.from_type(t))
617
618
619 class Tree:
620 def __init__(self, left: typing.Optional["Tree"], right: typing.Optional["Tree"]):
621 self.left = left
622 self.right = right
623
624 def __repr__(self):
625 return f"Tree({self.left}, {self.right})"
626
627
628 @pytest.mark.skipif(
629 settings.get_current_profile_name() == "crosshair",
630 reason="takes ~19 mins; datastructure explosion https://github.com/pschanely/hypothesis-crosshair/issues/27",
631 )
632 @given(tree=st.builds(Tree))
633 def test_resolving_recursive_type(tree):
634 assert isinstance(tree, Tree)
635
636
637 class TypedTree(typing.TypedDict):
638 nxt: typing.Optional["TypedTree"]
639
640
641 def test_resolving_recursive_typeddict():
642 assert_simple_property(
643 st.from_type(TypedTree),
644 lambda tree: isinstance(tree, dict) and len(tree) == 1 and "nxt" in tree,
645 )
646
647
648 class MyList:
649 def __init__(self, nxt: typing.Optional["MyList"] = None):
650 self.nxt = nxt
651
652 def __repr__(self):
653 return f"MyList({self.nxt})"
654
655 def __eq__(self, other):
656 return type(self) == type(other) and self.nxt == other.nxt
657
658
659 @given(lst=st.from_type(MyList))
660 def test_resolving_recursive_type_with_defaults(lst):
661 assert isinstance(lst, MyList)
662
663
664 def test_recursive_type_with_defaults_minimizes_to_defaults():
665 assert minimal(from_type(MyList), lambda ex: True) == MyList()
666
667
668 class MutualA:
669 def __init__(self, nxt: typing.Optional["MutualB"]):
670 self.nxt = nxt
671
672 def __repr__(self):
673 return f"A({self.nxt})"
674
675
676 class MutualB:
677 def __init__(self, nxt: typing.Optional["MutualA"]):
678 self.nxt = nxt
679
680 def __repr__(self):
681 return f"B({self.nxt})"
682
683
684 @given(nxt=st.from_type(MutualA))
685 def test_resolving_mutually_recursive_types(nxt):
686 i = 0
687 while nxt:
688 assert isinstance(nxt, [MutualA, MutualB][i % 2])
689 nxt = nxt.nxt
690 i += 1
691
692
693 def test_resolving_mutually_recursive_types_with_limited_stack():
694 orig_recursionlimit = sys.getrecursionlimit()
695 current_stack_depth = stack_depth_of_caller()
696 sys.setrecursionlimit(current_stack_depth + 100)
697 try:
698
699 @given(nxt=st.from_type(MutualA))
700 def test(nxt):
701 pass
702
703 test()
704 finally:
705 assert sys.getrecursionlimit() == current_stack_depth + 100
706 sys.setrecursionlimit(orig_recursionlimit)
707
708
709 class A_with_default:
710 def __init__(self, nxt: typing.Optional["B_with_default"] = None):
711 self.nxt = nxt
712
713 def __repr__(self):
714 return f"A_with_default({self.nxt})"
715
716
717 class B_with_default:
718 def __init__(self, nxt: typing.Optional["A_with_default"] = None):
719 self.nxt = nxt
720
721 def __repr__(self):
722 return f"B_with_default({self.nxt})"
723
724
725 @given(nxt=st.from_type(A_with_default))
726 def test_resolving_mutually_recursive_types_with_defaults(nxt):
727 # This test is required to cover the raise/except part of the recursion
728 # check in from_type, see
729 # https://github.com/HypothesisWorks/hypothesis/issues/3655. If the
730 # skip-nondefaulted-args check is removed, this test becomes redundant.
731 i = 0
732 while nxt:
733 assert isinstance(nxt, [A_with_default, B_with_default][i % 2])
734 nxt = nxt.nxt
735 i += 1
736
737
738 class SomeClass:
739 def __init__(self, value: int, next_node: typing.Optional["SomeClass"]) -> None:
740 assert value > 0
741 self.value = value
742 self.next_node = next_node
743
744 def __repr__(self) -> str:
745 return f"SomeClass({self.value}, next_node={self.next_node})"
746
747
748 def test_resolving_recursive_type_with_registered_constraint():
749 with temp_registered(
750 SomeClass, st.builds(SomeClass, value=st.integers(min_value=1))
751 ):
752
753 @given(s=st.from_type(SomeClass))
754 def test(s):
755 assert isinstance(s, SomeClass)
756
757 test()
758
759
760 def test_resolving_recursive_type_with_registered_constraint_not_none():
761 with temp_registered(
762 SomeClass, st.builds(SomeClass, value=st.integers(min_value=1))
763 ):
764 s = st.from_type(SomeClass)
765 print(s, s.wrapped_strategy)
766 find_any(s, lambda s: s.next_node is not None)
767
768
769 @given(from_type(tuple[()]) | from_type(_Tuple[()]))
770 def test_resolves_empty_Tuple_issue_1583_regression(ex):
771 # See e.g. https://github.com/python/mypy/commit/71332d58
772 assert ex == ()
773
774
775 def test_can_register_NewType():
776 Name = typing.NewType("Name", str)
777 st.register_type_strategy(Name, st.just("Eric Idle"))
778 assert_simple_property(st.from_type(Name), lambda x: x == "Eric Idle")
779
780
781 @given(st.from_type(typing.Callable))
782 def test_resolves_bare_callable_to_function(f):
783 val = f()
784 assert val is None
785 with pytest.raises(TypeError):
786 f(1)
787
788
789 @given(st.from_type(typing.Callable[[str], int]))
790 def test_resolves_callable_with_arg_to_function(f):
791 val = f("1")
792 assert isinstance(val, int)
793
794
795 @given(st.from_type(typing.Callable[..., int]))
796 def test_resolves_ellipses_callable_to_function(f):
797 val = f()
798 assert isinstance(val, int)
799 f(1)
800 f(1, 2, 3)
801 f(accepts_kwargs_too=1)
802
803
804 class AbstractFoo(abc.ABC):
805 @abc.abstractmethod
806 def foo(self):
807 pass
808
809
810 class ConcreteFoo(AbstractFoo):
811 def foo(self):
812 pass
813
814
815 @given(st.from_type(AbstractFoo))
816 def test_can_resolve_abstract_class(instance):
817 assert isinstance(instance, ConcreteFoo)
818 instance.foo()
819
820
821 class AbstractBar(abc.ABC):
822 @abc.abstractmethod
823 def bar(self):
824 pass
825
826
827 @fails_with(ResolutionFailed)
828 @given(st.from_type(AbstractBar))
829 def test_cannot_resolve_abstract_class_with_no_concrete_subclass(instance):
830 raise AssertionError("test body unreachable as strategy cannot resolve")
831
832
833 @fails_with(ResolutionFailed)
834 @given(st.from_type(type["ConcreteFoo"]))
835 def test_cannot_resolve_type_with_forwardref(instance):
836 raise AssertionError("test body unreachable as strategy cannot resolve")
837
838
839 @fails_with(ResolutionFailed)
840 @given(st.from_type(_Type["ConcreteFoo"]))
841 def test_cannot_resolve_type_with_forwardref_old(instance):
842 raise AssertionError("test body unreachable as strategy cannot resolve")
843
844
845 @pytest.mark.parametrize("typ", [typing.Hashable, typing.Sized])
846 @given(data=st.data())
847 def test_inference_on_generic_collections_abc_aliases(typ, data):
848 # regression test for inference bug on types that are just aliases
849 # types for simple interfaces in collections abc and take no args
850 # the typing module such as Hashable and Sized
851 # see https://github.com/HypothesisWorks/hypothesis/issues/2272
852 value = data.draw(st.from_type(typ))
853 assert isinstance(value, typ)
854
855
856 @given(st.from_type(typing.Sequence[set]))
857 def test_bytestring_not_treated_as_generic_sequence(val):
858 # Check that we don't fall into the specific problem from
859 # https://github.com/HypothesisWorks/hypothesis/issues/2257
860 assert not isinstance(val, bytes)
861 # Check it hasn't happened again from some other non-generic sequence type.
862 for x in val:
863 assert isinstance(x, set)
864
865
866 @pytest.mark.parametrize(
867 "type_", [int, Real, object, typing.Union[int, str], typing.Union[Real, str]]
868 )
869 def test_bytestring_is_valid_sequence_of_int_and_parent_classes(type_):
870 find_any(
871 st.from_type(typing.Sequence[type_]),
872 lambda val: isinstance(val, bytes),
873 )
874
875
876 @pytest.mark.parametrize("protocol", [typing.SupportsAbs, typing.SupportsRound])
877 @given(data=st.data())
878 def test_supportsop_types_support_protocol(protocol, data):
879 # test values drawn from SupportsOp types are indeed considered instances
880 # of that type.
881 value = data.draw(st.from_type(protocol))
882 # check that we aren't somehow generating instances of the protocol itself
883 assert value.__class__ != protocol
884 assert issubclass(type(value), protocol)
885
886
887 @pytest.mark.parametrize("restrict_custom_strategy", [True, False])
888 def test_generic_aliases_can_be_conditionally_resolved_by_registered_function(
889 restrict_custom_strategy,
890 ):
891 # Check that a custom strategy function may provide no strategy for a
892 # generic alias request like Container[T]. We test this under two scenarios:
893 # - where CustomContainer CANNOT be generated from requests for Container[T]
894 # (only for requests for exactly CustomContainer[T])
895 # - where CustomContainer CAN be generated from requests for Container[T]
896 T = typing.TypeVar("T")
897
898 @dataclass
899 class CustomContainer(typing.Container[T]):
900 content: T
901
902 def __contains__(self, value: object) -> bool:
903 return self.content == value
904
905 def get_custom_container_strategy(thing):
906 if restrict_custom_strategy and typing.get_origin(thing) != CustomContainer:
907 return NotImplemented
908 return st.builds(
909 CustomContainer, content=st.from_type(typing.get_args(thing)[0])
910 )
911
912 with temp_registered(CustomContainer, get_custom_container_strategy):
913
914 def is_custom_container_with_str(example):
915 return isinstance(example, CustomContainer) and isinstance(
916 example.content, str
917 )
918
919 def is_non_custom_container(example):
920 return isinstance(example, typing.Container) and not isinstance(
921 example, CustomContainer
922 )
923
924 assert_all_examples(
925 st.from_type(CustomContainer[str]), is_custom_container_with_str
926 )
927 # If the strategy function is restricting, it doesn't return a strategy
928 # for requests for Container[...], so it's never generated. When not
929 # restricting, it is generated.
930 if restrict_custom_strategy:
931 assert_all_examples(
932 st.from_type(typing.Container[str]), is_non_custom_container
933 )
934 else:
935 find_any(st.from_type(typing.Container[str]), is_custom_container_with_str)
936 find_any(st.from_type(typing.Container[str]), is_non_custom_container)
937
938
939 @pytest.mark.parametrize(
940 "protocol, typ",
941 [
942 (typing.SupportsFloat, float),
943 (typing.SupportsInt, int),
944 (typing.SupportsBytes, bytes),
945 (typing.SupportsComplex, complex),
946 ],
947 )
948 @given(data=st.data())
949 def test_supportscast_types_support_protocol_or_are_castable(protocol, typ, data):
950 value = data.draw(st.from_type(protocol))
951 # check that we aren't somehow generating instances of the protocol itself
952 assert value.__class__ != protocol
953 # test values drawn from the protocol types either support the protocol
954 # or can be cast to typ
955 assert issubclass(type(value), protocol) or types.can_cast(typ, value)
956
957
958 def test_can_cast():
959 assert types.can_cast(int, "0")
960 assert not types.can_cast(int, "abc")
961
962
963 @pytest.mark.parametrize("type_", [datetime.timezone, datetime.tzinfo])
964 def test_timezone_lookup(type_):
965 assert issubclass(type_, datetime.tzinfo)
966 assert_all_examples(st.from_type(type_), lambda t: isinstance(t, type_))
967
968
969 @pytest.mark.parametrize(
970 "typ",
971 [
972 _Set[typing.Hashable],
973 _FrozenSet[typing.Hashable],
974 _Dict[typing.Hashable, int],
975 set[typing.Hashable],
976 frozenset[typing.Hashable],
977 dict[typing.Hashable, int],
978 ],
979 )
980 @settings(suppress_health_check=[HealthCheck.data_too_large])
981 @given(data=st.data())
982 def test_generic_collections_only_use_hashable_elements(typ, data):
983 data.draw(from_type(typ))
984
985
986 @given(st.sets(st.integers() | st.binary(), min_size=2))
987 def test_no_byteswarning(_):
988 pass
989
990
991 @pytest.mark.skipif(
992 settings.get_current_profile_name() == "crosshair",
993 reason="Crosshair is too much slower at hashing values",
994 )
995 def test_hashable_type_unhashable_value():
996 # Decimal("snan") is not hashable; we should be able to generate it.
997 # See https://github.com/HypothesisWorks/hypothesis/issues/2320
998 find_any(
999 from_type(typing.Hashable),
1000 lambda x: not types._can_hash(x),
1001 settings(max_examples=10**5),
1002 )
1003
1004
1005 def test_unhashable_type():
1006 class UnhashableMeta(type):
1007 __hash__ = None
1008
1009 class UnhashableType(metaclass=UnhashableMeta):
1010 pass
1011
1012 assert_simple_property(
1013 st.from_type(UnhashableType), lambda x: isinstance(x, UnhashableType)
1014 )
1015
1016
1017 class _EmptyClass:
1018 def __init__(self, value=-1) -> None:
1019 pass
1020
1021
1022 @pytest.mark.parametrize(
1023 "typ,repr_",
1024 [
1025 (int, "integers()"),
1026 (list[str], "lists(text())"),
1027 (_List[str], "lists(text())"),
1028 ("not a type", "from_type('not a type')"),
1029 (random.Random, "randoms()"),
1030 (_EmptyClass, "from_type(tests.cover.test_lookup._EmptyClass)"),
1031 (
1032 st.SearchStrategy[str],
1033 "from_type(hypothesis.strategies.SearchStrategy[str])",
1034 ),
1035 ],
1036 )
1037 def test_repr_passthrough(typ, repr_):
1038 assert repr(st.from_type(typ)) == repr_
1039
1040
1041 class TreeForwardRefs(typing.NamedTuple):
1042 val: int
1043 l: typing.Optional["TreeForwardRefs"]
1044 r: typing.Optional["TreeForwardRefs"]
1045
1046
1047 @given(st.builds(TreeForwardRefs))
1048 def test_resolves_forward_references_outside_annotations(t):
1049 assert isinstance(t, TreeForwardRefs)
1050
1051
1052 def constructor(a: str = None): # noqa # deprecated implicit optional, for testing
1053 pass
1054
1055
1056 class WithOptionalInSignature:
1057 __signature__ = inspect.signature(constructor)
1058 __annotations__ = typing.get_type_hints(constructor)
1059
1060 def __init__(self, **kwargs):
1061 assert set(kwargs) == {"a"}
1062 self.a = kwargs["a"]
1063
1064
1065 def test_compat_get_type_hints_aware_of_None_default():
1066 # Regression test for https://github.com/HypothesisWorks/hypothesis/issues/2648
1067 strategy = st.builds(WithOptionalInSignature, a=...)
1068 find_any(strategy, lambda x: x.a is None)
1069 find_any(strategy, lambda x: x.a is not None)
1070
1071 if sys.version_info[:2] >= (3, 11):
1072 # https://docs.python.org/3.11/library/typing.html#typing.get_type_hints
1073 assert typing.get_type_hints(constructor)["a"] == str
1074 else:
1075 assert typing.get_type_hints(constructor)["a"] == typing.Optional[str]
1076 assert inspect.signature(constructor).parameters["a"].annotation == str
1077
1078
1079 _ValueType = typing.TypeVar("_ValueType")
1080
1081
1082 class Wrapper(typing.Generic[_ValueType]):
1083 _inner_value: _ValueType
1084
1085 def __init__(self, inner_value: _ValueType) -> None:
1086 self._inner_value = inner_value
1087
1088
1089 @given(st.builds(Wrapper))
1090 def test_issue_2603_regression(built):
1091 """It was impossible to build annotated classes with constructors."""
1092 assert isinstance(built, Wrapper)
1093
1094
1095 class AnnotatedConstructor(typing.Generic[_ValueType]):
1096 value: _ValueType # the same name we have in `__init__`
1097
1098 def __init__(self, value: int) -> None:
1099 """By this example we show, that ``int`` is more important than ``_ValueType``."""
1100 assert isinstance(value, int)
1101
1102
1103 @given(st.data())
1104 def test_constructor_is_more_important(data):
1105 """Constructor types should take precedence over all other annotations."""
1106 data.draw(st.builds(AnnotatedConstructor))
1107
1108
1109 def use_signature(self, value: str) -> None: ...
1110
1111
1112 class AnnotatedConstructorWithSignature(typing.Generic[_ValueType]):
1113 value: _ValueType # the same name we have in `__init__`
1114
1115 __signature__ = signature(use_signature)
1116
1117 def __init__(self, value: int) -> None:
1118 """By this example we show, that ``__signature__`` is the most important source."""
1119 assert isinstance(value, str)
1120
1121
1122 def selfless_signature(value: str) -> None: ...
1123
1124
1125 class AnnotatedConstructorWithSelflessSignature(AnnotatedConstructorWithSignature):
1126 __signature__ = signature(selfless_signature)
1127
1128
1129 def really_takes_str(value: int) -> None:
1130 """By this example we show, that ``__signature__`` is the most important source."""
1131 assert isinstance(value, str)
1132
1133
1134 really_takes_str.__signature__ = signature(selfless_signature)
1135
1136
1137 @pytest.mark.parametrize(
1138 "thing",
1139 [
1140 AnnotatedConstructorWithSignature,
1141 AnnotatedConstructorWithSelflessSignature,
1142 really_takes_str,
1143 ],
1144 )
1145 def test_signature_is_the_most_important_source(thing):
1146 """Signature types should take precedence over all other annotations."""
1147 check_can_generate_examples(st.builds(thing))
1148
1149
1150 class AnnotatedAndDefault:
1151 def __init__(self, foo: bool | None = None):
1152 self.foo = foo
1153
1154
1155 def test_from_type_can_be_default_or_annotation():
1156 find_any(st.from_type(AnnotatedAndDefault), lambda x: x.foo is None)
1157 find_any(st.from_type(AnnotatedAndDefault), lambda x: isinstance(x.foo, bool))
1158
1159
1160 @pytest.mark.parametrize("t", BUILTIN_TYPES, ids=lambda t: t.__name__)
1161 def test_resolves_builtin_types(t):
1162 with warnings.catch_warnings():
1163 warnings.simplefilter("ignore", SmallSearchSpaceWarning)
1164 assert_simple_property(st.from_type(t), lambda v: isinstance(v, t))
1165
1166
1167 @pytest.mark.parametrize("t", BUILTIN_TYPES, ids=lambda t: t.__name__)
1168 @given(data=st.data())
1169 @settings(max_examples=20)
1170 def test_resolves_forwardrefs_to_builtin_types(t, data):
1171 if t.__name__ == "object" and settings.get_current_profile_name() == "threading":
1172 # from_type(ForwardRef("object")) pulls from register_type_strategy,
1173 # and depending on threading I've seen `st.builds(Bar, st.integers())`
1174 # (from this file) be registered in one iteration and not the next,
1175 # causing Hypothesis to raise FlakyStrategyDefinition.
1176 #
1177 # (I would also expect st.from_type(object) to have this problem, but
1178 # I haven't seen that error under threading, yet).
1179 pytest.skip("ForwardRef('object') is inherently flaky under concurrency")
1180 s = st.from_type(typing.ForwardRef(t.__name__))
1181 v = data.draw(s)
1182 assert isinstance(v, t)
1183
1184
1185 @pytest.mark.parametrize("t", BUILTIN_TYPES, ids=lambda t: t.__name__)
1186 def test_resolves_type_of_builtin_types(t):
1187 assert_simple_property(st.from_type(type[t.__name__]), lambda v: v is t)
1188
1189
1190 @given(
1191 st.from_type(type[typing.Union["str", "int"]])
1192 | st.from_type(_Type[typing.Union["str", "int"]])
1193 )
1194 def test_resolves_type_of_union_of_forwardrefs_to_builtins(x):
1195 assert x in (str, int)
1196
1197
1198 @pytest.mark.parametrize(
1199 "type_",
1200 [
1201 # Old-style `List` because `list[int]() == list()`, so no need for the hint.
1202 getattr(typing, "List", None)[int],
1203 pytest.param(
1204 typing.Optional[int],
1205 marks=pytest.mark.skipif(
1206 sys.version_info >= (3, 14), reason="different error on 3.14+"
1207 ),
1208 ),
1209 ],
1210 )
1211 def test_builds_suggests_from_type(type_):
1212 with pytest.raises(
1213 InvalidArgument, match=re.escape(f"try using from_type({type_!r})")
1214 ):
1215 check_can_generate_examples(st.builds(type_))
1216
1217 try:
1218 check_can_generate_examples(st.builds(type_, st.just("has an argument")))
1219 raise AssertionError("Expected strategy to raise an error")
1220 except TypeError as err:
1221 assert not isinstance(err, InvalidArgument)
1222
1223
1224 @pytest.mark.skipif(sys.version_info < (3, 14), reason="different error on 3.14+")
1225 @pytest.mark.parametrize("type_", [typing.Optional[int]])
1226 def test_builds_suggests_from_type_on_construction(type_):
1227 with pytest.raises(
1228 InvalidArgument, match=re.escape(f"Try using from_type({type_!r})")
1229 ):
1230 check_can_generate_examples(st.builds(type_))
1231
1232 with pytest.raises(
1233 InvalidArgument, match=re.escape(f"Try using from_type({type_!r})")
1234 ):
1235 check_can_generate_examples(st.builds(type_, st.just("has an argument")))
1236
1237
1238 def test_builds_mentions_no_type_check():
1239 @typing.no_type_check
1240 def f(x: int):
1241 pass
1242
1243 msg = "@no_type_check decorator prevented Hypothesis from inferring a strategy"
1244 with pytest.raises(TypeError, match=msg):
1245 check_can_generate_examples(st.builds(f))
1246
1247
1248 class TupleSubtype(tuple):
1249 pass
1250
1251
1252 def test_tuple_subclasses_not_generic_sequences():
1253 # see https://github.com/HypothesisWorks/hypothesis/issues/3767.
1254 with temp_registered(TupleSubtype, st.builds(TupleSubtype)):
1255 s = st.from_type(typing.Sequence[int])
1256 assert_no_examples(s, lambda x: isinstance(x, tuple))
1257
1258
1259 def test_custom_strategy_function_resolves_types_conditionally():
1260 sentinel = object()
1261
1262 class A:
1263 pass
1264
1265 class B(A):
1266 pass
1267
1268 class C(A):
1269 pass
1270
1271 def resolve_custom_strategy_for_b(thing):
1272 if thing == B:
1273 return st.just(sentinel)
1274 return NotImplemented
1275
1276 with contextlib.ExitStack() as stack:
1277 stack.enter_context(temp_registered(B, resolve_custom_strategy_for_b))
1278 stack.enter_context(temp_registered(C, st.builds(C)))
1279
1280 # C's strategy can be used for A, but B's cannot because its function
1281 # only returns a strategy for requests for exactly B.
1282 assert_all_examples(st.from_type(A), lambda example: type(example) == C)
1283 assert_all_examples(st.from_type(B), lambda example: example is sentinel)
1284 assert_all_examples(st.from_type(C), lambda example: type(example) == C)
1285
1286
1287 class CustomInteger(int):
1288 def __init__(self, value: int, /) -> None:
1289 if not isinstance(value, int):
1290 raise TypeError
1291
1292
1293 @given(...)
1294 def test_from_type_resolves_required_posonly_args(n: CustomInteger):
1295 # st.builds() does not infer for positional arguments, but st.from_type()
1296 # does. See e.g. https://stackoverflow.com/q/79199376/ for motivation.
1297 assert isinstance(n, CustomInteger)
1298
1299
1300 class MyProtocol(typing.Protocol):
1301 pass
1302
1303
1304 def test_issue_4194_regression():
1305 # this was an edge case where we were calling issubclass on something
1306 # that was not a type, which errored. I don't have a more principled test
1307 # case or name for this.
1308 inner = typing.Union[typing.Sequence["A"], MyProtocol]
1309 A = typing.Union[typing.Sequence[inner], MyProtocol]
1310
1311 with (
1312 temp_registered(MyProtocol, st.just(b"")),
1313 temp_registered(typing.ForwardRef("A"), st.integers()),
1314 ):
1315 find_any(st.from_type(A))