| 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 inspect |
| 12 |
from collections import namedtuple |
| 13 |
|
| 14 |
import pytest |
| 15 |
|
| 16 |
from hypothesis import Phase, settings as Settings, strategies as st |
| 17 |
from hypothesis.stateful import ( |
| 18 |
Bundle, |
| 19 |
RuleBasedStateMachine, |
| 20 |
invariant, |
| 21 |
precondition, |
| 22 |
rule, |
| 23 |
run_state_machine_as_test, |
| 24 |
) |
| 25 |
|
| 26 |
from tests.common.utils import Why |
| 27 |
|
| 28 |
|
| 29 |
def run_to_notes(TestClass): |
| 30 |
TestCase = TestClass.TestCase |
| 31 |
# don't add explain phase notes to the error |
| 32 |
TestCase.settings = Settings(phases=set(Phase) - {Phase.explain}, max_examples=500) |
| 33 |
try: |
| 34 |
TestCase().runTest() |
| 35 |
except AssertionError as err: |
| 36 |
return err.__notes__ |
| 37 |
|
| 38 |
raise RuntimeError("Expected an assertion error") |
| 39 |
|
| 40 |
|
| 41 |
def assert_runs_to_output(TestClass, output): |
| 42 |
# remove the first line, which is always "Falsfying example:" |
| 43 |
actual = "\n".join(run_to_notes(TestClass)[1:]) |
| 44 |
assert actual == inspect.cleandoc(output.strip()) |
| 45 |
|
| 46 |
|
| 47 |
Leaf = namedtuple("Leaf", ("label",)) |
| 48 |
Split = namedtuple("Split", ("left", "right")) |
| 49 |
|
| 50 |
|
| 51 |
class BalancedTrees(RuleBasedStateMachine): |
| 52 |
trees = Bundle("BinaryTree") |
| 53 |
|
| 54 |
@rule(target=trees, x=st.booleans()) |
| 55 |
def leaf(self, x): |
| 56 |
return Leaf(x) |
| 57 |
|
| 58 |
@rule(target=trees, left=trees, right=trees) |
| 59 |
def split(self, left, right): |
| 60 |
return Split(left, right) |
| 61 |
|
| 62 |
@rule(tree=trees) |
| 63 |
def test_is_balanced(self, tree): |
| 64 |
if isinstance(tree, Leaf): |
| 65 |
return |
| 66 |
|
| 67 |
assert abs(self.size(tree.left) - self.size(tree.right)) <= 1 |
| 68 |
self.test_is_balanced(tree.left) |
| 69 |
self.test_is_balanced(tree.right) |
| 70 |
|
| 71 |
def size(self, tree): |
| 72 |
if isinstance(tree, Leaf): |
| 73 |
return 1 |
| 74 |
else: |
| 75 |
return 1 + self.size(tree.left) + self.size(tree.right) |
| 76 |
|
| 77 |
|
| 78 |
class DepthCharge: |
| 79 |
def __init__(self, value): |
| 80 |
if value is None: |
| 81 |
self.depth = 0 |
| 82 |
else: |
| 83 |
self.depth = value.depth + 1 |
| 84 |
|
| 85 |
|
| 86 |
class DepthMachine(RuleBasedStateMachine): |
| 87 |
charges = Bundle("charges") |
| 88 |
|
| 89 |
@rule(targets=(charges,), child=charges) |
| 90 |
def charge(self, child): |
| 91 |
return DepthCharge(child) |
| 92 |
|
| 93 |
@rule(targets=(charges,)) |
| 94 |
def none_charge(self): |
| 95 |
return DepthCharge(None) |
| 96 |
|
| 97 |
@rule(check=charges) |
| 98 |
def is_not_too_deep(self, check): |
| 99 |
assert check.depth < 3 |
| 100 |
|
| 101 |
|
| 102 |
class RoseTreeStateMachine(RuleBasedStateMachine): |
| 103 |
nodes = Bundle("nodes") |
| 104 |
|
| 105 |
@rule(target=nodes, source=st.lists(nodes)) |
| 106 |
def bunch(self, source): |
| 107 |
return source |
| 108 |
|
| 109 |
@rule(source=nodes) |
| 110 |
def shallow(self, source): |
| 111 |
def depth(ls): |
| 112 |
return 0 if not ls else 1 + max(map(depth, ls)) |
| 113 |
|
| 114 |
assert depth(source) <= 5 |
| 115 |
|
| 116 |
|
| 117 |
class NotTheLastMachine(RuleBasedStateMachine): |
| 118 |
stuff = Bundle("stuff") |
| 119 |
|
| 120 |
def __init__(self): |
| 121 |
super().__init__() |
| 122 |
self.last = None |
| 123 |
self.bye_called = False |
| 124 |
|
| 125 |
@rule(target=stuff) |
| 126 |
def hi(self): |
| 127 |
result = object() |
| 128 |
self.last = result |
| 129 |
return result |
| 130 |
|
| 131 |
@precondition(lambda self: not self.bye_called) |
| 132 |
@rule(v=stuff) |
| 133 |
def bye(self, v): |
| 134 |
assert v == self.last |
| 135 |
self.bye_called = True |
| 136 |
|
| 137 |
|
| 138 |
class PopulateMultipleTargets(RuleBasedStateMachine): |
| 139 |
b1 = Bundle("b1") |
| 140 |
b2 = Bundle("b2") |
| 141 |
|
| 142 |
@rule(targets=(b1, b2)) |
| 143 |
def populate(self): |
| 144 |
return 1 |
| 145 |
|
| 146 |
@rule(x=b1, y=b2) |
| 147 |
def fail(self, x, y): |
| 148 |
raise AssertionError |
| 149 |
|
| 150 |
|
| 151 |
class CanSwarm(RuleBasedStateMachine): |
| 152 |
"""This test will essentially never pass if you choose rules uniformly at |
| 153 |
random, because every time the snake rule fires we return to the beginning, |
| 154 |
so we will tend to undo progress well before we make enough progress for |
| 155 |
the test to fail. |
| 156 |
|
| 157 |
This tests our swarm testing functionality in stateful testing by ensuring |
| 158 |
that we can sometimes generate long runs of steps which exclude a |
| 159 |
particular rule. |
| 160 |
""" |
| 161 |
|
| 162 |
def __init__(self): |
| 163 |
super().__init__() |
| 164 |
self.seen = set() |
| 165 |
|
| 166 |
@rule(move=st.integers()) |
| 167 |
def ladder(self, move): |
| 168 |
self.seen.add(move) |
| 169 |
assert len(self.seen) <= 15 |
| 170 |
|
| 171 |
@rule() |
| 172 |
def snake(self): |
| 173 |
self.seen.clear() |
| 174 |
|
| 175 |
|
| 176 |
bad_machines = ( |
| 177 |
BalancedTrees, |
| 178 |
DepthMachine, |
| 179 |
RoseTreeStateMachine, |
| 180 |
NotTheLastMachine, |
| 181 |
PopulateMultipleTargets, |
| 182 |
CanSwarm, |
| 183 |
) |
| 184 |
|
| 185 |
for m in bad_machines: |
| 186 |
m.TestCase.settings = Settings( |
| 187 |
m.TestCase.settings, |
| 188 |
max_examples=1000, |
| 189 |
database=None, |
| 190 |
phases=set(Phase) - {Phase.shrink}, |
| 191 |
) |
| 192 |
|
| 193 |
|
| 194 |
@pytest.mark.parametrize( |
| 195 |
"machine", bad_machines, ids=[t.__name__ for t in bad_machines] |
| 196 |
) |
| 197 |
def test_bad_machines_fail(machine): |
| 198 |
if ( |
| 199 |
machine in [CanSwarm, RoseTreeStateMachine] |
| 200 |
and Settings.get_current_profile_name() == "crosshair" |
| 201 |
): |
| 202 |
# and also takes 10/6 minutes respectively, on top of not finding the failure |
| 203 |
pytest.xfail(reason=str(Why.undiscovered)) |
| 204 |
|
| 205 |
with pytest.raises(AssertionError): |
| 206 |
machine.TestCase().runTest() |
| 207 |
|
| 208 |
|
| 209 |
class MyStatefulMachine(RuleBasedStateMachine): |
| 210 |
def __init__(self): |
| 211 |
self.n_steps = 0 |
| 212 |
super().__init__() |
| 213 |
|
| 214 |
@rule() |
| 215 |
def step(self): |
| 216 |
self.n_steps += 1 |
| 217 |
assert self.n_steps <= 10 |
| 218 |
|
| 219 |
|
| 220 |
class TestMyStatefulMachine(MyStatefulMachine.TestCase): |
| 221 |
settings = Settings(derandomize=True, stateful_step_count=5) |
| 222 |
|
| 223 |
|
| 224 |
def test_multiple_precondition_bug(): |
| 225 |
# See https://github.com/HypothesisWorks/hypothesis/issues/2861 |
| 226 |
class MultiplePreconditionMachine(RuleBasedStateMachine): |
| 227 |
@rule(x=st.integers()) |
| 228 |
def good_method(self, x): |
| 229 |
pass |
| 230 |
|
| 231 |
@precondition(lambda self: True) |
| 232 |
@precondition(lambda self: False) |
| 233 |
@rule(x=st.integers()) |
| 234 |
def bad_method_a(self, x): |
| 235 |
raise AssertionError("This rule runs, even though it shouldn't.") |
| 236 |
|
| 237 |
@precondition(lambda self: False) |
| 238 |
@precondition(lambda self: True) |
| 239 |
@rule(x=st.integers()) |
| 240 |
def bad_method_b(self, x): |
| 241 |
raise AssertionError("This rule might be skipped for the wrong reason.") |
| 242 |
|
| 243 |
@precondition(lambda self: True) |
| 244 |
@rule(x=st.integers()) |
| 245 |
@precondition(lambda self: False) |
| 246 |
def bad_method_c(self, x): |
| 247 |
raise AssertionError("This rule runs, even though it shouldn't.") |
| 248 |
|
| 249 |
@rule(x=st.integers()) |
| 250 |
@precondition(lambda self: True) |
| 251 |
@precondition(lambda self: False) |
| 252 |
def bad_method_d(self, x): |
| 253 |
raise AssertionError("This rule runs, even though it shouldn't.") |
| 254 |
|
| 255 |
@precondition(lambda self: True) |
| 256 |
@precondition(lambda self: False) |
| 257 |
@invariant() |
| 258 |
def bad_invariant_a(self): |
| 259 |
raise AssertionError("This invariant runs, even though it shouldn't.") |
| 260 |
|
| 261 |
@precondition(lambda self: False) |
| 262 |
@precondition(lambda self: True) |
| 263 |
@invariant() |
| 264 |
def bad_invariant_b(self): |
| 265 |
raise AssertionError("This invariant runs, even though it shouldn't.") |
| 266 |
|
| 267 |
@precondition(lambda self: True) |
| 268 |
@invariant() |
| 269 |
@precondition(lambda self: False) |
| 270 |
def bad_invariant_c(self): |
| 271 |
raise AssertionError("This invariant runs, even though it shouldn't.") |
| 272 |
|
| 273 |
@invariant() |
| 274 |
@precondition(lambda self: True) |
| 275 |
@precondition(lambda self: False) |
| 276 |
def bad_invariant_d(self): |
| 277 |
raise AssertionError("This invariant runs, even though it shouldn't.") |
| 278 |
|
| 279 |
run_state_machine_as_test(MultiplePreconditionMachine) |
| 280 |
|
| 281 |
|
| 282 |
class UnrelatedCall(RuleBasedStateMachine): |
| 283 |
a = Bundle("a") |
| 284 |
|
| 285 |
def __init__(self): |
| 286 |
super().__init__() |
| 287 |
self.calls = set() |
| 288 |
|
| 289 |
@rule(target=a, a=st.integers()) |
| 290 |
def add_a(self, a): |
| 291 |
self.calls.add("add") |
| 292 |
return a |
| 293 |
|
| 294 |
@rule(v=a) |
| 295 |
def f(self, v): |
| 296 |
self.calls.add("f") |
| 297 |
|
| 298 |
@precondition(lambda self: "add" in self.calls) |
| 299 |
@rule(value=st.integers()) |
| 300 |
def unrelated(self, value): |
| 301 |
self.calls.add("unrelated") |
| 302 |
|
| 303 |
@rule() |
| 304 |
def invariant(self): |
| 305 |
# force all three calls to be made in a particular order (with the |
| 306 |
# `unrelated` precondition) so we always shrink to a particular counterexample. |
| 307 |
assert len(self.calls) != 3 |
| 308 |
|
| 309 |
|
| 310 |
def test_unrelated_rule_does_not_use_var_reference_repr(): |
| 311 |
# we are specifically looking for state.unrelated(value=0) not being replaced |
| 312 |
# with state.unrelated(value=a_0). The `unrelated` rule is drawing from |
| 313 |
# st.integers, not a bundle, so the values should not be conflated even if |
| 314 |
# they're both 0. |
| 315 |
assert_runs_to_output( |
| 316 |
UnrelatedCall, |
| 317 |
""" |
| 318 |
state = UnrelatedCall() |
| 319 |
a_0 = state.add_a(a=0) |
| 320 |
state.f(v=a_0) |
| 321 |
state.unrelated(value=0) |
| 322 |
state.invariant() |
| 323 |
state.teardown() |
| 324 |
""", |
| 325 |
) |
| 326 |
|
| 327 |
|
| 328 |
class SourceSameAsTarget(RuleBasedStateMachine): |
| 329 |
values = Bundle("values") |
| 330 |
|
| 331 |
@rule(target=values, value=st.lists(values)) |
| 332 |
def f(self, value): |
| 333 |
assert len(value) == 0 |
| 334 |
return value |
| 335 |
|
| 336 |
|
| 337 |
class SourceSameAsTargetUnclearOrigin(RuleBasedStateMachine): |
| 338 |
values = Bundle("values") |
| 339 |
|
| 340 |
def __init__(self): |
| 341 |
super().__init__() |
| 342 |
self.called = False |
| 343 |
|
| 344 |
@rule(target=values, value=st.just([]) | st.lists(values)) |
| 345 |
def f(self, value): |
| 346 |
assert not self.called |
| 347 |
# ensure we get two calls to f before failing. In the minimal failing |
| 348 |
# example, both will be from st.just([]). |
| 349 |
self.called = True |
| 350 |
return value |
| 351 |
|
| 352 |
|
| 353 |
def test_replaces_when_same_id(): |
| 354 |
assert_runs_to_output( |
| 355 |
SourceSameAsTarget, |
| 356 |
f""" |
| 357 |
state = {SourceSameAsTarget.__name__}() |
| 358 |
values_0 = state.f(value=[]) |
| 359 |
state.f(value=[values_0]) |
| 360 |
state.teardown() |
| 361 |
""", |
| 362 |
) |
| 363 |
|
| 364 |
|
| 365 |
def test_doesnt_replace_when_different_id(): |
| 366 |
assert_runs_to_output( |
| 367 |
SourceSameAsTargetUnclearOrigin, |
| 368 |
f""" |
| 369 |
state = {SourceSameAsTargetUnclearOrigin.__name__}() |
| 370 |
values_0 = state.f(value=[]) |
| 371 |
state.f(value=[]) |
| 372 |
state.teardown() |
| 373 |
""", |
| 374 |
) |