Debian Codegraph @

hypothesis-python/tests/test_annotated_types.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 re
12 import sys
13 from typing import Annotated
14
15 import pytest
16
17 from hypothesis import given, strategies as st
18 from hypothesis.errors import HypothesisWarning, ResolutionFailed
19 from hypothesis.strategies._internal.lazy import unwrap_strategies
20 from hypothesis.strategies._internal.strategies import FilteredStrategy
21 from hypothesis.strategies._internal.types import _get_constraints
22
23 from tests.common.debug import assert_simple_property, check_can_generate_examples
24
25 try:
26 import annotated_types as at
27 except ImportError:
28 pytest.skip(allow_module_level=True)
29
30
31 def test_strategy_priority_over_constraints():
32 expected_strategy = st.SearchStrategy()
33
34 strategy = st.from_type(Annotated[int, expected_strategy, at.Gt(1)])
35 assert strategy is expected_strategy
36
37
38 def test_invalid_annotated_type():
39 msg = re.escape("Did you mean `Annotated[str | int, 'dummy']`?")
40 with pytest.raises(ResolutionFailed, match=f".*{msg}$"):
41 check_can_generate_examples(
42 st.from_type(Annotated[str, "dummy", Annotated[int, "dummy"]])
43 )
44
45
46 @pytest.mark.parametrize(
47 "unsupported_constraints,message",
48 [
49 ((at.Timezone(None),), "Ignoring unsupported Timezone(tz=None)"),
50 ((at.MultipleOf(1),), "Ignoring unsupported MultipleOf(multiple_of=1)"),
51 (
52 (at.Timezone(None), at.MultipleOf(1)),
53 "Ignoring unsupported Timezone(tz=None), MultipleOf(multiple_of=1)",
54 ),
55 ],
56 )
57 def test_unsupported_constraints(unsupported_constraints, message):
58 if sys.version_info >= (3, 11):
59 # This is the preferred format, but also a SyntaxError on Python <= 3.10
60 t = eval("Annotated[int, *unsupported_constraints]", globals(), locals())
61 else:
62 t = Annotated.__class_getitem__((int, *unsupported_constraints))
63 with pytest.warns(HypothesisWarning, match=re.escape(message)):
64 check_can_generate_examples(st.from_type(t))
65
66
67 @pytest.mark.parametrize(
68 "annotated_type,expected_strategy_repr",
69 [
70 (Annotated[int, at.Gt(1)], "integers(min_value=2)"),
71 (Annotated[int, at.Ge(1)], "integers(min_value=1)"),
72 (Annotated[int, at.Lt(1)], "integers(max_value=0)"),
73 (Annotated[int, at.Le(1)], "integers(max_value=1)"),
74 (Annotated[int, at.Interval(ge=1, le=3)], "integers(1, 3)"),
75 (Annotated[int, at.Interval(ge=1), at.Ge(2)], "integers(min_value=2)"),
76 ],
77 )
78 def test_annotated_type_int(annotated_type, expected_strategy_repr):
79 strategy = unwrap_strategies(st.from_type(annotated_type))
80 assert repr(strategy) == expected_strategy_repr
81
82
83 def test_predicate_constraint():
84 def func(_):
85 return True
86
87 strategy = unwrap_strategies(st.from_type(Annotated[int, at.Predicate(func)]))
88 assert isinstance(strategy, FilteredStrategy)
89 assert strategy.flat_conditions == (func,)
90
91
92 class MyCollection:
93 def __init__(self, values: list[int]) -> None:
94 self._values = values
95
96 def __len__(self) -> int:
97 return len(self._values)
98
99
100 @pytest.mark.parametrize("lo", [0, 1])
101 @pytest.mark.parametrize("hi", [None, 10])
102 @pytest.mark.parametrize("type_", [list[int], set[int], MyCollection])
103 @given(data=st.data())
104 def test_collection_sizes(data, lo, hi, type_):
105 print(f"{type_=} {lo=} {hi=}")
106 assert lo < (hi or 11)
107 t = Annotated[type_, at.Len(min_length=lo, max_length=hi)]
108 s = st.from_type(t)
109 value = data.draw(s)
110 assert lo is None or lo <= len(value)
111 assert hi is None or len(value) <= hi
112
113
114 @given(st.data())
115 def test_collection_size_from_slice(data):
116 t = Annotated[MyCollection, "we just ignore this", slice(1, 10)]
117 value = data.draw(st.from_type(t))
118 assert 1 <= len(value) <= 10
119
120
121 def test_unhashable_annotated_metadata():
122 t = Annotated[int, {"key": "value"}]
123 assert_simple_property(st.from_type(t), lambda x: isinstance(x, int))
124
125
126 class GroupedStuff:
127 __is_annotated_types_grouped_metadata__ = True
128
129 def __init__(self, *args) -> None:
130 self._args = args
131
132 def __iter__(self):
133 return iter(self._args)
134
135 def __repr__(self) -> str:
136 return f"GroupedStuff({', '.join(map(repr, self._args))})"
137
138
139 def test_flattens_grouped_metadata():
140 grp = GroupedStuff(GroupedStuff(GroupedStuff(at.Len(min_length=1, max_length=5))))
141 constraints = list(_get_constraints(grp))
142 assert constraints == [at.MinLen(1), at.MaxLen(5)]
143
144
145 try:
146 # we can drop this ugly code when Python 3.10 reaches EOL
147 from typing import NotRequired, TypedDict
148 except ImportError:
149 pass
150 else:
151
152 class TypedDictWithAnnotations(TypedDict):
153 x: Annotated[int, at.Ge(0)]
154 y: Annotated[NotRequired[int], at.Ge(0)]
155 z: NotRequired[Annotated[int, at.Ge(0)]]
156
157 @given(st.from_type(TypedDictWithAnnotations))
158 def test_typeddict_with_annotated_constraints(value):
159 assert value["x"] >= 0
160 assert value.get("y", 0) >= 0
161 assert value.get("z", 0) >= 0