Debian Codegraph @

hypothesis-python/tests/cover/test_custom_reprs.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 hashlib
12 import re
13
14 import pytest
15
16 from hypothesis import Phase, given, settings, strategies as st
17 from hypothesis.strategies._internal.lazy import unwrap_strategies
18
19
20 def _get_output(test_fn):
21 with pytest.raises(AssertionError) as err:
22 test_fn()
23 return "\n".join(err.value.__notes__).strip()
24
25
26 def test_includes_non_default_args_in_repr():
27 assert repr(st.integers()) == "integers()"
28 assert repr(st.integers(min_value=1)) == "integers(min_value=1)"
29
30
31 def test_sampled_repr_leaves_range_as_range():
32 huge = 10**100
33 assert repr(st.sampled_from(range(huge))) == f"sampled_from(range(0, {huge}))"
34
35
36 def hi(there, stuff):
37 return there
38
39
40 def test_supports_positional_and_keyword_args_in_builds():
41 assert (
42 repr(st.builds(hi, st.integers(), there=st.booleans()))
43 == "builds(hi, integers(), there=booleans())"
44 )
45
46
47 def test_preserves_sequence_type_of_argument():
48 assert repr(st.sampled_from([0, 1])) == "sampled_from([0, 1])"
49 assert repr(st.sampled_from((0, 1))) == "sampled_from((0, 1))"
50
51
52 class IHaveABadRepr:
53 def __repr__(self):
54 raise ValueError("Oh no!")
55
56
57 def test_errors_are_deferred_until_repr_is_calculated():
58 s = (
59 st.builds(
60 lambda x, y: 1,
61 st.just(IHaveABadRepr()),
62 y=st.one_of(st.sampled_from((IHaveABadRepr(),)), st.just(IHaveABadRepr())),
63 )
64 .map(lambda t: t)
65 .filter(lambda t: True)
66 .flatmap(lambda t: st.just(IHaveABadRepr()))
67 )
68
69 with pytest.raises(ValueError):
70 repr(s)
71
72
73 @given(st.iterables(st.integers()))
74 def test_iterables_repr_is_useful(it):
75 # fairly hard-coded but useful; also ensures _values are inexhaustible
76 assert repr(it) == f"iter({it._values!r})"
77
78
79 class Foo:
80 def __init__(self, x: int) -> None:
81 self.x = x
82
83
84 class Bar(Foo):
85 pass
86
87
88 def test_reprs_as_created(snapshot):
89 @given(foo=st.builds(Foo), bar=st.from_type(Bar), baz=st.none().map(Foo))
90 @settings(print_blob=False, max_examples=10_000, derandomize=True)
91 def inner(foo, bar, baz):
92 assert baz.x is None
93 assert foo.x <= 0 or bar.x >= 0
94
95 assert _get_output(inner) == snapshot
96
97
98 def test_reprs_as_created_interactive(snapshot):
99 @given(st.data())
100 @settings(print_blob=False, max_examples=10_000)
101 def inner(data):
102 bar = data.draw(st.builds(Bar, st.just(10)))
103 assert not bar.x
104
105 assert _get_output(inner) == snapshot
106
107
108 CONSTANT_FOO = Foo(None)
109
110
111 def some_foo(*_):
112 return CONSTANT_FOO
113
114
115 def test_as_created_reprs_fallback_for_distinct_calls_same_obj():
116 # If we have *different* calls which return the *same* object, we skip our
117 # nice repr because it's unclear which one we should use.
118 @given(st.builds(some_foo), st.builds(some_foo, st.none()))
119 @settings(print_blob=False, max_examples=10_000)
120 def inner(a, b):
121 assert a is not b
122
123 with pytest.raises(AssertionError) as err:
124 inner()
125 expected_re = r"""
126 Falsifying example: inner\(
127 a=<.*Foo object at 0x[0-9A-Fa-f]+>,
128 b=<.*Foo object at 0x[0-9A-Fa-f]+>,
129 \)
130 """.strip()
131 got = "\n".join(err.value.__notes__).strip()
132 assert re.fullmatch(expected_re, got), got
133
134
135 def test_reprs_as_created_consistent_calls_despite_indentation(snapshot):
136 aas = "a" * 60
137 strat = st.builds(some_foo, st.just(aas))
138
139 # If we have multiple calls which return the same object, we can print their
140 # nice repr even if varying indentation means that they'll come out different!
141 @given(strat, st.builds(Bar, strat))
142 @settings(print_blob=False, max_examples=10_000)
143 def inner(a, b):
144 assert a == b
145
146 assert _get_output(inner) == snapshot
147
148
149 @pytest.mark.parametrize(
150 "strategy, expected_repr",
151 [
152 (st.characters(), "characters()"),
153 (st.characters(codec="utf-8"), "characters(codec='utf-8')"),
154 (st.characters(min_codepoint=65), "characters(min_codepoint=65)"),
155 (st.characters(max_codepoint=127), "characters(max_codepoint=127)"),
156 (st.characters(categories=["Lu", "Ll"]), "characters(categories=('Lu', 'Ll'))"),
157 (
158 st.characters(exclude_characters="abc"),
159 "characters(exclude_characters='abc')",
160 ),
161 (
162 st.characters(min_codepoint=65, max_codepoint=90),
163 "characters(min_codepoint=65, max_codepoint=90)",
164 ),
165 (
166 st.characters(codec="ascii", min_codepoint=32, max_codepoint=126),
167 "characters(min_codepoint=32, max_codepoint=126)",
168 ),
169 (
170 st.characters(categories=["Lu"], exclude_characters="AZ"),
171 "characters(categories=('Lu',), exclude_characters='AZ')",
172 ),
173 ],
174 )
175 def test_characters_repr(strategy, expected_repr):
176 assert repr(unwrap_strategies(strategy)) == expected_repr
177
178
179 def test_map_to_str_prints_as_repr(snapshot):
180 @given(s=st.integers().map(str))
181 @settings(phases=[Phase.generate, Phase.shrink], print_blob=False)
182 def inner(s):
183 raise AssertionError
184
185 assert _get_output(inner) == snapshot
186
187
188 def test_map_to_bytes_prints_as_repr(snapshot):
189 @given(b=st.binary().map(lambda b: hashlib.sha256(b).digest()))
190 @settings(phases=[Phase.generate, Phase.shrink], print_blob=False)
191 def inner(b):
192 raise AssertionError
193
194 assert _get_output(inner) == snapshot
195
196
197 def test_invalid_call_syntax_falls_back_to_repr(snapshot):
198 # When the call-style repr (e.g. "a b()") is invalid Python syntax but
199 # repr(obj) is valid, we should fall back to using repr(obj).
200 _BadName = type(
201 "a b",
202 (),
203 {"__repr__": lambda self: "'hello world'"},
204 )
205
206 @given(x=st.builds(_BadName))
207 @settings(phases=[Phase.generate, Phase.shrink], print_blob=False)
208 def inner(x):
209 raise AssertionError
210
211 assert _get_output(inner) == snapshot