| 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 math |
| 12 |
import sys |
| 13 |
from collections.abc import Collection, Iterable, Sequence |
| 14 |
from typing import Any |
| 15 |
|
| 16 |
from hypothesis import ( |
| 17 |
HealthCheck, |
| 18 |
assume, |
| 19 |
note, |
| 20 |
settings as Settings, |
| 21 |
strategies as st, |
| 22 |
) |
| 23 |
from hypothesis.errors import BackendCannotProceed |
| 24 |
from hypothesis.internal.compat import batched |
| 25 |
from hypothesis.internal.conjecture.choice import ( |
| 26 |
ChoiceTypeT, |
| 27 |
choice_permitted, |
| 28 |
) |
| 29 |
from hypothesis.internal.conjecture.data import ConjectureData |
| 30 |
from hypothesis.internal.conjecture.providers import ( |
| 31 |
COLLECTION_DEFAULT_MAX_SIZE, |
| 32 |
HypothesisProvider, |
| 33 |
PrimitiveProvider, |
| 34 |
with_register_backend, |
| 35 |
) |
| 36 |
from hypothesis.internal.floats import SMALLEST_SUBNORMAL, sign_aware_lte |
| 37 |
from hypothesis.internal.intervalsets import IntervalSet |
| 38 |
from hypothesis.stateful import RuleBasedStateMachine, initialize, precondition, rule |
| 39 |
from hypothesis.strategies import DrawFn, SearchStrategy |
| 40 |
from hypothesis.strategies._internal.strings import OneCharStringStrategy, TextStrategy |
| 41 |
|
| 42 |
|
| 43 |
def build_intervals(intervals: list[int]) -> list[tuple[int, int]]: |
| 44 |
if len(intervals) % 2: |
| 45 |
intervals = intervals[:-1] |
| 46 |
intervals.sort() |
| 47 |
return list(batched(intervals, 2, strict=True)) |
| 48 |
|
| 49 |
|
| 50 |
def interval_lists( |
| 51 |
*, min_codepoint: int = 0, max_codepoint: int = sys.maxunicode, min_size: int = 0 |
| 52 |
) -> SearchStrategy[Iterable[Sequence[int]]]: |
| 53 |
return ( |
| 54 |
st.lists( |
| 55 |
st.integers(min_codepoint, max_codepoint), |
| 56 |
unique=True, |
| 57 |
min_size=min_size * 2, |
| 58 |
) |
| 59 |
.map(sorted) |
| 60 |
.map(build_intervals) |
| 61 |
) |
| 62 |
|
| 63 |
|
| 64 |
def intervals( |
| 65 |
*, min_codepoint: int = 0, max_codepoint: int = sys.maxunicode, min_size: int = 0 |
| 66 |
) -> SearchStrategy[IntervalSet]: |
| 67 |
return st.builds( |
| 68 |
IntervalSet, |
| 69 |
interval_lists( |
| 70 |
min_codepoint=min_codepoint, max_codepoint=max_codepoint, min_size=min_size |
| 71 |
), |
| 72 |
) |
| 73 |
|
| 74 |
|
| 75 |
@st.composite |
| 76 |
def integer_weights( |
| 77 |
draw: DrawFn, min_value: int | None = None, max_value: int | None = None |
| 78 |
) -> dict[int, float]: |
| 79 |
# Sampler doesn't play well with super small floats, so exclude them |
| 80 |
weights = draw( |
| 81 |
st.dictionaries( |
| 82 |
st.integers(min_value=min_value, max_value=max_value), |
| 83 |
st.floats(0.001, 1), |
| 84 |
min_size=1, |
| 85 |
max_size=255, |
| 86 |
) |
| 87 |
) |
| 88 |
# invalid to have a weighting that disallows all possibilities |
| 89 |
assume(sum(weights.values()) != 0) |
| 90 |
# re-normalize probabilities to sum to some arbitrary target < 1 |
| 91 |
target = draw(st.floats(0.001, 0.999)) |
| 92 |
factor = target / sum(weights.values()) |
| 93 |
weights = {k: v * factor for k, v in weights.items()} |
| 94 |
# float rounding error can cause this to fail. |
| 95 |
assume(0.001 <= sum(weights.values()) <= 0.999) |
| 96 |
return weights |
| 97 |
|
| 98 |
|
| 99 |
@st.composite |
| 100 |
def integer_constraints( |
| 101 |
draw, |
| 102 |
*, |
| 103 |
use_min_value=None, |
| 104 |
use_max_value=None, |
| 105 |
use_shrink_towards=None, |
| 106 |
use_weights=None, |
| 107 |
use_forced=False, |
| 108 |
): |
| 109 |
min_value = None |
| 110 |
max_value = None |
| 111 |
shrink_towards = 0 |
| 112 |
weights = None |
| 113 |
|
| 114 |
if use_min_value is None: |
| 115 |
use_min_value = draw(st.booleans()) |
| 116 |
if use_max_value is None: |
| 117 |
use_max_value = draw(st.booleans()) |
| 118 |
use_shrink_towards = draw(st.booleans()) |
| 119 |
if use_weights is None: |
| 120 |
use_weights = ( |
| 121 |
draw(st.booleans()) if (use_min_value and use_max_value) else False |
| 122 |
) |
| 123 |
|
| 124 |
# Invariants: |
| 125 |
# (1) min_value <= forced <= max_value |
| 126 |
# (2) sum(weights.values()) < 1 |
| 127 |
# (3) len(weights) <= 255 |
| 128 |
|
| 129 |
if use_shrink_towards: |
| 130 |
shrink_towards = draw(st.integers()) |
| 131 |
|
| 132 |
forced = draw(st.integers()) if use_forced else None |
| 133 |
if use_weights: |
| 134 |
assert use_max_value |
| 135 |
assert use_min_value |
| 136 |
|
| 137 |
min_value = draw(st.integers(max_value=forced)) |
| 138 |
min_val = max(min_value, forced) if forced is not None else min_value |
| 139 |
max_value = draw(st.integers(min_value=min_val)) |
| 140 |
|
| 141 |
weights = draw(integer_weights(min_value, max_value)) |
| 142 |
else: |
| 143 |
if use_min_value: |
| 144 |
min_value = draw(st.integers(max_value=forced)) |
| 145 |
if use_max_value: |
| 146 |
min_vals = [] |
| 147 |
if min_value is not None: |
| 148 |
min_vals.append(min_value) |
| 149 |
if forced is not None: |
| 150 |
min_vals.append(forced) |
| 151 |
min_val = max(min_vals) if min_vals else None |
| 152 |
max_value = draw(st.integers(min_value=min_val)) |
| 153 |
|
| 154 |
if forced is not None: |
| 155 |
assume((forced - shrink_towards).bit_length() < 128) |
| 156 |
|
| 157 |
return { |
| 158 |
"min_value": min_value, |
| 159 |
"max_value": max_value, |
| 160 |
"shrink_towards": shrink_towards, |
| 161 |
"weights": weights, |
| 162 |
"forced": forced, |
| 163 |
} |
| 164 |
|
| 165 |
|
| 166 |
@st.composite |
| 167 |
def _collection_constraints( |
| 168 |
draw: DrawFn, |
| 169 |
*, |
| 170 |
forced: Any | None, |
| 171 |
use_min_size: bool | None = None, |
| 172 |
use_max_size: bool | None = None, |
| 173 |
) -> dict[str, int]: |
| 174 |
min_size = 0 |
| 175 |
max_size = COLLECTION_DEFAULT_MAX_SIZE |
| 176 |
# collections are quite expensive in entropy. cap to avoid overruns. |
| 177 |
cap = 50 |
| 178 |
|
| 179 |
if use_min_size is None: |
| 180 |
use_min_size = draw(st.booleans()) |
| 181 |
if use_max_size is None: |
| 182 |
use_max_size = draw(st.booleans()) |
| 183 |
|
| 184 |
if use_min_size: |
| 185 |
min_size = draw( |
| 186 |
st.integers(0, min(len(forced), cap) if forced is not None else cap) |
| 187 |
) |
| 188 |
|
| 189 |
if use_max_size: |
| 190 |
max_size = draw( |
| 191 |
st.integers( |
| 192 |
min_value=min_size if forced is None else max(min_size, len(forced)) |
| 193 |
) |
| 194 |
) |
| 195 |
if forced is None: |
| 196 |
# cap to some reasonable max size to avoid overruns. |
| 197 |
max_size = min(max_size, min_size + 100) |
| 198 |
|
| 199 |
return {"min_size": min_size, "max_size": max_size} |
| 200 |
|
| 201 |
|
| 202 |
@st.composite |
| 203 |
def string_constraints( |
| 204 |
draw: DrawFn, |
| 205 |
*, |
| 206 |
use_min_size: bool | None = None, |
| 207 |
use_max_size: bool | None = None, |
| 208 |
use_forced: bool = False, |
| 209 |
) -> Any: |
| 210 |
interval_set = draw(intervals()) |
| 211 |
forced = ( |
| 212 |
draw(TextStrategy(OneCharStringStrategy(interval_set))) if use_forced else None |
| 213 |
) |
| 214 |
constraints = draw( |
| 215 |
_collection_constraints( |
| 216 |
forced=forced, use_min_size=use_min_size, use_max_size=use_max_size |
| 217 |
) |
| 218 |
) |
| 219 |
# if the intervalset is empty, then the min size must be zero, because the |
| 220 |
# only valid value is the empty string. |
| 221 |
if len(interval_set) == 0: |
| 222 |
constraints["min_size"] = 0 |
| 223 |
|
| 224 |
return {"intervals": interval_set, "forced": forced, **constraints} |
| 225 |
|
| 226 |
|
| 227 |
@st.composite |
| 228 |
def bytes_constraints( |
| 229 |
draw: DrawFn, |
| 230 |
*, |
| 231 |
use_min_size: bool | None = None, |
| 232 |
use_max_size: bool | None = None, |
| 233 |
use_forced: bool = False, |
| 234 |
) -> Any: |
| 235 |
forced = draw(st.binary()) if use_forced else None |
| 236 |
|
| 237 |
constraints = draw( |
| 238 |
_collection_constraints( |
| 239 |
forced=forced, use_min_size=use_min_size, use_max_size=use_max_size |
| 240 |
) |
| 241 |
) |
| 242 |
return {"forced": forced, **constraints} |
| 243 |
|
| 244 |
|
| 245 |
@st.composite |
| 246 |
def float_constraints( |
| 247 |
draw, |
| 248 |
*, |
| 249 |
use_min_value=None, |
| 250 |
use_max_value=None, |
| 251 |
use_forced=False, |
| 252 |
): |
| 253 |
if use_min_value is None: |
| 254 |
use_min_value = draw(st.booleans()) |
| 255 |
if use_max_value is None: |
| 256 |
use_max_value = draw(st.booleans()) |
| 257 |
|
| 258 |
forced = draw(st.floats()) if use_forced else None |
| 259 |
pivot = forced if (use_forced and not math.isnan(forced)) else None |
| 260 |
min_value = -math.inf |
| 261 |
max_value = math.inf |
| 262 |
smallest_nonzero_magnitude = SMALLEST_SUBNORMAL |
| 263 |
allow_nan = True if (use_forced and math.isnan(forced)) else draw(st.booleans()) |
| 264 |
|
| 265 |
if use_min_value: |
| 266 |
min_value = draw(st.floats(max_value=pivot, allow_nan=False)) |
| 267 |
|
| 268 |
if use_max_value: |
| 269 |
if pivot is None: |
| 270 |
min_val = min_value |
| 271 |
else: |
| 272 |
min_val = pivot if sign_aware_lte(min_value, pivot) else min_value |
| 273 |
max_value = draw(st.floats(min_value=min_val, allow_nan=False)) |
| 274 |
|
| 275 |
largest_magnitude = max(abs(min_value), abs(max_value)) |
| 276 |
# can't force something smaller than our smallest magnitude. |
| 277 |
if pivot is not None and pivot != 0.0: |
| 278 |
largest_magnitude = min(largest_magnitude, pivot) |
| 279 |
|
| 280 |
# avoid drawing from an empty range |
| 281 |
if largest_magnitude > 0: |
| 282 |
smallest_nonzero_magnitude = draw( |
| 283 |
st.floats( |
| 284 |
min_value=0, |
| 285 |
# smallest_nonzero_magnitude breaks internal clamper invariants if |
| 286 |
# it is allowed to be larger than the magnitude of {min, max}_value. |
| 287 |
# |
| 288 |
# Let's also be reasonable here; smallest_nonzero_magnitude is used |
| 289 |
# for subnormals, so we will never provide a number above 1 in practice. |
| 290 |
max_value=min(largest_magnitude, 1.0), |
| 291 |
exclude_min=True, |
| 292 |
) |
| 293 |
) |
| 294 |
|
| 295 |
assert sign_aware_lte(min_value, max_value) |
| 296 |
return { |
| 297 |
"min_value": min_value, |
| 298 |
"max_value": max_value, |
| 299 |
"forced": forced, |
| 300 |
"allow_nan": allow_nan, |
| 301 |
"smallest_nonzero_magnitude": smallest_nonzero_magnitude, |
| 302 |
} |
| 303 |
|
| 304 |
|
| 305 |
@st.composite |
| 306 |
def boolean_constraints(draw: DrawFn, *, use_forced: bool = False) -> Any: |
| 307 |
forced = draw(st.booleans()) if use_forced else None |
| 308 |
# avoid invalid forced combinations |
| 309 |
p = draw(st.floats(0, 1, exclude_min=forced is True, exclude_max=forced is False)) |
| 310 |
|
| 311 |
return {"p": p, "forced": forced} |
| 312 |
|
| 313 |
|
| 314 |
def constraints_strategy(choice_type, strategy_constraints=None, *, use_forced=False): |
| 315 |
strategy = { |
| 316 |
"boolean": boolean_constraints, |
| 317 |
"integer": integer_constraints, |
| 318 |
"float": float_constraints, |
| 319 |
"bytes": bytes_constraints, |
| 320 |
"string": string_constraints, |
| 321 |
}[choice_type] |
| 322 |
if strategy_constraints is None: |
| 323 |
strategy_constraints = {} |
| 324 |
return strategy(**strategy_constraints.get(choice_type, {}), use_forced=use_forced) |
| 325 |
|
| 326 |
|
| 327 |
def choice_types_constraints(strategy_constraints=None, *, use_forced=False): |
| 328 |
options: list[ChoiceTypeT] = ["boolean", "integer", "float", "bytes", "string"] |
| 329 |
return st.one_of( |
| 330 |
st.tuples( |
| 331 |
st.just(name), |
| 332 |
constraints_strategy(name, strategy_constraints, use_forced=use_forced), |
| 333 |
) |
| 334 |
for name in options |
| 335 |
) |
| 336 |
|
| 337 |
|
| 338 |
def run_conformance_test( |
| 339 |
Provider: type[PrimitiveProvider], |
| 340 |
*, |
| 341 |
context_manager_exceptions: Collection[type[BaseException]] = (), |
| 342 |
settings: Settings | None = None, |
| 343 |
_realize_objects: SearchStrategy[Any] = ( |
| 344 |
st.from_type(object) | st.from_type(type).flatmap(st.from_type) |
| 345 |
), |
| 346 |
) -> None: |
| 347 |
""" |
| 348 |
Test that the given ``Provider`` class conforms to the |PrimitiveProvider| |
| 349 |
interface. |
| 350 |
|
| 351 |
For instance, this tests that ``Provider`` does not return out of bounds |
| 352 |
choices from any of the ``draw_*`` methods, or violate other invariants |
| 353 |
which Hypothesis depends on. |
| 354 |
|
| 355 |
This function is intended to be called at test-time, not at runtime. It is |
| 356 |
provided by Hypothesis to make it easy for third-party backend authors to |
| 357 |
test their provider. Backend authors wishing to test their provider should |
| 358 |
include a test similar to the following in their test suite: |
| 359 |
|
| 360 |
.. code-block:: python |
| 361 |
|
| 362 |
from hypothesis.internal.conjecture.provider_conformance import run_conformance_test |
| 363 |
|
| 364 |
def test_conformance(): |
| 365 |
run_conformance_test(MyProvider) |
| 366 |
|
| 367 |
If your provider can raise control flow exceptions inside one of the five |
| 368 |
``draw_*`` methods that are handled by your provider's |
| 369 |
``per_test_case_context_manager``, pass a list of these exceptions types to |
| 370 |
``context_manager_exceptions``. Otherwise, ``run_conformance_test`` will |
| 371 |
treat those exceptions as fatal errors. |
| 372 |
""" |
| 373 |
|
| 374 |
class CopiesRealizationProvider(HypothesisProvider): |
| 375 |
avoid_realization = Provider.avoid_realization |
| 376 |
|
| 377 |
with with_register_backend("copies_realization", CopiesRealizationProvider): |
| 378 |
|
| 379 |
@Settings( |
| 380 |
settings, |
| 381 |
suppress_health_check=[HealthCheck.too_slow], |
| 382 |
backend="copies_realization", |
| 383 |
) |
| 384 |
class ProviderConformanceTest(RuleBasedStateMachine): |
| 385 |
def __init__(self): |
| 386 |
super().__init__() |
| 387 |
|
| 388 |
@initialize(random=st.randoms()) |
| 389 |
def setup(self, random): |
| 390 |
if Provider.lifetime == "test_case": |
| 391 |
data = ConjectureData(random=random, provider=Provider) |
| 392 |
self.provider = data.provider |
| 393 |
else: |
| 394 |
self.provider = Provider(None) |
| 395 |
|
| 396 |
self.context_manager = self.provider.per_test_case_context_manager() |
| 397 |
self.context_manager.__enter__() |
| 398 |
self.frozen = False |
| 399 |
|
| 400 |
def _draw(self, choice_type, constraints): |
| 401 |
del constraints["forced"] |
| 402 |
draw_func = getattr(self.provider, f"draw_{choice_type}") |
| 403 |
|
| 404 |
try: |
| 405 |
choice = draw_func(**constraints) |
| 406 |
note(f"drew {choice_type} {choice}") |
| 407 |
expected_type = { |
| 408 |
"integer": int, |
| 409 |
"float": float, |
| 410 |
"bytes": bytes, |
| 411 |
"string": str, |
| 412 |
"boolean": bool, |
| 413 |
}[choice_type] |
| 414 |
assert isinstance(choice, expected_type) |
| 415 |
assert choice_permitted(choice, constraints) |
| 416 |
except context_manager_exceptions as e: |
| 417 |
note( |
| 418 |
f"caught exception {type(e)} in context_manager_exceptions: {e}" |
| 419 |
) |
| 420 |
try: |
| 421 |
self.context_manager.__exit__(type(e), e, None) |
| 422 |
except BackendCannotProceed: |
| 423 |
self.frozen = True |
| 424 |
return None |
| 425 |
|
| 426 |
return choice |
| 427 |
|
| 428 |
@precondition(lambda self: not self.frozen) |
| 429 |
@rule(constraints=integer_constraints()) |
| 430 |
def draw_integer(self, constraints): |
| 431 |
self._draw("integer", constraints) |
| 432 |
|
| 433 |
@precondition(lambda self: not self.frozen) |
| 434 |
@rule(constraints=float_constraints()) |
| 435 |
def draw_float(self, constraints): |
| 436 |
self._draw("float", constraints) |
| 437 |
|
| 438 |
@precondition(lambda self: not self.frozen) |
| 439 |
@rule(constraints=bytes_constraints()) |
| 440 |
def draw_bytes(self, constraints): |
| 441 |
self._draw("bytes", constraints) |
| 442 |
|
| 443 |
@precondition(lambda self: not self.frozen) |
| 444 |
@rule(constraints=string_constraints()) |
| 445 |
def draw_string(self, constraints): |
| 446 |
self._draw("string", constraints) |
| 447 |
|
| 448 |
@precondition(lambda self: not self.frozen) |
| 449 |
@rule(constraints=boolean_constraints()) |
| 450 |
def draw_boolean(self, constraints): |
| 451 |
self._draw("boolean", constraints) |
| 452 |
|
| 453 |
@precondition(lambda self: not self.frozen) |
| 454 |
@rule(label=st.integers()) |
| 455 |
def span_start(self, label): |
| 456 |
self.provider.span_start(label) |
| 457 |
|
| 458 |
@precondition(lambda self: not self.frozen) |
| 459 |
@rule(discard=st.booleans()) |
| 460 |
def span_end(self, discard): |
| 461 |
self.provider.span_end(discard) |
| 462 |
|
| 463 |
@precondition(lambda self: not self.frozen) |
| 464 |
@rule() |
| 465 |
def freeze(self): |
| 466 |
# phase-transition, mimicking data.freeze() at the end of a test case. |
| 467 |
self.frozen = True |
| 468 |
self.context_manager.__exit__(None, None, None) |
| 469 |
|
| 470 |
@precondition(lambda self: self.frozen) |
| 471 |
@rule(value=_realize_objects) |
| 472 |
def realize(self, value): |
| 473 |
# filter out nans and weirder things |
| 474 |
try: |
| 475 |
assume(value == value) |
| 476 |
except Exception: |
| 477 |
# e.g. value = Decimal('-sNaN') |
| 478 |
assume(False) |
| 479 |
|
| 480 |
# if `value` is non-symbolic, the provider should return it as-is. |
| 481 |
assert self.provider.realize(value) == value |
| 482 |
|
| 483 |
@precondition(lambda self: self.frozen) |
| 484 |
@rule() |
| 485 |
def observe_test_case(self): |
| 486 |
observations = self.provider.observe_test_case() |
| 487 |
assert isinstance(observations, dict) |
| 488 |
|
| 489 |
@precondition(lambda self: self.frozen) |
| 490 |
@rule(lifetime=st.sampled_from(["test_function", "test_case"])) |
| 491 |
def observe_information_messages(self, lifetime): |
| 492 |
observations = self.provider.observe_information_messages( |
| 493 |
lifetime=lifetime |
| 494 |
) |
| 495 |
for observation in observations: |
| 496 |
assert isinstance(observation, dict) |
| 497 |
|
| 498 |
def teardown(self): |
| 499 |
if not self.frozen: |
| 500 |
self.context_manager.__exit__(None, None, None) |
| 501 |
|
| 502 |
ProviderConformanceTest.TestCase().runTest() |