Debian Codegraph @

hypothesis-python/tests/cover/test_error_in_draw.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 re
12
13 import pytest
14
15 from hypothesis import given, strategies as st
16 from hypothesis.errors import HypothesisWarning
17 from hypothesis.stateful import RuleBasedStateMachine, rule, run_state_machine_as_test
18
19
20 def test_error_is_in_finally():
21 @given(st.data())
22 def test(d):
23 try:
24 d.draw(st.lists(st.integers(), min_size=3, unique=True))
25 finally:
26 raise ValueError
27
28 with pytest.raises(ValueError) as err:
29 test()
30
31 assert "[0, 1, -1]" in "\n".join(err.value.__notes__)
32
33
34 @given(st.data())
35 def test_warns_on_bool_strategy(data):
36 with pytest.warns(
37 HypothesisWarning,
38 match=r"bool\(.+\) is always True, did you mean to draw a value\?",
39 ):
40 if st.booleans(): # 'forgot' to draw from the strategy
41 pass
42
43
44 def test_adds_note_showing_which_strategy():
45 class X:
46 def __init__(self, y: int) -> None:
47 assert y == 7
48
49 @given(...)
50 def inner(value: X):
51 assert isinstance(value, X)
52
53 rep = re.escape(repr(st.from_type(X)))
54 with pytest.raises(AssertionError, match=f".*while generating 'value' from {rep}"):
55 inner()
56
57
58 def test_adds_note_showing_which_strategy_stateful():
59 strategy = st.integers().map(lambda x: x / 0)
60
61 class Machine(RuleBasedStateMachine):
62 @rule(value=strategy)
63 def take_a_step(self, value):
64 assert value
65
66 msg = f"while generating 'value' from {strategy!r} for rule take_a_step"
67 print(msg)
68 with pytest.raises(ZeroDivisionError, match=f".*{re.escape(msg)}"):
69 run_state_machine_as_test(Machine)