Debian Codegraph @

hypothesis-python/tests/cover/test_flakiness.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 sys
12
13 import pytest
14
15 from hypothesis import HealthCheck, Verbosity, assume, example, given, reject, settings
16 from hypothesis.core import StateForActualGivenExecution
17 from hypothesis.errors import Flaky, FlakyFailure, Unsatisfiable, UnsatisfiedAssumption
18 from hypothesis.internal.compat import ExceptionGroup
19 from hypothesis.internal.conjecture.engine import MIN_TEST_CALLS
20 from hypothesis.internal.scrutineer import Tracer
21 from hypothesis.strategies import booleans, composite, integers, lists, random_module
22
23 from tests.common.utils import Why, no_shrink, skipif_threading, xfail_on_crosshair
24
25
26 class Nope(Exception):
27 pass
28
29
30 def test_fails_only_once_is_flaky():
31 first_call = True
32
33 @given(integers())
34 def rude(x):
35 nonlocal first_call
36 if first_call:
37 first_call = False
38 raise Nope
39
40 with pytest.raises(FlakyFailure, match="Falsified on the first call but") as e:
41 rude()
42 exceptions = e.value.exceptions
43 assert len(exceptions) == 1
44 assert isinstance(exceptions[0], Nope)
45
46
47 def test_fails_differently_is_flaky():
48 call_count = 0
49
50 class DifferentNope(Exception):
51 pass
52
53 @given(integers())
54 @settings(database=None)
55 def rude(x):
56 nonlocal call_count
57 if x == 0:
58 call_count += 1
59 if call_count > 1:
60 raise Nope
61 else:
62 raise DifferentNope
63
64 with pytest.raises(FlakyFailure, match="Inconsistent results from replaying") as e:
65 rude()
66 exceptions = e.value.exceptions
67 assert len(exceptions) == 2
68 assert set(map(type, exceptions)) == {Nope, DifferentNope}
69
70
71 @skipif_threading # executing into global scope
72 @pytest.mark.skipif(sys.version_info < (3, 11), reason="except* syntax")
73 def test_exceptiongroup_wrapped_naked_exception_is_flaky():
74
75 # Defer parsing until runtime, as "except*" is syntax error pre 3.11
76 rude_def = """
77 first_call = True
78 def rude_fn(x):
79 global first_call
80 if first_call:
81 first_call = False
82 try:
83 raise Nope
84 except* Nope:
85 raise
86 """
87 exec(rude_def, globals())
88 rude = given(integers())(rude_fn) # noqa: F821 # defined by exec()
89
90 with pytest.raises(FlakyFailure, match="Falsified on the first call but") as e:
91 rude()
92 exceptions = e.value.exceptions
93 assert list(map(type, exceptions)) == [ExceptionGroup]
94 assert list(map(type, exceptions[0].exceptions)) == [Nope]
95
96
97 def test_gives_flaky_error_if_assumption_is_flaky():
98 seen = set()
99
100 @given(integers())
101 @settings(verbosity=Verbosity.quiet, database=None)
102 def oops(s):
103 assume(s not in seen)
104 seen.add(s)
105 raise AssertionError
106
107 with pytest.raises(FlakyFailure, match="Inconsistent results from replaying") as e:
108 oops()
109 exceptions = e.value.exceptions
110 assert len(exceptions) == 2
111 assert isinstance(exceptions[0], AssertionError)
112 assert isinstance(exceptions[1], UnsatisfiedAssumption)
113
114
115 def test_flaky_with_context_when_fails_only_under_tracing(monkeypatch):
116 # make anything fail under tracing
117 monkeypatch.setattr(Tracer, "can_trace", staticmethod(lambda: True))
118 monkeypatch.setattr(Tracer, "__enter__", lambda *_: 1 / 0)
119 # ensure tracing is always entered inside _execute_once_for_engine
120 monkeypatch.setattr(StateForActualGivenExecution, "_should_trace", lambda _: True)
121
122 @given(integers())
123 def test(x):
124 pass
125
126 with pytest.raises(
127 FlakyFailure, match="failed on the first run but now succeeds"
128 ) as e:
129 test()
130 exceptions = e.value.exceptions
131 assert len(exceptions) == 1
132 assert isinstance(exceptions[0], ZeroDivisionError)
133
134
135 @xfail_on_crosshair(Why.symbolic_outside_context)
136 def test_does_not_attempt_to_shrink_flaky_errors():
137 values = []
138
139 @settings(database=None)
140 @given(integers())
141 def test(x):
142 values.append(x)
143 assert len(values) != 1
144
145 with pytest.raises(FlakyFailure):
146 test()
147 # We try a total of ten calls in the generation phase, each usually a
148 # unique value, looking briefly (and unsuccessfully) for another bug.
149 assert 1 < len(set(values)) <= MIN_TEST_CALLS
150 # We don't try any new values while shrinking, just execute the test
151 # twice more (to check for flakiness and to raise the bug to the user).
152 assert set(values) == set(values[:-2])
153
154
155 class SatisfyMe(Exception):
156 pass
157
158
159 @composite
160 def single_bool_lists(draw):
161 n = draw(integers(0, 20))
162 result = [False] * (n + 1)
163 result[n] = True
164 return result
165
166
167 @xfail_on_crosshair(Why.nested_given)
168 @example([True, False, False, False], [3], None)
169 @example([False, True, False, False], [3], None)
170 @example([False, False, True, False], [3], None)
171 @example([False, False, False, True], [3], None)
172 @settings(
173 deadline=None, suppress_health_check=[HealthCheck.nested_given], max_examples=10
174 )
175 @given(lists(booleans()) | single_bool_lists(), lists(integers(1, 3)), random_module())
176 def test_failure_sequence_inducing(building, testing, rnd):
177 buildit = iter(building)
178 testit = iter(testing)
179
180 def build(x):
181 try:
182 assume(not next(buildit))
183 except StopIteration:
184 pass
185 return x
186
187 @given(integers().map(build))
188 @settings(
189 verbosity=Verbosity.quiet,
190 database=None,
191 suppress_health_check=list(HealthCheck),
192 phases=no_shrink,
193 max_examples=10,
194 )
195 def test(x):
196 try:
197 i = next(testit)
198 except StopIteration:
199 return
200 if i == 1:
201 return
202 elif i == 2:
203 reject()
204 else:
205 raise Nope
206
207 try:
208 test()
209 except (Nope, Flaky, Unsatisfiable):
210 pass
211 except UnsatisfiedAssumption:
212 raise SatisfyMe from None