| 1 | --- |
| 2 | tags: technical, python, intro |
| 3 | date: 2016-05-11 10:00 |
| 4 | title: Generating the right data |
| 5 | author: drmaciver |
| 6 | --- |
| 7 | |
| 8 | One thing that often causes people problems is figuring out how to generate |
| 9 | the right data to fit their data |
| 10 | model. You can start with just generating strings and integers, but eventually you want |
| 11 | to be able to generate |
| 12 | objects from your domain model. Hypothesis provides a lot of tools to help you build the |
| 13 | data you want, but sometimes the choice can be a bit overwhelming. |
| 14 | |
| 15 | Here's a worked example to walk you through some of the details and help you get to grips with how to use |
| 16 | them. |
| 17 | |
| 18 | <!--more--> |
| 19 | |
| 20 | Suppose we have the following class: |
| 21 | |
| 22 | ```python |
| 23 | class Project: |
| 24 | def __init__(self, name, start, end): |
| 25 | self.name = name |
| 26 | self.start = start |
| 27 | self.end = end |
| 28 | |
| 29 | def __repr__(self): |
| 30 | return f"Project {self.name} from {self.start.isoformat()} to {self.end.isoformat()}" |
| 31 | ``` |
| 32 | |
| 33 | A project has a name, a start date, and an end date. |
| 34 | |
| 35 | How do we generate such a thing? |
| 36 | |
| 37 | The idea is to break the problem down into parts, and then use the tools |
| 38 | Hypothesis provides to assemble those parts into a strategy for generating |
| 39 | our projects. |
| 40 | |
| 41 | We'll start by generating the data we need for each field, and then at the end |
| 42 | we'll see how to put it all together to generate a Project. |
| 43 | |
| 44 | ### Names |
| 45 | |
| 46 | First we need to generate a name. We'll use Hypothesis's standard text |
| 47 | strategy for that: |
| 48 | |
| 49 | ```pycon |
| 50 | >>> from hypothesis.strategies import text |
| 51 | >>> text().example() |
| 52 | '' |
| 53 | >>> text().example() |
| 54 | '\nŁ昘迥' |
| 55 | ``` |
| 56 | |
| 57 | Lets customize this a bit: First off, lets say project names have to be |
| 58 | non-empty. |
| 59 | |
| 60 | ```pycon |
| 61 | >>> text(min_size=1).example() |
| 62 | 'w\nC' |
| 63 | >>> text(min_size=1).example() |
| 64 | 'ሚಃJ»' |
| 65 | ``` |
| 66 | |
| 67 | Now, lets avoid the high end unicode for now (of course, your system *should* |
| 68 | handle the full range of unicode, but this is just an example, right?). |
| 69 | |
| 70 | To do this we need to pass an alphabet to the text strategy. This can either be |
| 71 | a range of characters or another strategy. We're going to use the *characters* |
| 72 | strategy, which gives you a flexible way of describing a strategy for single-character |
| 73 | text strings, to do that. |
| 74 | |
| 75 | ```pycon |
| 76 | i>>> characters(min_codepoint=1, max_codepoint=1000, exclude_categories=('Cc', 'Cs')).example() |
| 77 | '²' |
| 78 | >>> characters(min_codepoint=1, max_codepoint=1000, exclude_categories=('Cc', 'Cs')).example() |
| 79 | 'E' |
| 80 | >>> characters(min_codepoint=1, max_codepoint=1000, exclude_categories=('Cc', 'Cs')).example() |
| 81 | '̺' |
| 82 | |
| 83 | ``` |
| 84 | |
| 85 | The max and min codepoint parameters do what you'd expect: They limit the range of |
| 86 | permissible codepoints. We've blocked off the 0 codepoint (it's not really useful and |
| 87 | tends to just cause trouble with C libraries) and anything with a codepoint above |
| 88 | 1000 - so we're considering non-ASCII characters but nothing really high end. |
| 89 | |
| 90 | The blacklist\_categories parameter uses the notion of [unicode category](https://en.wikipedia.org/wiki/Unicode_character_property#General_Category) |
| 91 | to limit the range of acceptable characters. If you want to see what category a |
| 92 | character has you can use Python's unicodedata module to find out: |
| 93 | |
| 94 | ```pycon |
| 95 | >>> from unicodedata import category |
| 96 | >>> category('\n') |
| 97 | 'Cc' |
| 98 | >>> category('\t') |
| 99 | 'Cc' |
| 100 | >>> category(' ') |
| 101 | 'Zs' |
| 102 | >>> category('a') |
| 103 | 'Ll' |
| 104 | ``` |
| 105 | |
| 106 | The categories we've excluded are *control characters* and *surrogates*. Surrogates |
| 107 | are excluded by default but when you explicitly pass in blacklist categories you |
| 108 | need to exclude them yourself. |
| 109 | |
| 110 | So we can put that together with text() to get a name matching our requirements: |
| 111 | |
| 112 | ```pycon |
| 113 | >>> names = text(characters(max_codepoint=1000, exclude_categories=('Cc', 'Cs')), min_size=1) |
| 114 | ``` |
| 115 | |
| 116 | But this is still not quite right: We've allowed spaces in names, but we don't really want |
| 117 | a name to start with or end with a space. You can see that this is currently allowed by |
| 118 | asking Hypothesis for a more specific example: |
| 119 | |
| 120 | ```pycon |
| 121 | >>> find(names, lambda x: x[0] == ' ') |
| 122 | ' ' |
| 123 | ``` |
| 124 | |
| 125 | So let's fix it so that they can't by stripping the spaces off it. |
| 126 | |
| 127 | To do this we're going to use the strategy's *map* method which lets you compose it with |
| 128 | an arbitrary function to post-process the results into the for you want: |
| 129 | |
| 130 | ```pycon |
| 131 | >>> names = text(characters(max_codepoint=1000, exclude_categories=('Cc', 'Cs')), min_size=1).map( |
| 132 | ... lambda x: x.strip()) |
| 133 | ``` |
| 134 | |
| 135 | Now let's check that we can no longer have the above problem: |
| 136 | |
| 137 | ```pycon |
| 138 | >>> find(names, lambda x: x[0] == ' ') |
| 139 | Traceback (most recent call last): |
| 140 | File "<stdin>", line 1, in <module> |
| 141 | File "/usr/lib/python3.5/site-packages/hypothesis/core.py", line 648, in find |
| 142 | runner.run() |
| 143 | File "/usr/lib/python3.5/site-packages/hypothesis/internal/conjecture/engine.py", line 168, in run |
| 144 | self._run() |
| 145 | File "/usr/lib/python3.5/site-packages/hypothesis/internal/conjecture/engine.py", line 262, in _run |
| 146 | self.test_function(data) |
| 147 | File "/usr/lib/python3.5/site-packages/hypothesis/internal/conjecture/engine.py", line 68, in test_function |
| 148 | self._test_function(data) |
| 149 | File "/usr/lib/python3.5/site-packages/hypothesis/core.py", line 616, in template_condition |
| 150 | success = condition(result) |
| 151 | File "<stdin>", line 1, in <lambda> |
| 152 | IndexError: string index out of range |
| 153 | ``` |
| 154 | |
| 155 | Whoops! |
| 156 | |
| 157 | The problem is that our initial test worked because the strings we were generating were always |
| 158 | non-empty because of the min\_size parameter. We're still only generating non-empty strings, |
| 159 | but if we generate a string which is all spaces then strip it, the result will be empty |
| 160 | *after* our map. |
| 161 | |
| 162 | We can fix this using the strategy's *filter* function, which restricts to only generating |
| 163 | things which satisfy some condition: |
| 164 | |
| 165 | ```pycon |
| 166 | >>> names = text(characters(max_codepoint=1000, exclude_categories=('Cc', 'Cs')), min_size=1).map( |
| 167 | ... lambda s: s.strip()).filter(lambda s: len(s) > 0) |
| 168 | ``` |
| 169 | |
| 170 | And repeating the check: |
| 171 | |
| 172 | ```pycon |
| 173 | >>> find(names, lambda x: x[0] == ' ') |
| 174 | Traceback (most recent call last): |
| 175 | File "<stdin>", line 1, in <module> |
| 176 | File "/usr/lib/python3.5/site-packages/hypothesis/core.py", line 670, in find |
| 177 | raise NoSuchExample(get_pretty_function_description(condition)) |
| 178 | hypothesis.errors.NoSuchExample: No examples found of condition lambda x: <unknown> |
| 179 | ``` |
| 180 | |
| 181 | Hypothesis raises NoSuchExample to indicate that... well, that there's no such example. |
| 182 | |
| 183 | In general you should be a little bit careful with filter and only use it to filter |
| 184 | to conditions that are relatively hard to happen by accident. In this case it's fine |
| 185 | because the filter condition only fails if our initial draw was a string consisting |
| 186 | entirely of spaces, but if we'd e.g. tried the opposite and tried to filter to strings |
| 187 | that *only* had spaces, we'd have had a bad time of it and got a very slow and not |
| 188 | very useful test. |
| 189 | |
| 190 | Anyway, we now really do have a strategy that produces decent names for our projects. |
| 191 | Lets put this all together into a test that demonstrates that our names now have the |
| 192 | desired properties: |
| 193 | |
| 194 | ```python |
| 195 | from unicodedata import category |
| 196 | |
| 197 | from hypothesis import given |
| 198 | from hypothesis.strategies import characters, text |
| 199 | |
| 200 | names = ( |
| 201 | text(characters(max_codepoint=1000, exclude_categories=("Cc", "Cs")), min_size=1) |
| 202 | .map(lambda s: s.strip()) |
| 203 | .filter(lambda s: len(s) > 0) |
| 204 | ) |
| 205 | |
| 206 | |
| 207 | @given(names) |
| 208 | def test_names_match_our_requirements(name): |
| 209 | assert len(name) > 0 |
| 210 | assert name == name.strip() |
| 211 | for c in name: |
| 212 | assert 1 <= ord(c) <= 1000 |
| 213 | assert category(c) not in ("Cc", "Cs") |
| 214 | ``` |
| 215 | |
| 216 | It's not common practice to write tests for your strategies, but it can be helpful |
| 217 | when trying to figure things out. |
| 218 | |
| 219 | ### Dates and times |
| 220 | |
| 221 | Hypothesis has date and time generation in a hypothesis.extra subpackage because it |
| 222 | relies on pytz to generate them, but other than that it works in exactly the same |
| 223 | way as before: |
| 224 | |
| 225 | ```pycon |
| 226 | >>> from hypothesis.extra.datetime import datetimes |
| 227 | >>> datetimes().example() |
| 228 | datetime.datetime(1642, 1, 23, 2, 34, 28, 148985, tzinfo=<DstTzInfo 'Antarctica/Mawson' zzz0:00:00 STD>) |
| 229 | ``` |
| 230 | |
| 231 | Lets constrain our dates to be UTC, because the sensible thing to do is to use UTC |
| 232 | internally and convert on display to the user: |
| 233 | |
| 234 | ```pycon |
| 235 | >>> datetimes(timezones=('UTC',)).example() |
| 236 | datetime.datetime(6820, 2, 4, 19, 16, 27, 322062, tzinfo=<UTC>) |
| 237 | ``` |
| 238 | |
| 239 | We can also constrain our projects to start in a reasonable range of years, |
| 240 | as by default Hypothesis will cover the whole of representable history: |
| 241 | |
| 242 | ```pycon |
| 243 | >>> datetimes(timezones=('UTC',), min_year=2000, max_year=2100).example() |
| 244 | datetime.datetime(2084, 6, 9, 11, 48, 14, 213208, tzinfo=<UTC>) |
| 245 | ``` |
| 246 | |
| 247 | Again we can put together a test that checks this behaviour (though we have |
| 248 | less code here so it's less useful): |
| 249 | |
| 250 | ```python |
| 251 | from hypothesis import given |
| 252 | from hypothesis.extra.datetime import datetimes |
| 253 | |
| 254 | project_date = datetimes(timezones=("UTC",), min_year=2000, max_year=2100) |
| 255 | |
| 256 | |
| 257 | @given(project_date) |
| 258 | def test_dates_are_in_the_right_range(date): |
| 259 | assert 2000 <= date.year <= 2100 |
| 260 | assert date.tzinfo._tzname == "UTC" |
| 261 | ``` |
| 262 | |
| 263 | ### Putting it all together |
| 264 | |
| 265 | We can now generate all the parts for our project definitions, but how do we |
| 266 | generate a project? |
| 267 | |
| 268 | The first thing to reach for is the *builds* function. |
| 269 | |
| 270 | ```pycon |
| 271 | |
| 272 | >>> from hypothesis.strategies import builds |
| 273 | >>> projects = builds(Project, name=names, start=project_date, end=project_date) |
| 274 | >>> projects.example() |
| 275 | Project 'd!#ñcJν' from 2091-06-22T06:57:39.050162+00:00 to 2057-06-11T02:41:43.889510+00:00 |
| 276 | ``` |
| 277 | |
| 278 | builds lets you take a set of strategies and feed their results as arguments to a |
| 279 | function (or, in this case, class. Anything callable really) to create a new |
| 280 | strategy that works by drawing those arguments then passing them to the function |
| 281 | to give you that example. |
| 282 | |
| 283 | Unfortunately, this isn't quite right: |
| 284 | |
| 285 | ```pycon |
| 286 | >>> find(projects, lambda x: x.start > x.end) |
| 287 | Project '0' from 2000-01-01T00:00:00.000001+00:00 to 2000-01-01T00:00:00+00:00 |
| 288 | ``` |
| 289 | |
| 290 | Projects can start after they end when we use builds this way. One way to fix this would be |
| 291 | to use filter(): |
| 292 | |
| 293 | ```pycon |
| 294 | >>> projects = builds(Project, name=names, start=project_date, end=project_date).filter( |
| 295 | ... lambda p: p.start < p.end) |
| 296 | >>> find(projects, lambda x: x.start > x.end) |
| 297 | Traceback (most recent call last): |
| 298 | File "<stdin>", line 1, in <module> |
| 299 | File "/usr/lib/python3.5/site-packages/hypothesis/core.py", line 670, in find |
| 300 | raise NoSuchExample(get_pretty_function_description(condition)) |
| 301 | hypothesis.errors.NoSuchExample: No examples found of condition lambda x: <unknown> |
| 302 | ``` |
| 303 | |
| 304 | This will work, but it starts to edge into the territory of where filter should be |
| 305 | avoided - about half of the initially generated examples will fail the filter. |
| 306 | |
| 307 | What we'll do instead is draw two dates and use whichever one is smallest as the |
| 308 | start, and whatever is largest at the end. This is hard to do with builds because |
| 309 | of the dependence between the arguments, so instead we'll use builds' more advanced |
| 310 | cousin, *composite*: |
| 311 | |
| 312 | ```python |
| 313 | from hypothesis import assume |
| 314 | from hypothesis.strategies import composite |
| 315 | |
| 316 | |
| 317 | @composite |
| 318 | def projects(draw): |
| 319 | name = draw(names) |
| 320 | date1 = draw(project_date) |
| 321 | date2 = draw(project_date) |
| 322 | assume(date1 != date2) |
| 323 | start = min(date1, date2) |
| 324 | end = max(date1, date2) |
| 325 | return Project(name, start, end) |
| 326 | ``` |
| 327 | |
| 328 | The idea of composite is you get passed a magic first argument 'draw' that you can |
| 329 | use to get examples out of a strategy. You then make as many draws as you want and |
| 330 | use these to return the desired data. |
| 331 | |
| 332 | You can also use the *assume* function to discard the current call if you get yourself |
| 333 | into a state where you can't proceed or where it's easier to start again. In this case |
| 334 | we do that when we draw the same data twice. |
| 335 | |
| 336 | ```pycon |
| 337 | >>> projects().example() |
| 338 | Project 'rĂ5ĠǓ#' from 2000-05-14T07:21:12.282521+00:00 to 2026-05-12T13:20:43.225796+00:00 |
| 339 | >>> find(projects(), lambda x: x.start > x.end) |
| 340 | Traceback (most recent call last): |
| 341 | File "<stdin>", line 1, in <module> |
| 342 | File "/usr/lib/python3.5/site-packages/hypothesis/core.py", line 670, in find |
| 343 | raise NoSuchExample(get_pretty_function_description(condition)) |
| 344 | hypothesis.errors.NoSuchExample: No examples found of condition lambda x: <unknown> |
| 345 | ``` |
| 346 | |
| 347 | Note that in all of our examples we're now writing projects() instead of projects. That's |
| 348 | because composite returns a function rather than a strategy. Any arguments to your |
| 349 | defining function other than the first are also arguments to the one produced by composite. |
| 350 | |
| 351 | We can now put together one final test that we got this bit right too: |
| 352 | |
| 353 | ```python |
| 354 | @given(projects()) |
| 355 | def test_projects_end_after_they_started(project): |
| 356 | assert project.start < project.end |
| 357 | ``` |
| 358 | |
| 359 | ### Wrapping up |
| 360 | |
| 361 | There's a lot more to Hypothesis's data generation than this, but hopefully it gives you |
| 362 | a flavour of the sort of things to try and the sort of things that are possible. |
| 363 | |
| 364 | It's worth having a read of [the documentation](https://hypothesis.readthedocs.io/en/latest/data.html) |
| 365 | for this, and if you're still stuck then try asking [the community](https://hypothesis.readthedocs.io/en/latest/community.html) |
| 366 | for some help. We're pretty friendly. |