Debian Codegraph @

website/content/2016-07-23-what-is-hypothesis.md

raw symbols SCIP
1 ---
2 tags: python, intro
3 date: 2016-07-24 00:00
4 title: What is Hypothesis?
5 author: drmaciver
6 ---
7
8 Hypothesis is a library designed to help you write what are called
9 *property-based tests*.
10
11 The key idea of property based testing is that rather than writing a test
12 that tests just a single scenario, you write tests that describe a range
13 of scenarios and then let the computer explore the possibilities for you
14 rather than having to hand-write every one yourself.
15
16 In order to contrast this with the sort of tests you might be used to, when
17 talking about property-based testing we tend to describe the normal sort of
18 testing as *example-based testing*.
19
20 Property-based testing can be significantly more powerful than example based
21 testing, because it automates the most time consuming part of writing tests
22 - coming up with the specific examples - and will usually perform it better
23 than a human would. This allows you to focus on the parts that humans are
24 better at - understanding the system, its range of acceptable behaviours,
25 and how they might break.
26
27 You don't *need* a library to do property-based testing. If you've ever
28 written a test which generates some random data and uses it for testing,
29 that's a property-based test. But having a library can help you a lot,
30 making your tests easier to write, more robust, and better at finding
31 bugs. In the rest of this article we'll see how.
32
33 <!--more-->
34
35 ### How to use it
36
37 The key object of Hypothesis is a *strategy*. A strategy is a recipe for
38 describing the sort of data you want to generate. The existence of a rich
39 and comprehensive strategy library is the first big advantage of Hypothesis
40 over a more manual process: Rather than having to hand-write generators
41 for the data you want, you can just compose the ones that Hypothesis
42 provides you with to get the data you want. e.g. if you want a lists of
43 floats, you just use the strategy lists(floats()). As well as being
44 easier to write, the resulting data will usually have a distribution
45 that is much better at finding edge cases than all but the most heavily
46 tuned manual implementations.
47
48 As well as the basic out of the box strategy implementations, Hypothesis
49 has a number of tools for composing strategies with user defined functions
50 and constraints, making it fairly easy to generate the data you want.
51
52 Note: For the remainder of this article I'll focus on the Hypothesis for
53 Python implementation. The Java implementation is similar, but has a number
54 of small differences that I'll discuss in a later article.
55
56 Once you know how to generate your data, the main entry point to Hypothesis
57 is the @given decorator. This takes a function that accepts some arguments
58 and turns it into a normal test function.
59
60 An important consequence of that is that Hypothesis is not itself a test
61 runner. It works inside your normal testing framework - it will work fine
62 with nose, py.test, unittest, etc. because all it does is expose a function
63 of the right name that the test runner can then pick up.
64
65 Using it with a py.test or nose style test looks like this:
66
67 ```python
68 from mercurial.encoding import fromutf8b, toutf8b
69
70 from hypothesis import given
71 from hypothesis.strategies import binary
72
73
74 @given(binary())
75 def test_decode_inverts_encode(s):
76 assert fromutf8b(toutf8b(s)) == s
77 ```
78
79 (This is an example from testing Mercurial which found two bugs:
80 [4927](https://bz.mercurial-scm.org/show_bug.cgi?id=4927) and
81 [5031](https://bz.mercurial-scm.org/show_bug.cgi?id=5031)).
82
83 In this test we are asserting that for any binary string, converting
84 it to its utf8b representation and back again should result in the
85 same string we started with. The @given decorator then handles
86 executing this test over a range of different binary strings without
87 us having to explicitly specify any of the examples ourself.
88
89 When this is first run, you will see an error that looks something
90 like this:
91
92 ```
93 Falsifying example: test_decode_inverts_encode(s='\xc2\xc2\x80')
94
95 Traceback (most recent call last):
96 File "/home/david/.pyenv/versions/2.7/lib/python2.7/site-packages/hypothesis/core.py", line 443, in evaluate_test_data
97 search_strategy, test,
98 File "/home/david/.pyenv/versions/2.7/lib/python2.7/site-packages/hypothesis/executors.py", line 58, in default_new_style_executor
99 return function(data)
100 File "/home/david/.pyenv/versions/2.7/lib/python2.7/site-packages/hypothesis/core.py", line 110, in run
101 return test(*args, **kwargs)
102 File "/home/david/hg/test_enc.py", line 8, in test_decode_inverts_encode
103 assert fromutf8b(toutf8b(s)) == s
104 File "/home/david/hg/mercurial/encoding.py", line 485, in fromutf8b
105 u = s.decode("utf-8")
106 File "/home/david/.pyenv/versions/2.7/lib/python2.7/encodings/utf_8.py", line 16, in decode
107 return codecs.utf_8_decode(input, errors, True)
108 UnicodeDecodeError: 'utf8' codec can't decode byte 0xc2 in position 1: invalid continuation byte
109 ```
110
111 Note that the falsifying example is quite small. Hypothesis has a
112 "simplification" process which runs behind the scenes and generally
113 tries to give the impression that the test simply failed with one
114 example that happened to be a really nice one.
115
116 Another important thing to note is that because of the random nature
117 of Hypothesis and because this bug is relatively hard to find, this
118 test may run successfully a couple of times before finding it.
119
120 However, once that happens, when we rerun the test it will keep failing
121 with the same example. This is because Hypothesis has a local test
122 database that it saves failing examples in. When you rerun the test,
123 it will first try the previous failure.
124
125 This is pretty important: It means that although Hypothesis is at its
126 heart random testing, it is *repeatable* random testing: A bug will
127 never go away by chance, because a test will only start passing if
128 the example that previously failed no longer failed.
129
130 (This isn't entirely true because a bug could be caused by random
131 factors such as timing or hash randomization. However in these cases
132 it's true for example-based testing as well. If anything Hypothesis
133 is *more* robust here because it will tend to find these cases with
134 higher probability).
135
136 Ultimately that's "all" Hypothesis does: It provides repeatability,
137 reporting and simplification for randomized tests, and it provides
138 a large library of generators to make it easier to write them.
139
140 Because of these features, the workflow is a huge improvement on
141 writing your own property-based tests by hand, and thanks to the
142 library of generators it's often even easier than writing your
143 own example based tests by hand.
144
145 ### What now?
146
147 If you want to read more on the subject, there are a couple places
148 you could go:
149
150 * If you want to know more of the details of the process I described
151 when a test executes, you can check out the
152 [Anatomy of a test](../anatomy-of-a-test/)
153 article which will walk you through the steps in more detail.
154 * If you'd like more examples of how to use it, check out the rest of the
155 [articles](/articles).
156
157 But really the best way to learn more is to try to use it!
158 As you've hopefully seen in this article, it's quite approachable to
159 get started with. Try writing some tests and see what happens.