Debian Codegraph @

hypothesis-python/tests/common/debug.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 typing import TypeVar
12 from unittest import SkipTest
13
14 from hypothesis import HealthCheck, Phase, Verbosity, given, settings as Settings
15 from hypothesis._settings import local_settings
16 from hypothesis.control import _current_build_context
17 from hypothesis.errors import NoSuchExample, Unsatisfiable
18 from hypothesis.internal.reflection import get_pretty_function_description
19 from hypothesis.strategies import SearchStrategy
20
21 from tests.common.utils import no_shrink
22
23 TIME_INCREMENT = 0.00001
24 T = TypeVar("T")
25
26
27 # don't use hypothesis.errors.Found, which inherits from HypothesisException
28 # and therefore has weird semantics around e.g. backend="crosshair".
29 class Found(Exception):
30 pass
31
32
33 def minimal(
34 definition: SearchStrategy[T],
35 condition=lambda x: True,
36 settings: Settings | None = None,
37 ) -> T:
38 from tests.conftest import in_shrinking_benchmark
39
40 definition.validate()
41 result = None
42
43 def wrapped_condition(x):
44 # This sure seems pointless, but `test_sum_of_pair` fails otherwise...
45 return condition(x)
46
47 if (
48 context := _current_build_context.value
49 ) and context.data.provider.avoid_realization:
50 raise SkipTest("`minimal()` helper not supported under symbolic execution")
51
52 if settings is None:
53 settings = Settings(max_examples=500, phases=(Phase.generate, Phase.shrink))
54
55 verbosity = settings.verbosity
56 if verbosity == Verbosity.normal:
57 verbosity = Verbosity.quiet
58
59 @given(definition)
60 @Settings(
61 parent=settings,
62 suppress_health_check=list(HealthCheck),
63 report_multiple_bugs=False,
64 # we derandomize in general to avoid flaky tests, but we do want to
65 # measure this variation while benchmarking.
66 derandomize=not in_shrinking_benchmark,
67 database=None,
68 verbosity=verbosity,
69 )
70 def inner(x):
71 if wrapped_condition(x):
72 nonlocal result
73 result = x
74 raise Found
75
76 try:
77 inner()
78 except Found:
79 return result
80 raise Unsatisfiable(
81 f"Could not find any examples from {definition!r} that satisfied "
82 f"{get_pretty_function_description(condition)}"
83 )
84
85
86 def find_any(definition, condition=lambda _: True, settings=None):
87 # If nested within an existing @given
88 if context := _current_build_context.value:
89 while True:
90 if condition(s := context.data.draw(definition)):
91 return s
92
93 # If top-level
94 settings = settings or Settings.default
95 return minimal(
96 definition,
97 condition,
98 settings=Settings(
99 settings, phases=no_shrink, max_examples=max(1000, settings.max_examples)
100 ),
101 )
102
103
104 def assert_no_examples(strategy, condition=lambda _: True):
105 try:
106 assert_all_examples(strategy, lambda val: not condition(val))
107 except (Unsatisfiable, NoSuchExample):
108 pass
109
110
111 def assert_all_examples(strategy, predicate, settings=None):
112 """Asserts that all examples of the given strategy match the predicate.
113
114 :param strategy: Hypothesis strategy to check
115 :param predicate: (callable) Predicate that takes example and returns bool
116 """
117 if context := _current_build_context.value:
118 with local_settings(Settings(parent=settings)):
119 for _ in range(20):
120 s = context.data.draw(strategy)
121 msg = f"Found {s!r} using strategy {strategy} which does not match"
122 assert predicate(s), msg
123
124 else:
125
126 @given(strategy)
127 @Settings(parent=settings, database=None)
128 def assert_examples(s):
129 msg = f"Found {s!r} using strategy {strategy} which does not match"
130 assert predicate(s), msg
131
132 assert_examples()
133
134
135 def assert_simple_property(strategy, predicate, settings=None):
136 """Like assert_all_examples, intended as a self-documenting shortcut for simple constant
137 properties (`is`, `isinstance`, `==`, ...) that can be adequately verified in just a few
138 examples.
139
140 For more thorough checking, use assert_all_examples.
141 """
142
143 assert_all_examples(
144 strategy,
145 predicate,
146 Settings(
147 parent=settings,
148 max_examples=15,
149 suppress_health_check=list(HealthCheck),
150 ),
151 )
152
153
154 def check_can_generate_examples(strategy, settings=None):
155 """Tries to generate a small number of examples from the strategy, to verify that it can
156 do so without raising.
157
158 Nothing is returned, it only checks that no error is raised.
159 """
160
161 assert_simple_property(
162 strategy,
163 lambda _: True,
164 settings=Settings(
165 parent=settings,
166 phases=(Phase.generate,),
167 ),
168 )