Debian Codegraph @

hypothesis-python/tests/cover/test_interactive_example.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 os
12 import subprocess
13 import sys
14 import warnings
15 from decimal import Decimal
16
17 import pytest
18
19 from hypothesis import example, find, given, settings, strategies as st
20 from hypothesis.errors import (
21 HypothesisException,
22 InvalidArgument,
23 NonInteractiveExampleWarning,
24 Unsatisfiable,
25 )
26 from hypothesis.internal.compat import WINDOWS
27
28 from tests.common.debug import find_any
29 from tests.common.utils import (
30 Why,
31 fails_with,
32 skipif_emscripten,
33 skipif_threading,
34 xfail_on_crosshair,
35 )
36
37 pytest_plugins = "pytester"
38 # .example() uses random.shuffle, which changes the global random state and
39 # produces "do not use the `random` module inside strategies" deprecation warnings.
40 #
41 # Since we recommend against using .example() interactively, fixing this is
42 # an enhancement, not a bug.
43 pytestmark = pytest.mark.skipif(
44 settings.get_current_profile_name() == "threading",
45 reason=".example() is not thread-safe",
46 )
47
48
49 # Allow calling .example() without warnings for all tests in this module
50 @pytest.fixture(scope="function", autouse=True)
51 def _allow_noninteractive_example():
52 with warnings.catch_warnings():
53 warnings.simplefilter("ignore", NonInteractiveExampleWarning)
54 yield
55
56
57 def test_example_of_none_is_none():
58 assert st.none().example() is None
59
60
61 def test_exception_in_compare_can_still_have_example():
62 st.one_of(st.none().map(lambda n: Decimal("snan")), st.just(Decimal(0))).example()
63
64
65 @xfail_on_crosshair(Why.symbolic_outside_context)
66 def test_does_not_always_give_the_same_example():
67 s = st.integers()
68 assert len({s.example() for _ in range(100)}) >= 10
69
70
71 def test_raises_on_no_examples():
72 with pytest.raises(Unsatisfiable):
73 st.nothing().example()
74
75
76 @fails_with(HypothesisException)
77 @example(False)
78 @given(st.booleans())
79 def test_example_inside_given(b):
80 st.integers().example()
81
82
83 @fails_with(HypothesisException)
84 def test_example_inside_find():
85 find(st.integers(0, 100), lambda x: st.integers().example())
86
87
88 @fails_with(HypothesisException)
89 def test_example_inside_strategy():
90 find_any(st.booleans().map(lambda x: st.integers().example()))
91
92
93 def test_raises_on_arbitrary_data():
94 with pytest.raises(InvalidArgument):
95 st.data().example()
96
97
98 def test_non_interactive_example_emits_warning():
99 # Revert the effect of the allow_noninteractive_example autouse fixture
100 with warnings.catch_warnings():
101 warnings.simplefilter("always")
102 with pytest.warns(NonInteractiveExampleWarning):
103 st.text().example()
104
105
106 EXAMPLE_GENERATING_TEST = """
107 from hypothesis import strategies as st
108
109 def test_interactive_example():
110 st.integers().example()
111 """
112
113
114 @skipif_threading # pytester not thread safe
115 def test_selftests_exception_contains_note(pytester):
116 # The note is added by a pytest hook, so we need to run it under pytest in a
117 # subenvironment with (effectively) the same toplevel conftest.
118 with warnings.catch_warnings():
119 warnings.simplefilter("error")
120
121 pytester.makeconftest("from tests.conftest import *")
122 result = pytester.runpytest_inprocess(
123 pytester.makepyfile(EXAMPLE_GENERATING_TEST), "-p", "no:cacheprovider"
124 )
125 assert "helper methods in tests.common.debug" in "\n".join(result.outlines)
126
127
128 @skipif_emscripten
129 def test_script_example_does_not_emit_warning(tmp_path):
130 script = tmp_path / "script.py"
131 script.write_text(
132 "from hypothesis.strategies import integers\nintegers().example()\n",
133 encoding="utf-8",
134 )
135 # get rid of PYTEST_CURRENT_TEST, which we special-case as forcing this
136 # warning to still appear
137 env = os.environ.copy()
138 env.pop("PYTEST_CURRENT_TEST")
139 subprocess.check_call([sys.executable, "-Werror", str(script)], env=env)
140
141
142 @skipif_emscripten
143 @pytest.mark.skipif(WINDOWS, reason="pexpect.spawn not supported on Windows")
144 def test_interactive_example_does_not_emit_warning():
145 import pexpect
146
147 try:
148 child = pexpect.spawn(f"{sys.executable} -Werror")
149 child.expect(">>> ", timeout=10)
150 except pexpect.exceptions.EOF:
151 pytest.skip(
152 "Unable to run python with -Werror. This may be because you are "
153 "running from an old virtual environment - update your installed "
154 "copy of `virtualenv` and then create a fresh environment."
155 )
156 child.sendline("from hypothesis.strategies import none")
157 child.sendline("none().example()")
158 child.sendline("quit(code=0)")