| 1 | --- |
| 2 | tags: intro, python, technical, properties |
| 3 | date: 2016-06-05 16:00 |
| 4 | title: Evolving toward property-based testing with Hypothesis |
| 5 | author: jml |
| 6 | --- |
| 7 | |
| 8 | Many people are quite comfortable writing ordinary unit tests, but feel a bit |
| 9 | confused when they start with property-based testing. This post shows how two |
| 10 | ordinary programmers started with normal Python unit tests and nudged them |
| 11 | incrementally toward property-based tests, gaining many advantages on the way. |
| 12 | |
| 13 | <!--more--> |
| 14 | |
| 15 | Background |
| 16 | ---------- |
| 17 | |
| 18 | I used to work on a command-line tool with an interface much like git's. It |
| 19 | had a repository, and within that repository you could create branches and |
| 20 | switch between them. Let's call the tool `tlr`. |
| 21 | |
| 22 | It was supposed to behave something like this: |
| 23 | |
| 24 | List branches: |
| 25 | |
| 26 | $ tlr branch |
| 27 | foo |
| 28 | * master |
| 29 | |
| 30 | Switch to an existing branch: |
| 31 | |
| 32 | $ tlr checkout foo |
| 33 | * foo |
| 34 | master |
| 35 | |
| 36 | Create a branch and switch to it: |
| 37 | |
| 38 | $ tlr checkout -b new-branch |
| 39 | $ tlr branch |
| 40 | foo |
| 41 | master |
| 42 | * new-branch |
| 43 | |
| 44 | Early on, my colleague and I found a bug: when you created a new branch with |
| 45 | `checkout -b` it wouldn't switch to it. The behavior looked something like |
| 46 | this: |
| 47 | |
| 48 | $ tlr checkout -b new-branch |
| 49 | $ tlr branch |
| 50 | foo |
| 51 | * master |
| 52 | new-branch |
| 53 | |
| 54 | The previously active branch (in this case, `master`) stayed active, rather |
| 55 | than switching to the newly-created branch (`new-branch`). |
| 56 | |
| 57 | Before we fixed the bug, we decided to write a test. I thought this would be a |
| 58 | good chance to start using Hypothesis. |
| 59 | |
| 60 | Writing a simple test |
| 61 | --------------------- |
| 62 | |
| 63 | My colleague was less familiar with Hypothesis than I was, so we started with |
| 64 | a plain old Python unit test: |
| 65 | |
| 66 | ```python |
| 67 | def test_checkout_new_branch(self): |
| 68 | """Checking out a new branch makes it the current active branch.""" |
| 69 | tmpdir = FilePath(self.mktemp()) |
| 70 | tmpdir.makedirs() |
| 71 | repo = Repository.initialize(tmpdir.path) |
| 72 | repo.checkout("new-branch", create=True) |
| 73 | self.assertEqual("new-branch", repo.get_active_branch()) |
| 74 | ``` |
| 75 | |
| 76 | The first thing to notice here is that the string `"new-branch"` is not |
| 77 | actually relevant to the test. It's just a value we picked to exercise the |
| 78 | buggy code. The test should be able to pass with *any valid branch name*. |
| 79 | |
| 80 | Even before we started to use Hypothesis, we made this more explicit by making |
| 81 | the branch name a parameter to the test: |
| 82 | |
| 83 | ```python |
| 84 | def test_checkout_new_branch(self, branch_name="new-branch"): |
| 85 | tmpdir = FilePath(self.mktemp()) |
| 86 | tmpdir.makedirs() |
| 87 | repo = Repository.initialize(tmpdir.path) |
| 88 | repo.checkout(branch_name, create=True) |
| 89 | self.assertEqual(branch_name, repo.get_active_branch()) |
| 90 | ``` |
| 91 | |
| 92 | (For brevity, I'll elide the docstring from the rest of the code examples) |
| 93 | |
| 94 | We never manually provided the `branch_name` parameter, but this change made |
| 95 | it more clear that the test ought to pass regardless of the branch name. |
| 96 | |
| 97 | Introducing Hypothesis |
| 98 | ---------------------- |
| 99 | |
| 100 | Once we had a parameter, the next thing was to use Hypothesis to provide the |
| 101 | parameter for us. First, we imported Hypothesis: |
| 102 | |
| 103 | ```python |
| 104 | from hypothesis import given, strategies as st |
| 105 | ``` |
| 106 | |
| 107 | And then made the simplest change to our test to actually use it: |
| 108 | |
| 109 | ```python |
| 110 | @given(branch_name=st.just("new-branch")) |
| 111 | def test_checkout_new_branch(self, branch_name): |
| 112 | tmpdir = FilePath(self.mktemp()) |
| 113 | tmpdir.makedirs() |
| 114 | repo = Repository.initialize(tmpdir.path) |
| 115 | repo.checkout(branch_name, create=True) |
| 116 | self.assertEqual(branch_name, repo.get_active_branch()) |
| 117 | ``` |
| 118 | |
| 119 | Here, rather than providing the branch name as a default argument value, we |
| 120 | are telling Hypothesis to come up with a branch name for us using the |
| 121 | `just("new-branch")` |
| 122 | [strategy](https://hypothesis.readthedocs.io/en/latest/data.html). This |
| 123 | strategy will always come up with `"new-branch"`, so it's actually no |
| 124 | different from what we had before. |
| 125 | |
| 126 | What we actually wanted to test is that any valid branch name worked. We |
| 127 | didn't yet know how to generate any valid branch name, but using a |
| 128 | time-honored tradition we pretended that we did: |
| 129 | |
| 130 | ```python |
| 131 | def valid_branch_names(): |
| 132 | """Hypothesis strategy to generate arbitrary valid branch names.""" |
| 133 | # TODO: Improve this strategy. |
| 134 | return st.just("new-branch") |
| 135 | |
| 136 | |
| 137 | @given(branch_name=valid_branch_names()) |
| 138 | def test_checkout_new_branch(self, branch_name): |
| 139 | tmpdir = FilePath(self.mktemp()) |
| 140 | tmpdir.makedirs() |
| 141 | repo = Repository.initialize(tmpdir.path) |
| 142 | repo.checkout(branch_name, create=True) |
| 143 | self.assertEqual(branch_name, repo.get_active_branch()) |
| 144 | ``` |
| 145 | |
| 146 | Even if we had stopped here, this would have been an improvement. Although the |
| 147 | Hypothesis version of the test doesn't have any extra power over the vanilla |
| 148 | version, it is more explicit about what it's testing, and the |
| 149 | `valid_branch_names()` strategy can be reused by future tests, giving us a |
| 150 | single point for improving the coverage of many tests at once. |
| 151 | |
| 152 | Expanding the strategy |
| 153 | ---------------------- |
| 154 | |
| 155 | It's only when we get Hypothesis to start generating our data for us that we |
| 156 | really get to take advantage of its bug finding power. |
| 157 | |
| 158 | The first thing my colleague and I tried was: |
| 159 | |
| 160 | ```python |
| 161 | def valid_branch_names(): |
| 162 | return st.text() |
| 163 | ``` |
| 164 | |
| 165 | But that failed pretty hard-core. |
| 166 | |
| 167 | Turns out branch names were implemented as symlinks on disk, so valid branch |
| 168 | name has to be a valid file name on whatever filesystem the tests are running |
| 169 | on. This at least rules out empty names, `"."`, `".."`, very long names, names |
| 170 | with slashes in them, and probably others (it's actually |
| 171 | [really complicated](https://en.wikipedia.org/wiki/Filename#Comparison_of_filename_limitations)). |
| 172 | |
| 173 | Hypothesis had made something very clear to us: neither my colleague nor I |
| 174 | actually knew what a valid branch name should be. None of our interfaces |
| 175 | documented it, we had no validators, no clear ideas for rendering & display, |
| 176 | nothing. We had just been assuming that people would pick good, normal, |
| 177 | sensible names. |
| 178 | |
| 179 | It was as if we had suddenly gained the benefit of extensive real-world |
| 180 | end-user testing, just by calling the right function. This was: |
| 181 | |
| 182 | 1. Awesome. We've found bugs that our users won't. |
| 183 | 2. Annoying. We really didn't want to fix this bug right now. |
| 184 | |
| 185 | In the end, we compromised and implemented a relatively conservative strategy |
| 186 | to simulate the good, normal, sensible branch names that we expected: |
| 187 | |
| 188 | ```python |
| 189 | from string import ascii_lowercase |
| 190 | |
| 191 | VALID_BRANCH_CHARS = ascii_lowercase + "_-." |
| 192 | |
| 193 | |
| 194 | def valid_branch_names(): |
| 195 | # TODO: Handle unicode / weird branch names by rejecting them early, raising nice errors |
| 196 | # TODO: How do we handle case-insensitive file systems? |
| 197 | return st.text(alphabet=VALID_BRANCH_CHARS, min_size=1, max_size=112) |
| 198 | ``` |
| 199 | |
| 200 | Not ideal, but *much* more extensive than just hard-coding `"new-branch"`, and |
| 201 | much clearer communication of intent. |
| 202 | |
| 203 | Adding edge cases |
| 204 | ----------------- |
| 205 | |
| 206 | There's one valid branch name that this strategy *could* generate, but |
| 207 | probably won't: `master`. If we left the test just as it is, then one time in |
| 208 | a hojillion the strategy would generate `"master"` and the test would fail. |
| 209 | |
| 210 | Rather than waiting on chance, we encoded this in the `valid_branch_names` |
| 211 | strategy, to make it more likely: |
| 212 | |
| 213 | ```python |
| 214 | def valid_branch_names(): |
| 215 | return st.text(alphabet=letters, min_size=1, max_size=112).map( |
| 216 | lambda t: t.lower() |
| 217 | ) | st.just("master") |
| 218 | ``` |
| 219 | |
| 220 | When we ran the tests now, they failed with an exception due to the branch |
| 221 | `master` already existing. To fix this, we used `assume`: |
| 222 | |
| 223 | ```python |
| 224 | from hypothesis import assume |
| 225 | |
| 226 | |
| 227 | @given(branch_name=valid_branch_names()) |
| 228 | def test_checkout_new_branch(self, branch_name): |
| 229 | assume(branch_name != "master") |
| 230 | tmpdir = FilePath(self.mktemp()) |
| 231 | tmpdir.makedirs() |
| 232 | repo = Repository.initialize(tmpdir.path) |
| 233 | repo.checkout(branch_name, create=True) |
| 234 | self.assertEqual(branch_name, repo.get_active_branch()) |
| 235 | ``` |
| 236 | |
| 237 | Why did we add `master` to the valid branch names if we were just going to |
| 238 | exclude it anyway? Because when other tests say "give me a valid branch name", |
| 239 | we want *them* to make the decision about whether `master` is appropriate or |
| 240 | not. Any future test author will be compelled to actually think about whether |
| 241 | handling `master` is a thing that they want to do. That's one of the great |
| 242 | benefits of Hypothesis: it's like having a rigorous design critic in your |
| 243 | team. |
| 244 | |
| 245 | Going forward |
| 246 | ------------- |
| 247 | |
| 248 | We stopped there, but we need not have. Just as the test should have held for |
| 249 | any branch, it should also hold for any repository. We were just creating an |
| 250 | empty repository because it was convenient for us. |
| 251 | |
| 252 | If we were to continue, the next step would be to [write a `repositories()` |
| 253 | function to generate repositories]({% post_url 2016-05-11-generating-the-right-data/) |
| 254 | with more varied contents, commit histories, and existing branches. |
| 255 | The test might then look something like this: |
| 256 | |
| 257 | ```python |
| 258 | @given(repo=repositories(), branch_name=valid_branch_names()) |
| 259 | def test_checkout_new_branch(self, repo, branch_name): |
| 260 | """ |
| 261 | Checking out a new branch results in it being the current active |
| 262 | branch. |
| 263 | """ |
| 264 | assume(branch_name not in repo.get_branches()) |
| 265 | repo.checkout(branch_name, create=True) |
| 266 | self.assertEqual(branch_name, repo.get_active_branch()) |
| 267 | ``` |
| 268 | |
| 269 | This is about as close to a bona fide "property" as you're likely to get in |
| 270 | code that isn't a straight-up computer science problem: if you create and |
| 271 | switch to a branch that doesn't already exist, the new active branch is the |
| 272 | newly created branch. |
| 273 | |
| 274 | We got there not by sitting down and thinking about the properties of our |
| 275 | software in the abstract, nor by necessarily knowing much about property-based |
| 276 | testing, but rather by incrementally taking advantage of features of Python |
| 277 | and Hypothesis. On the way, we discovered and, umm, contained a whole class of |
| 278 | bugs, and we made sure that all future tests would be heaps more powerful. |
| 279 | Win. |