| 1 | --- |
| 2 | tags: python, technical, intro |
| 3 | date: 2016-04-19 07:00 |
| 4 | title: Rule Based Stateful Testing |
| 5 | author: drmaciver |
| 6 | --- |
| 7 | |
| 8 | Hypothesis's standard testing mechanisms are very good for testing things that can be |
| 9 | considered direct functions of data. But supposed you have some complex stateful |
| 10 | system or object that you want to test. How can you do that? |
| 11 | |
| 12 | In this article we'll see how to use Hypothesis's *rule based state machines* to define |
| 13 | tests that generate not just simple data, but entire programs using some stateful |
| 14 | object. These will give the same level of boost to testing the behaviour of the |
| 15 | object as you get to testing the data it accepts. |
| 16 | |
| 17 | <!--more--> |
| 18 | |
| 19 | The model of a stateful system we'll be using is a [priority queue](https://en.wikipedia.org/wiki/Priority_queue) |
| 20 | implemented as a binary heap. |
| 21 | |
| 22 | We have the following operations: |
| 23 | |
| 24 | * newheap() - returns a new heap |
| 25 | * heappush(heap, value) - place a new value into the heap |
| 26 | * heappop(heap) - remove and return the smallest value currently on the heap. Error if heap is empty. |
| 27 | * heapempty(heap) - return True if the heap has no elements, else False. |
| 28 | |
| 29 | We'll use the following implementation of these: |
| 30 | |
| 31 | ```python |
| 32 | def heapnew(): |
| 33 | return [] |
| 34 | |
| 35 | |
| 36 | def heapempty(heap): |
| 37 | return not heap |
| 38 | |
| 39 | |
| 40 | def heappush(heap, value): |
| 41 | heap.append(value) |
| 42 | index = len(heap) - 1 |
| 43 | while index > 0: |
| 44 | parent = (index - 1) // 2 |
| 45 | if heap[parent] > heap[index]: |
| 46 | heap[parent], heap[index] = heap[index], heap[parent] |
| 47 | index = parent |
| 48 | else: |
| 49 | break |
| 50 | |
| 51 | |
| 52 | def heappop(heap): |
| 53 | return heap.pop(0) |
| 54 | ``` |
| 55 | |
| 56 | (Note that this implementation is *wrong*. heappop as implemented will return the smallest element |
| 57 | if the heap currently satisfies the heap property, but it will not rebalance the heap afterwards |
| 58 | so it may leave the heap in an invalid state) |
| 59 | |
| 60 | We could test this readily enough using @given with something like the following: |
| 61 | |
| 62 | |
| 63 | ```python |
| 64 | from hypothesis import given |
| 65 | from hypothesis.strategies import integers, lists |
| 66 | |
| 67 | |
| 68 | @given(lists(integers())) |
| 69 | def test_pop_in_sorted_order(ls): |
| 70 | h = heapnew() |
| 71 | for l in ls: |
| 72 | heappush(h, l) |
| 73 | r = [] |
| 74 | while not heapempty(h): |
| 75 | r.append(heappop(h)) |
| 76 | assert r == sorted(ls) |
| 77 | ``` |
| 78 | |
| 79 | And this indeed finds the bug: |
| 80 | |
| 81 | ``` |
| 82 | > assert r == sorted(ls) |
| 83 | E assert [0, 1, 0] == [0, 0, 1] |
| 84 | E At index 1 diff: 1 != 0 |
| 85 | E Use -v to get the full diff |
| 86 | |
| 87 | binheap.py:74: AssertionError |
| 88 | ----- Hypothesis ----- |
| 89 | Falsifying example: test_pop_in_sorted_order(ls=[0, 1, 0]) |
| 90 | ``` |
| 91 | |
| 92 | So we replace heappop with a correct implementation which rebalances the heap: |
| 93 | |
| 94 | ```python |
| 95 | def heappop(heap): |
| 96 | if len(heap) == 0: |
| 97 | raise ValueError("Empty heap") |
| 98 | if len(heap) == 1: |
| 99 | return heap.pop() |
| 100 | result = heap[0] |
| 101 | heap[0] = heap.pop() |
| 102 | index = 0 |
| 103 | while index * 2 + 1 < len(heap): |
| 104 | children = [index * 2 + 1, index * 2 + 2] |
| 105 | children = [i for i in children if i < len(heap)] |
| 106 | assert children |
| 107 | children.sort(key=lambda x: heap[x]) |
| 108 | for c in children: |
| 109 | if heap[index] > heap[c]: |
| 110 | heap[index], heap[c] = heap[c], heap[index] |
| 111 | index = c |
| 112 | break |
| 113 | else: |
| 114 | break |
| 115 | return result |
| 116 | ``` |
| 117 | |
| 118 | But how do we know this is enough? Might some combination of mixing pushes and pops break the |
| 119 | invariants of the heap in a way that this simple pattern of pushing everything then popping |
| 120 | everything cannot witness? |
| 121 | |
| 122 | This is where the rule based state machines come in. Instead of just letting Hypothesis give |
| 123 | us data which we feed into a fixed structure of test, we let Hypothesis choose which operations |
| 124 | to perform on our data structure: |
| 125 | |
| 126 | ```python |
| 127 | from hypothesis.stateful import RuleBasedStateMachine, precondition, rule |
| 128 | |
| 129 | |
| 130 | class HeapMachine(RuleBasedStateMachine): |
| 131 | def __init__(self): |
| 132 | super().__init__() |
| 133 | self.heap = [] |
| 134 | |
| 135 | @rule(value=integers()) |
| 136 | def push(self, value): |
| 137 | heappush(self.heap, value) |
| 138 | |
| 139 | @rule() |
| 140 | @precondition(lambda self: self.heap) |
| 141 | def pop(self): |
| 142 | correct = min(self.heap) |
| 143 | result = heappop(self.heap) |
| 144 | assert correct == result |
| 145 | ``` |
| 146 | |
| 147 | @rule is a slightly restricted version of @given that only works for methods on a RuleBasedStateMachine. |
| 148 | |
| 149 | However it has one *major* difference from @given, which is that multiple rules can be chained together: |
| 150 | A test using this state machine doesn't just run each rule in isolation, it instantiates an instance of |
| 151 | the machine and then runs multiple rules in succession. |
| 152 | |
| 153 | The @precondition decorator constrains when a rule is allowed to fire: We are not allowed to pop from |
| 154 | an empty heap, so the pop rule may only fire when there is data to be popped. |
| 155 | |
| 156 | We can run this by getting a standard unit test TestCase object out of it to be picked up by unittest |
| 157 | or py.test as normal: |
| 158 | |
| 159 | ```python |
| 160 | TestHeaps = HeapMachine.TestCase |
| 161 | ``` |
| 162 | |
| 163 | With our original broken heappop we find the same bug as before: |
| 164 | |
| 165 | ``` |
| 166 | E AssertionError: assert 0 == 1 |
| 167 | |
| 168 | binheap.py:90: AssertionError |
| 169 | ----- Captured stdout call ----- |
| 170 | Step #1: push(value=1) |
| 171 | Step #2: push(value=0) |
| 172 | Step #3: push(value=0) |
| 173 | Step #4: pop() |
| 174 | Step #5: pop() |
| 175 | ``` |
| 176 | |
| 177 | With the fixed implementation the test passes. |
| 178 | |
| 179 | As it currently stands, this is already very useful. It's particularly good for testing single standalone |
| 180 | objects or services like storage systems. |
| 181 | |
| 182 | But one limitation of it as we have written it is that it only concerns ourselves with a single heap. What |
| 183 | if we wanted to combine two heaps? For example, suppose we wanted a heap merging operation that takes two |
| 184 | heaps and returns a new heap containing the values in either of the original two. |
| 185 | |
| 186 | As before, we'll start with a broken implementation: |
| 187 | |
| 188 | ```python |
| 189 | def heapmerge(x, y): |
| 190 | x, y = sorted((x, y)) |
| 191 | return x + y |
| 192 | ``` |
| 193 | |
| 194 | We can't just write a strategy for heaps, because each heap would be a fresh object and thus it would not |
| 195 | preserve the stateful aspect. |
| 196 | |
| 197 | What we instead do is use the other big feature of Hypothesis's rule bases state machines: Bundles. |
| 198 | |
| 199 | Bundles allow rules to return as well as accept values. A bundle is a strategy which generates anything |
| 200 | a rule has previously provided to it. Using them is as follows: |
| 201 | |
| 202 | |
| 203 | ```python |
| 204 | class HeapMachine(RuleBasedStateMachine): |
| 205 | Heaps = Bundle("heaps") |
| 206 | |
| 207 | @rule(target=Heaps) |
| 208 | def newheap(self): |
| 209 | return [] |
| 210 | |
| 211 | @rule(heap=Heaps, value=integers()) |
| 212 | def push(self, heap, value): |
| 213 | heappush(heap, value) |
| 214 | |
| 215 | @rule(heap=Heaps.filter(bool)) |
| 216 | def pop(self, heap): |
| 217 | correct = min(heap) |
| 218 | result = heappop(heap) |
| 219 | assert correct == result |
| 220 | |
| 221 | @rule(target=Heaps, heap1=Heaps, heap2=Heaps) |
| 222 | def merge(self, heap1, heap2): |
| 223 | return heapmerge(heap1, heap2) |
| 224 | ``` |
| 225 | |
| 226 | So now instead of a single heap we manage a collection of heaps. All of our previous operations become |
| 227 | constrained by an instance of a heap. |
| 228 | |
| 229 | Note the use of filter: A bundle is a strategy you can use like any other. In this case the filter replaces |
| 230 | our use of a precondition because we now only care about whether this *specific* heap is empty. |
| 231 | |
| 232 | This is sufficient to find the fact that our implementation is wrong: |
| 233 | |
| 234 | ``` |
| 235 | @rule(heap=Heaps.filter(bool)) |
| 236 | def pop(self, heap): |
| 237 | correct = min(heap) |
| 238 | result = heappop(heap) |
| 239 | > assert correct == result |
| 240 | E AssertionError: assert 0 == 1 |
| 241 | |
| 242 | binheap.py:105: AssertionError |
| 243 | |
| 244 | ----- Captured stdout call ----- |
| 245 | |
| 246 | Step #1: v1 = newheap() |
| 247 | Step #2: push(heap=v1, value=0) |
| 248 | Step #3: push(heap=v1, value=1) |
| 249 | Step #4: push(heap=v1, value=1) |
| 250 | Step #5: v2 = merge(heap2=v1, heap1=v1) |
| 251 | Step #6: pop(heap=v2) |
| 252 | Step #7: pop(heap=v2) |
| 253 | ``` |
| 254 | |
| 255 | We create a small heap, merge it with itself, and rapidly discover that it has become unbalanced. |
| 256 | |
| 257 | We can fix this by fixing our heapmerge to be correct: |
| 258 | |
| 259 | ```python |
| 260 | def heapmerge(x, y): |
| 261 | result = list(x) |
| 262 | for v in y: |
| 263 | heappush(result, v) |
| 264 | return result |
| 265 | ``` |
| 266 | |
| 267 | But that's boring. Lets introduce a more *interestingly* broken implementation instead: |
| 268 | |
| 269 | ```python |
| 270 | def heapmerge(x, y): |
| 271 | result = [] |
| 272 | i = 0 |
| 273 | j = 0 |
| 274 | while i < len(x) and j < len(y): |
| 275 | if x[i] <= y[j]: |
| 276 | result.append(x[i]) |
| 277 | i += 1 |
| 278 | else: |
| 279 | result.append(y[j]) |
| 280 | j += 1 |
| 281 | result.extend(x[i:]) |
| 282 | result.extend(y[j:]) |
| 283 | return result |
| 284 | ``` |
| 285 | |
| 286 | This merge operation selectively splices two heaps together as if we were merging two |
| 287 | sorted lists (heaps aren't actually sorted, but the code still works regardless it |
| 288 | just doesn't do anything very meaningful). |
| 289 | |
| 290 | This is wrong, but it turns out to work surprisingly well for small heaps and it's |
| 291 | not completely straightforward to find an example showing that it's wrong. |
| 292 | |
| 293 | Here's what Hypothesis comes up with: |
| 294 | |
| 295 | ``` |
| 296 | Step #1: v1 = newheap() |
| 297 | Step #2: push(heap=v1, value=0) |
| 298 | Step #3: v2 = merge(heap1=v1, heap2=v1) |
| 299 | Step #4: v3 = merge(heap1=v2, heap2=v2) |
| 300 | Step #5: push(heap=v3, value=-1) |
| 301 | Step #6: v4 = merge(heap1=v1, heap2=v2) |
| 302 | Step #7: pop(heap=v4) |
| 303 | Step #8: push(heap=v3, value=-1) |
| 304 | Step #9: v5 = merge(heap1=v1, heap2=v2) |
| 305 | Step #10: v6 = merge(heap1=v5, heap2=v4) |
| 306 | Step #11: v7 = merge(heap1=v6, heap2=v3) |
| 307 | Step #12: pop(heap=v7) |
| 308 | Step #13: pop(heap=v7) |
| 309 | ``` |
| 310 | |
| 311 | Through a careful set of heap creation and merging, Hypothesis manages to find a series |
| 312 | of merges that produce an unbalanced heap. Every heap prior to v7 is balanced, but v7 looks |
| 313 | like this: |
| 314 | |
| 315 | ``` |
| 316 | >>> v7 |
| 317 | [-1, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0] |
| 318 | ``` |
| 319 | |
| 320 | Which doesn't satisfy the heap property because of that -1 far down in the list. |
| 321 | |
| 322 | I don't know about you, but I would never have come up with that example. There's probably |
| 323 | a simpler one given a different set of operations - e.g. one thing that would probably improve |
| 324 | the quality of this test is to let Hypothesis instantiate a new heap with a list of elements |
| 325 | which it pops onto it. |
| 326 | |
| 327 | But the nice thing about rule based stateful testing is that I don't *have* to come up with |
| 328 | the example. Instead Hypothesis is able to guarantee that every combination of operations |
| 329 | on my objects works, and can flush out some remarkably subtle bugs in the process. |
| 330 | |
| 331 | Because after all, if it takes this complicated an example to demonstrate that a completely |
| 332 | wrong implementation is wrong, how hard can it sometimes be to demonstrate subtle bugs? |
| 333 | |
| 334 | ### Real world usage |
| 335 | |
| 336 | This feature is currently somewhat under-documented so hasn't seen as widespread adoption as |
| 337 | it could. However, there are at least two interesting real world examples: |
| 338 | |
| 339 | 1. Hypothesis uses it to test itself. Hypothesis has [tests of its example database]( |
| 340 | https://github.com/HypothesisWorks/hypothesis-python/blob/master/tests/cover/test_database_agreement.py) |
| 341 | which work very much like the above, and [a small model of its test API]( |
| 342 | https://github.com/HypothesisWorks/hypothesis-python/blob/master/tests/nocover/test_strategy_state.py) |
| 343 | which generates random strategies and runs tests using them. |
| 344 | 2. It's being used to [test Mercurial](https://www.mercurial-scm.org/pipermail/mercurial-devel/2016-February/080037.html) |
| 345 | generating random. So far it's found [bug 5112](https://bz.mercurial-scm.org/show_bug.cgi?id=5112) and |
| 346 | [bug 5113](https://bz.mercurial-scm.org/show_bug.cgi?id=5113). The usage pattern on Mercurial is one |
| 347 | such that the stateful testing probably needs more resources, more rules and more work on deployment |
| 348 | before it's going to find much more than that though. |