| 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 |
"""This module provides support for a stateful style of testing, where tests |
| 12 |
attempt to find a sequence of operations that cause a breakage rather than just |
| 13 |
a single value. |
| 14 |
|
| 15 |
Notably, the set of steps available at any point may depend on the |
| 16 |
execution to date. |
| 17 |
""" |
| 18 |
|
| 19 |
import collections |
| 20 |
import dataclasses |
| 21 |
import inspect |
| 22 |
from collections.abc import Callable, Iterable, Sequence |
| 23 |
from dataclasses import dataclass, field |
| 24 |
from functools import lru_cache |
| 25 |
from io import StringIO |
| 26 |
from time import perf_counter |
| 27 |
from typing import Any, ClassVar, TypeVar, overload |
| 28 |
from unittest import TestCase |
| 29 |
|
| 30 |
from hypothesis import strategies as st |
| 31 |
from hypothesis._settings import HealthCheck, Verbosity, settings as Settings |
| 32 |
from hypothesis.control import _current_build_context, current_build_context |
| 33 |
from hypothesis.core import TestFunc, given |
| 34 |
from hypothesis.errors import ( |
| 35 |
FlakyStrategyDefinition, |
| 36 |
InvalidArgument, |
| 37 |
InvalidDefinition, |
| 38 |
) |
| 39 |
from hypothesis.internal.compat import add_note, batched |
| 40 |
from hypothesis.internal.conjecture.engine import BUFFER_SIZE |
| 41 |
from hypothesis.internal.conjecture.junkdrawer import gc_cumulative_time |
| 42 |
from hypothesis.internal.conjecture.utils import calc_label_from_name |
| 43 |
from hypothesis.internal.healthcheck import fail_health_check |
| 44 |
from hypothesis.internal.observability import observability_enabled |
| 45 |
from hypothesis.internal.reflection import ( |
| 46 |
function_digest, |
| 47 |
get_pretty_function_description, |
| 48 |
nicerepr, |
| 49 |
proxies, |
| 50 |
) |
| 51 |
from hypothesis.internal.validation import check_type |
| 52 |
from hypothesis.reporting import current_verbosity, report |
| 53 |
from hypothesis.strategies._internal.featureflags import FeatureStrategy |
| 54 |
from hypothesis.strategies._internal.strategies import ( |
| 55 |
Ex, |
| 56 |
OneOfStrategy, |
| 57 |
SearchStrategy, |
| 58 |
check_strategy, |
| 59 |
) |
| 60 |
from hypothesis.utils.deprecation import note_deprecation |
| 61 |
from hypothesis.vendor.pretty import RepresentationPrinter |
| 62 |
|
| 63 |
T = TypeVar("T") |
| 64 |
STATE_MACHINE_RUN_LABEL = calc_label_from_name("another state machine step") |
| 65 |
|
| 66 |
|
| 67 |
def _is_singleton(obj: object) -> bool: |
| 68 |
""" |
| 69 |
Returns True if two separately created instances of v will have the same id |
| 70 |
(due to interning). |
| 71 |
""" |
| 72 |
# The range [-5, 256] is a cpython implementation detail. This may not work |
| 73 |
# well on other platforms. |
| 74 |
if isinstance(obj, int) and -5 <= obj <= 256: |
| 75 |
return True |
| 76 |
# cpython also interns compile-time strings, but let's just ignore those for |
| 77 |
# now. |
| 78 |
return isinstance(obj, bool) or obj is None |
| 79 |
|
| 80 |
|
| 81 |
class _OmittedArgument: |
| 82 |
"""Sentinel class to prevent overlapping overloads in type hints. See comments |
| 83 |
above the overloads of @rule.""" |
| 84 |
|
| 85 |
|
| 86 |
class TestCaseProperty: # pragma: no cover |
| 87 |
def __get__(self, obj, typ=None): |
| 88 |
if obj is not None: |
| 89 |
typ = type(obj) |
| 90 |
return typ._to_test_case() |
| 91 |
|
| 92 |
def __set__(self, obj, value): |
| 93 |
raise AttributeError("Cannot set TestCase") |
| 94 |
|
| 95 |
def __delete__(self, obj): |
| 96 |
raise AttributeError("Cannot delete TestCase") |
| 97 |
|
| 98 |
|
| 99 |
def get_state_machine_test( |
| 100 |
state_machine_factory, *, settings=None, _min_steps=0, _flaky_state=None |
| 101 |
): |
| 102 |
# This function is split out from run_state_machine_as_test so that |
| 103 |
# HypoFuzz can get and call the test function directly. |
| 104 |
if settings is None: |
| 105 |
try: |
| 106 |
settings = state_machine_factory.TestCase.settings |
| 107 |
check_type(Settings, settings, "state_machine_factory.TestCase.settings") |
| 108 |
except AttributeError: |
| 109 |
settings = Settings(deadline=None, suppress_health_check=list(HealthCheck)) |
| 110 |
check_type(Settings, settings, "settings") |
| 111 |
check_type(int, _min_steps, "_min_steps") |
| 112 |
if _min_steps < 0: |
| 113 |
# Because settings can vary via e.g. profiles, settings.stateful_step_count |
| 114 |
# overrides this argument and we don't bother cross-validating. |
| 115 |
raise InvalidArgument(f"_min_steps={_min_steps} must be non-negative.") |
| 116 |
_flaky_state = _flaky_state or {} |
| 117 |
|
| 118 |
@settings |
| 119 |
@given(st.data()) |
| 120 |
def run_state_machine(data): |
| 121 |
cd = data.conjecture_data |
| 122 |
machine: RuleBasedStateMachine = state_machine_factory() |
| 123 |
check_type(RuleBasedStateMachine, machine, "state_machine_factory()") |
| 124 |
cd.hypothesis_runner = machine |
| 125 |
machine._observability_predicates = cd._observability_predicates # alias |
| 126 |
|
| 127 |
print_steps = ( |
| 128 |
current_build_context().is_final or current_verbosity() >= Verbosity.debug |
| 129 |
) |
| 130 |
cd._stateful_repr_parts = [] |
| 131 |
|
| 132 |
def output(s): |
| 133 |
if print_steps: |
| 134 |
report(s) |
| 135 |
if observability_enabled(): |
| 136 |
cd._stateful_repr_parts.append(s) |
| 137 |
|
| 138 |
try: |
| 139 |
output(f"state = {machine.__class__.__name__}()") |
| 140 |
machine.check_invariants(settings, output, cd._stateful_run_times) |
| 141 |
max_steps = settings.stateful_step_count |
| 142 |
steps_run = 0 |
| 143 |
|
| 144 |
while True: |
| 145 |
# We basically always want to run the maximum number of steps, |
| 146 |
# but need to leave a small probability of terminating early |
| 147 |
# in order to allow for reducing the number of steps once we |
| 148 |
# find a failing test case, so we stop with probability of |
| 149 |
# 2 ** -16 during normal operation but force a stop when we've |
| 150 |
# generated enough steps. |
| 151 |
cd.start_span(STATE_MACHINE_RUN_LABEL) |
| 152 |
must_stop = None |
| 153 |
if steps_run >= max_steps: |
| 154 |
must_stop = True |
| 155 |
elif steps_run <= _min_steps: |
| 156 |
must_stop = False |
| 157 |
elif cd.length > (0.8 * BUFFER_SIZE): |
| 158 |
# Better to stop after fewer steps, than always overrun and retry. |
| 159 |
# See https://github.com/HypothesisWorks/hypothesis/issues/3618 |
| 160 |
must_stop = True |
| 161 |
|
| 162 |
start_draw = perf_counter() |
| 163 |
start_gc = gc_cumulative_time() |
| 164 |
if cd.draw_boolean(p=2**-16, forced=must_stop): |
| 165 |
break |
| 166 |
steps_run += 1 |
| 167 |
|
| 168 |
# Choose a rule to run, preferring an initialize rule if there are |
| 169 |
# any which have not been run yet. |
| 170 |
_flaky_state["selecting_rule"] = True |
| 171 |
if machine._initialize_rules_to_run: |
| 172 |
init_rules = [ |
| 173 |
st.tuples(st.just(rule), st.fixed_dictionaries(rule.arguments)) |
| 174 |
for rule in machine._initialize_rules_to_run |
| 175 |
] |
| 176 |
rule, data = cd.draw(st.one_of(init_rules)) |
| 177 |
machine._initialize_rules_to_run.remove(rule) |
| 178 |
else: |
| 179 |
rule, data = cd.draw(machine._rules_strategy) |
| 180 |
_flaky_state["selecting_rule"] = False |
| 181 |
draw_label = f"generate:rule:{rule.function.__name__}" |
| 182 |
cd.draw_times.setdefault(draw_label, 0.0) |
| 183 |
in_gctime = gc_cumulative_time() - start_gc |
| 184 |
cd.draw_times[draw_label] += perf_counter() - start_draw - in_gctime |
| 185 |
|
| 186 |
# Pretty-print the values this rule was called with *before* calling |
| 187 |
# _add_results_to_targets, to avoid printing arguments which are also |
| 188 |
# a return value using the variable name they are assigned to. |
| 189 |
# See https://github.com/HypothesisWorks/hypothesis/issues/2341 |
| 190 |
if print_steps or observability_enabled(): |
| 191 |
data_to_print = { |
| 192 |
k: machine._pretty_print(v) for k, v in data.items() |
| 193 |
} |
| 194 |
|
| 195 |
# Assign 'result' here in case executing the rule fails below |
| 196 |
result = multiple() |
| 197 |
try: |
| 198 |
data = dict(data) |
| 199 |
for k, v in list(data.items()): |
| 200 |
if isinstance(v, VarReference): |
| 201 |
data[k] = machine.names_to_values[v.name] |
| 202 |
elif isinstance(v, list) and all( |
| 203 |
isinstance(item, VarReference) for item in v |
| 204 |
): |
| 205 |
data[k] = [machine.names_to_values[item.name] for item in v] |
| 206 |
|
| 207 |
label = f"execute:rule:{rule.function.__name__}" |
| 208 |
start = perf_counter() |
| 209 |
start_gc = gc_cumulative_time() |
| 210 |
result = rule.function(machine, **data) |
| 211 |
in_gctime = gc_cumulative_time() - start_gc |
| 212 |
cd._stateful_run_times[label] += perf_counter() - start - in_gctime |
| 213 |
|
| 214 |
if rule.targets: |
| 215 |
if isinstance(result, MultipleResults): |
| 216 |
machine._add_results_to_targets(rule.targets, result.values) |
| 217 |
else: |
| 218 |
machine._add_results_to_targets(rule.targets, [result]) |
| 219 |
elif result is not None: |
| 220 |
fail_health_check( |
| 221 |
settings, |
| 222 |
"Rules should return None if they have no target bundle, " |
| 223 |
f"but {rule.function.__qualname__} returned {result!r}", |
| 224 |
HealthCheck.return_value, |
| 225 |
) |
| 226 |
finally: |
| 227 |
if print_steps or observability_enabled(): |
| 228 |
# 'result' is only used if the step has target bundles. |
| 229 |
# If it does, and the result is a 'MultipleResult', |
| 230 |
# then 'print_step' prints a multi-variable assignment. |
| 231 |
output(machine._repr_step(rule, data_to_print, result)) |
| 232 |
machine.check_invariants(settings, output, cd._stateful_run_times) |
| 233 |
cd.stop_span() |
| 234 |
finally: |
| 235 |
output("state.teardown()") |
| 236 |
machine.teardown() |
| 237 |
|
| 238 |
# Use a machine digest to identify stateful tests in the example database |
| 239 |
run_state_machine.hypothesis.inner_test._hypothesis_internal_add_digest = ( |
| 240 |
function_digest(state_machine_factory) |
| 241 |
) |
| 242 |
# Copy some attributes so @seed and @reproduce_failure "just work" |
| 243 |
run_state_machine._hypothesis_internal_use_seed = getattr( |
| 244 |
state_machine_factory, "_hypothesis_internal_use_seed", None |
| 245 |
) |
| 246 |
run_state_machine._hypothesis_internal_use_reproduce_failure = getattr( |
| 247 |
state_machine_factory, "_hypothesis_internal_use_reproduce_failure", None |
| 248 |
) |
| 249 |
run_state_machine._hypothesis_internal_print_given_args = False |
| 250 |
return run_state_machine |
| 251 |
|
| 252 |
|
| 253 |
def run_state_machine_as_test(state_machine_factory, *, settings=None, _min_steps=0): |
| 254 |
"""Run a state machine definition as a test, either silently doing nothing |
| 255 |
or printing a minimal breaking program and raising an exception. |
| 256 |
|
| 257 |
state_machine_factory is anything which returns an instance of |
| 258 |
RuleBasedStateMachine when called with no arguments - it can be a class or a |
| 259 |
function. settings will be used to control the execution of the test. |
| 260 |
""" |
| 261 |
flaky_state = {"selecting_rule": False} |
| 262 |
state_machine_test = get_state_machine_test( |
| 263 |
state_machine_factory, |
| 264 |
settings=settings, |
| 265 |
_min_steps=_min_steps, |
| 266 |
_flaky_state=flaky_state, |
| 267 |
) |
| 268 |
try: |
| 269 |
state_machine_test() |
| 270 |
except FlakyStrategyDefinition as err: |
| 271 |
if flaky_state["selecting_rule"]: |
| 272 |
add_note( |
| 273 |
err, |
| 274 |
"while selecting a rule to run. This is usually caused by " |
| 275 |
"a flaky precondition, or a bundle that was unexpectedly empty.", |
| 276 |
) |
| 277 |
raise |
| 278 |
|
| 279 |
|
| 280 |
class StateMachineMeta(type): |
| 281 |
def __setattr__(cls, name, value): |
| 282 |
if name == "settings" and isinstance(value, Settings): |
| 283 |
descr = f"settings({value.show_changed()})" |
| 284 |
raise AttributeError( |
| 285 |
f"Assigning {cls.__name__}.settings = {descr} does nothing. Assign " |
| 286 |
f"to {cls.__name__}.TestCase.settings, or use @{descr} as a decorator " |
| 287 |
f"on the {cls.__name__} class." |
| 288 |
) |
| 289 |
return super().__setattr__(name, value) |
| 290 |
|
| 291 |
|
| 292 |
@dataclass(slots=True, frozen=True) |
| 293 |
class _SetupState: |
| 294 |
rules: list["Rule"] |
| 295 |
invariants: list["Invariant"] |
| 296 |
initializers: list["Rule"] |
| 297 |
|
| 298 |
|
| 299 |
class RuleBasedStateMachine(metaclass=StateMachineMeta): |
| 300 |
"""A RuleBasedStateMachine gives you a structured way to define state machines. |
| 301 |
|
| 302 |
The idea is that a state machine carries the system under test and some supporting |
| 303 |
data. This data can be stored in instance variables or |
| 304 |
divided into Bundles. The state machine has a set of rules which may read data |
| 305 |
from bundles (or just from normal strategies), push data onto |
| 306 |
bundles, change the state of the machine, or verify properties. |
| 307 |
At any given point a random applicable rule will be executed. |
| 308 |
""" |
| 309 |
|
| 310 |
_setup_state_per_class: ClassVar[dict[type, _SetupState]] = {} |
| 311 |
|
| 312 |
def __init__(self) -> None: |
| 313 |
setup_state = self.setup_state() |
| 314 |
if not setup_state.rules: |
| 315 |
raise InvalidDefinition( |
| 316 |
f"State machine {type(self).__name__} defines no rules" |
| 317 |
) |
| 318 |
|
| 319 |
if isinstance(s := vars(type(self)).get("settings"), Settings): |
| 320 |
tname = type(self).__name__ |
| 321 |
descr = f"settings({s.show_changed()})" |
| 322 |
raise InvalidDefinition( |
| 323 |
f"Assigning settings = {descr} as a class attribute does nothing. " |
| 324 |
f"Assign to {tname}.TestCase.settings, or use @{descr} as a decorator " |
| 325 |
f"on the {tname} class." |
| 326 |
) |
| 327 |
|
| 328 |
self.rules = setup_state.rules |
| 329 |
self.invariants = setup_state.invariants |
| 330 |
# copy since we pop from this as we run initialize rules. |
| 331 |
self._initialize_rules_to_run = setup_state.initializers.copy() |
| 332 |
|
| 333 |
self.bundles: dict[str, list] = {} |
| 334 |
self.names_counters: collections.Counter = collections.Counter() |
| 335 |
self.names_list: list[str] = [] |
| 336 |
self.names_to_values: dict[str, Any] = {} |
| 337 |
self.__stream = StringIO() |
| 338 |
self.__printer = RepresentationPrinter( |
| 339 |
self.__stream, context=_current_build_context.value |
| 340 |
) |
| 341 |
self._rules_strategy = RuleStrategy(self) |
| 342 |
|
| 343 |
def _pretty_print(self, value): |
| 344 |
if isinstance(value, VarReference): |
| 345 |
return value.name |
| 346 |
elif isinstance(value, list) and all( |
| 347 |
isinstance(item, VarReference) for item in value |
| 348 |
): |
| 349 |
return "[" + ", ".join([item.name for item in value]) + "]" |
| 350 |
self.__stream.seek(0) |
| 351 |
self.__stream.truncate(0) |
| 352 |
self.__printer.output_width = 0 |
| 353 |
self.__printer.buffer_width = 0 |
| 354 |
self.__printer.buffer.clear() |
| 355 |
self.__printer.pretty(value) |
| 356 |
self.__printer.flush() |
| 357 |
return self.__stream.getvalue() |
| 358 |
|
| 359 |
def __repr__(self): |
| 360 |
return f"{type(self).__name__}({nicerepr(self.bundles)})" |
| 361 |
|
| 362 |
def _new_name(self, target): |
| 363 |
result = f"{target}_{self.names_counters[target]}" |
| 364 |
self.names_counters[target] += 1 |
| 365 |
self.names_list.append(result) |
| 366 |
return result |
| 367 |
|
| 368 |
def _last_names(self, n: int) -> list[str]: |
| 369 |
len_ = len(self.names_list) |
| 370 |
assert len_ >= n |
| 371 |
return self.names_list[len_ - n :] |
| 372 |
|
| 373 |
def bundle(self, name): |
| 374 |
return self.bundles.setdefault(name, []) |
| 375 |
|
| 376 |
@classmethod |
| 377 |
def setup_state(cls): |
| 378 |
try: |
| 379 |
return cls._setup_state_per_class[cls] |
| 380 |
except KeyError: |
| 381 |
pass |
| 382 |
|
| 383 |
rules: list[Rule] = [] |
| 384 |
initializers: list[Rule] = [] |
| 385 |
invariants: list[Invariant] = [] |
| 386 |
|
| 387 |
for _name, f in inspect.getmembers(cls): |
| 388 |
rule = getattr(f, RULE_MARKER, None) |
| 389 |
initializer = getattr(f, INITIALIZE_RULE_MARKER, None) |
| 390 |
invariant = getattr(f, INVARIANT_MARKER, None) |
| 391 |
if rule is not None: |
| 392 |
rules.append(rule) |
| 393 |
if initializer is not None: |
| 394 |
initializers.append(initializer) |
| 395 |
if invariant is not None: |
| 396 |
invariants.append(invariant) |
| 397 |
|
| 398 |
if ( |
| 399 |
getattr(f, PRECONDITIONS_MARKER, None) is not None |
| 400 |
and rule is None |
| 401 |
and invariant is None |
| 402 |
): |
| 403 |
raise InvalidDefinition( |
| 404 |
f"{_rule_qualname(f)} has been decorated with @precondition, " |
| 405 |
"but not @rule (or @invariant), which is not allowed. A " |
| 406 |
"precondition must be combined with a rule or an invariant, " |
| 407 |
"since it has no effect alone." |
| 408 |
) |
| 409 |
|
| 410 |
state = _SetupState( |
| 411 |
rules=rules, initializers=initializers, invariants=invariants |
| 412 |
) |
| 413 |
cls._setup_state_per_class[cls] = state |
| 414 |
return state |
| 415 |
|
| 416 |
def _repr_step(self, rule: "Rule", data: Any, result: Any) -> str: |
| 417 |
output_assignment = "" |
| 418 |
extra_assignment_lines = [] |
| 419 |
if rule.targets: |
| 420 |
number_of_results = ( |
| 421 |
len(result.values) if isinstance(result, MultipleResults) else 1 |
| 422 |
) |
| 423 |
number_of_last_names = len(rule.targets) * number_of_results |
| 424 |
last_names = self._last_names(number_of_last_names) |
| 425 |
if isinstance(result, MultipleResults): |
| 426 |
if len(result.values) == 1: |
| 427 |
# len-1 tuples |
| 428 |
output_per_target = [f"({name},)" for name in last_names] |
| 429 |
output_assignment = " = ".join(output_per_target) + " = " |
| 430 |
elif result.values: |
| 431 |
# multiple values, multiple targets -- use the first target |
| 432 |
# for the assignment from function, and do the other target |
| 433 |
# assignments on separate lines |
| 434 |
names_per_target = list(batched(last_names, number_of_results)) |
| 435 |
first_target_output = ", ".join(names_per_target[0]) |
| 436 |
output_assignment = first_target_output + " = " |
| 437 |
for other_target_names in names_per_target[1:]: |
| 438 |
other_target_output = ", ".join(other_target_names) |
| 439 |
extra_assignment_lines.append( |
| 440 |
other_target_output + " = " + first_target_output |
| 441 |
) |
| 442 |
else: |
| 443 |
output_assignment = " = ".join(last_names) + " = " |
| 444 |
args = ", ".join(f"{k}={v}" for k, v in data.items()) |
| 445 |
output_line = f"{output_assignment}state.{rule.function.__name__}({args})" |
| 446 |
return "\n".join([output_line] + extra_assignment_lines) |
| 447 |
|
| 448 |
def _add_results_to_targets(self, targets, results): |
| 449 |
# Note, the assignment order here is reflected in _repr_step |
| 450 |
for target in targets: |
| 451 |
for result in results: |
| 452 |
name = self._new_name(target) |
| 453 |
|
| 454 |
def printer(obj, p, cycle, name=name): |
| 455 |
return p.text(name) |
| 456 |
|
| 457 |
# see |
| 458 |
# https://github.com/HypothesisWorks/hypothesis/pull/4266#discussion_r1949619102 |
| 459 |
if not _is_singleton(result): |
| 460 |
self.__printer.singleton_pprinters.setdefault(id(result), printer) |
| 461 |
self.names_to_values[name] = result |
| 462 |
self.bundles.setdefault(target, []).append(VarReference(name)) |
| 463 |
|
| 464 |
def check_invariants(self, settings, output, runtimes): |
| 465 |
for invar in self.invariants: |
| 466 |
if self._initialize_rules_to_run and not invar.check_during_init: |
| 467 |
continue |
| 468 |
if not all(precond(self) for precond in invar.preconditions): |
| 469 |
continue |
| 470 |
name = invar.function.__name__ |
| 471 |
if ( |
| 472 |
current_build_context().is_final |
| 473 |
or settings.verbosity >= Verbosity.debug |
| 474 |
or observability_enabled() |
| 475 |
): |
| 476 |
output(f"state.{name}()") |
| 477 |
start = perf_counter() |
| 478 |
result = invar.function(self) |
| 479 |
runtimes[f"execute:invariant:{name}"] += perf_counter() - start |
| 480 |
if result is not None: |
| 481 |
fail_health_check( |
| 482 |
settings, |
| 483 |
"The return value of an @invariant is always ignored, but " |
| 484 |
f"{invar.function.__qualname__} returned {result!r} " |
| 485 |
"instead of None", |
| 486 |
HealthCheck.return_value, |
| 487 |
) |
| 488 |
|
| 489 |
def teardown(self): |
| 490 |
"""Called after a run has finished executing to clean up any necessary |
| 491 |
state. |
| 492 |
|
| 493 |
Does nothing by default. |
| 494 |
""" |
| 495 |
|
| 496 |
TestCase = TestCaseProperty() |
| 497 |
|
| 498 |
@classmethod |
| 499 |
@lru_cache |
| 500 |
def _to_test_case(cls): |
| 501 |
class StateMachineTestCase(TestCase): |
| 502 |
settings = Settings(deadline=None, suppress_health_check=list(HealthCheck)) |
| 503 |
|
| 504 |
def runTest(self): |
| 505 |
run_state_machine_as_test(cls, settings=self.settings) |
| 506 |
|
| 507 |
runTest.is_hypothesis_test = True |
| 508 |
runTest._hypothesis_state_machine_class = cls |
| 509 |
|
| 510 |
StateMachineTestCase.__name__ = cls.__name__ + ".TestCase" |
| 511 |
StateMachineTestCase.__qualname__ = cls.__qualname__ + ".TestCase" |
| 512 |
return StateMachineTestCase |
| 513 |
|
| 514 |
|
| 515 |
@dataclass(slots=True, frozen=False) |
| 516 |
class Rule: |
| 517 |
targets: Any |
| 518 |
function: Any |
| 519 |
arguments: Any |
| 520 |
preconditions: Any |
| 521 |
bundles: tuple["Bundle", ...] = field(init=False) |
| 522 |
_cached_hash: int | None = field(init=False, default=None) |
| 523 |
_cached_repr: str | None = field(init=False, default=None) |
| 524 |
arguments_strategies: dict[Any, Any] = field(init=False, default_factory=dict) |
| 525 |
|
| 526 |
def __post_init__(self): |
| 527 |
bundles = [] |
| 528 |
for k, v in sorted(self.arguments.items()): |
| 529 |
assert not isinstance(v, BundleReferenceStrategy) |
| 530 |
if isinstance(v, Bundle): |
| 531 |
bundles.append(v) |
| 532 |
consume = isinstance(v, BundleConsumer) |
| 533 |
v = BundleReferenceStrategy(v.name, consume=consume) |
| 534 |
self.arguments_strategies[k] = v |
| 535 |
self.bundles = tuple(bundles) |
| 536 |
|
| 537 |
def __repr__(self) -> str: |
| 538 |
if self._cached_repr is None: |
| 539 |
bits = [ |
| 540 |
f"{field.name}=" |
| 541 |
f"{get_pretty_function_description(getattr(self, field.name))}" |
| 542 |
for field in dataclasses.fields(self) |
| 543 |
if getattr(self, field.name) |
| 544 |
] |
| 545 |
self._cached_repr = f"{self.__class__.__name__}({', '.join(bits)})" |
| 546 |
return self._cached_repr |
| 547 |
|
| 548 |
def __hash__(self): |
| 549 |
# sampled_from uses hash in calc_label, and we want this to be fast when |
| 550 |
# sampling stateful rules, so we cache here. |
| 551 |
if self._cached_hash is None: |
| 552 |
self._cached_hash = hash( |
| 553 |
( |
| 554 |
self.targets, |
| 555 |
self.function, |
| 556 |
tuple(self.arguments.items()), |
| 557 |
self.preconditions, |
| 558 |
self.bundles, |
| 559 |
) |
| 560 |
) |
| 561 |
return self._cached_hash |
| 562 |
|
| 563 |
|
| 564 |
self_strategy = st.runner() |
| 565 |
|
| 566 |
|
| 567 |
class BundleReferenceStrategy(SearchStrategy): |
| 568 |
def __init__(self, name: str, *, consume: bool = False): |
| 569 |
super().__init__() |
| 570 |
self.name = name |
| 571 |
self.consume = consume |
| 572 |
|
| 573 |
def do_draw(self, data): |
| 574 |
machine = data.draw(self_strategy) |
| 575 |
bundle = machine.bundle(self.name) |
| 576 |
if not bundle: |
| 577 |
data.mark_invalid(f"Cannot draw from empty bundle {self.name!r}") |
| 578 |
# Shrink towards the right rather than the left. This makes it easier |
| 579 |
# to delete data generated earlier, as when the error is towards the |
| 580 |
# end there can be a lot of hard to remove padding. |
| 581 |
position = data.draw_integer(0, len(bundle) - 1, shrink_towards=len(bundle)) |
| 582 |
if self.consume: |
| 583 |
return bundle.pop(position) # pragma: no cover # coverage is flaky here |
| 584 |
else: |
| 585 |
return bundle[position] |
| 586 |
|
| 587 |
|
| 588 |
class Bundle(SearchStrategy[Ex]): |
| 589 |
"""A collection of values for use in stateful testing. |
| 590 |
|
| 591 |
Bundles are a kind of strategy where values can be added by rules, |
| 592 |
and (like any strategy) used as inputs to future rules. |
| 593 |
|
| 594 |
The ``name`` argument they are passed is the they are referred to |
| 595 |
internally by the state machine; no two bundles may have |
| 596 |
the same name. It is idiomatic to use the attribute |
| 597 |
being assigned to as the name of the Bundle:: |
| 598 |
|
| 599 |
class MyStateMachine(RuleBasedStateMachine): |
| 600 |
keys = Bundle("keys") |
| 601 |
|
| 602 |
Bundles can contain the same value more than once; this becomes |
| 603 |
relevant when using :func:`~hypothesis.stateful.consumes` to remove |
| 604 |
values again. |
| 605 |
|
| 606 |
If the ``consume`` argument is set to True, then all values that are |
| 607 |
drawn from this bundle will be consumed (as above) when requested. |
| 608 |
""" |
| 609 |
|
| 610 |
def __init__( |
| 611 |
self, name: str, *, consume: bool = False, draw_references: bool = True |
| 612 |
) -> None: |
| 613 |
super().__init__() |
| 614 |
self.name = name |
| 615 |
self.__reference_strategy = BundleReferenceStrategy(name, consume=consume) |
| 616 |
self.draw_references = draw_references |
| 617 |
|
| 618 |
def do_draw(self, data): |
| 619 |
machine = data.draw(self_strategy) |
| 620 |
reference = data.draw(self.__reference_strategy) |
| 621 |
return machine.names_to_values[reference.name] |
| 622 |
|
| 623 |
def __repr__(self): |
| 624 |
consume = self.__reference_strategy.consume |
| 625 |
if consume is False: |
| 626 |
return f"Bundle(name={self.name!r})" |
| 627 |
return f"Bundle(name={self.name!r}, {consume=})" |
| 628 |
|
| 629 |
def calc_is_empty(self, recur): |
| 630 |
# We assume that a bundle will grow over time |
| 631 |
return False |
| 632 |
|
| 633 |
def is_currently_empty(self, data): |
| 634 |
# ``self_strategy`` is an instance of the ``st.runner()`` strategy. |
| 635 |
# Hence drawing from it only returns the current state machine without |
| 636 |
# modifying the underlying choice sequence. |
| 637 |
machine = data.draw(self_strategy) |
| 638 |
return not bool(machine.bundle(self.name)) |
| 639 |
|
| 640 |
def flatmap(self, expand): |
| 641 |
if self.draw_references: |
| 642 |
return type(self)( |
| 643 |
self.name, |
| 644 |
consume=self.__reference_strategy.consume, |
| 645 |
draw_references=False, |
| 646 |
).flatmap(expand) |
| 647 |
return super().flatmap(expand) |
| 648 |
|
| 649 |
def __hash__(self): |
| 650 |
# Making this hashable means we hit the fast path of "everything is |
| 651 |
# hashable" in st.sampled_from label calculation when sampling which rule |
| 652 |
# to invoke next. |
| 653 |
|
| 654 |
# Mix in "Bundle" for collision resistance |
| 655 |
return hash(("Bundle", self.name)) |
| 656 |
|
| 657 |
|
| 658 |
class BundleConsumer(Bundle[Ex]): |
| 659 |
def __init__(self, bundle: Bundle[Ex]) -> None: |
| 660 |
super().__init__(bundle.name, consume=True) |
| 661 |
|
| 662 |
|
| 663 |
def consumes(bundle: Bundle[Ex]) -> SearchStrategy[Ex]: |
| 664 |
"""When introducing a rule in a RuleBasedStateMachine, this function can |
| 665 |
be used to mark bundles from which each value used in a step with the |
| 666 |
given rule should be removed. This function returns a strategy object |
| 667 |
that can be manipulated and combined like any other. |
| 668 |
|
| 669 |
For example, a rule declared with |
| 670 |
|
| 671 |
``@rule(value1=b1, value2=consumes(b2), value3=lists(consumes(b3)))`` |
| 672 |
|
| 673 |
will consume a value from Bundle ``b2`` and several values from Bundle |
| 674 |
``b3`` to populate ``value2`` and ``value3`` each time it is executed. |
| 675 |
""" |
| 676 |
if not isinstance(bundle, Bundle): |
| 677 |
raise TypeError("Argument to be consumed must be a bundle.") |
| 678 |
return BundleConsumer(bundle) |
| 679 |
|
| 680 |
|
| 681 |
@dataclass(slots=True, frozen=True) |
| 682 |
class MultipleResults(Iterable[Ex]): |
| 683 |
values: tuple[Ex, ...] |
| 684 |
|
| 685 |
def __iter__(self): |
| 686 |
return iter(self.values) |
| 687 |
|
| 688 |
|
| 689 |
def multiple(*args: T) -> MultipleResults[T]: |
| 690 |
"""This function can be used to pass multiple results to the target(s) of |
| 691 |
a rule. Just use ``return multiple(result1, result2, ...)`` in your rule. |
| 692 |
|
| 693 |
It is also possible to use ``return multiple()`` with no arguments in |
| 694 |
order to end a rule without passing any result. |
| 695 |
""" |
| 696 |
return MultipleResults(args) |
| 697 |
|
| 698 |
|
| 699 |
def _convert_targets(targets, target): |
| 700 |
"""Single validator and converter for target arguments.""" |
| 701 |
if target is not None: |
| 702 |
if targets: |
| 703 |
raise InvalidArgument( |
| 704 |
f"Passing both targets={targets!r} and target={target!r} is " |
| 705 |
f"redundant - pass targets={(*targets, target)!r} instead." |
| 706 |
) |
| 707 |
targets = (target,) |
| 708 |
|
| 709 |
converted_targets = [] |
| 710 |
for t in targets: |
| 711 |
if not isinstance(t, Bundle): |
| 712 |
msg = "Got invalid target %r of type %r, but all targets must be Bundles." |
| 713 |
if isinstance(t, OneOfStrategy): |
| 714 |
msg += ( |
| 715 |
"\nIt looks like you passed `one_of(a, b)` or `a | b` as " |
| 716 |
"a target. You should instead pass `targets=(a, b)` to " |
| 717 |
"add the return value of this rule to both the `a` and " |
| 718 |
"`b` bundles, or define a rule for each target if it " |
| 719 |
"should be added to exactly one." |
| 720 |
) |
| 721 |
raise InvalidArgument(msg % (t, type(t))) |
| 722 |
while isinstance(t, Bundle): |
| 723 |
if isinstance(t, BundleConsumer): |
| 724 |
note_deprecation( |
| 725 |
f"Using consumes({t.name}) doesn't makes sense in this context. " |
| 726 |
"This will be an error in a future version of Hypothesis.", |
| 727 |
since="2021-09-08", |
| 728 |
has_codemod=False, |
| 729 |
stacklevel=2, |
| 730 |
) |
| 731 |
t = t.name |
| 732 |
converted_targets.append(t) |
| 733 |
return tuple(converted_targets) |
| 734 |
|
| 735 |
|
| 736 |
RULE_MARKER = "hypothesis_stateful_rule" |
| 737 |
INITIALIZE_RULE_MARKER = "hypothesis_stateful_initialize_rule" |
| 738 |
PRECONDITIONS_MARKER = "hypothesis_stateful_preconditions" |
| 739 |
INVARIANT_MARKER = "hypothesis_stateful_invariant" |
| 740 |
|
| 741 |
|
| 742 |
_RuleType = Callable[..., MultipleResults[Ex] | Ex] |
| 743 |
_RuleWrapper = Callable[[_RuleType[Ex]], _RuleType[Ex]] |
| 744 |
|
| 745 |
|
| 746 |
def _rule_qualname(f: Any) -> str: |
| 747 |
# we define rules / invariants / initializes inside of wrapper functions, which |
| 748 |
# makes f.__qualname__ look like: |
| 749 |
# test_precondition.<locals>.BadStateMachine.has_precondition_but_no_rule |
| 750 |
# which is not ideal. This function returns just |
| 751 |
# BadStateMachine.has_precondition_but_no_rule |
| 752 |
# instead. |
| 753 |
return f.__qualname__.rsplit("<locals>.")[-1] |
| 754 |
|
| 755 |
|
| 756 |
# We cannot exclude `target` or `targets` from any of these signatures because |
| 757 |
# otherwise they would be matched against the `kwargs`, either leading to |
| 758 |
# overlapping overloads of incompatible return types, or a concrete |
| 759 |
# implementation that does not accept all overloaded variant signatures. |
| 760 |
# Although it is possible to reorder the variants to fix the former, it will |
| 761 |
# always lead to the latter, as then the omitted parameter could be typed as |
| 762 |
# a `SearchStrategy`, which the concrete implementation does not accept. |
| 763 |
# |
| 764 |
# Omitted `targets` parameters, where the default value is used, are typed with |
| 765 |
# a special `_OmittedArgument` type. We cannot type them as `tuple[()]`, because |
| 766 |
# `tuple[()]` is a subtype of `Sequence[Bundle[Ex]]`, leading to signature |
| 767 |
# overlaps with incompatible return types. The `_OmittedArgument` type will never be |
| 768 |
# encountered at runtime, and exists solely to annotate the default of `targets`. |
| 769 |
# PEP 661 (Sentinel Values) might provide a more elegant alternative in the future. |
| 770 |
# |
| 771 |
# We could've also annotated `targets` as `tuple[_OmittedArgument]`, but then when |
| 772 |
# both `target` and `targets` are provided, mypy describes the type error as an |
| 773 |
# invalid argument type for `targets` (expected `tuple[_OmittedArgument]`, got ...). |
| 774 |
# By annotating it as a bare `_OmittedArgument` type, mypy's error will warn that |
| 775 |
# there is no overloaded signature matching the call, which is more descriptive. |
| 776 |
# |
| 777 |
# When `target` xor `targets` is provided, the function to decorate must return |
| 778 |
# a value whose type matches the one stored in the bundle. When neither are |
| 779 |
# provided, the function to decorate must return nothing. There is no variant |
| 780 |
# for providing `target` and `targets`, as these parameters are mutually exclusive. |
| 781 |
@overload |
| 782 |
def rule( |
| 783 |
*, |
| 784 |
targets: Sequence[Bundle[Ex]], |
| 785 |
target: None = ..., |
| 786 |
**kwargs: SearchStrategy, |
| 787 |
) -> _RuleWrapper[Ex]: # pragma: no cover |
| 788 |
... |
| 789 |
|
| 790 |
|
| 791 |
@overload |
| 792 |
def rule( |
| 793 |
*, target: Bundle[Ex], targets: _OmittedArgument = ..., **kwargs: SearchStrategy |
| 794 |
) -> _RuleWrapper[Ex]: # pragma: no cover |
| 795 |
... |
| 796 |
|
| 797 |
|
| 798 |
@overload |
| 799 |
def rule( |
| 800 |
*, |
| 801 |
target: None = ..., |
| 802 |
targets: _OmittedArgument = ..., |
| 803 |
**kwargs: SearchStrategy, |
| 804 |
) -> Callable[[Callable[..., None]], Callable[..., None]]: # pragma: no cover |
| 805 |
... |
| 806 |
|
| 807 |
|
| 808 |
def rule( |
| 809 |
*, |
| 810 |
targets: Sequence[Bundle[Ex]] | _OmittedArgument = (), |
| 811 |
target: Bundle[Ex] | None = None, |
| 812 |
**kwargs: SearchStrategy, |
| 813 |
) -> _RuleWrapper[Ex] | Callable[[Callable[..., None]], Callable[..., None]]: |
| 814 |
"""Decorator for RuleBasedStateMachine. Any Bundle present in ``target`` or |
| 815 |
``targets`` will define where the end result of this function should go. If |
| 816 |
both are empty then the end result will be discarded. |
| 817 |
|
| 818 |
``target`` must be a Bundle, or if the result should be replicated to multiple |
| 819 |
bundles you can pass a tuple of them as the ``targets`` argument. |
| 820 |
It is invalid to use both arguments for a single rule. If the result |
| 821 |
should go to exactly one of several bundles, define a separate rule for |
| 822 |
each case. |
| 823 |
|
| 824 |
kwargs then define the arguments that will be passed to the function |
| 825 |
invocation. If their value is a Bundle, or if it is ``consumes(b)`` |
| 826 |
where ``b`` is a Bundle, then values that have previously been produced |
| 827 |
for that bundle will be provided. If ``consumes`` is used, the value |
| 828 |
will also be removed from the bundle. |
| 829 |
|
| 830 |
Any other kwargs should be strategies and values from them will be |
| 831 |
provided. |
| 832 |
""" |
| 833 |
converted_targets = _convert_targets(targets, target) |
| 834 |
for k, v in kwargs.items(): |
| 835 |
check_strategy(v, name=k) |
| 836 |
|
| 837 |
def accept(f): |
| 838 |
if getattr(f, INVARIANT_MARKER, None): |
| 839 |
raise InvalidDefinition( |
| 840 |
f"{_rule_qualname(f)} is used with both @rule and @invariant, " |
| 841 |
"which is not allowed. A function may be either a rule or an " |
| 842 |
"invariant, but not both." |
| 843 |
) |
| 844 |
existing_rule = getattr(f, RULE_MARKER, None) |
| 845 |
existing_initialize_rule = getattr(f, INITIALIZE_RULE_MARKER, None) |
| 846 |
if existing_rule is not None: |
| 847 |
raise InvalidDefinition( |
| 848 |
f"{_rule_qualname(f)} has been decorated with @rule twice, which is " |
| 849 |
"not allowed." |
| 850 |
) |
| 851 |
if existing_initialize_rule is not None: |
| 852 |
raise InvalidDefinition( |
| 853 |
f"{_rule_qualname(f)} has been decorated with both @rule and " |
| 854 |
"@initialize, which is not allowed." |
| 855 |
) |
| 856 |
|
| 857 |
preconditions = getattr(f, PRECONDITIONS_MARKER, ()) |
| 858 |
rule = Rule( |
| 859 |
targets=converted_targets, |
| 860 |
arguments=kwargs, |
| 861 |
function=f, |
| 862 |
preconditions=preconditions, |
| 863 |
) |
| 864 |
|
| 865 |
@proxies(f) |
| 866 |
def rule_wrapper(*args, **kwargs): |
| 867 |
return f(*args, **kwargs) |
| 868 |
|
| 869 |
setattr(rule_wrapper, RULE_MARKER, rule) |
| 870 |
return rule_wrapper |
| 871 |
|
| 872 |
return accept |
| 873 |
|
| 874 |
|
| 875 |
# See also comments of `rule`'s overloads. |
| 876 |
@overload |
| 877 |
def initialize( |
| 878 |
*, |
| 879 |
targets: Sequence[Bundle[Ex]], |
| 880 |
target: None = ..., |
| 881 |
**kwargs: SearchStrategy, |
| 882 |
) -> _RuleWrapper[Ex]: # pragma: no cover |
| 883 |
... |
| 884 |
|
| 885 |
|
| 886 |
@overload |
| 887 |
def initialize( |
| 888 |
*, target: Bundle[Ex], targets: _OmittedArgument = ..., **kwargs: SearchStrategy |
| 889 |
) -> _RuleWrapper[Ex]: # pragma: no cover |
| 890 |
... |
| 891 |
|
| 892 |
|
| 893 |
@overload |
| 894 |
def initialize( |
| 895 |
*, |
| 896 |
target: None = ..., |
| 897 |
targets: _OmittedArgument = ..., |
| 898 |
**kwargs: SearchStrategy, |
| 899 |
) -> Callable[[Callable[..., None]], Callable[..., None]]: # pragma: no cover |
| 900 |
... |
| 901 |
|
| 902 |
|
| 903 |
def initialize( |
| 904 |
*, |
| 905 |
targets: Sequence[Bundle[Ex]] | _OmittedArgument = (), |
| 906 |
target: Bundle[Ex] | None = None, |
| 907 |
**kwargs: SearchStrategy, |
| 908 |
) -> _RuleWrapper[Ex] | Callable[[Callable[..., None]], Callable[..., None]]: |
| 909 |
"""Decorator for RuleBasedStateMachine. |
| 910 |
|
| 911 |
An initialize decorator behaves like a rule, but all ``@initialize()`` decorated |
| 912 |
methods will be called before any ``@rule()`` decorated methods, in an arbitrary |
| 913 |
order. Each ``@initialize()`` method will be called exactly once per run, unless |
| 914 |
one raises an exception - after which only the ``.teardown()`` method will be run. |
| 915 |
``@initialize()`` methods may not have preconditions. |
| 916 |
""" |
| 917 |
converted_targets = _convert_targets(targets, target) |
| 918 |
for k, v in kwargs.items(): |
| 919 |
check_strategy(v, name=k) |
| 920 |
|
| 921 |
def accept(f): |
| 922 |
if getattr(f, INVARIANT_MARKER, None): |
| 923 |
raise InvalidDefinition( |
| 924 |
f"{_rule_qualname(f)} is used with both @initialize and @invariant, " |
| 925 |
"which is not allowed. A function may be either an initialization " |
| 926 |
"rule or an invariant, but not both." |
| 927 |
) |
| 928 |
existing_rule = getattr(f, RULE_MARKER, None) |
| 929 |
existing_initialize_rule = getattr(f, INITIALIZE_RULE_MARKER, None) |
| 930 |
if existing_rule is not None: |
| 931 |
raise InvalidDefinition( |
| 932 |
f"{_rule_qualname(f)} has been decorated with both @rule and " |
| 933 |
"@initialize, which is not allowed." |
| 934 |
) |
| 935 |
if existing_initialize_rule is not None: |
| 936 |
raise InvalidDefinition( |
| 937 |
f"{_rule_qualname(f)} has been decorated with @initialize twice, " |
| 938 |
"which is not allowed." |
| 939 |
) |
| 940 |
preconditions = getattr(f, PRECONDITIONS_MARKER, ()) |
| 941 |
if preconditions: |
| 942 |
raise InvalidDefinition( |
| 943 |
f"{_rule_qualname(f)} has been decorated with both @initialize and " |
| 944 |
"@precondition, which is not allowed. An initialization rule " |
| 945 |
"runs unconditionally and may not have a precondition." |
| 946 |
) |
| 947 |
rule = Rule( |
| 948 |
targets=converted_targets, |
| 949 |
arguments=kwargs, |
| 950 |
function=f, |
| 951 |
preconditions=preconditions, |
| 952 |
) |
| 953 |
|
| 954 |
@proxies(f) |
| 955 |
def rule_wrapper(*args, **kwargs): |
| 956 |
return f(*args, **kwargs) |
| 957 |
|
| 958 |
setattr(rule_wrapper, INITIALIZE_RULE_MARKER, rule) |
| 959 |
return rule_wrapper |
| 960 |
|
| 961 |
return accept |
| 962 |
|
| 963 |
|
| 964 |
@dataclass(slots=True, frozen=True) |
| 965 |
class VarReference: |
| 966 |
name: str |
| 967 |
|
| 968 |
|
| 969 |
# There are multiple alternatives for annotating the `precond` type, all of them |
| 970 |
# have drawbacks. See https://github.com/HypothesisWorks/hypothesis/pull/3068#issuecomment-906642371 |
| 971 |
def precondition(precond: Callable[[Any], bool]) -> Callable[[TestFunc], TestFunc]: |
| 972 |
"""Decorator to apply a precondition for rules in a RuleBasedStateMachine. |
| 973 |
Specifies a precondition for a rule to be considered as a valid step in the |
| 974 |
state machine, which is more efficient than using :func:`~hypothesis.assume` |
| 975 |
within the rule. The ``precond`` function will be called with the instance of |
| 976 |
RuleBasedStateMachine and should return True or False. Usually it will need |
| 977 |
to look at attributes on that instance. |
| 978 |
|
| 979 |
For example:: |
| 980 |
|
| 981 |
class MyTestMachine(RuleBasedStateMachine): |
| 982 |
state = 1 |
| 983 |
|
| 984 |
@precondition(lambda self: self.state != 0) |
| 985 |
@rule(numerator=integers()) |
| 986 |
def divide_with(self, numerator): |
| 987 |
self.state = numerator / self.state |
| 988 |
|
| 989 |
If multiple preconditions are applied to a single rule, it is only considered |
| 990 |
a valid step when all of them return True. Preconditions may be applied to |
| 991 |
invariants as well as rules. |
| 992 |
""" |
| 993 |
|
| 994 |
def decorator(f): |
| 995 |
@proxies(f) |
| 996 |
def precondition_wrapper(*args, **kwargs): |
| 997 |
return f(*args, **kwargs) |
| 998 |
|
| 999 |
existing_initialize_rule = getattr(f, INITIALIZE_RULE_MARKER, None) |
| 1000 |
if existing_initialize_rule is not None: |
| 1001 |
raise InvalidDefinition( |
| 1002 |
f"{_rule_qualname(f)} has been decorated with both @initialize and " |
| 1003 |
"@precondition, which is not allowed. An initialization rule " |
| 1004 |
"runs unconditionally and may not have a precondition." |
| 1005 |
) |
| 1006 |
|
| 1007 |
rule = getattr(f, RULE_MARKER, None) |
| 1008 |
invariant = getattr(f, INVARIANT_MARKER, None) |
| 1009 |
if rule is not None: |
| 1010 |
assert invariant is None |
| 1011 |
new_rule = dataclasses.replace( |
| 1012 |
rule, preconditions=(*rule.preconditions, precond) |
| 1013 |
) |
| 1014 |
setattr(precondition_wrapper, RULE_MARKER, new_rule) |
| 1015 |
elif invariant is not None: |
| 1016 |
assert rule is None |
| 1017 |
new_invariant = dataclasses.replace( |
| 1018 |
invariant, preconditions=(*invariant.preconditions, precond) |
| 1019 |
) |
| 1020 |
setattr(precondition_wrapper, INVARIANT_MARKER, new_invariant) |
| 1021 |
else: |
| 1022 |
setattr( |
| 1023 |
precondition_wrapper, |
| 1024 |
PRECONDITIONS_MARKER, |
| 1025 |
(*getattr(f, PRECONDITIONS_MARKER, ()), precond), |
| 1026 |
) |
| 1027 |
|
| 1028 |
return precondition_wrapper |
| 1029 |
|
| 1030 |
return decorator |
| 1031 |
|
| 1032 |
|
| 1033 |
@dataclass(slots=True, frozen=True) |
| 1034 |
class Invariant: |
| 1035 |
function: Any |
| 1036 |
preconditions: Any |
| 1037 |
check_during_init: bool |
| 1038 |
|
| 1039 |
def __repr__(self) -> str: |
| 1040 |
parts = [ |
| 1041 |
f"function={get_pretty_function_description(self.function)}", |
| 1042 |
f"{self.preconditions=}", |
| 1043 |
f"{self.check_during_init=}", |
| 1044 |
] |
| 1045 |
return f"Invariant({', '.join(parts)})" |
| 1046 |
|
| 1047 |
|
| 1048 |
def invariant(*, check_during_init: bool = False) -> Callable[[TestFunc], TestFunc]: |
| 1049 |
"""Decorator to apply an invariant for rules in a RuleBasedStateMachine. |
| 1050 |
The decorated function will be run after every rule and can raise an |
| 1051 |
exception to indicate failed invariants. |
| 1052 |
|
| 1053 |
For example:: |
| 1054 |
|
| 1055 |
class MyTestMachine(RuleBasedStateMachine): |
| 1056 |
state = 1 |
| 1057 |
|
| 1058 |
@invariant() |
| 1059 |
def is_nonzero(self): |
| 1060 |
assert self.state != 0 |
| 1061 |
|
| 1062 |
By default, invariants are only checked after all |
| 1063 |
:func:`@initialize() <hypothesis.stateful.initialize>` rules have been run. |
| 1064 |
Pass ``check_during_init=True`` for invariants which can also be checked |
| 1065 |
during initialization. |
| 1066 |
""" |
| 1067 |
check_type(bool, check_during_init, "check_during_init") |
| 1068 |
|
| 1069 |
def accept(f): |
| 1070 |
if getattr(f, RULE_MARKER, None) or getattr(f, INITIALIZE_RULE_MARKER, None): |
| 1071 |
raise InvalidDefinition( |
| 1072 |
f"{_rule_qualname(f)} has been decorated with both @invariant and " |
| 1073 |
"@rule, which is not allowed." |
| 1074 |
) |
| 1075 |
existing_invariant = getattr(f, INVARIANT_MARKER, None) |
| 1076 |
if existing_invariant is not None: |
| 1077 |
raise InvalidDefinition( |
| 1078 |
f"{_rule_qualname(f)} has been decorated with @invariant twice, " |
| 1079 |
"which is not allowed." |
| 1080 |
) |
| 1081 |
preconditions = getattr(f, PRECONDITIONS_MARKER, ()) |
| 1082 |
invar = Invariant( |
| 1083 |
function=f, |
| 1084 |
preconditions=preconditions, |
| 1085 |
check_during_init=check_during_init, |
| 1086 |
) |
| 1087 |
|
| 1088 |
@proxies(f) |
| 1089 |
def invariant_wrapper(*args, **kwargs): |
| 1090 |
return f(*args, **kwargs) |
| 1091 |
|
| 1092 |
setattr(invariant_wrapper, INVARIANT_MARKER, invar) |
| 1093 |
return invariant_wrapper |
| 1094 |
|
| 1095 |
return accept |
| 1096 |
|
| 1097 |
|
| 1098 |
class RuleStrategy(SearchStrategy): |
| 1099 |
def __init__(self, machine: RuleBasedStateMachine) -> None: |
| 1100 |
super().__init__() |
| 1101 |
self.machine = machine |
| 1102 |
self.rules = machine.rules.copy() |
| 1103 |
|
| 1104 |
self.enabled_rules_strategy = st.shared( |
| 1105 |
FeatureStrategy(at_least_one_of={r.function.__name__ for r in self.rules}), |
| 1106 |
key=("enabled rules", machine), |
| 1107 |
) |
| 1108 |
|
| 1109 |
# The order is a bit arbitrary. Primarily we're trying to group rules |
| 1110 |
# that write to the same location together, and to put rules with no |
| 1111 |
# target first as they have less effect on the structure. We order from |
| 1112 |
# fewer to more arguments on grounds that it will plausibly need less |
| 1113 |
# data. This probably won't work especially well and we could be |
| 1114 |
# smarter about it, but it's better than just doing it in definition |
| 1115 |
# order. |
| 1116 |
self.rules.sort( |
| 1117 |
key=lambda rule: ( |
| 1118 |
sorted(rule.targets), |
| 1119 |
len(rule.arguments), |
| 1120 |
rule.function.__name__, |
| 1121 |
) |
| 1122 |
) |
| 1123 |
self.rules_strategy = st.sampled_from(self.rules) |
| 1124 |
|
| 1125 |
def __repr__(self): |
| 1126 |
return f"{self.__class__.__name__}(machine={self.machine.__class__.__name__}({{...}}))" |
| 1127 |
|
| 1128 |
def do_draw(self, data): |
| 1129 |
if not any(self.is_valid(rule) for rule in self.rules): |
| 1130 |
rules = ", ".join([rule.function.__name__ for rule in self.rules]) |
| 1131 |
msg = ( |
| 1132 |
f"No progress can be made from state {self.machine!r}, because no " |
| 1133 |
f"available rule had a True precondition. rules: {rules}" |
| 1134 |
) |
| 1135 |
raise InvalidDefinition(msg) from None |
| 1136 |
|
| 1137 |
feature_flags = data.draw(self.enabled_rules_strategy) |
| 1138 |
|
| 1139 |
def rule_is_enabled(r): |
| 1140 |
# Note: The order of the filters here is actually quite important, |
| 1141 |
# because checking is_enabled makes choices, so increases the size of |
| 1142 |
# the choice sequence. This means that if we are in a case where many |
| 1143 |
# rules are invalid we would make a lot more choices if we ask if they |
| 1144 |
# are enabled before we ask if they are valid, so our test cases would |
| 1145 |
# be artificially large. |
| 1146 |
return self.is_valid(r) and feature_flags.is_enabled(r.function.__name__) |
| 1147 |
|
| 1148 |
rule = data.draw(self.rules_strategy.filter(rule_is_enabled)) |
| 1149 |
|
| 1150 |
arguments = {} |
| 1151 |
for k, strat in rule.arguments_strategies.items(): |
| 1152 |
try: |
| 1153 |
arguments[k] = data.draw(strat) |
| 1154 |
except Exception as err: |
| 1155 |
rname = rule.function.__name__ |
| 1156 |
add_note(err, f"while generating {k!r} from {strat!r} for rule {rname}") |
| 1157 |
raise |
| 1158 |
return (rule, arguments) |
| 1159 |
|
| 1160 |
def is_valid(self, rule): |
| 1161 |
for b in rule.bundles: |
| 1162 |
if not self.machine.bundle(b.name): |
| 1163 |
return False |
| 1164 |
|
| 1165 |
predicates = self.machine._observability_predicates |
| 1166 |
desc = f"{self.machine.__class__.__qualname__}, rule {rule.function.__name__}," |
| 1167 |
for pred in rule.preconditions: |
| 1168 |
meets_precond = pred(self.machine) |
| 1169 |
where = f"{desc} precondition {get_pretty_function_description(pred)}" |
| 1170 |
predicates[where].update_count(condition=meets_precond) |
| 1171 |
if not meets_precond: |
| 1172 |
return False |
| 1173 |
|
| 1174 |
return True |