Debian Codegraph @

website/content/2017-07-16-types-and-properties.md

raw symbols SCIP
1 ---
2 tags: technical, details, python, alternatives
3 date: 2017-07-16 10:00
4 title: Moving Beyond Types
5 author: drmaciver
6 ---
7
8 If you look at the original property-based testing library, the Haskell version of QuickCheck,
9 tests are very closely tied to types: The way you typically specify a property is by inferring
10 the data that needs to be generated from the types the test function expects for its arguments.
11
12 This is a bad idea.
13
14 <!--more-->
15
16 The first part of why
17 [I've talked about already](../integrated-shrinking/) -
18 you don't want to tie the shrinking of the data to its type, because it makes testing
19 significantly more brittle.
20
21 But you could solve that and still have data generation be tied to type, and it would still
22 be a bad idea.
23
24 The reason for this is very simple: Often you want to generate something much more specific
25 than any value of a given type.
26
27 If you look at the [Hypothesis strategies module](https://hypothesis.readthedocs.io/en/latest/data.html)
28 and what you can generate, many of these look like types. But if you look closer, nearly
29 every single one of them has options to configure them to be more specific.
30
31 Consider something like the following:
32
33 ```python
34 from statistics import mean
35
36 from hypothesis import given, strategies as st
37
38
39 @given(st.lists(st.floats(allow_nan=False, allow_infinity=False), min_size=1))
40 def test_mean_is_in_bounds(ls):
41 assert min(ls) <= mean(ls) <= max(ls)
42 ```
43
44 In this test we've restricted the domain we're testing on so we can focus on a property
45 that doesn't hold in generality: The mean of an empty list is an
46 error, so that needs a special case test for it, and calculations with `NaN` or infinity
47 are special cases that don't always have a well-defined result and even when they do
48 don't necessarily satisfy this property.
49
50 This happens a lot: Frequently there are properties that only hold in some restricted
51 domain, and so you want more specific tests for that domain to complement your other
52 tests for the larger range of data.
53
54 When this happens you need tools to generate something more specific, and those requirements
55 don't map naturally to types.
56
57 Consider writing this code based on types instead:
58
59 ```python
60 from statistics import mean
61
62 from hypothesis import given, strategies as st
63
64
65 @given(ls=...)
66 def test_mean_is_in_bounds(ls: list[float]):
67 assert min(ls) <= mean(ls) <= max(ls)
68 ```
69
70 (this code doesn't work at the time of this writing, but it will soon -
71 [the pull request to implement it](https://github.com/HypothesisWorks/hypothesis-python/pull/643)
72 is in fairly late-stage review).
73
74 But this doesn't do the right thing: We've dropped the conditions from the
75 previous test that our floats are all finite and our lists are all non-empty. So now
76 we have to add a precondition to make the test valid:
77
78 ```python
79 import math
80 from statistics import mean
81
82 from hypothesis import assume, given, strategies as st
83
84
85 @given(ls=...)
86 def test_mean_is_in_bounds(ls: list[float]):
87 assume(len(ls) > 1)
88 assume(all(math.isfinite(x) for x in ls))
89 assert min(ls) <= mean(ls) <= max(ls)
90 ```
91
92 But this is now substantially longer and less readable than the original approach!
93
94 In Haskell, traditionally we would fix this with a newtype declaration which wraps the type.
95 We could find a newtype NonEmptyList and a newtype FiniteFloat and then say that we actually
96 wanted a NonEmptyList[FiniteFloat] there.
97
98 In Python we could probably do more or less the same thing, either by creating new wrapper
99 types or by subclassing list and float (which you shouldn't do. Subclassing builtins in Python
100 leads to really weird behaviour) if we wanted to save a few lines, but it's much more noisy.
101
102 But why should we bother? Especially if we're only using these in one test, we're not actually
103 interested in these types at all, and it just adds a whole bunch of syntactic noise when you
104 could just pass the data generators directly. Defining new types for the data you want to generate
105 is purely a workaround for a limitation of the API.
106
107 If you were working in a dependently typed language where you could already naturally express
108 this in the type system it *might* be OK (I don't have any direct experience of working in
109 type systems that strong), but I'm sceptical of being able to make it work well - you're unlikely
110 to be able to automatically derive data generators in the general case, because the needs of
111 data generation "go in the opposite direction" from types (a type is effectively a predicate which
112 consumes a value, where a data generator is a function that produces a value, so in order to produce
113 a generator for a type automatically you need to basically invert the predicate). I suspect most
114 approaches here will leave you with a bunch of sharp edges, but I would be interested to see
115 experiments in this direction.
116
117 That being said, I don't think it's that useful to do. Where stronger types are naturally
118 present in the program, taking advantage of them to get better testing is certainly worth
119 doing, but creating a specific type to represent the exact range of valid inputs to a
120 specific test isn't because for tests the impact of a run time error that you could have caught at
121 compile time is substantially reduced (all it causes is a spurious test failure - where your
122 tests are long running or non-deterministic as in property-based testing this *does* matter,
123 but it still doesn't cause a problem in production).
124
125 But this is creating hard problems where none need exist, and beside which it's not the situation
126 with most of the current generation of languages and property based libraries for them.
127 Here, using explicit data generators is a clear improvement, and just as well-typed
128 (in a statically typed language each data generator has a return type after all).
129
130 You *can* use data generators directly in Haskell QuickCheck too, with an explicit
131 [forAll](https://hackage.haskell.org/package/QuickCheck-2.10.0.1/docs/Test-QuickCheck-Property.html#v:forAll)
132 but it's almost as awkward as the newtype approach, particularly if you want more than one
133 data generator (it's even more awkward if you want shrinking - you have to use forAllWithShrink and
134 explicitly pass a shrink function).
135
136 This is more or less intrinsic to the type based approach. If you want tinkering with the
137 data generation to be non-awkward, starting from data generators needs to become the default.
138
139 And experience suggests that when you make customising the data generation easy, people do
140 it. It's nice to be able to be more specific in your testing, but if you make it too high
141 effort people either don't do it, or do it using less effective methods like adding
142 preconditions to tests (assume in Hypothesis, or `==>` in QuickCheck), either of which reduces
143 the quality of your testing and causes more bugs to slip through as a result.
144
145 Fortunately, it already *is* the default in most of the newer implementations of
146 property-based testing. The only holdouts are ones that directly copied Haskell QuickCheck.
147
148 Originally this was making a virtue of a necessity - most of the implementations
149 which started off the trend of data generator first tests are either for dynamic languages
150 (e.g. Erlang, Clojure, Python) or languages with very weak type systems (e.g. C) where
151 type first is more or less impossible, but it's proven to be a much more usable design.
152
153 And it's perfectly compatible with static typing too. [Hedgehog](https://hackage.haskell.org/package/hedgehog)
154 is a relatively recent property-based testing library for Haskell that takes this approach,
155 and it works just as well in Haskell as it does in any language.
156
157 It's also perfectly compatible with being able to derive a data generator from a type
158 for the cases where you really want to. We saw a hint at that with the upcoming
159 Hypothesis implementation above. You could easily do the same by having something
160 like the following in Haskell (mimicking the type class of QuickCheck):
161
162 ```haskell
163 class Arbitrary a where
164 arbitrary :: Gen a
165 ```
166
167 You can then simply use `arbitrary` like you would any other data generator. As far as I know
168 Hedgehog doesn't do this anywhere (but you can use QuickCheck's Arbitrary with
169 the hedgehog-quickcheck package), but in principle there's nothing stopping it.
170
171 Having this also makes it much easier to define new data generators. I'm unlikely to use the
172 support for `@given` much, but I'm much more excited that it will also
173 work with `builds`, which will allow for a fairly seamless transition between
174 inferring the default strategy for a type and writing a custom generator. You
175 will, for example, be able to do `builds(MyType)` and have every constructor
176 argument automatically filled in (if it's suitably annotated), but you can
177 also do e.g. `builds(MyType, some_field=some_generator)` to override a particular
178 default while leaving the others alone.
179
180 (This API is somewhere where the dynamic nature of Python helps a fair bit, but you
181 could almost certainly do something equivalent in Haskell with a bit more noise
182 or a bit more template Haskell)
183
184 So this approach doesn't have to be data generator-only, even if it's data generator first,
185 but if you're going to pick one the flexibility of the data generator based test specification
186 is hard to beat, regardless of how good your type system is.