| 1 | --- |
| 2 | tags: python, intro, technical, properties |
| 3 | date: 2016-04-16 06:00 |
| 4 | title: The Encode/Decode invariant |
| 5 | author: drmaciver |
| 6 | --- |
| 7 | |
| 8 | One of the simplest types of invariant to find once you move past |
| 9 | [just fuzzing your code](../getting-started-with-hypothesis/) is asserting that two |
| 10 | different operations should produce the same result, and one of the simplest instances of |
| 11 | *that* is looking for encode/decode pairs. That is, you have some function that takes a |
| 12 | value and encodes it as another value, and another that is supposed to reverse the process. |
| 13 | |
| 14 | This is ripe for testing with Hypothesis because it has a natural completely defined |
| 15 | specification: Encoding and then decoding should be exactly the same as doing nothing. |
| 16 | |
| 17 | Let's look at a concrete example. |
| 18 | |
| 19 | <!--more--> |
| 20 | |
| 21 | The following code is a lightly reformatted version of |
| 22 | an implementation of [Run Length Encoding](https://en.wikipedia.org/wiki/Run-length_encoding) |
| 23 | taken [from Rosetta Code](http://rosettacode.org/wiki/Run-length_encoding). |
| 24 | |
| 25 | ```python |
| 26 | def encode(input_string): |
| 27 | count = 1 |
| 28 | prev = "" |
| 29 | lst = [] |
| 30 | for character in input_string: |
| 31 | if character != prev: |
| 32 | if prev: |
| 33 | entry = (prev, count) |
| 34 | lst.append(entry) |
| 35 | count = 1 |
| 36 | prev = character |
| 37 | else: |
| 38 | count += 1 |
| 39 | else: |
| 40 | entry = (character, count) |
| 41 | lst.append(entry) |
| 42 | return lst |
| 43 | |
| 44 | |
| 45 | def decode(lst): |
| 46 | q = "" |
| 47 | for character, count in lst: |
| 48 | q += character * count |
| 49 | return q |
| 50 | ``` |
| 51 | |
| 52 | We can test this using Hypothesis and py.test as follows: |
| 53 | |
| 54 | |
| 55 | ```python |
| 56 | from hypothesis import given |
| 57 | from hypothesis.strategies import text |
| 58 | |
| 59 | |
| 60 | @given(text()) |
| 61 | def test_decode_inverts_encode(s): |
| 62 | assert decode(encode(s)) == s |
| 63 | ``` |
| 64 | |
| 65 | This asserts what we described above: If we encode a string as run length encoded and then |
| 66 | decode it, we get back to where we started. |
| 67 | |
| 68 | This test finds a bug, not through the actual invariant. Instead it finds one through pure |
| 69 | fuzzing: The code does not correctly handle the empty string. |
| 70 | |
| 71 | |
| 72 | ``` |
| 73 | Falsifying example: test_decode_inverts_encode(s='') |
| 74 | |
| 75 | UnboundLocalError: local variable 'character' referenced before assignment |
| 76 | ``` |
| 77 | |
| 78 | One of the nice features of testing invariants is that they incorporate the fuzzing you |
| 79 | could be doing anyway, more or less for free, so even trivial invariants can often |
| 80 | find interesting problems. |
| 81 | |
| 82 | We can fix this bug by adding a guard to the encode function: |
| 83 | |
| 84 | ```python |
| 85 | if not input_string: |
| 86 | return [] |
| 87 | ``` |
| 88 | |
| 89 | The test now passes, which isn't very interesting, so let's break the code. We'll delete |
| 90 | a line from our implementation of encode which resets the count when the character changes: |
| 91 | |
| 92 | |
| 93 | ```python |
| 94 | def encode(input_string): |
| 95 | if not input_string: |
| 96 | return [] |
| 97 | count = 1 |
| 98 | prev = "" |
| 99 | lst = [] |
| 100 | for character in input_string: |
| 101 | if character != prev: |
| 102 | if prev: |
| 103 | entry = (prev, count) |
| 104 | lst.append(entry) |
| 105 | # count = 1 # Missing reset operation |
| 106 | prev = character |
| 107 | else: |
| 108 | count += 1 |
| 109 | else: |
| 110 | entry = (character, count) |
| 111 | lst.append(entry) |
| 112 | return lst |
| 113 | ``` |
| 114 | |
| 115 | Now the test fails: |
| 116 | |
| 117 | ``` |
| 118 | @given(text()) |
| 119 | def test_decode_inverts_encode(s): |
| 120 | > assert decode(encode(s)) == s |
| 121 | E assert '1100' == '110' |
| 122 | E - 1100 |
| 123 | E ? - |
| 124 | E + 110 |
| 125 | |
| 126 | test_encoding.py:35: AssertionError |
| 127 | ------------------------------------ Hypothesis ------------------------------------ |
| 128 | Falsifying example: test_decode_inverts_encode(s='110') |
| 129 | |
| 130 | ``` |
| 131 | |
| 132 | Not resetting the count did indeed produce unintended data that doesn't translate back |
| 133 | to the original thing. Hypothesis has given us the shortest example that could trigger |
| 134 | it - two identical characters followed by one different one. It's not *quite* the |
| 135 | simplest example according to Hypothesis's preferred ordering - that would be '001' - |
| 136 | but it's still simple enough to be quite legible, which helps to rapidly diagnose |
| 137 | the problem when you see it in real code. |
| 138 | |
| 139 | Encode/decode loops like this are *very* common, because you will frequently want to |
| 140 | serialize your domain objects to other representations - into forms, into APIs, into |
| 141 | the database, and these are things that are so integral to your applications that it's |
| 142 | worth getting all the edge cases right. |
| 143 | |
| 144 | Other examples of this: |
| 145 | |
| 146 | * [This talk by Matt Bacchman](https://speakerdeck.com/bachmann1234/property-based-testing-hypothesis) |
| 147 | in which he discovers an eccentricity of formats for dates. |
| 148 | * Mercurial bugs [4927](https://bz.mercurial-scm.org/show_bug.cgi?id=4927) and [5031](https://bz.mercurial-scm.org/show_bug.cgi?id=5031) |
| 149 | were found by applying this sort of testing to their internal UTF8b encoding functions. |
| 150 | * [This test](https://github.com/The-Compiler/qutebrowser/blob/24a71e5c2ebbffd9021694f32fa9ec51d0046d5a/tests/unit/browser/test_webelem.py#L652). |
| 151 | Has caught three bugs in Qutebrowser's JavaScript escaping ([1](https://github.com/The-Compiler/qutebrowser/commit/73e9fd11188ce4dddd7626e39d691e0df649e87c), |
| 152 | [2](https://github.com/The-Compiler/qutebrowser/commit/93d27cbb5f49085dd5a7f5e05f2cc45cc84f94a4), |
| 153 | [3](https://github.com/The-Compiler/qutebrowser/commit/24a71e5c2ebbffd9021694f32fa9ec51d0046d5a)), which could have caused data loss if a user had run |
| 154 | into them. |