Debian Codegraph @

hypothesis-python/tests/cover/test_stateful.py

raw
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 re
12 from collections import defaultdict
13 from typing import ClassVar
14
15 import pytest
16 from _pytest.outcomes import Failed, Skipped
17 from pytest import raises
18
19 from hypothesis import (
20 HealthCheck,
21 Phase,
22 __version__,
23 reproduce_failure,
24 seed,
25 settings as Settings,
26 strategies as st,
27 )
28 from hypothesis.control import current_build_context
29 from hypothesis.core import encode_failure
30 from hypothesis.database import InMemoryExampleDatabase
31 from hypothesis.errors import (
32 DidNotReproduce,
33 Flaky,
34 FlakyStrategyDefinition,
35 InvalidArgument,
36 InvalidDefinition,
37 )
38 from hypothesis.stateful import (
39 Bundle,
40 RuleBasedStateMachine,
41 consumes,
42 get_state_machine_test,
43 initialize,
44 invariant,
45 multiple,
46 precondition,
47 rule,
48 run_state_machine_as_test,
49 )
50 from hypothesis.strategies import binary, data, integers, just, lists
51
52 from tests.common.utils import (
53 Why,
54 capture_out,
55 skipif_threading,
56 validate_deprecation,
57 xfail_on_crosshair,
58 )
59 from tests.nocover.test_stateful import DepthMachine
60
61 NO_BLOB_SETTINGS = Settings(print_blob=False, phases=tuple(Phase)[:-1])
62
63
64 class MultipleRulesSameFuncMachine(RuleBasedStateMachine):
65 def myfunc(self, data):
66 print(data)
67
68 rule1 = rule(data=just("rule1data"))(myfunc)
69 rule2 = rule(data=just("rule2data"))(myfunc)
70
71
72 class PreconditionMachine(RuleBasedStateMachine):
73 num = 0
74
75 @rule()
76 def add_one(self):
77 self.num += 1
78
79 @rule()
80 def set_to_zero(self):
81 self.num = 0
82
83 @rule(num=integers())
84 @precondition(lambda self: self.num != 0)
85 def div_by_precondition_after(self, num):
86 self.num = num / self.num
87
88 @precondition(lambda self: self.num != 0)
89 @rule(num=integers())
90 def div_by_precondition_before(self, num):
91 self.num = num / self.num
92
93
94 TestPrecondition = PreconditionMachine.TestCase
95 TestPrecondition.settings = Settings(TestPrecondition.settings, max_examples=10)
96
97
98 def test_picks_up_settings_at_first_use_of_testcase():
99 assert TestPrecondition.settings.max_examples == 10
100
101
102 def test_multiple_rules_same_func():
103 test_class = MultipleRulesSameFuncMachine.TestCase
104 with capture_out() as o:
105 test_class().runTest()
106 output = o.getvalue()
107 assert "rule1data" in output
108 assert "rule2data" in output
109
110
111 def test_can_get_test_case_off_machine_instance():
112 assert DepthMachine().TestCase is DepthMachine().TestCase
113 assert DepthMachine().TestCase is not None
114
115
116 class FlakyDrawLessMachine(RuleBasedStateMachine):
117 @rule(d=data())
118 def action(self, d):
119 if current_build_context().is_final:
120 d.draw(binary(min_size=1, max_size=1))
121 else:
122 buffer = binary(min_size=1024, max_size=1024)
123 assert 0 not in buffer
124
125
126 def test_flaky_draw_less_raises_flaky():
127 with raises(Flaky):
128 FlakyDrawLessMachine.TestCase().runTest()
129
130
131 def test_result_is_added_to_target():
132 class TargetStateMachine(RuleBasedStateMachine):
133 nodes = Bundle("nodes")
134
135 @rule(target=nodes, source=lists(nodes))
136 def bunch(self, source):
137 assert len(source) == 0
138 return source
139
140 test_class = TargetStateMachine.TestCase
141 try:
142 test_class().runTest()
143 raise RuntimeError("Expected an assertion error")
144 except AssertionError as err:
145 notes = err.__notes__
146 regularized_notes = [re.sub(r"[0-9]+", "i", note) for note in notes]
147 assert "state.bunch(source=[nodes_i])" in regularized_notes
148
149
150 class FlakyStateMachine(RuleBasedStateMachine):
151 @rule()
152 def action(self):
153 assert current_build_context().is_final
154
155
156 def test_flaky_raises_flaky():
157 with raises(Flaky):
158 FlakyStateMachine.TestCase().runTest()
159
160
161 class FlakyPreconditionMachine(RuleBasedStateMachine):
162 @precondition(lambda self: not current_build_context().is_final)
163 @rule()
164 def action(self):
165 raise AssertionError
166
167
168 def test_flaky_precondition_error_message():
169 with raises(FlakyStrategyDefinition) as exc_info:
170 FlakyPreconditionMachine.TestCase().runTest()
171 assert any("flaky precondition" in note for note in exc_info.value.__notes__)
172
173
174 class FlakyDrawInRuleMachine(RuleBasedStateMachine):
175 # Flakiness inside rule execution (via data().draw()) happens AFTER rule selection,
176 # so the "flaky precondition" note should NOT be added.
177 @rule(d=data())
178 def action(self, d):
179 if current_build_context().is_final:
180 d.draw(st.integers(0, 0))
181 d.draw(st.integers())
182 raise AssertionError
183
184
185 def test_flaky_draw_in_rule_no_precondition_note():
186 # When flakiness occurs during rule execution (not rule selection),
187 # the error message should NOT mention flaky preconditions.
188 with raises(FlakyStrategyDefinition) as exc_info:
189 FlakyDrawInRuleMachine.TestCase().runTest()
190 notes = getattr(exc_info.value, "__notes__", [])
191 assert not any("flaky precondition" in note for note in notes)
192
193
194 def test_get_state_machine_test_is_importable():
195 # Regression test: get_state_machine_test is used by HypoFuzz
196 assert callable(get_state_machine_test)
197
198
199 class FlakyRatchettingMachine(RuleBasedStateMachine):
200 ratchet = 0
201
202 @rule(d=data())
203 def action(self, d):
204 FlakyRatchettingMachine.ratchet += 1
205 n = FlakyRatchettingMachine.ratchet
206 d.draw(lists(integers(), min_size=n, max_size=n))
207 raise AssertionError
208
209
210 @Settings(
211 stateful_step_count=10,
212 max_examples=30,
213 suppress_health_check=[HealthCheck.filter_too_much],
214 ) # speed this up
215 class MachineWithConsumingRule(RuleBasedStateMachine):
216 b1 = Bundle("b1")
217 b2 = Bundle("b2")
218
219 def __init__(self):
220 self.created_counter = 0
221 self.consumed_counter = 0
222 super().__init__()
223
224 @invariant()
225 def bundle_length(self):
226 assert len(self.bundle("b1")) == self.created_counter - self.consumed_counter
227
228 @rule(target=b1)
229 def populate_b1(self):
230 self.created_counter += 1
231 return self.created_counter
232
233 @rule(target=b2, consumed=consumes(b1))
234 def depopulate_b1(self, consumed):
235 self.consumed_counter += 1
236 return consumed
237
238 @rule(consumed=lists(consumes(b1), max_size=3))
239 def depopulate_b1_multiple(self, consumed):
240 self.consumed_counter += len(consumed)
241
242 @rule(value1=b1, value2=b2)
243 def check(self, value1, value2):
244 assert value1 != value2
245
246
247 TestMachineWithConsumingRule = MachineWithConsumingRule.TestCase
248
249
250 def test_multiple():
251 none = multiple()
252 some = multiple(1, 2.01, "3", b"4", 5)
253 assert len(none.values) == 0
254 assert len(some.values) == 5
255 assert set(some.values) == {1, 2.01, "3", b"4", 5}
256
257
258 class MachineUsingMultiple(RuleBasedStateMachine):
259 b = Bundle("b")
260
261 def __init__(self):
262 self.expected_bundle_length = 0
263 super().__init__()
264
265 @invariant()
266 def bundle_length(self):
267 assert len(self.bundle("b")) == self.expected_bundle_length
268
269 @rule(target=b, items=lists(elements=integers(), max_size=10))
270 def populate_bundle(self, items):
271 self.expected_bundle_length += len(items)
272 return multiple(*items)
273
274 @rule(target=b)
275 def do_not_populate(self):
276 return multiple()
277
278
279 TestMachineUsingMultiple = MachineUsingMultiple.TestCase
280
281
282 def test_multiple_variables_printed():
283 class ProducesMultiple(RuleBasedStateMachine):
284 b = Bundle("b")
285
286 @initialize(target=b)
287 def populate_bundle(self):
288 return multiple(1, 2)
289
290 @rule()
291 def fail_fast(self):
292 raise AssertionError
293
294 with raises(AssertionError) as err:
295 run_state_machine_as_test(ProducesMultiple)
296
297 # This is tightly coupled to the output format of the step printing.
298 # The first line is "Falsifying Example:..." the second is creating
299 # the state machine, the third is calling the "initialize" method.
300 assignment_line = err.value.__notes__[2]
301 # 'populate_bundle()' returns 2 values, so should be
302 # expanded to 2 variables.
303 assert assignment_line == "b_0, b_1 = state.populate_bundle()"
304
305 # Make sure MultipleResult is iterable so the printed code is valid.
306 # See https://github.com/HypothesisWorks/hypothesis/issues/2311
307 state = ProducesMultiple()
308 _b_0, _b_1 = state.populate_bundle()
309 with raises(AssertionError):
310 state.fail_fast()
311
312
313 def test_multiple_variables_printed_single_element():
314 # https://github.com/HypothesisWorks/hypothesis/issues/3236
315 class ProducesMultiple(RuleBasedStateMachine):
316 b = Bundle("b")
317
318 @initialize(target=b)
319 def populate_bundle(self):
320 return multiple(1)
321
322 @rule(b=b)
323 def fail_fast(self, b):
324 assert b != 1
325
326 with raises(AssertionError) as err:
327 run_state_machine_as_test(ProducesMultiple)
328
329 assignment_line = err.value.__notes__[2]
330 assert assignment_line == "(b_0,) = state.populate_bundle()"
331
332 state = ProducesMultiple()
333 (v1,) = state.populate_bundle()
334 state.fail_fast((v1,)) # passes if tuple not unpacked
335 with raises(AssertionError):
336 state.fail_fast(v1)
337
338
339 def test_no_variables_printed():
340 class ProducesNoVariables(RuleBasedStateMachine):
341 b = Bundle("b")
342
343 @initialize(target=b)
344 def populate_bundle(self):
345 return multiple()
346
347 @rule()
348 def fail_fast(self):
349 raise AssertionError
350
351 with raises(AssertionError) as err:
352 run_state_machine_as_test(ProducesNoVariables)
353
354 # This is tightly coupled to the output format of the step printing.
355 # The first line is "Falsifying Example:..." the second is creating
356 # the state machine, the third is calling the "initialize" method.
357 assignment_line = err.value.__notes__[2]
358 # 'populate_bundle()' returns 0 values, so there should be no
359 # variable assignment.
360 assert assignment_line == "state.populate_bundle()"
361
362
363 def test_consumes_typecheck():
364 with pytest.raises(TypeError):
365 consumes(integers())
366
367
368 def test_ratchetting_raises_flaky():
369 with raises(Flaky):
370 FlakyRatchettingMachine.TestCase().runTest()
371
372
373 def test_empty_machine_is_invalid():
374 class EmptyMachine(RuleBasedStateMachine):
375 pass
376
377 with raises(InvalidDefinition):
378 EmptyMachine.TestCase().runTest()
379
380
381 def test_machine_with_no_terminals_is_invalid():
382 class NonTerminalMachine(RuleBasedStateMachine):
383 @rule(value=Bundle("hi"))
384 def bye(self, hi):
385 pass
386
387 with raises(InvalidDefinition):
388 NonTerminalMachine.TestCase().runTest()
389
390
391 def test_minimizes_errors_in_teardown():
392 # temporary debugging to try to narrow down a potential thread-safety issue
393 import threading
394
395 from hypothesis import Verbosity
396
397 counter = 0
398
399 @Settings(database=None, verbosity=Verbosity.debug)
400 class Foo(RuleBasedStateMachine):
401 @initialize()
402 def init(self):
403 nonlocal counter
404 counter = 0
405 print(f"[{threading.get_ident()}] init", counter)
406
407 @rule()
408 def increment(self):
409 nonlocal counter
410 counter += 1
411 print(f"[{threading.get_ident()}] increment", counter)
412
413 def teardown(self):
414 nonlocal counter
415 print(f"[{threading.get_ident()}] teardown", counter)
416 assert not counter
417
418 with raises(AssertionError):
419 run_state_machine_as_test(Foo)
420 assert counter == 1
421
422
423 class RequiresInit(RuleBasedStateMachine):
424 def __init__(self, threshold):
425 super().__init__()
426 self.threshold = threshold
427
428 @rule(value=integers())
429 def action(self, value):
430 if value > self.threshold:
431 raise ValueError(f"{value} is too high")
432
433
434 def test_can_use_factory_for_tests():
435 with raises(ValueError):
436 run_state_machine_as_test(
437 lambda: RequiresInit(42), settings=Settings(max_examples=100)
438 )
439
440
441 class FailsEventually(RuleBasedStateMachine):
442 def __init__(self):
443 super().__init__()
444 self.counter = 0
445
446 @rule()
447 def increment(self):
448 self.counter += 1
449 assert self.counter < 10
450
451
452 FailsEventually.TestCase.settings = Settings(stateful_step_count=5)
453
454
455 @skipif_threading
456 def test_can_explicitly_pass_settings():
457 run_state_machine_as_test(FailsEventually)
458 try:
459 FailsEventually.TestCase.settings = Settings(
460 FailsEventually.TestCase.settings, stateful_step_count=15
461 )
462 run_state_machine_as_test(
463 FailsEventually, settings=Settings(stateful_step_count=2)
464 )
465 finally:
466 FailsEventually.TestCase.settings = Settings(
467 FailsEventually.TestCase.settings, stateful_step_count=5
468 )
469
470
471 def test_settings_argument_is_validated():
472 with pytest.raises(InvalidArgument):
473 run_state_machine_as_test(FailsEventually, settings=object())
474
475
476 def test_runner_that_checks_factory_produced_a_machine():
477 with pytest.raises(InvalidArgument):
478 run_state_machine_as_test(object)
479
480
481 @skipif_threading
482 def test_settings_attribute_is_validated():
483 real_settings = FailsEventually.TestCase.settings
484 try:
485 FailsEventually.TestCase.settings = object()
486 with pytest.raises(InvalidArgument):
487 run_state_machine_as_test(FailsEventually)
488 finally:
489 FailsEventually.TestCase.settings = real_settings
490
491
492 def test_saves_failing_example_in_database():
493 db = InMemoryExampleDatabase()
494 ss = Settings(
495 database=db, max_examples=1000, suppress_health_check=list(HealthCheck)
496 )
497 with raises(AssertionError):
498 run_state_machine_as_test(DepthMachine, settings=ss)
499 assert any(list(db.data.values()))
500
501
502 def test_can_run_with_no_db():
503 with raises(AssertionError):
504 run_state_machine_as_test(
505 DepthMachine, settings=Settings(database=None, max_examples=10_000)
506 )
507
508
509 def test_stateful_double_rule_is_forbidden(recwarn):
510 with pytest.raises(InvalidDefinition):
511
512 class DoubleRuleMachine(RuleBasedStateMachine):
513 @rule(num=just(1))
514 @rule(num=just(2))
515 def whatevs(self, num):
516 pass
517
518
519 def test_can_explicitly_call_functions_when_precondition_not_satisfied():
520 class BadPrecondition(RuleBasedStateMachine):
521 def __init__(self):
522 super().__init__()
523
524 @precondition(lambda self: False)
525 @rule()
526 def test_blah(self):
527 raise ValueError
528
529 @rule()
530 def test_foo(self):
531 self.test_blah()
532
533 with pytest.raises(ValueError):
534 run_state_machine_as_test(BadPrecondition)
535
536
537 def test_invariant():
538 """If an invariant raise an exception, the exception is propagated."""
539
540 class Invariant(RuleBasedStateMachine):
541 def __init__(self):
542 super().__init__()
543
544 @invariant()
545 def test_blah(self):
546 raise ValueError
547
548 @rule()
549 def do_stuff(self):
550 pass
551
552 with pytest.raises(ValueError):
553 run_state_machine_as_test(Invariant)
554
555
556 def test_no_double_invariant():
557 """The invariant decorator can't be applied multiple times to a single
558 function."""
559 with raises(InvalidDefinition):
560
561 class Invariant(RuleBasedStateMachine):
562 def __init__(self):
563 super().__init__()
564
565 @invariant()
566 @invariant()
567 def test_blah(self):
568 pass
569
570 @rule()
571 def do_stuff(self):
572 pass
573
574
575 def test_invariant_precondition():
576 """If an invariant precodition isn't met, the invariant isn't run.
577
578 The precondition decorator can be applied in any order.
579 """
580
581 class Invariant(RuleBasedStateMachine):
582 def __init__(self):
583 super().__init__()
584
585 @invariant()
586 @precondition(lambda _: False)
587 def an_invariant(self):
588 raise ValueError
589
590 @precondition(lambda _: False)
591 @invariant()
592 def another_invariant(self):
593 raise ValueError
594
595 @rule()
596 def do_stuff(self):
597 pass
598
599 run_state_machine_as_test(Invariant)
600
601
602 @pytest.mark.parametrize(
603 "decorators",
604 [
605 (invariant(), rule()),
606 (rule(), invariant()),
607 (invariant(), initialize()),
608 (initialize(), invariant()),
609 (invariant(), precondition(lambda self: True), rule()),
610 (rule(), precondition(lambda self: True), invariant()),
611 (precondition(lambda self: True), invariant(), rule()),
612 (precondition(lambda self: True), rule(), invariant()),
613 ],
614 ids=lambda x: "-".join(f.__qualname__.split(".")[0] for f in x),
615 )
616 def test_invariant_and_rule_are_incompatible(decorators):
617 """It's an error to apply @invariant and @rule to the same method."""
618
619 def method(self):
620 pass
621
622 for d in decorators[:-1]:
623 method = d(method)
624 with pytest.raises(InvalidDefinition):
625 decorators[-1](method)
626
627
628 def test_invalid_rule_argument():
629 """Rule kwargs that are not a Strategy are expected to raise an InvalidArgument error."""
630 with pytest.raises(InvalidArgument):
631
632 class InvalidRuleMachine(RuleBasedStateMachine):
633 @rule(strategy=object())
634 def do_stuff(self):
635 pass
636
637
638 def test_invalid_initialize_argument():
639 """Initialize kwargs that are not a Strategy are expected to raise an InvalidArgument error."""
640 with pytest.raises(InvalidArgument):
641
642 class InvalidInitialize(RuleBasedStateMachine):
643 @initialize(strategy=object())
644 def initialize(self):
645 pass
646
647
648 def test_multiple_invariants():
649 """If multiple invariants are present, they all get run."""
650
651 class Invariant(RuleBasedStateMachine):
652 def __init__(self):
653 super().__init__()
654 self.first_invariant_ran = False
655
656 @invariant()
657 def invariant_1(self):
658 self.first_invariant_ran = True
659
660 @precondition(lambda self: self.first_invariant_ran)
661 @invariant()
662 def invariant_2(self):
663 raise ValueError
664
665 @rule()
666 def do_stuff(self):
667 pass
668
669 with pytest.raises(ValueError):
670 run_state_machine_as_test(Invariant)
671
672
673 def test_explicit_invariant_call_with_precondition():
674 """Invariants can be called explicitly even if their precondition is not
675 satisfied."""
676
677 class BadPrecondition(RuleBasedStateMachine):
678 def __init__(self):
679 super().__init__()
680
681 @precondition(lambda self: False)
682 @invariant()
683 def test_blah(self):
684 raise ValueError
685
686 @rule()
687 def test_foo(self):
688 self.test_blah()
689
690 with pytest.raises(ValueError):
691 run_state_machine_as_test(BadPrecondition)
692
693
694 def test_invariant_checks_initial_state_if_no_initialize_rules():
695 """Invariants are checked before any rules run."""
696
697 class BadPrecondition(RuleBasedStateMachine):
698 def __init__(self):
699 super().__init__()
700 self.num = 0
701
702 @invariant()
703 def test_blah(self):
704 if self.num == 0:
705 raise ValueError
706
707 @rule()
708 def test_foo(self):
709 self.num += 1
710
711 with pytest.raises(ValueError):
712 run_state_machine_as_test(BadPrecondition)
713
714
715 def test_invariant_failling_present_in_falsifying_example():
716 @Settings(print_blob=False)
717 class BadInvariant(RuleBasedStateMachine):
718 @initialize()
719 def initialize_1(self):
720 pass
721
722 @invariant()
723 def invariant_1(self):
724 raise ValueError
725
726 @rule()
727 def rule_1(self):
728 pass
729
730 with pytest.raises(ValueError) as err:
731 run_state_machine_as_test(BadInvariant)
732
733 result = "\n".join(err.value.__notes__)
734 assert (
735 result
736 == """
737 Falsifying example:
738 state = BadInvariant()
739 state.initialize_1()
740 state.invariant_1()
741 state.teardown()
742 """.strip()
743 )
744
745
746 def test_invariant_present_in_falsifying_example():
747 @Settings(print_blob=False, phases=tuple(Phase)[:-1])
748 class BadRuleWithGoodInvariants(RuleBasedStateMachine):
749 def __init__(self):
750 super().__init__()
751 self.num = 0
752
753 @initialize()
754 def initialize_1(self):
755 pass
756
757 @invariant(check_during_init=True)
758 def invariant_1(self):
759 pass
760
761 @invariant(check_during_init=False)
762 def invariant_2(self):
763 pass
764
765 @precondition(lambda self: self.num > 0)
766 @invariant()
767 def invariant_3(self):
768 pass
769
770 @rule()
771 def rule_1(self):
772 self.num += 1
773 if self.num == 2:
774 raise ValueError
775
776 with pytest.raises(ValueError) as err:
777 run_state_machine_as_test(BadRuleWithGoodInvariants)
778
779 expected = """
780 Falsifying example:
781 state = BadRuleWithGoodInvariants()
782 state.invariant_1()
783 state.initialize_1()
784 state.invariant_1()
785 state.invariant_2()
786 state.rule_1()
787 state.invariant_1()
788 state.invariant_2()
789 state.invariant_3()
790 state.rule_1()
791 state.teardown()
792 """.strip()
793
794 result = "\n".join(err.value.__notes__).strip()
795 assert expected == result
796
797
798 def test_always_runs_at_least_one_step():
799 class CountSteps(RuleBasedStateMachine):
800 def __init__(self):
801 super().__init__()
802 self.count = 0
803
804 @rule()
805 def do_something(self):
806 self.count += 1
807
808 def teardown(self):
809 assert self.count > 0
810
811 run_state_machine_as_test(CountSteps)
812
813
814 def test_removes_needless_steps():
815 """Regression test from an example based on
816 tests/nocover/test_database_agreement.py, but without the expensive bits.
817 Comparing two database implementations in which deletion is broken, so as
818 soon as a key/value pair is successfully deleted the test will now fail if
819 you ever check that key.
820
821 The main interesting feature of this is that it has a lot of
822 opportunities to generate keys and values before it actually fails,
823 but will still fail with very high probability.
824 """
825
826 @Settings(derandomize=True, max_examples=1000, deadline=None)
827 class IncorrectDeletion(RuleBasedStateMachine):
828 def __init__(self):
829 super().__init__()
830 self.__saved = defaultdict(set)
831 self.__deleted = defaultdict(set)
832
833 keys = Bundle("keys")
834 values = Bundle("values")
835
836 @rule(target=keys, k=binary())
837 def k(self, k):
838 return k
839
840 @rule(target=values, v=binary())
841 def v(self, v):
842 return v
843
844 @rule(k=keys, v=values)
845 def save(self, k, v):
846 self.__saved[k].add(v)
847
848 @rule(k=keys, v=values)
849 def delete(self, k, v):
850 if v in self.__saved[k]:
851 self.__deleted[k].add(v)
852
853 @rule(k=keys)
854 def values_agree(self, k):
855 assert not self.__deleted[k]
856
857 with pytest.raises(AssertionError) as err:
858 run_state_machine_as_test(IncorrectDeletion)
859
860 result = "\n".join(err.value.__notes__)
861 assert result.count(" = state.k(") == 1
862 assert result.count(" = state.v(") == 1
863
864
865 def test_prints_equal_values_with_correct_variable_name():
866 @Settings(max_examples=100, suppress_health_check=list(HealthCheck))
867 class MovesBetweenBundles(RuleBasedStateMachine):
868 b1 = Bundle("b1")
869 b2 = Bundle("b2")
870
871 @rule(target=b1)
872 def create(self):
873 return []
874
875 @rule(target=b2, source=b1)
876 def transfer(self, source):
877 return source
878
879 @rule(source=b2)
880 def fail(self, source):
881 raise AssertionError
882
883 with pytest.raises(AssertionError) as err:
884 run_state_machine_as_test(MovesBetweenBundles)
885
886 result = "\n".join(err.value.__notes__)
887 for m in ["create", "transfer", "fail"]:
888 assert result.count("state." + m) == 1
889 assert "b1_0 = state.create()" in result
890 assert "b2_0 = state.transfer(source=b1_0)" in result
891 assert "state.fail(source=b2_0)" in result
892
893
894 def test_initialize_rule():
895 @Settings(max_examples=1000)
896 class WithInitializeRules(RuleBasedStateMachine):
897 initialized: ClassVar = []
898
899 @initialize()
900 def initialize_a(self):
901 self.initialized.append("a")
902
903 @initialize()
904 def initialize_b(self):
905 self.initialized.append("b")
906
907 @initialize()
908 def initialize_c(self):
909 self.initialized.append("c")
910
911 @rule()
912 def fail_fast(self):
913 raise AssertionError
914
915 with pytest.raises(AssertionError) as err:
916 run_state_machine_as_test(WithInitializeRules)
917
918 assert set(WithInitializeRules.initialized[-3:]) == {"a", "b", "c"}
919 result = err.value.__notes__[1:]
920 assert result[0] == "state = WithInitializeRules()"
921 # Initialize rules call order is shuffled
922 assert {result[1], result[2], result[3]} == {
923 "state.initialize_a()",
924 "state.initialize_b()",
925 "state.initialize_c()",
926 }
927 assert result[4] == "state.fail_fast()"
928 assert result[5] == "state.teardown()"
929
930
931 def test_initialize_rule_populate_bundle():
932 class WithInitializeBundleRules(RuleBasedStateMachine):
933 a = Bundle("a")
934
935 @initialize(target=a, dep=just("dep"))
936 def initialize_a(self, dep):
937 return f"a a_0 with ({dep})"
938
939 @rule(param=a)
940 def fail_fast(self, param):
941 raise AssertionError
942
943 WithInitializeBundleRules.TestCase.settings = NO_BLOB_SETTINGS
944 with pytest.raises(AssertionError) as err:
945 run_state_machine_as_test(WithInitializeBundleRules)
946
947 result = "\n".join(err.value.__notes__)
948 assert (
949 result
950 == """
951 Falsifying example:
952 state = WithInitializeBundleRules()
953 a_0 = state.initialize_a(dep='dep')
954 state.fail_fast(param=a_0)
955 state.teardown()
956 """.strip()
957 )
958
959
960 def test_initialize_rule_dont_mix_with_precondition():
961 with pytest.raises(
962 InvalidDefinition,
963 match=(
964 "BadStateMachine\\.initialize has been decorated with both @initialize "
965 "and @precondition"
966 ),
967 ):
968
969 class BadStateMachine(RuleBasedStateMachine):
970 @precondition(lambda self: True)
971 @initialize()
972 def initialize(self):
973 pass
974
975 # Also test decorator application in reverse order
976
977 with pytest.raises(
978 InvalidDefinition,
979 match=(
980 "BadStateMachineReverseOrder\\.initialize has been decorated with both "
981 "@initialize and @precondition"
982 ),
983 ):
984
985 class BadStateMachineReverseOrder(RuleBasedStateMachine):
986 @initialize()
987 @precondition(lambda self: True)
988 def initialize(self):
989 pass
990
991
992 def test_initialize_rule_dont_mix_with_regular_rule():
993 with pytest.raises(
994 InvalidDefinition,
995 match="BadStateMachine\\.initialize has been decorated with both @rule and @initialize",
996 ):
997
998 class BadStateMachine(RuleBasedStateMachine):
999 @rule()
1000 @initialize()
1001 def initialize(self):
1002 pass
1003
1004 with pytest.raises(
1005 InvalidDefinition,
1006 match=(
1007 "BadStateMachineReverseOrder\\.initialize has been decorated with both "
1008 "@rule and @initialize"
1009 ),
1010 ):
1011
1012 class BadStateMachineReverseOrder(RuleBasedStateMachine):
1013 @initialize()
1014 @rule()
1015 def initialize(self):
1016 pass
1017
1018
1019 def test_initialize_rule_cannot_be_double_applied():
1020 with pytest.raises(
1021 InvalidDefinition,
1022 match="BadStateMachine\\.initialize has been decorated with @initialize twice",
1023 ):
1024
1025 class BadStateMachine(RuleBasedStateMachine):
1026 @initialize()
1027 @initialize()
1028 def initialize(self):
1029 pass
1030
1031
1032 def test_initialize_rule_in_state_machine_with_inheritance():
1033 class ParentStateMachine(RuleBasedStateMachine):
1034 initialized: ClassVar = []
1035
1036 @initialize()
1037 def initialize_a(self):
1038 self.initialized.append("a")
1039
1040 class ChildStateMachine(ParentStateMachine):
1041 @initialize()
1042 def initialize_b(self):
1043 self.initialized.append("b")
1044
1045 @rule()
1046 def fail_fast(self):
1047 raise AssertionError
1048
1049 with pytest.raises(AssertionError) as err:
1050 run_state_machine_as_test(ChildStateMachine)
1051
1052 assert set(ChildStateMachine.initialized[-2:]) == {"a", "b"}
1053 result = err.value.__notes__[1:]
1054 assert result[0] == "state = ChildStateMachine()"
1055 # Initialize rules call order is shuffled
1056 assert {result[1], result[2]} == {"state.initialize_a()", "state.initialize_b()"}
1057 assert result[3] == "state.fail_fast()"
1058 assert result[4] == "state.teardown()"
1059
1060
1061 def test_can_manually_call_initialize_rule():
1062 class StateMachine(RuleBasedStateMachine):
1063 initialize_called_counter = 0
1064
1065 @initialize()
1066 def initialize(self):
1067 self.initialize_called_counter += 1
1068
1069 @rule()
1070 def fail_eventually(self):
1071 self.initialize()
1072 assert self.initialize_called_counter <= 2
1073
1074 StateMachine.TestCase.settings = NO_BLOB_SETTINGS
1075 with pytest.raises(AssertionError) as err:
1076 run_state_machine_as_test(StateMachine)
1077
1078 result = "\n".join(err.value.__notes__)
1079 assert (
1080 result
1081 == """
1082 Falsifying example:
1083 state = StateMachine()
1084 state.initialize()
1085 state.fail_eventually()
1086 state.fail_eventually()
1087 state.teardown()
1088 """.strip()
1089 )
1090
1091
1092 def test_steps_printed_despite_pytest_fail():
1093 # Test for https://github.com/HypothesisWorks/hypothesis/issues/1372
1094 @Settings(print_blob=False)
1095 class RaisesProblem(RuleBasedStateMachine):
1096 @rule()
1097 def oops(self):
1098 pytest.fail("note that this raises a BaseException")
1099
1100 with pytest.raises(Failed) as err:
1101 run_state_machine_as_test(RaisesProblem)
1102 assert (
1103 "\n".join(err.value.__notes__).strip()
1104 == """
1105 Falsifying example:
1106 state = RaisesProblem()
1107 state.oops()
1108 state.teardown()""".strip()
1109 )
1110
1111
1112 def test_steps_not_printed_with_pytest_skip(capsys):
1113 class RaisesProblem(RuleBasedStateMachine):
1114 @rule()
1115 def skip_whole_test(self):
1116 pytest.skip()
1117
1118 with pytest.raises(Skipped):
1119 run_state_machine_as_test(RaisesProblem)
1120 out, _ = capsys.readouterr()
1121 assert "state" not in out
1122
1123
1124 def test_rule_deprecation_targets_and_target():
1125 k, v = Bundle("k"), Bundle("v")
1126 with pytest.raises(InvalidArgument):
1127 rule(targets=(k,), target=v)
1128
1129
1130 def test_rule_deprecation_bundle_by_name():
1131 Bundle("k")
1132 with pytest.raises(InvalidArgument):
1133 rule(target="k")
1134
1135
1136 def test_rule_non_bundle_target():
1137 with pytest.raises(InvalidArgument):
1138 rule(target=integers())
1139
1140
1141 def test_rule_non_bundle_target_oneof():
1142 k, v = Bundle("k"), Bundle("v")
1143 pattern = r".+ `one_of(a, b)` or `a | b` .+"
1144 with pytest.raises(InvalidArgument, match=pattern):
1145 rule(target=k | v)
1146
1147
1148 def test_uses_seed(capsys):
1149 @seed(0)
1150 class TrivialMachine(RuleBasedStateMachine):
1151 @rule()
1152 def oops(self):
1153 raise AssertionError
1154
1155 with pytest.raises(AssertionError):
1156 run_state_machine_as_test(TrivialMachine)
1157 out, _ = capsys.readouterr()
1158 assert "@seed" not in out
1159
1160
1161 def test_reproduce_failure_works():
1162 @reproduce_failure(__version__, encode_failure([False, 0, True]))
1163 class TrivialMachine(RuleBasedStateMachine):
1164 @rule()
1165 def oops(self):
1166 raise AssertionError
1167
1168 with pytest.raises(AssertionError):
1169 run_state_machine_as_test(TrivialMachine, settings=Settings(print_blob=True))
1170
1171
1172 def test_reproduce_failure_fails_if_no_error():
1173 @reproduce_failure(__version__, encode_failure([False, 0, True]))
1174 class TrivialMachine(RuleBasedStateMachine):
1175 @rule()
1176 def ok(self):
1177 pass
1178
1179 with pytest.raises(DidNotReproduce):
1180 run_state_machine_as_test(TrivialMachine, settings=Settings(print_blob=True))
1181
1182
1183 def test_cannot_have_zero_steps():
1184 with pytest.raises(InvalidArgument):
1185 Settings(stateful_step_count=0)
1186
1187
1188 def test_arguments_do_not_use_names_of_return_values():
1189 # See https://github.com/HypothesisWorks/hypothesis/issues/2341
1190 class TrickyPrintingMachine(RuleBasedStateMachine):
1191 data = Bundle("data")
1192
1193 @initialize(target=data, value=integers())
1194 def init_data(self, value):
1195 return value
1196
1197 @rule(d=data)
1198 def mostly_fails(self, d):
1199 assert d == 42
1200
1201 with pytest.raises(AssertionError) as err:
1202 run_state_machine_as_test(TrickyPrintingMachine)
1203 assert "data_0 = state.init_data(value=0)" in err.value.__notes__
1204 assert "data_0 = state.init_data(value=data_0)" not in err.value.__notes__
1205
1206
1207 class TrickyInitMachine(RuleBasedStateMachine):
1208 @initialize()
1209 def init_a(self):
1210 self.a = 0
1211
1212 @rule()
1213 def inc(self):
1214 self.a += 1
1215
1216 @invariant()
1217 def check_a_positive(self):
1218 # This will fail if run before the init_a method, but without
1219 # @invariant(check_during_init=True) it will only run afterwards.
1220 assert self.a >= 0
1221
1222
1223 def test_invariants_are_checked_after_init_steps():
1224 run_state_machine_as_test(TrickyInitMachine)
1225
1226
1227 def test_invariants_can_be_checked_during_init_steps():
1228 class UndefinedMachine(TrickyInitMachine):
1229 @invariant(check_during_init=True)
1230 def check_a_defined(self):
1231 # This will fail because `a` is undefined before the init rule.
1232 self.a
1233
1234 with pytest.raises(AttributeError):
1235 run_state_machine_as_test(UndefinedMachine)
1236
1237
1238 def test_check_during_init_must_be_boolean():
1239 invariant(check_during_init=False)
1240 invariant(check_during_init=True)
1241 with pytest.raises(InvalidArgument):
1242 invariant(check_during_init="not a bool")
1243
1244
1245 def test_deprecated_target_consumes_bundle():
1246 # It would be nicer to raise this error at runtime, but the internals make
1247 # this sadly impractical. Most InvalidDefinition errors happen at, well,
1248 # definition-time already anyway, so it's not *worse* than the status quo.
1249 with validate_deprecation():
1250 rule(target=consumes(Bundle("b")))
1251
1252
1253 @Settings(stateful_step_count=5)
1254 class MinStepsMachine(RuleBasedStateMachine):
1255 @initialize()
1256 def init_a(self):
1257 self.a = 0
1258
1259 @rule()
1260 def inc(self):
1261 self.a += 1
1262
1263 @invariant()
1264 def not_too_many_steps(self):
1265 assert self.a < 10
1266
1267 def teardown(self):
1268 assert self.a >= 2
1269
1270
1271 # Replay overruns after we trigger a crosshair.util.IgnoreAttempt exception for n=3
1272 @xfail_on_crosshair(Why.other)
1273 def test_min_steps_argument():
1274 # You must pass a non-negative integer...
1275 for n_steps in (-1, "nan", 5.0):
1276 with pytest.raises(InvalidArgument):
1277 run_state_machine_as_test(MinStepsMachine, _min_steps=n_steps)
1278
1279 # and if you do, we'll take at least that many steps
1280 run_state_machine_as_test(MinStepsMachine, _min_steps=3)
1281
1282 # (oh, and it's OK if you ask for more than we're actually going to take)
1283 run_state_machine_as_test(MinStepsMachine, _min_steps=20)
1284
1285
1286 class ErrorsOnClassAttributeSettings(RuleBasedStateMachine):
1287 settings = Settings(derandomize=True)
1288
1289 @rule()
1290 def step(self):
1291 pass
1292
1293
1294 def test_fails_on_settings_class_attribute():
1295 with pytest.raises(
1296 InvalidDefinition,
1297 match=r"Assigning .+ as a class attribute does nothing",
1298 ):
1299 run_state_machine_as_test(ErrorsOnClassAttributeSettings)
1300
1301
1302 def test_single_target_multiple():
1303 class Machine(RuleBasedStateMachine):
1304 a = Bundle("a")
1305
1306 @initialize(target=a)
1307 def initialize(self):
1308 return multiple("ret1", "ret2", "ret3")
1309
1310 @rule(param=a)
1311 def fail_fast(self, param):
1312 raise AssertionError
1313
1314 Machine.TestCase.settings = NO_BLOB_SETTINGS
1315 with pytest.raises(AssertionError) as err:
1316 run_state_machine_as_test(Machine)
1317
1318 result = "\n".join(err.value.__notes__)
1319 assert (
1320 result
1321 == """
1322 Falsifying example:
1323 state = Machine()
1324 a_0, a_1, a_2 = state.initialize()
1325 state.fail_fast(param=a_2)
1326 state.teardown()
1327 """.strip()
1328 )
1329
1330
1331 @pytest.mark.parametrize(
1332 "bundle_names,initial,repr_",
1333 [
1334 ("a", "ret1", "a_0 = state.init()"),
1335 ("aba", "ret1", "a_0 = b_0 = a_1 = state.init()"),
1336 ("a", multiple(), "state.init()"),
1337 ("aba", multiple(), "state.init()"),
1338 ("a", multiple("ret1"), "(a_0,) = state.init()"),
1339 ("aba", multiple("ret1"), "(a_0,) = (b_0,) = (a_1,) = state.init()"),
1340 ("a", multiple("ret1", "ret2"), "a_0, a_1 = state.init()"),
1341 (
1342 "aba",
1343 multiple("ret1", "ret2"),
1344 "\n".join( # noqa: FLY002 # no, f-string is not more readable
1345 [
1346 "a_0, a_1 = state.init()",
1347 "b_0, b_1 = a_0, a_1",
1348 "a_2, a_3 = a_0, a_1",
1349 ]
1350 ),
1351 ),
1352 ],
1353 )
1354 def test_targets_repr(bundle_names, initial, repr_):
1355 bundles = {name: Bundle(name) for name in bundle_names}
1356
1357 class Machine(RuleBasedStateMachine):
1358 @initialize(targets=[bundles[name] for name in bundle_names])
1359 def init(self):
1360 return initial
1361
1362 @rule()
1363 def fail_fast(self):
1364 raise AssertionError
1365
1366 Machine.TestCase.settings = NO_BLOB_SETTINGS
1367 with pytest.raises(AssertionError) as err:
1368 run_state_machine_as_test(Machine)
1369
1370 result = "\n".join(err.value.__notes__)
1371 assert (
1372 result
1373 == f"""
1374 Falsifying example:
1375 state = Machine()
1376 {repr_}
1377 state.fail_fast()
1378 state.teardown()
1379 """.strip()
1380 )
1381
1382
1383 def test_multiple_targets():
1384 class Machine(RuleBasedStateMachine):
1385 a = Bundle("a")
1386 b = Bundle("b")
1387
1388 @initialize(targets=(a, b))
1389 def initialize(self):
1390 return multiple("ret1", "ret2", "ret3")
1391
1392 @rule(
1393 a1=consumes(a),
1394 a2=consumes(a),
1395 a3=consumes(a),
1396 b1=consumes(b),
1397 b2=consumes(b),
1398 b3=consumes(b),
1399 )
1400 def fail_fast(self, a1, a2, a3, b1, b2, b3):
1401 raise AssertionError
1402
1403 Machine.TestCase.settings = NO_BLOB_SETTINGS
1404 with pytest.raises(AssertionError) as err:
1405 run_state_machine_as_test(Machine)
1406
1407 result = "\n".join(err.value.__notes__)
1408 assert (
1409 result
1410 == """
1411 Falsifying example:
1412 state = Machine()
1413 a_0, a_1, a_2 = state.initialize()
1414 b_0, b_1, b_2 = a_0, a_1, a_2
1415 state.fail_fast(a1=a_2, a2=a_1, a3=a_0, b1=b_2, b2=b_1, b3=b_0)
1416 state.teardown()
1417 """.strip()
1418 )
1419
1420
1421 def test_multiple_common_targets():
1422 class Machine(RuleBasedStateMachine):
1423 a = Bundle("a")
1424 b = Bundle("b")
1425
1426 @initialize(targets=(a, b, a))
1427 def initialize(self):
1428 return multiple("ret1", "ret2", "ret3")
1429
1430 @rule(
1431 a1=consumes(a),
1432 a2=consumes(a),
1433 a3=consumes(a),
1434 a4=consumes(a),
1435 a5=consumes(a),
1436 a6=consumes(a),
1437 b1=consumes(b),
1438 b2=consumes(b),
1439 b3=consumes(b),
1440 )
1441 def fail_fast(self, a1, a2, a3, a4, a5, a6, b1, b2, b3):
1442 raise AssertionError
1443
1444 Machine.TestCase.settings = NO_BLOB_SETTINGS
1445 with pytest.raises(AssertionError) as err:
1446 run_state_machine_as_test(Machine)
1447
1448 result = "\n".join(err.value.__notes__)
1449 assert (
1450 result
1451 == """
1452 Falsifying example:
1453 state = Machine()
1454 a_0, a_1, a_2 = state.initialize()
1455 b_0, b_1, b_2 = a_0, a_1, a_2
1456 a_3, a_4, a_5 = a_0, a_1, a_2
1457 state.fail_fast(a1=a_5, a2=a_4, a3=a_3, a4=a_2, a5=a_1, a6=a_0, b1=b_2, b2=b_1, b3=b_0)
1458 state.teardown()
1459 """.strip()
1460 )
1461
1462
1463 class LotsOfEntropyPerStepMachine(RuleBasedStateMachine):
1464 # Regression tests for https://github.com/HypothesisWorks/hypothesis/issues/3618
1465 @rule(data=binary(min_size=512, max_size=512))
1466 def rule1(self, data):
1467 assert data
1468
1469
1470 @pytest.mark.skipif(
1471 Settings.get_current_profile_name() == "crosshair",
1472 reason="takes hours; too much symbolic data",
1473 )
1474 def test_lots_of_entropy():
1475 run_state_machine_as_test(LotsOfEntropyPerStepMachine)
1476
1477
1478 def test_flatmap():
1479 class Machine(RuleBasedStateMachine):
1480 buns = Bundle("buns")
1481
1482 @initialize(target=buns)
1483 def create_bun(self):
1484 return 0
1485
1486 @rule(target=buns, bun=buns.flatmap(lambda x: just(x + 1)))
1487 def use_flatmap(self, bun):
1488 assert isinstance(bun, int)
1489 return bun
1490
1491 @rule(bun=buns)
1492 def use_directly(self, bun):
1493 assert isinstance(bun, int)
1494
1495 Machine.TestCase.settings = Settings(stateful_step_count=5, max_examples=10)
1496 run_state_machine_as_test(Machine)
1497
1498
1499 def test_use_bundle_within_other_strategies():
1500 class Class:
1501 def __init__(self, value):
1502 self.value = value
1503
1504 class Machine(RuleBasedStateMachine):
1505 my_bundle = Bundle("my_bundle")
1506
1507 @initialize(target=my_bundle)
1508 def set_initial(self, /) -> str:
1509 return "sample text"
1510
1511 @rule(instance=st.builds(Class, my_bundle))
1512 def check(self, instance):
1513 assert isinstance(instance, Class)
1514 assert isinstance(instance.value, str)
1515
1516 Machine.TestCase.settings = Settings(stateful_step_count=5, max_examples=10)
1517 run_state_machine_as_test(Machine)
1518
1519
1520 def test_precondition_cannot_be_used_without_rule():
1521 class BadStateMachine(RuleBasedStateMachine):
1522 @precondition(lambda: True)
1523 def has_precondition_but_no_rule(self):
1524 pass
1525
1526 @rule(n=st.integers())
1527 def trivial(self, n):
1528 pass
1529
1530 with pytest.raises(
1531 InvalidDefinition,
1532 match=(
1533 "BadStateMachine\\.has_precondition_but_no_rule has been decorated "
1534 "with @precondition, but not @rule"
1535 ),
1536 ):
1537 BadStateMachine.TestCase().runTest()