Debian Codegraph @

hypothesis-python/tests/nocover/test_threading.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 time
13 from threading import Barrier, Thread
14
15 import pytest
16
17 from hypothesis import given, settings, strategies as st
18 from hypothesis.errors import DeadlineExceeded, InvalidArgument
19 from hypothesis.internal.conjecture.junkdrawer import ensure_free_stackframes
20 from hypothesis.stateful import RuleBasedStateMachine, invariant, rule
21 from hypothesis.strategies import SearchStrategy
22
23 from tests.common.debug import check_can_generate_examples
24 from tests.common.utils import run_concurrently
25
26 pytestmark = pytest.mark.skipif(
27 settings.get_current_profile_name() == "crosshair",
28 reason="crosshair is not thread safe",
29 )
30
31
32 def test_can_run_given_in_thread():
33 has_run_successfully = False
34
35 @given(st.integers())
36 def test(n):
37 nonlocal has_run_successfully
38 has_run_successfully = True
39
40 t = Thread(target=test)
41 t.start()
42 t.join()
43 assert has_run_successfully
44
45
46 def test_run_stateful_test_concurrently():
47 class MyStateMachine(RuleBasedStateMachine):
48 def __init__(self):
49 super().__init__()
50
51 @rule(n=st.integers())
52 def my_rule(self, n):
53 pass
54
55 @invariant()
56 def my_invariant(self):
57 pass
58
59 TestMyStateful = MyStateMachine.TestCase().runTest
60 run_concurrently(TestMyStateful, n=2)
61
62
63 def do_work(*, multiplier=1):
64 # arbitrary moderately-expensive work
65 for x in range(500 * multiplier):
66 _y = x**x
67
68
69 def test_run_different_tests_in_threads():
70 @given(st.integers())
71 def test1(n):
72 do_work()
73
74 @given(st.integers())
75 def test2(n):
76 do_work()
77
78 thread1 = Thread(target=test1)
79 thread2 = Thread(target=test2)
80
81 thread1.start()
82 thread2.start()
83 thread1.join()
84 thread2.join()
85
86
87 def test_run_given_concurrently():
88 @given(st.data(), st.integers(-5, 5).map(lambda x: 10**x))
89 def test(data, magnitude):
90 assert magnitude != 0
91 data.draw(st.complex_numbers(max_magnitude=magnitude))
92
93 run_concurrently(test, n=2)
94
95
96 def test_stackframes_restores_original_recursion_limit():
97 original_recursionlimit = sys.getrecursionlimit()
98
99 def test():
100 with ensure_free_stackframes():
101 do_work()
102
103 # also mix in a hypothesis test; why not.
104 @given(st.integers())
105 @settings(max_examples=10)
106 def test(n):
107 pass
108
109 test()
110
111 threads = []
112 for _ in range(4):
113 threads.append(Thread(target=test))
114 for thread in threads:
115 thread.start()
116 for thread in threads:
117 thread.join(timeout=10)
118
119 assert sys.getrecursionlimit() == original_recursionlimit
120
121
122 @pytest.mark.parametrize(
123 "strategy",
124 [
125 st.recursive(st.none(), st.lists, max_leaves=-1),
126 st.recursive(st.none(), st.lists, max_leaves=0),
127 st.recursive(st.none(), st.lists, max_leaves=1.0),
128 ],
129 )
130 def test_handles_invalid_args_cleanly(strategy):
131 # we previously had a race in SearchStrategy.validate, where one thread would
132 # set `validate_called = True` (which it has to do first for recursive
133 # strategies), then another thread would try to generate before the validation
134 # finished and errored, and would get into weird technically-valid states
135 # like interpreting 1.0 as 1. I saw FlakyStrategyDefinition here because the
136 # validating + errored thread drew zero choices, but the other thread drew
137 # 1 choice, for the same shared strategy.
138
139 def check():
140 with pytest.raises(InvalidArgument):
141 check_can_generate_examples(strategy)
142
143 run_concurrently(check, n=4)
144
145
146 def test_single_thread_can_raise_deadline_exceeded():
147 # a slow test running inside a thread, but not concurrently, should still
148 # be able to raise DeadlineExceeded.
149 @given(st.integers())
150 @settings(max_examples=5)
151 def slow_test(n):
152 do_work()
153 time.sleep(0.4)
154
155 def target():
156 with pytest.raises(DeadlineExceeded):
157 slow_test()
158
159 thread = Thread(target=target)
160 thread.start()
161 thread.join(timeout=10)
162
163
164 def test_deadline_exceeded_not_raised_under_concurrent_threads():
165 # it's still possible for multithreaded calls to a slow function to raise
166 # DeadlineExceeded, if the first thread completes its entire test before
167 # any other thread starts. For this test, prevent this scenario with a barrier,
168 # forcing the threads to run in parallel.
169 n_threads = 8
170 barrier = Barrier(n_threads)
171
172 @given(st.integers())
173 @settings(max_examples=5)
174 def slow_test(n):
175 do_work()
176 time.sleep(0.4)
177 barrier.wait()
178
179 run_concurrently(slow_test, n=n_threads)
180
181
182 def test_deadline_exceeded_can_be_raised_after_threads():
183 # if we had concurrent threads before, but they've finished now, we should
184 # still be able to raise DeadlineExceeded normally. Importantly, we test this
185 # for the same test as was running before, since concurrent thread use is
186 # tracked per-@given.
187
188 @given(st.integers())
189 @settings(max_examples=5)
190 def slow_test(n):
191 do_work()
192 if should_sleep:
193 time.sleep(0.4)
194
195 should_sleep = False
196 run_concurrently(slow_test, n=8)
197
198 should_sleep = True
199 with pytest.raises(DeadlineExceeded):
200 slow_test()
201
202
203 def test_one_of_branches_lock():
204 class SlowBranchesStrategy(SearchStrategy):
205 @property
206 def branches(self):
207 # multiplier=2 reproduces more consistently than multiplier=1 for me
208 do_work(multiplier=2)
209 return [st.integers(), st.text()]
210
211 branch_counts = set()
212 s = st.one_of(SlowBranchesStrategy(), SlowBranchesStrategy())
213
214 def test():
215 branches = len(s.branches)
216 branch_counts.add(branches)
217
218 run_concurrently(test, n=10)
219 assert len(branch_counts) == 1
220 # there are 4 independent strategies, but only 2 distinct ones -
221 # st.integers(), and st.text().
222 assert branch_counts == {2}