Debian Codegraph @

hypothesis-python/tests/cover/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 from threading import Barrier, Thread
12
13 import pytest
14
15 from hypothesis import given, settings, strategies as st
16 from hypothesis.utils.threading import ThreadLocal
17
18 from tests.common.utils import skipif_emscripten
19
20
21 def test_threadlocal_setattr_and_getattr():
22 threadlocal = ThreadLocal(a=lambda: 1, b=lambda: 2)
23 assert threadlocal.a == 1
24 assert threadlocal.b == 2
25 # check that we didn't add attributes to the ThreadLocal instance itself
26 # instead of its threading.local() variable
27 assert set(threadlocal.__dict__) == {
28 "_ThreadLocal__initialized",
29 "_ThreadLocal__kwargs",
30 "_ThreadLocal__threadlocal",
31 }
32
33 threadlocal.a = 3
34 assert threadlocal.a == 3
35 assert threadlocal.b == 2
36 assert set(threadlocal.__dict__) == {
37 "_ThreadLocal__initialized",
38 "_ThreadLocal__kwargs",
39 "_ThreadLocal__threadlocal",
40 }
41
42
43 def test_nonexistent_getattr_raises():
44 threadlocal = ThreadLocal(a=lambda: 1)
45 with pytest.raises(AttributeError):
46 threadlocal.c
47
48
49 def test_nonexistent_setattr_raises():
50 threadlocal = ThreadLocal(a=lambda: 1)
51 with pytest.raises(AttributeError):
52 threadlocal.c = 2
53
54
55 def test_raises_if_not_passed_callable():
56 with pytest.raises(TypeError):
57 ThreadLocal(a=1)
58
59
60 @skipif_emscripten
61 @pytest.mark.skipif(
62 settings.get_current_profile_name() == "crosshair",
63 reason="crosshair is not thread-safe",
64 )
65 def test_run_given_concurrently():
66 # this is just a basic covering test. The more complicated and complete threading
67 # tests are in nocover/test_threading.py.
68
69 n_threads = 2
70 barrier = Barrier(n_threads)
71
72 @given(st.integers())
73 def test(n):
74 barrier.wait()
75
76 threads = [Thread(target=test) for _ in range(n_threads)]
77
78 for thread in threads:
79 thread.start()
80
81 for thread in threads:
82 thread.join(timeout=10)
83
84
85 # rely on our pytest-run-parallel job to test this, since this only happens because
86 # pytest instantiates a new class instance for each parametrization.
87 class TestNoDifferingExecutorsHealthCheck:
88 @given(st.integers())
89 @pytest.mark.parametrize("x", range(2))
90 def test_a(self, x, i):
91 pass