Debian Codegraph @

hypothesis-python/tests/nocover/test_recursive.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 import threading
13
14 import pytest
15
16 from hypothesis import HealthCheck, given, settings, strategies as st
17
18 from tests.common.debug import find_any, minimal
19 from tests.common.utils import Why, flaky, xfail_if_gil_disabled, xfail_on_crosshair
20
21
22 def test_can_generate_with_large_branching():
23 def flatten(x):
24 if isinstance(x, list):
25 return sum(map(flatten, x), [])
26 else:
27 return [x]
28
29 size = 20
30
31 xs = minimal(
32 st.recursive(
33 st.integers(),
34 lambda x: st.lists(x, min_size=size // 2),
35 max_leaves=size * 2,
36 ),
37 lambda x: isinstance(x, list) and len(flatten(x)) >= size,
38 )
39 assert flatten(xs) == [0] * size
40
41
42 def test_can_generate_some_depth_with_large_branching():
43 def depth(x):
44 if x and isinstance(x, list):
45 return 1 + max(map(depth, x))
46 else:
47 return 1
48
49 xs = minimal(st.recursive(st.integers(), st.lists), lambda x: depth(x) > 1)
50 assert xs in ([0], [[]])
51
52
53 @pytest.mark.skipif(
54 settings.get_current_profile_name() == "crosshair", reason="takes 2 hours"
55 )
56 def test_can_find_quite_broad_lists():
57 def breadth(x):
58 if isinstance(x, list):
59 return sum(map(breadth, x))
60 else:
61 return 1
62
63 target = 10
64
65 broad = minimal(
66 st.recursive(st.booleans(), lambda x: st.lists(x, max_size=target // 2)),
67 lambda x: breadth(x) >= target,
68 settings=settings(max_examples=10000),
69 )
70 assert breadth(broad) == target
71
72
73 def test_drawing_many_near_boundary():
74 size = 4
75 elems = st.recursive(
76 st.booleans(),
77 lambda x: st.lists(x, min_size=2 * (size - 1), max_size=2 * size).map(tuple),
78 max_leaves=2 * size - 1,
79 )
80 ls = minimal(st.lists(elems), lambda x: len(set(x)) >= size)
81 assert len(ls) == size
82
83
84 @xfail_on_crosshair(Why.undiscovered)
85 def test_can_use_recursive_data_in_sets():
86 nested_sets = st.recursive(st.booleans(), st.frozensets, max_leaves=3)
87 find_any(nested_sets, settings=settings(deadline=None))
88
89 def flatten(x):
90 if isinstance(x, bool):
91 return frozenset((x,))
92 else:
93 result = frozenset()
94 for t in x:
95 result |= flatten(t)
96 if len(result) == 2:
97 break
98 return result
99
100 x = minimal(nested_sets, lambda x: len(flatten(x)) == 2, settings(deadline=None))
101 assert x in (
102 frozenset((False, True)),
103 frozenset((False, frozenset((True,)))),
104 frozenset((frozenset((False, True)),)),
105 )
106
107
108 @flaky(max_runs=2, min_passes=1)
109 def test_can_form_sets_of_recursive_data():
110 size = 3
111
112 trees = st.sets(
113 st.recursive(
114 st.booleans(),
115 lambda x: st.lists(x, min_size=size).map(tuple),
116 max_leaves=20,
117 )
118 )
119 xs = minimal(trees, lambda x: len(x) >= size)
120 assert len(xs) == size
121
122
123 @pytest.mark.skipif(
124 settings.get_current_profile_name() == "crosshair", reason="not threadsafe"
125 )
126 def test_drawing_from_recursive_strategy_is_thread_safe():
127 shared_strategy = st.recursive(
128 st.integers(), lambda s: st.lists(s, max_size=2), max_leaves=20
129 )
130 errors = []
131
132 @settings(
133 database=None, deadline=None, suppress_health_check=[HealthCheck.too_slow]
134 )
135 @given(data=st.data())
136 def test(data):
137 try:
138 data.draw(shared_strategy)
139 except Exception as exc:
140 errors.append(exc)
141
142 original_recursionlimit = sys.getrecursionlimit()
143 threads = []
144 for _ in range(4):
145 threads.append(threading.Thread(target=test))
146
147 for thread in threads:
148 thread.start()
149 for thread in threads:
150 thread.join()
151
152 assert sys.getrecursionlimit() == original_recursionlimit
153 assert not errors
154
155
156 SELF_REF = st.recursive(
157 st.deferred(lambda: st.booleans() | SELF_REF),
158 lambda s: st.lists(s, min_size=1),
159 )
160
161
162 @settings(
163 suppress_health_check=[HealthCheck.too_slow, HealthCheck.filter_too_much],
164 max_examples=5,
165 )
166 @given(SELF_REF)
167 def test_self_ref_regression(_):
168 # See https://github.com/HypothesisWorks/hypothesis/issues/2794
169 pass
170
171
172 @pytest.mark.skipif(sys.version_info >= (3, 14), reason="gc changes")
173 @xfail_if_gil_disabled
174 @flaky(min_passes=1, max_runs=2)
175 def test_gc_hooks_do_not_cause_unraisable_recursionerror(testdir):
176 # We were concerned in #3979 that we might see bad results from a RecursionError
177 # inside the GC hook, if the stack was already deep and someone (e.g. Pytest)
178 # had installed a sys.unraisablehook which raises that later.
179
180 # This test is potentially flaky, because the stack usage of a function is not
181 # constant. Regardless, if the test passes just once that's sufficient proof that
182 # it's not the GC (or accounting of it) that is at fault. Note, I haven't actually
183 # seen it fail/flake, but I believe it could happen in principle.
184 #
185 # What we *have* seen on CI with xdist is flaky segmentation faults. Hence, the
186 # test is executed in a subprocess.
187 script = """
188 import gc
189 import pytest
190
191 from hypothesis import given, strategies as st
192
193 # The number of cycles sufficient to reliably trigger GC, experimentally found
194 # to be a few hundred on CPython. Multiply by 10 for safety margin.
195 NUM_CYCLES = 5_000
196
197 def probe_depth():
198 try:
199 return probe_depth() + 1
200 except RecursionError:
201 return 0
202
203 def at_depth(depth, fn):
204 if depth <= 1:
205 return fn()
206 else:
207 # Recurse towards requested depth
208 return at_depth(depth - 1, fn)
209
210 def gen_cycles():
211 for _ in range(NUM_CYCLES):
212 a = [None]
213 b = [a]
214 a[0] = b
215
216 def gen_cycles_at_depth(depth, *, gc_disable):
217 try:
218 if gc_disable:
219 gc.disable()
220 at_depth(depth, gen_cycles)
221 dead_objects = gc.collect()
222 if dead_objects is not None: # is None on PyPy
223 if gc_disable:
224 assert dead_objects >= 2 * NUM_CYCLES
225 else:
226 # collection was triggered
227 assert dead_objects < 2 * NUM_CYCLES
228 finally:
229 gc.enable()
230
231 # Warmup to de-flake PyPy (the first run has much lower effective limits)
232 probe_depth()
233
234 @given(st.booleans())
235 def test_gc_hooks_recursive(_):
236 max_depth = probe_depth()
237
238 # Lower the limit to where we can successfully generate cycles
239 # when no gc is performed
240 while True:
241 try:
242 gen_cycles_at_depth(max_depth, gc_disable=True)
243 except RecursionError:
244 max_depth -= 1
245 else:
246 break
247 # Note that PyPy is a bit weird, in that it raises RecursionError at
248 # (maxdepth - n) for small positive n, but not at exactly (maxdepth).
249 # In general, it is really finicky to get the details right in this
250 # test, so be careful.
251
252 # Now check that the limit is unchanged with gc enabled, and also that
253 # leaving a few frames for the callbacks does not fail.
254 if hasattr(gc, "callbacks"): # see comment above
255 for n in range(1, 4):
256 gen_cycles_at_depth(max_depth - n, gc_disable=False)
257 gen_cycles_at_depth(max_depth, gc_disable=False)
258 with pytest.raises(RecursionError):
259 gen_cycles_at_depth(max_depth + 1, gc_disable=False)
260 """
261 testdir.makepyfile(script)
262 testdir.runpytest_subprocess().assert_outcomes(passed=1)