| 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 dataclasses |
| 12 |
import itertools |
| 13 |
import math |
| 14 |
import sys |
| 15 |
import time |
| 16 |
import warnings |
| 17 |
from contextlib import contextmanager, nullcontext |
| 18 |
from random import Random |
| 19 |
from threading import RLock |
| 20 |
|
| 21 |
import pytest |
| 22 |
|
| 23 |
from hypothesis import ( |
| 24 |
HealthCheck, |
| 25 |
Verbosity, |
| 26 |
assume, |
| 27 |
errors, |
| 28 |
given, |
| 29 |
settings, |
| 30 |
strategies as st, |
| 31 |
) |
| 32 |
from hypothesis.control import current_build_context |
| 33 |
from hypothesis.database import InMemoryExampleDatabase |
| 34 |
from hypothesis.errors import ( |
| 35 |
BackendCannotProceed, |
| 36 |
Flaky, |
| 37 |
FlakyBackendFailure, |
| 38 |
HypothesisException, |
| 39 |
HypothesisWarning, |
| 40 |
InvalidArgument, |
| 41 |
Unsatisfiable, |
| 42 |
) |
| 43 |
from hypothesis.internal.compat import WINDOWS, int_to_bytes |
| 44 |
from hypothesis.internal.conjecture.data import ConjectureData, PrimitiveProvider |
| 45 |
from hypothesis.internal.conjecture.engine import ConjectureRunner |
| 46 |
from hypothesis.internal.conjecture.provider_conformance import run_conformance_test |
| 47 |
from hypothesis.internal.conjecture.providers import ( |
| 48 |
AVAILABLE_PROVIDERS, |
| 49 |
COLLECTION_DEFAULT_MAX_SIZE, |
| 50 |
HypothesisProvider, |
| 51 |
with_register_backend, |
| 52 |
) |
| 53 |
from hypothesis.internal.floats import SIGNALING_NAN, clamp |
| 54 |
from hypothesis.internal.intervalsets import IntervalSet |
| 55 |
from hypothesis.internal.observability import Observation, _callbacks |
| 56 |
|
| 57 |
from tests.common.debug import minimal |
| 58 |
from tests.common.utils import ( |
| 59 |
capture_observations, |
| 60 |
capture_out, |
| 61 |
) |
| 62 |
from tests.conjecture.common import nodes |
| 63 |
|
| 64 |
|
| 65 |
class PrngProvider(PrimitiveProvider): |
| 66 |
# A test-only implementation of the PrimitiveProvider interface, which uses |
| 67 |
# a very simple PRNG to choose each value. Dumb but efficient, and entirely |
| 68 |
# independent of our real backend |
| 69 |
|
| 70 |
def __init__(self, conjecturedata: "ConjectureData | None", /) -> None: |
| 71 |
super().__init__(conjecturedata) |
| 72 |
self.prng = Random(0) |
| 73 |
|
| 74 |
def draw_boolean( |
| 75 |
self, |
| 76 |
p: float = 0.5, |
| 77 |
) -> bool: |
| 78 |
return self.prng.random() < p |
| 79 |
|
| 80 |
def draw_integer( |
| 81 |
self, |
| 82 |
min_value: int | None = None, |
| 83 |
max_value: int | None = None, |
| 84 |
*, |
| 85 |
weights: dict[int, float] | None = None, |
| 86 |
shrink_towards: int = 0, |
| 87 |
) -> int: |
| 88 |
# shrink_towards is fully ignored here. It would be nice to implement |
| 89 |
# weights, but it's tricky to fully conform it to our |
| 90 |
# provider_conformance test. |
| 91 |
assert isinstance(shrink_towards, int) |
| 92 |
assert weights is None or isinstance(weights, dict) |
| 93 |
|
| 94 |
if min_value is None and max_value is None: |
| 95 |
min_value = -(2**127) |
| 96 |
max_value = 2**127 - 1 |
| 97 |
elif min_value is None: |
| 98 |
min_value = max_value - 2**64 |
| 99 |
elif max_value is None: |
| 100 |
max_value = min_value + 2**64 |
| 101 |
return self.prng.randint(min_value, max_value) |
| 102 |
|
| 103 |
def draw_float( |
| 104 |
self, |
| 105 |
*, |
| 106 |
min_value: float = -math.inf, |
| 107 |
max_value: float = math.inf, |
| 108 |
allow_nan: bool = True, |
| 109 |
smallest_nonzero_magnitude: float, |
| 110 |
) -> float: |
| 111 |
if allow_nan and self.prng.random() < 1 / 32: |
| 112 |
nans = [math.nan, -math.nan, SIGNALING_NAN, -SIGNALING_NAN] |
| 113 |
return self.prng.choice(nans) |
| 114 |
|
| 115 |
# small chance of inf values, if they are in bounds |
| 116 |
if min_value <= math.inf <= max_value and self.prng.random() < 1 / 32: |
| 117 |
return math.inf |
| 118 |
if min_value <= -math.inf <= max_value and self.prng.random() < 1 / 32: |
| 119 |
return -math.inf |
| 120 |
|
| 121 |
# get rid of infs, they cause nans if we pass them to prng.uniform |
| 122 |
min_value_bound = min_value |
| 123 |
max_value_bound = max_value |
| 124 |
if min_value in [-math.inf, math.inf]: |
| 125 |
min_value_bound = math.copysign(1, min_value) * sys.float_info.max |
| 126 |
# being too close to the bounds causes prng.uniform to only return |
| 127 |
# inf. |
| 128 |
min_value_bound /= 2 |
| 129 |
if max_value in [-math.inf, math.inf]: |
| 130 |
max_value_bound = math.copysign(1, max_value) * sys.float_info.max |
| 131 |
max_value_bound /= 2 |
| 132 |
|
| 133 |
value = self.prng.uniform(min_value_bound, max_value_bound) |
| 134 |
# random.uniform can in fact provide out of bounds values, e.g. |
| 135 |
# random.uniform(-8.98846567431158e+307, 8.98846567431158e+307) |
| 136 |
# can produce math.inf, which is strictly greater than 8.98846567431158e+307 |
| 137 |
value = clamp(min_value, value, max_value) |
| 138 |
if value and abs(value) < smallest_nonzero_magnitude: |
| 139 |
return ( |
| 140 |
smallest_nonzero_magnitude |
| 141 |
if min_value <= smallest_nonzero_magnitude <= max_value |
| 142 |
else -smallest_nonzero_magnitude |
| 143 |
) |
| 144 |
return value |
| 145 |
|
| 146 |
def draw_string( |
| 147 |
self, |
| 148 |
intervals: IntervalSet, |
| 149 |
*, |
| 150 |
min_size: int = 0, |
| 151 |
max_size: int = COLLECTION_DEFAULT_MAX_SIZE, |
| 152 |
) -> str: |
| 153 |
size = self.prng.randint( |
| 154 |
min_size, max(min_size, min(100 if max_size is None else max_size, 100)) |
| 155 |
) |
| 156 |
if len(intervals) == 0: |
| 157 |
return "" |
| 158 |
return "".join(map(chr, self.prng.choices(intervals, k=size))) |
| 159 |
|
| 160 |
def draw_bytes( |
| 161 |
self, |
| 162 |
min_size: int = 0, |
| 163 |
max_size: int = COLLECTION_DEFAULT_MAX_SIZE, |
| 164 |
) -> bytes: |
| 165 |
# cap max size for performance |
| 166 |
max_size = 100 if max_size is None else min(max_size, 100) |
| 167 |
size = self.prng.randint(min_size, max_size) |
| 168 |
return self.prng.randbytes(size) |
| 169 |
|
| 170 |
|
| 171 |
_temp_register_backend_lock = RLock() |
| 172 |
|
| 173 |
|
| 174 |
# same as with_register_backend, but adds a lock for our threading tests. |
| 175 |
@contextmanager |
| 176 |
def temp_register_backend(name, provider_cls): |
| 177 |
with _temp_register_backend_lock, with_register_backend(name, provider_cls): |
| 178 |
yield |
| 179 |
|
| 180 |
|
| 181 |
@pytest.mark.parametrize( |
| 182 |
"strategy", |
| 183 |
[ |
| 184 |
st.booleans(), |
| 185 |
st.integers(0, 3), |
| 186 |
st.floats(0, 1), |
| 187 |
st.text(max_size=3), |
| 188 |
st.binary(max_size=3), |
| 189 |
], |
| 190 |
ids=repr, |
| 191 |
) |
| 192 |
def test_find_with_backend_then_convert_to_buffer_shrink_and_replay(strategy): |
| 193 |
db = InMemoryExampleDatabase() |
| 194 |
assert not db.data |
| 195 |
|
| 196 |
with temp_register_backend("prng", PrngProvider): |
| 197 |
|
| 198 |
@settings(database=db, backend="prng") |
| 199 |
@given(strategy) |
| 200 |
def test(value): |
| 201 |
if isinstance(value, float): |
| 202 |
assert value >= 0.5 |
| 203 |
else: |
| 204 |
assert value |
| 205 |
|
| 206 |
with pytest.raises(AssertionError): |
| 207 |
test() |
| 208 |
|
| 209 |
assert db.data |
| 210 |
buffers = {x for x in db.data[next(iter(db.data))] if x} |
| 211 |
assert buffers, db.data |
| 212 |
|
| 213 |
|
| 214 |
def test_backend_can_shrink_integers(): |
| 215 |
with temp_register_backend("prng", PrngProvider): |
| 216 |
n = minimal( |
| 217 |
st.integers(), |
| 218 |
lambda n: n >= 123456, |
| 219 |
settings=settings(backend="prng", database=None), |
| 220 |
) |
| 221 |
|
| 222 |
assert n == 123456 |
| 223 |
|
| 224 |
|
| 225 |
def test_backend_can_shrink_bytes(): |
| 226 |
with temp_register_backend("prng", PrngProvider): |
| 227 |
b = minimal( |
| 228 |
# this test doubles as coverage for popping draw_bytes ir nodes, |
| 229 |
# and that path is only taken with fixed size for the moment. can |
| 230 |
# be removed when we support variable length binary at the ir level. |
| 231 |
st.binary(min_size=2, max_size=2), |
| 232 |
lambda b: len(b) >= 2 and b[1] >= 10, |
| 233 |
settings=settings(backend="prng", database=None), |
| 234 |
) |
| 235 |
|
| 236 |
assert b == int_to_bytes(10, size=2) |
| 237 |
|
| 238 |
|
| 239 |
def test_backend_can_shrink_strings(): |
| 240 |
with temp_register_backend("prng", PrngProvider): |
| 241 |
s = minimal( |
| 242 |
st.text(), |
| 243 |
lambda s: len(s) >= 10, |
| 244 |
settings=settings(backend="prng", database=None), |
| 245 |
) |
| 246 |
|
| 247 |
assert len(s) == 10 |
| 248 |
|
| 249 |
|
| 250 |
def test_backend_can_shrink_booleans(): |
| 251 |
with temp_register_backend("prng", PrngProvider): |
| 252 |
b = minimal( |
| 253 |
st.booleans(), lambda b: b, settings=settings(backend="prng", database=None) |
| 254 |
) |
| 255 |
|
| 256 |
assert b |
| 257 |
|
| 258 |
|
| 259 |
def test_backend_can_shrink_floats(): |
| 260 |
with temp_register_backend("prng", PrngProvider): |
| 261 |
f = minimal( |
| 262 |
st.floats(), |
| 263 |
lambda f: f >= 100.5, |
| 264 |
settings=settings(backend="prng", database=None), |
| 265 |
) |
| 266 |
|
| 267 |
assert f == 101.0 |
| 268 |
|
| 269 |
|
| 270 |
# mostly a shoehorned coverage test until the shrinker is migrated to the ir |
| 271 |
# and calls cached_test_function with backends consistently. |
| 272 |
@given(nodes()) |
| 273 |
def test_new_conjecture_data_with_backend(node): |
| 274 |
def test(data): |
| 275 |
getattr(data, f"draw_{node.type}")(**node.constraints) |
| 276 |
|
| 277 |
with temp_register_backend("prng", PrngProvider): |
| 278 |
runner = ConjectureRunner(test, settings=settings(backend="prng")) |
| 279 |
runner.cached_test_function([node.value]) |
| 280 |
|
| 281 |
|
| 282 |
# trivial provider for tests which don't care about drawn distributions. |
| 283 |
class TrivialProvider(PrimitiveProvider): |
| 284 |
def draw_integer(self, *args, **constraints): |
| 285 |
return 1 |
| 286 |
|
| 287 |
def draw_boolean(self, *args, **constraints): |
| 288 |
return True |
| 289 |
|
| 290 |
def draw_float(self, *args, **constraints): |
| 291 |
return 1.0 |
| 292 |
|
| 293 |
def draw_bytes(self, *args, **constraints): |
| 294 |
return b"" |
| 295 |
|
| 296 |
def draw_string(self, *args, **constraints): |
| 297 |
return "" |
| 298 |
|
| 299 |
|
| 300 |
class InvalidLifetime(TrivialProvider): |
| 301 |
|
| 302 |
lifetime = "forever and a day" |
| 303 |
|
| 304 |
|
| 305 |
def test_invalid_lifetime(): |
| 306 |
with ( |
| 307 |
temp_register_backend("invalid_lifetime", InvalidLifetime), |
| 308 |
pytest.raises(InvalidArgument), |
| 309 |
): |
| 310 |
ConjectureRunner(lambda: True, settings=settings(backend="invalid_lifetime")) |
| 311 |
|
| 312 |
|
| 313 |
function_lifetime_init_count = 0 |
| 314 |
|
| 315 |
|
| 316 |
class LifetimeTestFunction(TrivialProvider): |
| 317 |
lifetime = "test_function" |
| 318 |
|
| 319 |
def __init__(self, conjecturedata): |
| 320 |
super().__init__(conjecturedata) |
| 321 |
# hacky, but no easy alternative. |
| 322 |
global function_lifetime_init_count |
| 323 |
function_lifetime_init_count += 1 |
| 324 |
|
| 325 |
|
| 326 |
def test_function_lifetime(): |
| 327 |
with temp_register_backend("lifetime_function", LifetimeTestFunction): |
| 328 |
|
| 329 |
@given(st.integers()) |
| 330 |
@settings(backend="lifetime_function") |
| 331 |
def test_function(n): |
| 332 |
pass |
| 333 |
|
| 334 |
assert function_lifetime_init_count == 0 |
| 335 |
test_function() |
| 336 |
assert function_lifetime_init_count == 1 |
| 337 |
test_function() |
| 338 |
assert function_lifetime_init_count == 2 |
| 339 |
|
| 340 |
|
| 341 |
test_case_lifetime_init_count = 0 |
| 342 |
|
| 343 |
|
| 344 |
class LifetimeTestCase(TrivialProvider): |
| 345 |
lifetime = "test_case" |
| 346 |
|
| 347 |
def __init__(self, conjecturedata): |
| 348 |
super().__init__(conjecturedata) |
| 349 |
global test_case_lifetime_init_count |
| 350 |
test_case_lifetime_init_count += 1 |
| 351 |
|
| 352 |
|
| 353 |
def test_case_lifetime(): |
| 354 |
test_function_count = 0 |
| 355 |
|
| 356 |
with temp_register_backend("lifetime_case", LifetimeTestCase): |
| 357 |
|
| 358 |
@given(st.integers()) |
| 359 |
@settings(backend="lifetime_case", database=InMemoryExampleDatabase()) |
| 360 |
def test_function(n): |
| 361 |
nonlocal test_function_count |
| 362 |
test_function_count += 1 |
| 363 |
|
| 364 |
assert test_case_lifetime_init_count == 0 |
| 365 |
test_function() |
| 366 |
|
| 367 |
# we create a new provider each time we *try* to generate an input to the |
| 368 |
# test function, but this could be filtered out, discarded as duplicate, |
| 369 |
# etc. We also sometimes try predetermined inputs to the test function, |
| 370 |
# such as ChoiceTemplate(type="simplest"), which does not entail creating |
| 371 |
# providers. These two facts combined mean that the number of inits could be |
| 372 |
# anywhere reasonably close to the number of function calls. |
| 373 |
assert ( |
| 374 |
test_function_count - 10 |
| 375 |
<= test_case_lifetime_init_count |
| 376 |
<= test_function_count + 10 |
| 377 |
) |
| 378 |
|
| 379 |
|
| 380 |
def test_flaky_with_backend(): |
| 381 |
with temp_register_backend("trivial", TrivialProvider), capture_observations(): |
| 382 |
|
| 383 |
calls = 0 |
| 384 |
|
| 385 |
@given(st.integers()) |
| 386 |
@settings(backend="trivial", database=None) |
| 387 |
def test_function(n): |
| 388 |
nonlocal calls |
| 389 |
calls += 1 |
| 390 |
assert n != calls % 2 |
| 391 |
|
| 392 |
with pytest.raises(Flaky): |
| 393 |
test_function() |
| 394 |
|
| 395 |
|
| 396 |
class BadRealizeProvider(TrivialProvider): |
| 397 |
def realize(self, value, *, for_failure=False): |
| 398 |
return None |
| 399 |
|
| 400 |
|
| 401 |
def test_bad_realize(): |
| 402 |
with temp_register_backend("bad_realize", BadRealizeProvider): |
| 403 |
|
| 404 |
@given(st.integers()) |
| 405 |
@settings(backend="bad_realize") |
| 406 |
def test_function(n): |
| 407 |
pass |
| 408 |
|
| 409 |
with pytest.raises( |
| 410 |
HypothesisException, |
| 411 |
match=r"expected .* from BadRealizeProvider.realize", |
| 412 |
): |
| 413 |
test_function() |
| 414 |
|
| 415 |
|
| 416 |
class RealizeProvider(TrivialProvider): |
| 417 |
# self-documenting constant |
| 418 |
REALIZED = 42 |
| 419 |
avoid_realization = True |
| 420 |
|
| 421 |
def realize(self, value, *, for_failure=False): |
| 422 |
if isinstance(value, int): |
| 423 |
return self.REALIZED |
| 424 |
return value |
| 425 |
|
| 426 |
|
| 427 |
def test_realize(): |
| 428 |
with temp_register_backend("realize", RealizeProvider): |
| 429 |
values = [] |
| 430 |
|
| 431 |
@given(st.integers()) |
| 432 |
@settings(backend="realize") |
| 433 |
def test_function(n): |
| 434 |
values.append(current_build_context().data.provider.realize(n)) |
| 435 |
|
| 436 |
test_function() |
| 437 |
|
| 438 |
# first draw is 0 from ChoiceTemplate(type="simplest") |
| 439 |
assert values[0] == 0 |
| 440 |
assert all(n == RealizeProvider.REALIZED for n in values[1:]) |
| 441 |
|
| 442 |
|
| 443 |
def test_realize_dependent_draw(): |
| 444 |
with temp_register_backend("realize", RealizeProvider): |
| 445 |
|
| 446 |
@given(st.data()) |
| 447 |
@settings(backend="realize") |
| 448 |
def test_function(data): |
| 449 |
n1 = data.draw(st.integers()) |
| 450 |
n2 = data.draw(st.integers(n1, n1 + 10)) |
| 451 |
assert n1 <= n2 |
| 452 |
|
| 453 |
test_function() |
| 454 |
|
| 455 |
|
| 456 |
@pytest.mark.parametrize("verbosity", [Verbosity.verbose, Verbosity.debug]) |
| 457 |
def test_realization_with_verbosity(verbosity): |
| 458 |
with temp_register_backend("realize", RealizeProvider): |
| 459 |
|
| 460 |
@given(st.floats()) |
| 461 |
@settings(backend="realize", verbosity=verbosity) |
| 462 |
def test_function(f): |
| 463 |
pass |
| 464 |
|
| 465 |
with capture_out() as out: |
| 466 |
test_function() |
| 467 |
assert "Trying example: test_function(\n f=<symbolic>,\n)" in out.getvalue() |
| 468 |
|
| 469 |
|
| 470 |
@pytest.mark.parametrize("verbosity", [Verbosity.verbose, Verbosity.debug]) |
| 471 |
def test_realization_with_verbosity_draw(verbosity): |
| 472 |
with temp_register_backend("realize", RealizeProvider): |
| 473 |
|
| 474 |
@given(st.data()) |
| 475 |
@settings(backend="realize", verbosity=verbosity) |
| 476 |
def test_function(data): |
| 477 |
data.draw(st.integers()) |
| 478 |
|
| 479 |
with capture_out() as out: |
| 480 |
test_function() |
| 481 |
assert "Draw 1: <symbolic>" in out.getvalue() |
| 482 |
|
| 483 |
|
| 484 |
def test_realization_with_observability(): |
| 485 |
with temp_register_backend("realize", RealizeProvider): |
| 486 |
|
| 487 |
@given(st.data()) |
| 488 |
@settings(backend="realize") |
| 489 |
def test_function(data): |
| 490 |
data.draw(st.integers()) |
| 491 |
|
| 492 |
with capture_observations() as observations: |
| 493 |
test_function() |
| 494 |
|
| 495 |
test_cases = [tc for tc in observations if tc.type == "test_case"] |
| 496 |
assert {tc.representation for tc in test_cases} == { |
| 497 |
# from the first ChoiceTemplate(type="simplest") example |
| 498 |
"test_function(\n data=data(...),\n)\nDraw 1: 0", |
| 499 |
# from all other examples. data=<symbolic> isn't ideal; we should special |
| 500 |
# case this as data=data(...). |
| 501 |
f"test_function(\n data=<symbolic>,\n)\nDraw 1: {RealizeProvider.REALIZED}", |
| 502 |
} |
| 503 |
|
| 504 |
|
| 505 |
class ObservableProvider(TrivialProvider): |
| 506 |
def observe_test_case(self): |
| 507 |
return {"msg_key": "some message", "data_key": [1, "2", {}]} |
| 508 |
|
| 509 |
def observe_information_messages(self, *, lifetime): |
| 510 |
if lifetime == "test_case": |
| 511 |
yield {"type": "info", "title": "trivial-data", "content": {"k2": "v2"}} |
| 512 |
else: |
| 513 |
assert lifetime == "test_function" |
| 514 |
yield {"type": "alert", "title": "Trivial alert", "content": "message here"} |
| 515 |
yield {"type": "info", "title": "trivial-data", "content": {"k2": "v2"}} |
| 516 |
|
| 517 |
|
| 518 |
def test_custom_observations_from_backend(): |
| 519 |
with temp_register_backend("observable", ObservableProvider): |
| 520 |
|
| 521 |
@given(st.booleans()) |
| 522 |
@settings(backend="observable", database=None) |
| 523 |
def test_function(_): |
| 524 |
pass |
| 525 |
|
| 526 |
with capture_observations() as ls: |
| 527 |
test_function() |
| 528 |
|
| 529 |
assert len(ls) >= 3 |
| 530 |
cases = [t.metadata.backend for t in ls if t.type == "test_case"] |
| 531 |
assert {"msg_key": "some message", "data_key": [1, "2", {}]} in cases |
| 532 |
|
| 533 |
infos = [ |
| 534 |
{k: v for k, v in dataclasses.asdict(t).items() if k in ("title", "content")} |
| 535 |
for t in ls |
| 536 |
if t.type != "test_case" |
| 537 |
] |
| 538 |
assert {"title": "Trivial alert", "content": "message here"} in infos |
| 539 |
assert {"title": "trivial-data", "content": {"k2": "v2"}} in infos |
| 540 |
|
| 541 |
|
| 542 |
class NeverProceedsObservable(ObservableProvider): |
| 543 |
def realize(self, value, *, for_failure=False): |
| 544 |
raise BackendCannotProceed |
| 545 |
|
| 546 |
|
| 547 |
def test_custom_observations_cannot_realize(): |
| 548 |
with temp_register_backend("never_proceeds", NeverProceedsObservable): |
| 549 |
|
| 550 |
@given(st.integers()) |
| 551 |
@settings(backend="never_proceeds", database=None) |
| 552 |
def test_function(_): |
| 553 |
pass |
| 554 |
|
| 555 |
with capture_observations() as ls: |
| 556 |
test_function() |
| 557 |
|
| 558 |
assert "<backend failed to realize symbolic arguments>" in repr(ls) |
| 559 |
|
| 560 |
|
| 561 |
def test_backend_realize_cannot_proceed_increments_invalid(): |
| 562 |
def test(data): |
| 563 |
data.draw_integer() |
| 564 |
|
| 565 |
with with_register_backend("never_proceeds", NeverProceedsObservable): |
| 566 |
runner = ConjectureRunner( |
| 567 |
test, |
| 568 |
settings=settings(backend="never_proceeds", database=None), |
| 569 |
) |
| 570 |
assert runner.invalid_examples == 0 |
| 571 |
runner.cached_test_function([1]) |
| 572 |
assert runner.invalid_examples == 1 |
| 573 |
|
| 574 |
|
| 575 |
def test_backend_realize_cannot_proceed_exception_increments_invalid(): |
| 576 |
# test the alternative code path where the test is interesting and we realize |
| 577 |
# the values with for_failure=True |
| 578 |
def test(data): |
| 579 |
data.draw_integer() |
| 580 |
raise ValueError |
| 581 |
|
| 582 |
with with_register_backend("never_proceeds", NeverProceedsObservable): |
| 583 |
runner = ConjectureRunner( |
| 584 |
test, |
| 585 |
settings=settings(backend="never_proceeds", database=None), |
| 586 |
) |
| 587 |
assert runner.invalid_examples == 0 |
| 588 |
runner.cached_test_function([1]) |
| 589 |
assert runner.invalid_examples == 1 |
| 590 |
|
| 591 |
|
| 592 |
class FallibleProvider(TrivialProvider): |
| 593 |
def __init__(self, conjecturedata: "ConjectureData", /) -> None: |
| 594 |
super().__init__(conjecturedata) |
| 595 |
self._it = itertools.cycle([1, 1, "discard_test_case", "other"]) |
| 596 |
|
| 597 |
def draw_integer(self, *args, **constraints): |
| 598 |
x = next(self._it) |
| 599 |
if isinstance(x, str): |
| 600 |
raise BackendCannotProceed(x) |
| 601 |
return x |
| 602 |
|
| 603 |
|
| 604 |
def test_falls_back_to_default_backend(): |
| 605 |
with temp_register_backend("fallible", FallibleProvider): |
| 606 |
seen_other_ints = False |
| 607 |
|
| 608 |
@given(st.integers()) |
| 609 |
@settings(backend="fallible", database=None, max_examples=100) |
| 610 |
def test_function(x): |
| 611 |
nonlocal seen_other_ints |
| 612 |
seen_other_ints |= x != 1 |
| 613 |
|
| 614 |
test_function() |
| 615 |
assert seen_other_ints # must have swapped backends then |
| 616 |
|
| 617 |
|
| 618 |
def test_can_raise_unsatisfiable_after_falling_back(): |
| 619 |
with temp_register_backend("fallible", FallibleProvider): |
| 620 |
|
| 621 |
@given(st.integers()) |
| 622 |
@settings( |
| 623 |
backend="fallible", |
| 624 |
database=None, |
| 625 |
max_examples=100, |
| 626 |
suppress_health_check=[HealthCheck.filter_too_much], |
| 627 |
) |
| 628 |
def test_function(x): |
| 629 |
assume(x == "unsatisfiable") |
| 630 |
|
| 631 |
with pytest.raises(Unsatisfiable): |
| 632 |
test_function() |
| 633 |
|
| 634 |
|
| 635 |
class ExhaustibleProvider(TrivialProvider): |
| 636 |
scope = "exhausted" |
| 637 |
|
| 638 |
def __init__(self, conjecturedata: "ConjectureData", /) -> None: |
| 639 |
super().__init__(conjecturedata) |
| 640 |
self._calls = 0 |
| 641 |
|
| 642 |
def draw_integer(self, *args, **constraints): |
| 643 |
self._calls += 1 |
| 644 |
if self._calls > 20: |
| 645 |
# This is complete nonsense of course, so we'll see Hypothesis complain |
| 646 |
# that we found a problem after the backend reported verification. |
| 647 |
raise BackendCannotProceed(self.scope) |
| 648 |
return self._calls |
| 649 |
|
| 650 |
|
| 651 |
class UnsoundVerifierProvider(ExhaustibleProvider): |
| 652 |
scope = "verified" |
| 653 |
|
| 654 |
|
| 655 |
@pytest.mark.parametrize("provider", [ExhaustibleProvider, UnsoundVerifierProvider]) |
| 656 |
def test_notes_incorrect_verification(provider): |
| 657 |
msg = "backend='p' claimed to verify this test passes - please send them a bug report!" |
| 658 |
with temp_register_backend("p", provider): |
| 659 |
|
| 660 |
@given(st.integers()) |
| 661 |
@settings(backend="p", database=None, max_examples=100) |
| 662 |
def test_function(x): |
| 663 |
assert x >= 0 # True from this backend, false in general! |
| 664 |
|
| 665 |
with pytest.raises(AssertionError) as ctx: |
| 666 |
test_function() |
| 667 |
assert (msg in ctx.value.__notes__) == (provider is UnsoundVerifierProvider) |
| 668 |
|
| 669 |
|
| 670 |
def test_invalid_provider_kw(): |
| 671 |
with pytest.raises(InvalidArgument, match="got an instance instead"): |
| 672 |
ConjectureData( |
| 673 |
random=None, |
| 674 |
provider=TrivialProvider(None), |
| 675 |
provider_kw={"one": "two"}, |
| 676 |
) |
| 677 |
|
| 678 |
|
| 679 |
def test_available_providers_deprecation(): |
| 680 |
with pytest.warns(errors.HypothesisDeprecationWarning): |
| 681 |
from hypothesis.internal.conjecture.data import AVAILABLE_PROVIDERS # noqa |
| 682 |
|
| 683 |
with pytest.raises(ImportError): |
| 684 |
from hypothesis.internal.conjecture.data import does_not_exist # noqa |
| 685 |
|
| 686 |
|
| 687 |
@pytest.mark.parametrize("backend", AVAILABLE_PROVIDERS.keys()) |
| 688 |
@pytest.mark.parametrize( |
| 689 |
"strategy", [st.integers(), st.text(), st.floats(), st.booleans(), st.binary()] |
| 690 |
) |
| 691 |
def test_can_generate_from_all_available_providers(backend, strategy): |
| 692 |
# note: database=InMemoryExampleDatabase() is for compatibility with HypoFuzz |
| 693 |
# here. |
| 694 |
@given(strategy) |
| 695 |
@settings(backend=backend, database=InMemoryExampleDatabase()) |
| 696 |
def f(x): |
| 697 |
raise ValueError |
| 698 |
|
| 699 |
with ( |
| 700 |
pytest.raises(ValueError), |
| 701 |
( |
| 702 |
pytest.warns( |
| 703 |
HypothesisWarning, match="/dev/urandom is not available on windows" |
| 704 |
) |
| 705 |
if backend == "hypothesis-urandom" and WINDOWS |
| 706 |
else nullcontext() |
| 707 |
), |
| 708 |
): |
| 709 |
f() |
| 710 |
|
| 711 |
|
| 712 |
def test_saves_on_fatal_error_with_backend(): |
| 713 |
with temp_register_backend("trivial", TrivialProvider): |
| 714 |
db = InMemoryExampleDatabase() |
| 715 |
|
| 716 |
@given(st.integers()) |
| 717 |
@settings(backend="trivial", database=db) |
| 718 |
def test_function(n): |
| 719 |
raise BaseException("marker") |
| 720 |
|
| 721 |
with pytest.raises(BaseException, match="marker"): |
| 722 |
test_function() |
| 723 |
|
| 724 |
assert len(db.data) == 1 |
| 725 |
|
| 726 |
|
| 727 |
class SoundnessTestProvider(TrivialProvider): |
| 728 |
def __init__(self, conjecturedata): |
| 729 |
super().__init__(conjecturedata) |
| 730 |
self.n = 0 |
| 731 |
|
| 732 |
def draw_integer(self, **constraints): |
| 733 |
self.n += 1 |
| 734 |
if self.n == 1: |
| 735 |
return 1 |
| 736 |
|
| 737 |
raise BackendCannotProceed("verified") |
| 738 |
|
| 739 |
|
| 740 |
def test_raising_verified_after_failure_is_sound(): |
| 741 |
# see https://github.com/pschanely/hypothesis-crosshair/issues/31#issuecomment-2852940574 |
| 742 |
|
| 743 |
with temp_register_backend("soundness_test", SoundnessTestProvider): |
| 744 |
|
| 745 |
@given(st.integers()) |
| 746 |
@settings(backend="soundness_test", database=None) |
| 747 |
def f(n): |
| 748 |
assert n != 1 |
| 749 |
|
| 750 |
with pytest.raises(AssertionError) as e: |
| 751 |
f() |
| 752 |
# full message as of writing: "backend='soundness_test' claimed to |
| 753 |
# verify this test passes - please send them a bug report!" |
| 754 |
assert all("backend" not in note for note in e.value.__notes__) |
| 755 |
|
| 756 |
|
| 757 |
def test_replay_choices(): |
| 758 |
# trivial covering test |
| 759 |
provider = TrivialProvider(None) |
| 760 |
provider.replay_choices([1]) |
| 761 |
|
| 762 |
|
| 763 |
class ObservationProvider(TrivialProvider): |
| 764 |
add_observability_callback = True |
| 765 |
|
| 766 |
def __init__(self, conjecturedata: "ConjectureData", /) -> None: |
| 767 |
super().__init__(conjecturedata) |
| 768 |
# calls to per_test_case_context_manager and on_observation alternate, |
| 769 |
# starting with per_test_case_context_manager |
| 770 |
self.expected = "per_test_case_context_manager" |
| 771 |
|
| 772 |
@contextmanager |
| 773 |
def per_test_case_context_manager(self): |
| 774 |
assert self.expected == "per_test_case_context_manager" |
| 775 |
self.expected = "on_observation" |
| 776 |
yield |
| 777 |
|
| 778 |
def on_observation(self, observation: Observation) -> None: |
| 779 |
assert self.expected == "on_observation" |
| 780 |
self.expected = "per_test_case_context_manager" |
| 781 |
|
| 782 |
|
| 783 |
@temp_register_backend("observation", ObservationProvider) |
| 784 |
def test_on_observation_alternates(): |
| 785 |
@given(st.integers()) |
| 786 |
@settings(backend="observation") |
| 787 |
def f(n): |
| 788 |
pass |
| 789 |
|
| 790 |
f() |
| 791 |
|
| 792 |
|
| 793 |
@temp_register_backend("observation", ObservationProvider) |
| 794 |
def test_on_observation_alternates_on_failure(): |
| 795 |
@given(st.integers()) |
| 796 |
@settings(backend="observation") |
| 797 |
def f(n): |
| 798 |
# Hypothesis tries n == 0 first, and if that fails then we don't exercise |
| 799 |
# any provider-specific paths. |
| 800 |
if n == 1: |
| 801 |
raise ValueError("unique identifier") |
| 802 |
|
| 803 |
with pytest.raises(ValueError, match="unique identifier"): |
| 804 |
f() |
| 805 |
|
| 806 |
|
| 807 |
@temp_register_backend("observation", TrivialProvider) |
| 808 |
def test_on_observation_no_override(): |
| 809 |
@given(st.integers()) |
| 810 |
@settings(backend="observation") |
| 811 |
def f(n): |
| 812 |
assert _callbacks == {} |
| 813 |
|
| 814 |
f() |
| 815 |
|
| 816 |
|
| 817 |
@pytest.mark.parametrize("provider", [HypothesisProvider, PrngProvider]) |
| 818 |
def test_provider_conformance(provider): |
| 819 |
with warnings.catch_warnings(): |
| 820 |
# emitted by available_timezones() from st.timezone_keys() on 3.11+ |
| 821 |
# with tzdata installed. see https://github.com/python/cpython/issues/137841. |
| 822 |
# Once cpython fixes this, we can remove this. |
| 823 |
if sys.version_info >= (3, 11): |
| 824 |
warnings.simplefilter("ignore", EncodingWarning) |
| 825 |
run_conformance_test( |
| 826 |
provider, settings=settings(max_examples=20, stateful_step_count=20) |
| 827 |
) |
| 828 |
|
| 829 |
|
| 830 |
# see https://github.com/HypothesisWorks/hypothesis/issues/4462 and discussion |
| 831 |
# in https://github.com/HypothesisWorks/hypothesis/pull/4470 |
| 832 |
def test_backend_deadline_exceeded_raised_as_flaky_backend_failure(): |
| 833 |
with temp_register_backend("trivial", TrivialProvider): |
| 834 |
|
| 835 |
@given(st.integers()) |
| 836 |
@settings(backend="trivial", database=None) |
| 837 |
def f(n): |
| 838 |
if isinstance(current_build_context().data.provider, TrivialProvider): |
| 839 |
time.sleep(1) |
| 840 |
|
| 841 |
with pytest.raises(FlakyBackendFailure): |
| 842 |
f() |
| 843 |
|
| 844 |
|
| 845 |
def test_backend_cannot_proceed_raises_on_invalid_scope(): |
| 846 |
with pytest.raises(InvalidArgument): |
| 847 |
BackendCannotProceed("not a valid scope") |