Debian Codegraph @

website/content/2016-04-15-getting-started-with-hypothesis.md

raw symbols SCIP
1 ---
2 tags: intro, python, technical, properties
3 date: 2016-04-15 13:00
4 title: Getting started with Hypothesis
5 author: drmaciver
6 ---
7
8 Hypothesis will speed up your testing process and improve your software quality,
9 but when first starting out people often struggle to figure out exactly how to use it.
10
11 Until you're used to thinking in this style of testing, it's not always obvious what the invariants of your
12 code actually *are*, and people get stuck trying to come up with interesting ones to test.
13
14 Fortunately, there's a simple invariant which every piece of software should satisfy, and which can be
15 remarkably powerful as a way to uncover surprisingly deep bugs in your software.
16
17 <!--more-->
18
19 That invariant is simple: The software shouldn't crash. Or sometimes, it should only crash in defined
20 ways.
21
22 There is then a standard test you can write for most of your code that asserts this
23 invariant.
24
25 It consists of two steps:
26
27 1. Pick a function in your code base that you want to be better tested.
28 2. Call it with random data.
29
30 This style of testing is usually called *fuzzing*.
31
32 This will possibly require you to figure out how to generate your domain objects. Hypothesis
33 [has a pretty extensive library](../generating-the-right-data/)
34 of tools (called 'strategies' in Hypothesis terminology) for generating
35 custom types but if you can, try to start somewhere where the types you
36 need aren’t *too* complicated to generate.
37
38 Chances are actually pretty good that you’ll find something wrong this way if you pick a
39 sufficiently interesting entry point. For example, there’s a long track record of people trying to
40 test interesting properties with their text handling and getting unicode errors when text()
41 gives them something that their code didn’t know how to handle.
42
43 You’ll probably get exceptions here you don’t care about. e.g. some arguments to functions may not be valid.
44 Set up your test to ignore those.
45
46 So at this point you’ll have something like this:
47
48 ```python
49 from hypothesis import given, reject
50 from hypothesis.strategies import integers, text
51
52
53 @given(integers(), text())
54 def test_some_stuff(x, y):
55 try:
56 my_function(x, y)
57 except SomeExpectedException:
58 reject()
59 ```
60
61 In this example we generate two values - one integer, one text - and
62 pass them to your test function. Hypothesis will repeatedly call the
63 test function with values drawn from these strategies, trying to find
64 one that produces an unexpected exception.
65
66 When an exception we know is possible happens (e.g. a ValueError because
67 some argument was out of range) we call reject. This discards the
68 example, and Hypothesis won't count it towards the 'budget' of examples
69 it is allowed to run.
70
71 This is already a pretty good starting point and does have a decent
72 tendency to flush out bugs. You’ll often find cases where you forgot some
73 boundary condition and your code misbehaves as a result. But there’s
74 still plenty of room to improve.
75
76 There are now two directions you can go in from here:
77
78 1. Try to assert some things about the function’s result. Anything at all. What type is it?
79 Can it be None? Does it have any relation at all to the input values that you can check?
80 It doesn’t have to be clever - even very trivial properties are useful here.
81 2. Start making your code more defensive.
82
83 The second part is probably the most productive one.
84
85 The goal is to turn faulty assumptions in your code into crashes instead of silent corruption of your application state. You can do this in a couple ways:
86
87 1. Add argument checking to your functions (Hypothesis uses a dedicated InvalidArgumentException for this case, but you can raise whatever errors you find appropriate).
88 2. Add a whole bunch of assertions into your code itself.
89 Even when it’s hard to reason about formal properties of your code, it’s usually relatively easy to add local properties, and assertions are a great way to encode them. John Regehr has [a good post on this subject](http://blog.regehr.org/archives/1091) if you want to know more about it.
90
91 This approach will make your code more robust even if you don’t find any bugs in it during testing (and you’ll probably find bugs in it during testing), and it gives you a nice easy route into property based testing by letting you focus on only one half of the problem at a time.
92
93 Once you think you've got the hang of this, a good next step is to start looking for
94 [places with complex optimizations](../testing-performance-optimizations/) or
95 [Encode/Decode pairs](../encode-decode-invariant/) in
96 your code, as they're a fairly easy properties to test and are both rich sources of bugs.