| 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 |
""" |
| 12 |
This file tests for our ability to make precise shrinks. |
| 13 |
|
| 14 |
Terminology: A shrink is *precise* if there is a single span (draw call) that |
| 15 |
it replaces, without leaving any of the data before or after that draw call changed. |
| 16 |
Otherwise, it is sloppy. |
| 17 |
|
| 18 |
Precise shrinks correspond to the changes we can make to drawn data in isolation |
| 19 |
of the rest of the test case. e.g. if we draw a list, we want to always be able |
| 20 |
to delete an element from it without affecting things outside that list. If we |
| 21 |
draw an integer, we always want to be able to subtract from it. |
| 22 |
|
| 23 |
An example of a sloppy shrink is that we can sloppily replace any list with a prefix |
| 24 |
of it by changing the boolean that says if we should draw more elements with False. |
| 25 |
However leaves all the data corresponding to the rest of the list after that prefix |
| 26 |
in the test case, so everything after the drawn list is deleted. |
| 27 |
|
| 28 |
Having a rich vocabulary of precise shrinks we can make allows us to more easily |
| 29 |
reason about shrunk data, because we can look at the data and think in terms of |
| 30 |
what changes the shrinker would have made to it, and the fact that it hasn't |
| 31 |
means we know that it's important. e.g. this numeric value can't be smaller, this |
| 32 |
list can't have fewer elements. |
| 33 |
|
| 34 |
Sloppy shrinks in contrast just make the test case smaller. This is still good, |
| 35 |
obviously, and we rely on sloppy shrinks for a lot of shrinker performance and |
| 36 |
quality - often what we can expect is that we get to a smaller test case faster |
| 37 |
through sloppy shrinks, and then precise shrinks guarantee properties of the final |
| 38 |
result. |
| 39 |
""" |
| 40 |
|
| 41 |
|
| 42 |
import itertools |
| 43 |
from collections.abc import Callable |
| 44 |
from functools import lru_cache |
| 45 |
from random import Random |
| 46 |
from typing import TypeVar |
| 47 |
|
| 48 |
import pytest |
| 49 |
|
| 50 |
from hypothesis import find, settings, strategies as st |
| 51 |
from hypothesis.control import BuildContext |
| 52 |
from hypothesis.errors import StopTest, UnsatisfiedAssumption |
| 53 |
from hypothesis.internal.conjecture.data import ConjectureData, ConjectureResult, Status |
| 54 |
from hypothesis.internal.conjecture.engine import ( |
| 55 |
ConjectureRunner, |
| 56 |
ExitReason, |
| 57 |
RunIsComplete, |
| 58 |
) |
| 59 |
from hypothesis.internal.conjecture.shrinker import sort_key |
| 60 |
|
| 61 |
from tests.conjecture.common import interesting_origin |
| 62 |
|
| 63 |
T = TypeVar("T") |
| 64 |
|
| 65 |
pytestmark = [ |
| 66 |
pytest.mark.skipif( |
| 67 |
settings.get_current_profile_name() == "crosshair", |
| 68 |
reason="using internals for testing in a way crosshair doesn't support", |
| 69 |
), |
| 70 |
pytest.mark.skipif( |
| 71 |
settings.get_current_profile_name() == "threading", |
| 72 |
reason="not worth making thread-safe atm", |
| 73 |
), |
| 74 |
] |
| 75 |
|
| 76 |
|
| 77 |
def safe_draw(data, strategy): |
| 78 |
"""Set up just enough of the Hypothesis machinery to use draw on |
| 79 |
a strategy.""" |
| 80 |
with BuildContext(data, wrapped_test=None): |
| 81 |
try: |
| 82 |
return data.draw(strategy) |
| 83 |
except UnsatisfiedAssumption: |
| 84 |
data.mark_invalid() |
| 85 |
|
| 86 |
|
| 87 |
def precisely_shrink( |
| 88 |
strategy, |
| 89 |
is_interesting=lambda x: True, |
| 90 |
initial_condition=lambda x: True, |
| 91 |
end_marker=st.integers(), |
| 92 |
seed=0, |
| 93 |
): |
| 94 |
"""Generates a random value from the strategy and then precisely shrinks it, |
| 95 |
by shrinking it with some value immediately afterwards that is not allowed to |
| 96 |
be modified during shrinking.""" |
| 97 |
random = Random(seed) |
| 98 |
|
| 99 |
while True: |
| 100 |
data = ConjectureData(random=random) |
| 101 |
try: |
| 102 |
initial_value = safe_draw(data, strategy) |
| 103 |
except StopTest: |
| 104 |
continue |
| 105 |
if is_interesting(initial_value) and initial_condition(initial_value): |
| 106 |
break |
| 107 |
|
| 108 |
target_check_value = safe_draw(data, end_marker) |
| 109 |
|
| 110 |
initial_choices = data.choices |
| 111 |
|
| 112 |
replay = ConjectureData.for_choices(initial_choices) |
| 113 |
assert safe_draw(replay, strategy) == initial_value |
| 114 |
assert safe_draw(replay, end_marker) == target_check_value |
| 115 |
|
| 116 |
def test_function(data): |
| 117 |
value = safe_draw(data, strategy) |
| 118 |
check_value = safe_draw(data, end_marker) |
| 119 |
if is_interesting(value) and check_value == target_check_value: |
| 120 |
data.mark_interesting(interesting_origin()) |
| 121 |
|
| 122 |
runner = ConjectureRunner(test_function, random=random) |
| 123 |
try: |
| 124 |
buf = runner.cached_test_function(initial_choices) |
| 125 |
assert buf.status == Status.INTERESTING |
| 126 |
assert buf.choices == initial_choices |
| 127 |
assert runner.interesting_examples |
| 128 |
runner.shrink_interesting_examples() |
| 129 |
except RunIsComplete: |
| 130 |
assert runner.exit_reason in (ExitReason.finished, ExitReason.max_shrinks) |
| 131 |
(result,) = runner.interesting_examples.values() |
| 132 |
|
| 133 |
data = ConjectureData.for_choices(result.choices) |
| 134 |
result_value = safe_draw(data, strategy) |
| 135 |
data.freeze() |
| 136 |
return data.as_result(), result_value |
| 137 |
|
| 138 |
|
| 139 |
common_strategies_with_types = [ |
| 140 |
(type(None), st.none()), |
| 141 |
(bool, st.booleans()), |
| 142 |
(bytes, st.binary()), |
| 143 |
(str, st.text()), |
| 144 |
(int, st.integers()), |
| 145 |
] |
| 146 |
|
| 147 |
common_strategies = [v for _, v in common_strategies_with_types] |
| 148 |
|
| 149 |
|
| 150 |
@lru_cache |
| 151 |
def minimal_for_strategy(s): |
| 152 |
return precisely_shrink(s, end_marker=st.none()) |
| 153 |
|
| 154 |
|
| 155 |
def minimal_nodes_for_strategy(s): |
| 156 |
return minimal_for_strategy(s)[0].nodes |
| 157 |
|
| 158 |
|
| 159 |
def test_strategy_list_is_in_sorted_order(): |
| 160 |
assert common_strategies == sorted( |
| 161 |
common_strategies, key=lambda s: sort_key(minimal_nodes_for_strategy(s)) |
| 162 |
) |
| 163 |
|
| 164 |
|
| 165 |
@pytest.mark.parametrize("typ,strat", common_strategies_with_types) |
| 166 |
@pytest.mark.parametrize("require_truthy", [False, True]) |
| 167 |
def test_can_precisely_shrink_values(typ, strat, require_truthy): |
| 168 |
if typ is type(None) and require_truthy: |
| 169 |
pytest.skip("None is falsey") |
| 170 |
if require_truthy: |
| 171 |
cond = bool |
| 172 |
else: |
| 173 |
cond = lambda x: True |
| 174 |
_result, shrunk = precisely_shrink(strat, is_interesting=cond) |
| 175 |
assert shrunk == find(strat, cond) |
| 176 |
|
| 177 |
|
| 178 |
alternatives = [ |
| 179 |
comb |
| 180 |
for n in (2, 3, 4) |
| 181 |
for comb in itertools.combinations(common_strategies_with_types, n) |
| 182 |
] |
| 183 |
|
| 184 |
indexed_alternatives = [ |
| 185 |
(i, j, a) for a in alternatives for i, j in itertools.combinations(range(len(a)), 2) |
| 186 |
] |
| 187 |
|
| 188 |
|
| 189 |
@pytest.mark.parametrize("i,j,a", indexed_alternatives) |
| 190 |
@pytest.mark.parametrize("seed", [0, 4389048901]) |
| 191 |
def test_can_precisely_shrink_alternatives(i, j, a, seed): |
| 192 |
types = [u for u, _ in a] |
| 193 |
combined_strategy = st.one_of(*[v for _, v in a]) |
| 194 |
|
| 195 |
_result, value = precisely_shrink( |
| 196 |
combined_strategy, |
| 197 |
initial_condition=lambda x: isinstance(x, types[j]), |
| 198 |
is_interesting=lambda x: not any(isinstance(x, types[k]) for k in range(i)), |
| 199 |
seed=seed, |
| 200 |
) |
| 201 |
assert isinstance(value, types[i]) |
| 202 |
|
| 203 |
|
| 204 |
@pytest.mark.parametrize( |
| 205 |
"a", list(itertools.combinations(common_strategies_with_types, 3)) |
| 206 |
) |
| 207 |
@pytest.mark.parametrize("seed", [0, 4389048901]) |
| 208 |
def test_precise_shrink_with_blocker(a, seed): |
| 209 |
# We're reordering this so that there is a "blocking" unusually large |
| 210 |
# strategy in the middle. |
| 211 |
x, y, z = a |
| 212 |
a = (x, z, y) |
| 213 |
|
| 214 |
types = [u for u, _ in a] |
| 215 |
combined_strategy = st.one_of(*[v for _, v in a]) |
| 216 |
|
| 217 |
_result, value = precisely_shrink( |
| 218 |
combined_strategy, |
| 219 |
initial_condition=lambda x: isinstance(x, types[2]), |
| 220 |
is_interesting=lambda x: True, |
| 221 |
seed=seed, |
| 222 |
) |
| 223 |
|
| 224 |
assert isinstance(value, types[0]) |
| 225 |
|
| 226 |
|
| 227 |
def find_random( |
| 228 |
s: st.SearchStrategy[T], condition: Callable[[T], bool], seed=None |
| 229 |
) -> tuple[ConjectureResult, T]: |
| 230 |
random = Random(seed) |
| 231 |
while True: |
| 232 |
data = ConjectureData(random=random) |
| 233 |
try: |
| 234 |
with BuildContext(data=data, wrapped_test=None): |
| 235 |
value = data.draw(s) |
| 236 |
if condition(value): |
| 237 |
data.freeze() |
| 238 |
return (data.as_result(), value) |
| 239 |
except (StopTest, UnsatisfiedAssumption): |
| 240 |
continue |
| 241 |
|
| 242 |
|
| 243 |
def shrinks(strategy, nodes, *, allow_sloppy=True, seed=0): |
| 244 |
results = {} |
| 245 |
random = Random(seed) |
| 246 |
choices = tuple(n.value for n in nodes) |
| 247 |
|
| 248 |
if allow_sloppy: |
| 249 |
|
| 250 |
def test_function(data): |
| 251 |
value = safe_draw(data, strategy) |
| 252 |
results[data.nodes] = value |
| 253 |
|
| 254 |
runner = ConjectureRunner(test_function, settings=settings(max_examples=10**9)) |
| 255 |
initial = runner.cached_test_function(choices) |
| 256 |
assert isinstance(initial, ConjectureResult) |
| 257 |
try: |
| 258 |
runner.shrink(initial, lambda x: x.choices == initial.choices) |
| 259 |
except RunIsComplete: |
| 260 |
assert runner.exit_reason in (ExitReason.finished, ExitReason.max_shrinks) |
| 261 |
else: |
| 262 |
trial = ConjectureData(prefix=choices, random=random) |
| 263 |
with BuildContext(trial, wrapped_test=None): |
| 264 |
trial.draw(strategy) |
| 265 |
assert trial.choices == choices, "choice sequence is already sloppy" |
| 266 |
padding = safe_draw(trial, st.integers()) |
| 267 |
initial_choices = trial.choices |
| 268 |
|
| 269 |
def test_function(data): |
| 270 |
value = safe_draw(data, strategy) |
| 271 |
key = data.nodes |
| 272 |
padding_check = safe_draw(data, st.integers()) |
| 273 |
if padding_check == padding: |
| 274 |
results[key] = value |
| 275 |
|
| 276 |
runner = ConjectureRunner(test_function, settings=settings(max_examples=10**9)) |
| 277 |
initial = runner.cached_test_function(initial_choices) |
| 278 |
assert len(results) == 1 |
| 279 |
try: |
| 280 |
runner.shrink(initial, lambda x: x.choices == initial_choices) |
| 281 |
except RunIsComplete: |
| 282 |
assert runner.exit_reason in (ExitReason.finished, ExitReason.max_shrinks) |
| 283 |
|
| 284 |
results.pop(nodes) |
| 285 |
seen = set() |
| 286 |
result_list = [] |
| 287 |
|
| 288 |
for k, v in sorted(results.items(), key=lambda x: sort_key(x[0])): |
| 289 |
t = repr(v) |
| 290 |
if t in seen: |
| 291 |
continue |
| 292 |
seen.add(t) |
| 293 |
result_list.append((k, v)) |
| 294 |
return result_list |
| 295 |
|
| 296 |
|
| 297 |
@pytest.mark.parametrize("a", list(itertools.product(*([common_strategies[1:]] * 2)))) |
| 298 |
@pytest.mark.parametrize("block_falsey", [False, True]) |
| 299 |
@pytest.mark.parametrize("allow_sloppy", [False, True]) |
| 300 |
@pytest.mark.parametrize("seed", [0, 2452, 99085240570]) |
| 301 |
def test_always_shrinks_to_none(a, seed, block_falsey, allow_sloppy): |
| 302 |
combined_strategy = st.one_of(st.none(), *a) |
| 303 |
|
| 304 |
result, _value = find_random(combined_strategy, lambda x: x is not None) |
| 305 |
shrunk_values = shrinks( |
| 306 |
combined_strategy, result.nodes, allow_sloppy=allow_sloppy, seed=seed |
| 307 |
) |
| 308 |
assert shrunk_values[0][1] is None |
| 309 |
|
| 310 |
|
| 311 |
@pytest.mark.parametrize( |
| 312 |
"i,alts", [(i, alt) for alt in alternatives for i in range(1, len(alt))] |
| 313 |
) |
| 314 |
@pytest.mark.parametrize("force_small", [False, True]) |
| 315 |
@pytest.mark.parametrize("seed", [0, 2452, 99085240570]) |
| 316 |
def test_can_shrink_to_every_smaller_alternative(i, alts, seed, force_small): |
| 317 |
types = [t for t, _ in alts] |
| 318 |
strats = [s for _, s in alts] |
| 319 |
combined_strategy = st.one_of(*strats) |
| 320 |
if force_small: |
| 321 |
result, _value = precisely_shrink( |
| 322 |
combined_strategy, is_interesting=lambda x: type(x) is types[i], seed=seed |
| 323 |
) |
| 324 |
else: |
| 325 |
result, _value = find_random( |
| 326 |
combined_strategy, lambda x: type(x) is types[i], seed=seed |
| 327 |
) |
| 328 |
|
| 329 |
shrunk = shrinks( |
| 330 |
combined_strategy, |
| 331 |
result.nodes, |
| 332 |
allow_sloppy=False, |
| 333 |
# Arbitrary change so we don't use the same seed for each Random. |
| 334 |
seed=seed * 17, |
| 335 |
) |
| 336 |
shrunk_values = [t for _, t in shrunk] |
| 337 |
|
| 338 |
for j in range(i): |
| 339 |
assert any(isinstance(x, types[j]) for x in shrunk_values) |