Debian Codegraph @

hypothesis-python/tests/cover/test_regressions.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 pickle
12 import random
13 from datetime import timedelta
14 from unittest.mock import Mock
15
16 import pytest
17
18 from hypothesis import (
19 Verbosity,
20 assume,
21 errors,
22 given,
23 seed,
24 settings,
25 strategies as st,
26 )
27 from hypothesis.internal import compat
28 from hypothesis.internal.escalation import InterestingOrigin
29
30 from tests.common.utils import skipif_threading
31
32
33 def strat():
34 return st.builds(dict, one=strat_one())
35
36
37 @st.composite
38 def strat_one(draw):
39 return draw(st.builds(dict, val=st.builds(dict, two=strat_two())))
40
41
42 @st.composite
43 def strat_two(draw):
44 return draw(st.builds(dict, some_text=st.text(min_size=1)))
45
46
47 @given(strat())
48 def test_issue751(v):
49 pass
50
51
52 def test_can_find_non_zero():
53 # This future proofs against a possible failure mode where the depth bound
54 # is triggered but we've fixed the behaviour of min_size so that it can
55 # handle that: We want to make sure that we're really not depth bounding
56 # the text in the leaf nodes.
57
58 @settings(verbosity=Verbosity.quiet)
59 @given(strat())
60 def test(v):
61 assert "0" in v["one"]["val"]["two"]["some_text"]
62
63 with pytest.raises(AssertionError):
64 test()
65
66
67 def test_mock_injection():
68 """Ensure that it's possible for mechanisms like `pytest.fixture` and
69 `patch` to inject mocks into hypothesis test functions without side
70 effects.
71
72 (covers https://github.com/HypothesisWorks/hypothesis-
73 python/issues/491)
74 """
75
76 class Bar:
77 pass
78
79 @given(inp=st.integers())
80 def test_foo_spec(bar, inp):
81 pass
82
83 test_foo_spec(Bar())
84 test_foo_spec(Mock(Bar))
85 test_foo_spec(Mock())
86
87
88 def test_regression_issue_1230():
89 strategy = st.builds(
90 lambda x, y: dict(list(x.items()) + list(y.items())),
91 st.fixed_dictionaries({"0": st.text()}),
92 st.builds(
93 lambda dictionary, keys: {key: dictionary[key] for key in keys},
94 st.fixed_dictionaries({"1": st.lists(elements=st.sampled_from(["a"]))}),
95 st.sets(elements=st.sampled_from(["1"])),
96 ),
97 )
98
99 @seed(81581571036124932593143257836081491416)
100 @settings(database=None)
101 @given(strategy)
102 def test_false_is_false(params):
103 assume(params.get("0") not in ("", "\x00"))
104 raise ValueError
105
106 with pytest.raises(ValueError):
107 test_false_is_false()
108
109
110 @given(st.integers())
111 def random_func(x):
112 random.random()
113
114
115 @skipif_threading
116 def test_prng_state_unpolluted_by_given_issue_1266():
117 # Checks that @given doesn't leave the global PRNG in a particular
118 # modified state; there may be no effect or random effect but not
119 # a consistent end-state.
120 first = random.getstate()
121 random_func()
122 second = random.getstate()
123 random_func()
124 third = random.getstate()
125 if first == second:
126 assert second == third
127 else:
128 assert second != third
129
130
131 exc_instances = [
132 errors.NoSuchExample("foobar", extra="baz"),
133 errors.DeadlineExceeded(
134 runtime=timedelta(seconds=1.5), deadline=timedelta(seconds=1.0)
135 ),
136 errors.RewindRecursive(int),
137 errors.UnsatisfiedAssumption("reason for unsatisfied"),
138 errors.FlakyReplay(
139 "reason",
140 interesting_origins=[InterestingOrigin.from_exception(BaseException())],
141 ),
142 errors.FlakyFailure("check with BaseException", [BaseException()]),
143 errors.BackendCannotProceed("verified"),
144 ]
145
146
147 @pytest.mark.parametrize("exc", exc_instances, ids=repr)
148 def test_exceptions_are_picklable(exc):
149 # See https://github.com/HypothesisWorks/hypothesis/issues/3426
150 pickle.loads(pickle.dumps(exc))
151
152
153 def test_no_missed_custom_init_exceptions():
154 untested_errors_with_custom_init = {
155 et
156 for et in vars(errors).values()
157 if isinstance(et, type)
158 and et not in vars(compat).values() # skip types imported for compatibility
159 and issubclass(et, Exception)
160 and ("__init__" in vars(et) or "__new__" in vars(et))
161 } - {type(exc) for exc in exc_instances}
162 print(untested_errors_with_custom_init)
163 assert not untested_errors_with_custom_init