Debian Codegraph @

hypothesis-python/docs/stateful.rst

raw
1 Stateful tests
2 ==============
3
4 .. note::
5
6 See also `How not to Die Hard with Hypothesis <https://hypothesis.works/articles/how-not-to-die-hard-with-hypothesis/>`__ and `An Introduction to Rule-Based Stateful Testing <https://hypothesis.works/articles/rule-based-stateful-testing/>`__.
7
8 With |@given|, your tests are still something that you mostly write yourself, with Hypothesis providing some data. With Hypothesis's *stateful testing*, Hypothesis instead tries to generate not just data but entire tests. You specify a number of primitive actions that can be combined together, and then Hypothesis will try to find sequences of those actions that result in a failure.
9
10 You may not need stateful tests
11 -------------------------------
12
13 The basic idea of stateful testing is to make Hypothesis choose actions as well as values for your test, and state machines are a great declarative way to do just that.
14
15 For simpler cases though, you might not need them at all - a standard test with |@given| might be enough, since you can use |st.data| in branches or loops. In fact, that's how the state machine explorer works internally. For more complex workloads though, where a higher level API comes into it's own, keep reading!
16
17 Rule-based state machines
18 -------------------------
19
20 A state machine is very similar to a normal |@given| based test in that it takes values drawn from strategies and passes them to a user defined test function, which may use assertions to check the system's behavior. The key difference is that where |@given| based tests must be independent, rules can be chained together - a single test run may involve multiple rule invocations, which may interact in various ways.
21
22 Rules can take normal strategies as arguments, but normal strategies, with the exception of :func:`~hypothesis.strategies.runner` and |st.data|, cannot take into account the current state of the machine. This is where bundles come in.
23
24 A rule can, in place of a normal strategy, take a :class:`~hypothesis.stateful.Bundle`. A :class:`hypothesis.stateful.Bundle` is a named collection of generated values that can be reused by other operations in the test. They are populated with the results of rules, and may be used as arguments to rules, allowing data to flow from one rule to another, and rules to work on the results of previous computations or actions.
25
26 Specifically, a rule that specifies ``target=a_bundle`` will cause its return value to be added to that bundle. A rule that specifies ``an_argument=a_bundle`` as a strategy will draw a value from that bundle. A rule can also specify that an argument chooses a value from a bundle and removes that value by using :func:`~hypothesis.stateful.consumes` as in ``an_argument=consumes(a_bundle)``.
27
28 .. note::
29 There is some overlap between what you can do with Bundles and what you can do with instance variables. Both represent state that rules can manipulate. If you do not need to draw values that depend on the machine's state, you can simply use instance variables. If you do need to draw values that depend on the machine's state, Bundles provide a fairly straightforward way to do this. If you need rules that draw values that depend on the machine's state in some more complicated way, you will have to abandon bundles. You can use :func:`~hypothesis.strategies.runner` and |.flatmap| to access the instance from a rule: the strategy ``runner().flatmap(lambda self: sampled_from(self.a_list))`` will draw from the instance variable ``a_list``. If you need something more complicated still, you can use |st.data| to draw data from the instance (or anywhere else) based on logic in the rule.
30
31 The following rule based state machine example is a simplified version of a test for Hypothesis's example database implementation. An example database maps keys to sets of values, and in this test we compare one implementation of it to a simplified in memory model of its behaviour, which just stores the same values in a Python ``dict``. The test then runs operations against both the real database and the in-memory representation of it and looks for discrepancies in their behaviour.
32
33 .. code:: python
34
35 import shutil
36 import tempfile
37 from collections import defaultdict
38
39 import hypothesis.strategies as st
40 from hypothesis.database import DirectoryBasedExampleDatabase
41 from hypothesis.stateful import Bundle, RuleBasedStateMachine, rule
42
43 class DatabaseComparison(RuleBasedStateMachine):
44 def __init__(self):
45 super().__init__()
46 self.tempd = tempfile.mkdtemp()
47 self.database = DirectoryBasedExampleDatabase(self.tempd)
48 self.model = defaultdict(set)
49
50 keys = Bundle("keys")
51 values = Bundle("values")
52
53 @rule(target=keys, k=st.binary())
54 def add_key(self, k):
55 return k
56
57 @rule(target=values, v=st.binary())
58 def add_value(self, v):
59 return v
60
61 @rule(k=keys, v=values)
62 def save(self, k, v):
63 self.model[k].add(v)
64 self.database.save(k, v)
65
66 @rule(k=keys, v=values)
67 def delete(self, k, v):
68 self.model[k].discard(v)
69 self.database.delete(k, v)
70
71 @rule(k=keys)
72 def values_agree(self, k):
73 assert set(self.database.fetch(k)) == self.model[k]
74
75 def teardown(self):
76 shutil.rmtree(self.tempd)
77
78 TestDBComparison = DatabaseComparison.TestCase
79
80 In this we declare two bundles - one for keys, and one for values. We have two trivial rules which just populate them with data (``k`` and ``v``), and three non-trivial rules: ``save`` saves a value under a key and ``delete`` removes a value from a key, in both cases also updating the model of what *should* be in the database. ``values_agree`` then checks that the contents of the database agrees with the model for a particular key.
81
82 .. note::
83
84 While this could have been simplified by not using bundles, generating keys and values directly in the ``save`` and ``delete`` rules, using bundles encourages Hypothesis to choose the same keys and values for multiple operations. The bundle operations establish a "universe" of keys and values that are used in the rules.
85
86 We can now integrate this into our test suite by getting a unittest TestCase from it:
87
88 .. code:: python
89
90 TestTrees = DatabaseComparison.TestCase
91
92 # Or just run with pytest's unittest support
93 if __name__ == "__main__":
94 unittest.main()
95
96 This test currently passes, but if we comment out the line where we call ``self.model[k].discard(v)``, we would see the following output when run under pytest::
97
98 AssertionError: assert set() == {b''}
99
100 ------------ Hypothesis ------------
101
102 state = DatabaseComparison()
103 var1 = state.add_key(k=b'')
104 var2 = state.add_value(v=var1)
105 state.save(k=var1, v=var2)
106 state.delete(k=var1, v=var2)
107 state.values_agree(k=var1)
108 state.teardown()
109
110 Note how it's printed out a very short program that will demonstrate the problem. The output from a rule based state machine should generally be pretty close to Python code - if you have custom ``repr`` implementations that don't return valid Python then it might not be, but most of the time you should just be able to copy and paste the code into a test to reproduce it.
111
112 You can control the detailed behaviour with a settings object on the TestCase (this is a normal hypothesis settings object using the defaults at the time the TestCase class was first referenced). For example if you wanted to run fewer examples with larger programs you could change the settings to:
113
114 .. code:: python
115
116 DatabaseComparison.TestCase.settings = settings(
117 max_examples=50, stateful_step_count=100
118 )
119
120 Which doubles the number of steps each program runs and halves the number of test cases that will be run.
121
122 Rules
123 -----
124
125 As said earlier, rules are the most common feature used in RuleBasedStateMachine. They are defined by applying the :func:`~hypothesis.stateful.rule` decorator
126 on a function. Note that RuleBasedStateMachine must have at least one rule defined and that a single function cannot be used to define multiple rules (this is to avoid having multiple rules doing the same things). Due to the stateful execution method, rules generally cannot take arguments from other sources such as fixtures or ``pytest.mark.parametrize`` - consider providing them via a strategy such as :func:`~hypothesis.strategies.sampled_from` instead.
127
128 Initializes
129 -----------
130
131 Initializes are a special case of rules, which are guaranteed to be run exactly once before any normal rule is called. Note if multiple initialize rules are defined, they will all be called but in any order, and that order will vary from run to run.
132
133 Initializes are typically useful to populate bundles:
134
135 .. code:: python
136
137 import hypothesis.strategies as st
138 from hypothesis.stateful import Bundle, RuleBasedStateMachine, initialize, rule
139
140 name_strategy = st.text(min_size=1).filter(lambda x: "/" not in x)
141
142 class NumberModifier(RuleBasedStateMachine):
143 folders = Bundle("folders")
144 files = Bundle("files")
145
146 @initialize(target=folders)
147 def init_folders(self):
148 return "/"
149
150 @rule(target=folders, parent=folders, name=name_strategy)
151 def create_folder(self, parent, name):
152 return f"{parent}/{name}"
153
154 @rule(target=files, parent=folders, name=name_strategy)
155 def create_file(self, parent, name):
156 return f"{parent}/{name}"
157
158 Initializes can also allow you to initialize the system under test in a way that depends on values chosen from a strategy. You could do this by putting an instance variable in the state machine that indicates whether the system under test has been initialized or not, and then using preconditions (below) to ensure that exactly one of the rules that initialize it get run before any rules that depend on it being initialized.
159
160 Preconditions
161 -------------
162
163 While it's possible to use :func:`~hypothesis.assume` in RuleBasedStateMachine rules, if you use it in only a few rules you can quickly run into a situation where few or none of your rules pass their assumptions. Thus, Hypothesis provides a :func:`~hypothesis.stateful.precondition` decorator to avoid this problem. The :func:`~hypothesis.stateful.precondition` decorator is used on ``rule``-decorated functions, and must be given a function that returns True or False based on the RuleBasedStateMachine instance.
164
165 .. code:: python
166
167 from hypothesis.stateful import RuleBasedStateMachine, precondition, rule
168
169 class NumberModifier(RuleBasedStateMachine):
170 num = 0
171
172 @rule()
173 def add_one(self):
174 self.num += 1
175
176 @precondition(lambda self: self.num != 0)
177 @rule()
178 def divide_with_one(self):
179 self.num = 1 / self.num
180
181 By using :func:`~hypothesis.stateful.precondition` here instead of :func:`~hypothesis.assume`, Hypothesis can filter the inapplicable rules before running them. This makes it much more likely that a useful sequence of steps will be generated.
182
183 Note that currently preconditions can't access bundles; if you need to use preconditions, you should store relevant data on the instance instead.
184
185 Invariants
186 ----------
187
188 Often there are invariants that you want to ensure are met after every step in a process. It would be possible to add these as rules that are run, but they would be run zero or multiple times between other rules. Hypothesis provides a decorator that marks a function to be run after every step.
189
190 .. code:: python
191
192 from hypothesis.stateful import RuleBasedStateMachine, invariant, rule
193
194 class NumberModifier(RuleBasedStateMachine):
195 num = 0
196
197 @rule()
198 def add_two(self):
199 self.num += 2
200 if self.num > 50:
201 self.num += 1
202
203 @invariant()
204 def is_even(self):
205 assert self.num % 2 == 0
206
207 NumberTest = NumberModifier.TestCase
208
209 Invariants can also have :func:`~hypothesis.stateful.precondition`\ s applied to them, in which case they will only be run if the precondition function returns true.
210
211 Note that currently invariants can't access bundles; if you need to use invariants, you should store relevant data on the instance instead.
212
213 More fine grained control
214 -------------------------
215
216 If you want to bypass the TestCase infrastructure you can invoke these manually. The stateful module exposes the function ``run_state_machine_as_test``, which takes an arbitrary function returning a RuleBasedStateMachine and an optional settings parameter and does the same as the class based runTest provided.