Debian Codegraph @

website/content/2016-09-04-hypothesis-vs-eris.md

raw symbols SCIP
1 ---
2 tags: technical, python, intro
3 date: 2016-09-04 15:00
4 title: Hypothesis vs. Eris
5 author: giorgiosironi
6 ---
7
8 [Eris](https://github.com/giorgiosironi/eris/) is a library for property-based testing of PHP code, inspired by the mature frameworks that other languages provide like [QuickCheck](https://hackage.haskell.org/package/QuickCheck), Clojure's [test.check](https://github.com/clojure/test.check) and of course Hypothesis.
9
10 Here is a side-by-side comparison of some basic and advanced features that have been implemented in both Hypothesis and Eris, which may help developers coming from either Python or PHP and looking at the other side.
11
12 <!--more-->
13
14 ## Hello, world
15
16 The first example can be considered an `Hello, world` of randomized testing: given two random numbers, their sum should be constant no matter the order in which they are summed. The test case has two input parameters, so that it can be run dozens or hundreds of times, each run with different and increasingly complex input values.
17
18 Hypothesis provides an idiomatic Python solution, the `@given` decorator, that can be used to compose the strategies objects instantiated from `hypothesis.strategies`. The test case is very similar to an example-based one, except for the addition of arguments:
19
20 ```python
21 import unittest
22
23 from hypothesis import given, strategies as st
24
25
26 class TestEris(unittest.TestCase):
27 "Comparing the syntax and implementation of features with Eris"
28
29 @given(st.integers(), st.integers())
30 def test_sum_is_commutative(self, first, second):
31 x = first + second
32 y = second + first
33 self.assertEqual(
34 x, y, "Sum between %d and %d should be commutative" % (first, second)
35 )
36 ```
37
38 In this example, I am using the unittest syntax for maximum test portability, but this does not affect Hypothesis, which works across testing frameworks.
39
40 Eris provides functionality with a trait instead, that can be composed into the test cases that need access to randomized input. The test method is not augmented with additional parameters, but its code is moved inside an anonymous function for the `then()` primitive. Input distributions are defined in a mathematically-named `forAll()` primitive:
41
42 ```php
43 <?php
44 use Eris\Generator;
45 use Eris\TestTrait;
46
47 class IntegerTest extends PHPUnit_Framework_TestCase
48 {
49 use TestTrait;
50
51 public function testSumIsCommutative()
52 {
53 $this
54 ->forAll(
55 Generator\int(),
56 Generator\int()
57 )
58 ->then(function ($first, $second) {
59 $x = $first + $second;
60 $y = $second + $first;
61 $this->assertEquals(
62 $x,
63 $y,
64 "Sum between {$first} and {$second} should be commutative"
65 );
66 });
67 }
68 ```
69
70 Both these tests will be run hundreds of times, each computing two sums and comparing them for equality with the assertion library of the underlying testing framework (unittest and PHPUnit).
71
72 ## Composing strategies
73
74 A very simple composition problem consists of generating a collection data structured whose elements are drawn from a known distribution, for example a list of integers. Hypothesis provides *strategies* that can compose other strategies, in this case to build a list of random integers of arbitrary length:
75
76 ```python
77 @given(st.lists(st.integers()))
78 def test_sorting_a_list_twice_is_the_same_as_sorting_it_once(self, xs):
79 xs.sort()
80 ys = list(xs)
81 xs.sort()
82 self.assertEqual(xs, ys)
83 ```
84
85 Eris calls *generators* the objects representing statistical distributions, but uses the same compositional pattern for higher-order values like lists and all collections:
86
87 ```php
88 public function testArraySortingIsIdempotent()
89 {
90 $this
91 ->forAll(
92 Generator\seq(Generator\nat())
93 )
94 ->then(function ($array) {
95 sort($array);
96 $expected = $array;
97 sort($array);
98 $this->assertEquals($expected, $array);
99 });
100 }
101 ```
102
103 In both these test cases, we generate a random list and check that the sorting operation is idempotent: operating it twice on the input data gives the same result as operating it once.
104
105 ## Filtering generated values
106
107 Not all problems are abstract enough to accept all values in input, so it may be necessary to exclude part of the generated values when they do not fit our needs.
108
109 Hypothesis provides a `filter()` method to apply a lambda to values, expressing a condition for them to be included in the test:
110
111 ```python
112 @given(st.integers().filter(lambda x: x > 42))
113 def test_filtering(self, x):
114 self.assertGreater(x, 42)
115 ```
116
117 Eris allows to filter values with a predicate in the same way, but prefers to allocate the filter to the generic `ForAll` object rather than decorate it on each Generator:
118
119 ```php
120 public function testWhenWithAnAnonymousFunctionWithGherkinSyntax()
121 {
122 $this
123 ->forAll(
124 Generator\choose(0, 1000)
125 )
126 ->when(function ($n) {
127 return $n > 42;
128 })
129 ->then(function ($number) {
130 $this->assertTrue(
131 $number > 42,
132 "\$number was filtered to be more than 42, but it's $number"
133 );
134 });
135 }
136 ```
137
138 Filtering and the constructs that follow are integrated with shrinking in both Hypothesis and Eris: once a test fails and shrinking starts, constraints and transformations will continue to be applied to the generated values so that the simpler inputs are still going to belong to the same distribution; in this scenario, shrinking would only be able to propose numbers greater than 42.
139
140 ## Transforming generated values
141
142 Another common need consists of transforming the generated value to a different space, for example the set of all even numbers rather than the (larger) set of integers. Hypothesis allows to do this by passing a lambda to the `map()` method of a strategy:
143
144 ```python
145 @given(st.integers().map(lambda x: x * 2))
146 def test_mapping(self, x):
147 self.assertEqual(x % 2, 0)
148 ```
149
150 Eris instead provides a `Map` higher-order generator, which applies the lambda during generation:
151
152 ```php
153 public function testApplyingAFunctionToGeneratedValues()
154 {
155 $this
156 ->forAll(
157 Generator\map(
158 function ($n) { return $n * 2; },
159 Generator\nat()
160 )
161 )
162 ->then(function ($number) {
163 $this->assertTrue(
164 $number % 2 == 0,
165 "$number is not even"
166 );
167 });
168 }
169 ```
170
171 In both cases, the advantage of using the `map` support from the library (rather than writing our own multiplying code in the tests) is that the resulting object can be further composed to build larger data structures like a list or set of even numbers.
172
173 ## Generators with random parameters
174
175 It's possible to build even stricter values, that have internal constraints that must be satisfied but can't easily be generated by applying a pure function to a previously generated value.
176
177 Hypothesis provides the `flatmap()` method to pass the output of an inner strategy to a lambda that creates an outer strategy to use in the test. Here a list of 4 integers is passed to the lambda, to generate a tuple consisting of the list and a random element chosen from it:
178
179 ```python
180 @given(
181 st.lists(st.integers(), min_size=4, max_size=4).flatmap(
182 lambda xs: st.tuples(st.just(xs), st.sampled_from(xs))
183 )
184 )
185 def test_list_and_element_from_it(self, pair):
186 (generated_list, element) = pair
187 self.assertIn(element, generated_list)
188 ```
189
190 Eris does the same with a slightly different naming, calling this primitive `bind`:
191
192 ```php
193 public function testCreatingABrandNewGeneratorFromAGeneratedValue()
194 {
195 $this
196 ->forAll(
197 Generator\bind(
198 Generator\vector(4, Generator\nat()),
199 function ($vector) {
200 return Generator\tuple(
201 Generator\elements($vector),
202 Generator\constant($vector)
203 );
204 }
205 )
206 )
207 ->then(function ($tuple) {
208 list($element, $vector) = $tuple;
209 $this->assertContains($element, $vector);
210 });
211 }
212 ```
213
214 ## What the future brings
215
216 Hypothesis is a much more mature project than Eris, especially when it comes to keeping state between test runs or acting as a generic random data provider rather than as an extension to a testing framework. It will be interesting to continue porting Hypothesis features to the PHP world, given the original features and patterns that Hypothesis shows with respect to the rest of the `*Check` world.
217
218 ## References
219
220 The Hypothesis examples shown in this post can be found in [this example repository](https://github.com/giorgiosironi/hypothesis-exploration/blob/master/test_eris.py).
221
222 The Eris examples can instead be found in the example/ folder of [the](https://github.com/giorgiosironi/eris/blob/master/examples/IntegerTest.php#L9) [Eris](https://github.com/giorgiosironi/eris/blob/master/examples/SequenceTest.php#L31) [repository](https://github.com/giorgiosironi/eris/blob/master/examples/WhenTest.php#L8) [on](https://github.com/giorgiosironi/eris/blob/master/examples/MapTest.php#L8) [GitHub](https://github.com/giorgiosironi/eris/blob/master/examples/BindTest.php#L8).