Debian Codegraph @

website/content/2016-10-17-canonical-serialization.md

raw symbols SCIP
1 ---
2 tags: python, intro, technical, properties
3 date: 2016-10-17 06:00
4 title: Another invariant to test for encoders
5 author: drmaciver
6 ---
7
8 [The encode/decode invariant](../encode-decode-invariant/)
9 is one of the most important properties to know about for testing your code with Hypothesis
10 or other property-based testing systems, because it captures a very common pattern and is
11 very good at finding bugs.
12
13 But how do you go beyond it? If encoders are that common, surely there must be other things
14 to test with them?
15
16 <!--more-->
17
18 The first thing that people tend to try is to simply reverse the order of operations. Continuing
19 the same example from the encode/decode post, this would look something like this:
20
21 ```python
22 from hypothesis import given
23 from hypothesis.strategies import characters, integers, lists, tuples
24
25
26 @given(lists(tuples(characters(), integers(1, 10))))
27 def test_encode_inverts_decode(s):
28 assert encode(decode(s)) == s
29 ```
30
31 But unlike the other way around, this test can fail for reasons that are not obviously
32 errors in the system under test. In particular this will fail with the example [('0', 1), ('0', 1)],
33 because this will be decoded into '00', which will then be encoded into [('0', 2)].
34
35 In general, it is quite common to have multiple non-canonical representations of data
36 when encoding: e.g. JSON has non-significant whitespace, an IP address has a wide range
37 of human readable representations, most compressors will evolve to improve their compression
38 over time but will still be able to handle compressed files made with old versions of
39 the code, etc.
40
41 So this test *shouldn't* be expected to pass.
42
43 To rescue this, we might imagine we had some sort of function make\_canonical which
44 took an encoded data representation and replaced it with a canonical version of that (e.g.
45 by normalizing whitespace). The test could then look like this:
46
47
48 ```python
49 @given(lists(tuples(characters(), integers(1, 10))))
50 def test_encode_inverts_decode(s):
51 assert make_canonical(encode(decode(s))) == make_canonical(s)
52 ```
53
54 But where would we get that make\_canonical function from? It's not something we really
55 want to write ourselves.
56
57 Fortunately we can put together the pieces we already have to define such a function
58 fairly easily. To see this, lets think about what properties make\_canonical should have.
59
60 The following seem reasonable:
61
62 1. encode should always produce canonical data. i.e. encode(t) == make_canonical(encode(t))
63 2. Canonical data should represent the same value. i.e. decode(s) == decode(make_canonical(s))
64
65 But we already know that decode(encode(t)) == t from our original property, so we have a
66 natural source of data that is the output of encode: We just decode the data and then
67 encode it again.
68
69 This gives us the following natural definition of make_canonical:
70
71 ```python
72 def make_canonical(data):
73 return encode(decode(data))
74 ```
75
76 But this is nearly the same as the thing we were testing, so we can rewrite our test as:
77
78 ```python
79 @given(lists(tuples(characters(), integers(1, 10))))
80 def test_encode_inverts_decode(s):
81 assert make_canonical(make_canonical(s)) == make_canonical(s)
82 ```
83
84 This property is called
85 being idempotent (annoyingly "idempotent" gets used to mean something subtly different
86 in most API design, but this is the original mathematical meaning).
87
88 It's less obviously necessary than the original one, and you can certainly
89 write encode/decode pairs that are arguably correct but don't have it (e.g. because
90 they change the order of keys in a dictionary, or include a timestamp or sequence
91 number in the output), but I think it's
92 still worth having and testing. Enforcing consistency like this both helps with debugging
93 when things go wrong and also tends to flush out other bugs along the way.
94
95 Even if you don't want to enforce this property, it highlights an important issue: You
96 do need *some* sort of testing of the decoder that doesn't just operate on output from
97 the encoder, because the encoder will potentially only output a relatively small subset
98 of the valid range of the format.
99
100 Often however you'll get the property for free. If the encode and decode functions
101 have the property that whenever x == y then f(x) == f(y), then this property automatically
102 holds, because make_canonical(x) is encode(decode(encode(decode(x)))), and we know from the
103 first property that decode(encode(t)) == t, so with t = decode(x) this expression is
104 encode(decode(x)), which is make_canonical(x) as required.
105
106 Most encode/decode pairs will have this property, but not all.
107
108 The easiest ways to fail to have it are to have side-effects (the aforementioned sequence
109 number or randomization), but even without side effects it's possible for it to fail
110 if equality doesn't capture every detail about the type. For example in
111 Python, if 1.0 was serialized as 1, then the two would compare equal and the property
112 would pass, but when re-encoding it might exhibit very different properties (although
113 you'd hope that it wouldn't). Another example is that in Python an OrderedDict and a
114 dict compare equal regardless of iteration order, which means that two apparently
115 equal types might encode to different things if they have different iteration orders
116 defined.
117
118 Ultimately these issues are probably quite niche. It's likely still worth testing for
119 this property, both because of these problems and also because often [mathematically
120 equivalent properties can still catch different issues](../tests-as-complete-specifications/),
121 but it's significantly less important than the more general property we started
122 with.
123
124 --------------------------------------
125
126 Thanks to [Georges Dubus](https://twitter.com/georgesdubus) who pointed out
127 the key insight behind the last section on this property following from the original
128 one.