Debian Codegraph @

hypothesis-python/docs/reference/api.rst

raw
1 API Reference
2 =============
3
4 Reference for non-strategy objects that are part of the Hypothesis API. For documentation on strategies, see the :doc:`strategies reference </reference/strategies>`.
5
6 ``@given``
7 ----------
8
9 .. autofunction:: hypothesis.given
10
11 .. standard #: directives in the source don't work for hypothesis.infer,
12 .. see https://github.com/sphinx-doc/sphinx/issues/6495
13
14 .. data:: hypothesis.infer
15
16 An alias for ``...`` (|ellipsis|). |infer| can be passed to |@given| or
17 |st.builds| to indicate that a strategy for that parameter should be inferred
18 from its type annotations.
19
20 In all cases, using |infer| is equivalent to using ``...``.
21
22
23 Inferred strategies
24 ~~~~~~~~~~~~~~~~~~~
25
26 In some cases, Hypothesis can work out what to do when you omit arguments. This is based on introspection, *not* magic, and therefore has well-defined limits.
27
28 |st.builds| will check the signature of the ``target`` (using :func:`python:inspect.signature`). If there are required arguments with type annotations and
29 no strategy was passed to |st.builds|, |st.from_type| is used to fill them in. You can also pass the value ``...`` (``Ellipsis``) as a keyword argument, to force this inference for arguments with a default value.
30
31 .. code-block:: pycon
32
33 >>> def func(a: int, b: str):
34 ... return [a, b]
35 ...
36 >>> builds(func).example()
37 [-6993, '']
38
39 |@given| does not perform any implicit inference for required arguments, as this would break compatibility with pytest fixtures. ``...`` (:obj:`python:Ellipsis`), can be used as a keyword argument to explicitly fill in an argument from its type annotation. You can also use the |infer| alias if writing a literal ``...`` seems too weird.
40
41 .. code:: python
42
43 @given(a=...) # or @given(a=infer)
44 def test(a: int):
45 pass
46
47 # is equivalent to
48 @given(a=from_type(int))
49 def test(a):
50 pass
51
52 ``@given(...)`` can also be specified to fill all arguments from their type annotations.
53
54 .. code:: python
55
56 @given(...)
57 def test(a: int, b: str):
58 pass
59
60 # is equivalent to
61 @given(a=..., b=...)
62 def test(a, b):
63 pass
64
65 Limitations
66 ^^^^^^^^^^^
67
68 Hypothesis does not inspect :pep:`484` type comments at runtime. While |st.from_type| will work as usual, inference in |st.builds| and |@given| will only work if you manually create the ``__annotations__`` attribute (e.g. by using ``@annotations(...)`` and ``@returns(...)`` decorators).
69
70 The :mod:`python:typing` module changes between different Python releases, including at minor versions. These are all supported on a best-effort basis, but you may encounter problems. Please report them to us, and consider updating to a newer version of Python as a workaround.
71
72 Explicit inputs
73 ---------------
74
75 .. seealso::
76
77 See also the :doc:`/tutorial/replaying-failures` tutorial, which discusses using explicit inputs to reproduce failures.
78
79 .. autoclass:: hypothesis.example
80 .. automethod:: hypothesis.example.xfail
81 .. automethod:: hypothesis.example.via
82
83 .. _reproducing-inputs:
84
85 Reproducing inputs
86 ------------------
87
88 .. seealso::
89
90 See also the :doc:`/tutorial/replaying-failures` tutorial.
91
92 .. autofunction:: hypothesis.reproduce_failure
93 .. autofunction:: hypothesis.seed
94
95 Control
96 -------
97
98 Functions that can be called from anywhere inside a test, to either modify how Hypothesis treats the current test case, or to give Hypothesis more information about the current test case.
99
100 .. autofunction:: hypothesis.assume
101 .. autofunction:: hypothesis.note
102 .. autofunction:: hypothesis.event
103
104 You can mark custom events in a test using |event|:
105
106 .. code:: python
107
108 from hypothesis import event, given, strategies as st
109
110 @given(st.integers().filter(lambda x: x % 2 == 0))
111 def test_even_integers(i):
112 event(f"i mod 3 = {i%3}")
113
114 These events appear in :ref:`observability <observability>` output, as well as the output of :ref:`our pytest plugin <pytest-plugin>` when run with ``--hypothesis-show-statistics``.
115
116 For instance, in the latter case, you would see output like:
117
118 .. code-block:: none
119
120 test_even_integers:
121
122 - during generate phase (0.09 seconds):
123 - Typical runtimes: < 1ms, ~ 59% in data generation
124 - 100 passing examples, 0 failing examples, 32 invalid examples
125 - Events:
126 * 54.55%, Retried draw from integers().filter(lambda x: x % 2 == 0) to satisfy filter
127 * 31.06%, i mod 3 = 2
128 * 28.79%, i mod 3 = 0
129 * 24.24%, Aborted test because unable to satisfy integers().filter(lambda x: x % 2 == 0)
130 * 15.91%, i mod 3 = 1
131 - Stopped because settings.max_examples=100
132
133 Arguments to ``event`` can be any hashable type, but two events will be considered the same
134 if they are the same when converted to a string with :obj:`python:str`.
135
136 .. _targeted:
137
138 Targeted property-based testing
139 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
140
141 Targeted property-based testing combines the advantages of both search-based and property-based testing. Instead of being completely random, targeted PBT uses a search-based component to guide the input generation towards values that have a higher probability of falsifying a property. This explores the input space more effectively and requires fewer tests to find a bug or achieve a high confidence in the system being tested than random PBT. (`Löscher and Sagonas <http://proper.softlab.ntua.gr/Publications.html>`__)
142
143 This is not *always* a good idea - for example calculating the search metric might take time better spent running more uniformly-random test cases, or your target metric might accidentally lead Hypothesis *away* from bugs - but if there is a natural metric like "floating-point error", "load factor" or "queue length", we encourage you to experiment with targeted testing.
144
145 We recommend that users also skim the papers introducing targeted PBT; from `ISSTA 2017 <http://proper.softlab.ntua.gr/papers/issta2017.pdf>`__ and `ICST 2018 <http://proper.softlab.ntua.gr/papers/icst2018.pdf>`__. For the curious, the initial implementation in Hypothesis uses hill-climbing search via a mutating fuzzer, with some tactics inspired by simulated annealing to avoid getting stuck and endlessly mutating a local maximum.
146
147 .. code-block:: python
148
149 from hypothesis import given, strategies as st, target
150
151 @given(st.floats(0, 1e100), st.floats(0, 1e100), st.floats(0, 1e100))
152 def test_associativity_with_target(a, b, c):
153 ab_c = (a + b) + c
154 a_bc = a + (b + c)
155 difference = abs(ab_c - a_bc)
156 target(difference) # Without this, the test almost always passes
157 assert difference < 2.0
158
159 .. autofunction:: hypothesis.target
160
161 Settings
162 --------
163
164 .. seealso::
165
166 See also :doc:`the tutorial for settings </tutorial/settings>`.
167
168 .. autoclass:: hypothesis.settings
169 :members:
170
171 .. autoclass:: hypothesis.Phase
172 :members:
173
174 .. autoclass:: hypothesis.Verbosity
175 :members:
176
177 .. autoclass:: hypothesis.HealthCheck
178 :undoc-members:
179 :inherited-members:
180 :exclude-members: all
181
182 .. _database:
183
184 Database
185 --------
186
187 .. autoclass:: hypothesis.database.ExampleDatabase
188 :members:
189 :private-members: _broadcast_change, _start_listening, _stop_listening
190
191 .. autoclass:: hypothesis.database.InMemoryExampleDatabase
192 .. autoclass:: hypothesis.database.DirectoryBasedExampleDatabase
193 .. autoclass:: hypothesis.database.GitHubArtifactDatabase
194 .. autoclass:: hypothesis.database.ReadOnlyDatabase
195 .. autoclass:: hypothesis.database.MultiplexedDatabase
196 .. autoclass:: hypothesis.database.BackgroundWriteDatabase
197 .. autoclass:: hypothesis.extra.redis.RedisExampleDatabase
198
199 .. _stateful:
200
201 Stateful tests
202 --------------
203
204 .. autoclass:: hypothesis.stateful.RuleBasedStateMachine
205
206 Rules
207 ~~~~~
208
209 .. autofunction:: hypothesis.stateful.rule
210 .. autofunction:: hypothesis.stateful.consumes
211 .. autofunction:: hypothesis.stateful.multiple
212 .. autoclass:: hypothesis.stateful.Bundle
213 .. autofunction:: hypothesis.stateful.initialize
214 .. autofunction:: hypothesis.stateful.precondition
215 .. autofunction:: hypothesis.stateful.invariant
216
217 Running state machines
218 ~~~~~~~~~~~~~~~~~~~~~~
219
220 If you want to bypass the TestCase infrastructure you can invoke these manually. The stateful module exposes |run_state_machine_as_test|, which takes an arbitrary function returning a |RuleBasedStateMachine| and an optional settings parameter and does the same as the class based runTest provided.
221
222 .. autofunction:: hypothesis.stateful.run_state_machine_as_test
223
224 Hypothesis exceptions
225 ---------------------
226
227 Custom exceptions raised by Hypothesis.
228
229 .. autoclass:: hypothesis.errors.HypothesisException
230 .. autoclass:: hypothesis.errors.HypothesisDeprecationWarning
231 .. autoclass:: hypothesis.errors.NonInteractiveExampleWarning
232 .. autoclass:: hypothesis.errors.Flaky
233 .. autoclass:: hypothesis.errors.FlakyStrategyDefinition
234 .. autoclass:: hypothesis.errors.FlakyFailure
235 .. autoclass:: hypothesis.errors.FlakyBackendFailure
236 .. autoclass:: hypothesis.errors.InvalidArgument
237 .. autoclass:: hypothesis.errors.ResolutionFailed
238 .. autoclass:: hypothesis.errors.Unsatisfiable
239 .. autoclass:: hypothesis.errors.DidNotReproduce
240 .. autoclass:: hypothesis.errors.DeadlineExceeded
241
242 .. _hypothesis-django:
243
244 Django
245 ------
246
247 .. seealso::
248
249 See the :ref:`Django strategies reference <django-strategies>` for documentation on strategies in the ``hypothesis.extra.django`` module.
250
251 Hypothesis offers a number of features specific for Django testing, available
252 in the ``hypothesis[django]`` :doc:`extra </extras>`. This is tested
253 against each supported series with mainstream or extended support -
254 if you're still getting security patches, you can test with Hypothesis.
255
256 .. autoclass:: hypothesis.extra.django.TestCase
257
258 Using it is quite straightforward: All you need to do is subclass
259 :class:`hypothesis.extra.django.TestCase` or
260 :class:`hypothesis.extra.django.SimpleTestCase` or
261 :class:`hypothesis.extra.django.TransactionTestCase` or
262 :class:`~hypothesis.extra.django.LiveServerTestCase` or
263 :class:`~hypothesis.extra.django.StaticLiveServerTestCase`
264 and you can use |@given| as normal,
265 and the transactions will be per example
266 rather than per test function as they would be if you used |@given| with a normal
267 django test suite (this is important because your test function will be called
268 multiple times and you don't want them to interfere with each other). Test cases
269 on these classes that do not use
270 |@given| will be run as normal for :class:`django:django.test.TestCase` or :class:`django:django.test.TransactionTestCase`.
271
272 .. autoclass:: hypothesis.extra.django.SimpleTestCase
273 .. autoclass:: hypothesis.extra.django.TransactionTestCase
274 .. autoclass:: hypothesis.extra.django.LiveServerTestCase
275 .. autoclass:: hypothesis.extra.django.StaticLiveServerTestCase
276
277 We recommend avoiding :class:`~hypothesis.extra.django.TransactionTestCase`
278 unless you really have to run each test case in a database transaction.
279 Because Hypothesis runs this in a loop, the performance problems :class:`django:django.test.TransactionTestCase` normally has
280 are significantly exacerbated and your tests will be really slow.
281 If you are using :class:`~hypothesis.extra.django.TransactionTestCase`,
282 you may need to use ``@settings(suppress_health_check=[HealthCheck.too_slow])``
283 to avoid a |HealthCheck| error due to slow example generation.
284
285 Having set up a test class, you can now pass |@given|
286 a strategy for Django models with |django.from_model|.
287 For example, using :gh-file:`the trivial django project we have for testing
288 <hypothesis-python/tests/django/toystore/models.py>`:
289
290 .. code-block:: pycon
291
292 >>> from hypothesis.extra.django import from_model
293 >>> from toystore.models import Customer
294 >>> c = from_model(Customer).example()
295 >>> c
296 <Customer: Customer object>
297 >>> c.email
298 '[email protected]'
299 >>> c.name
300 '\U00109d3d\U000e07be\U000165f8\U0003fabf\U000c12cd\U000f1910\U00059f12\U000519b0\U0003fabf\U000f1910\U000423fb\U000423fb\U00059f12\U000e07be\U000c12cd\U000e07be\U000519b0\U000165f8\U0003fabf\U0007bc31'
301 >>> c.age
302 -873375803
303
304 Hypothesis has just created this with whatever the relevant type of data is.
305
306 Obviously the customer's age is implausible, which is only possible because
307 we have not used (eg) :class:`~django:django.core.validators.MinValueValidator`
308 to set the valid range for this field (or used a
309 :class:`~django:django.db.models.PositiveSmallIntegerField`, which would only
310 need a maximum value validator).
311
312 If you *do* have validators attached, Hypothesis will only generate examples
313 that pass validation. Sometimes that will mean that we fail a
314 :class:`~hypothesis.HealthCheck` because of the filtering, so let's explicitly
315 pass a strategy to skip validation at the strategy level:
316
317 .. code-block:: pycon
318
319 >>> from hypothesis.strategies import integers
320 >>> c = from_model(Customer, age=integers(min_value=0, max_value=120)).example()
321 >>> c
322 <Customer: Customer object>
323 >>> c.age
324 5
325
326 Custom field types
327 ~~~~~~~~~~~~~~~~~~
328
329 If you have a custom Django field type you can register it with Hypothesis's
330 model deriving functionality by registering a default strategy for it:
331
332 .. code-block:: pycon
333
334 >>> from toystore.models import CustomishField, Customish
335 >>> from_model(Customish).example()
336 hypothesis.errors.InvalidArgument: Missing arguments for mandatory field
337 customish for model Customish
338 >>> from hypothesis.extra.django import register_field_strategy
339 >>> from hypothesis.strategies import just
340 >>> register_field_strategy(CustomishField, just("hi"))
341 >>> x = from_model(Customish).example()
342 >>> x.customish
343 'hi'
344
345 Note that this mapping is on exact type. Subtypes will not inherit it.
346
347 Generating child models
348 ~~~~~~~~~~~~~~~~~~~~~~~
349
350 For the moment there's no explicit support in hypothesis-django for generating
351 dependent models. i.e. a Company model will generate no Shops. However if you
352 want to generate some dependent models as well, you can emulate this by using
353 the |.flatmap| function as follows:
354
355 .. code:: python
356
357 from hypothesis.strategies import just, lists
358
359 def generate_with_shops(company):
360 return lists(from_model(Shop, company=just(company))).map(lambda _: company)
361
362 company_with_shops_strategy = from_model(Company).flatmap(generate_with_shops)
363
364 Let's unpack what this is doing:
365
366 The way flatmap works is that we draw a value from the original strategy, then
367 apply a function to it which gives us a new strategy. We then draw a value from
368 *that* strategy. So in this case we're first drawing a company, and then we're
369 drawing a list of shops belonging to that company: The |st.just| strategy is a
370 strategy such that drawing it always produces the individual value, so
371 ``from_model(Shop, company=just(company))`` is a strategy that generates a Shop belonging
372 to the original company.
373
374 So the following code would give us a list of shops all belonging to the same
375 company:
376
377 .. code:: python
378
379 from_model(Company).flatmap(lambda c: lists(from_model(Shop, company=just(c))))
380
381 The only difference from this and the above is that we want the company, not
382 the shops. This is where the inner map comes in. We build the list of shops
383 and then throw it away, instead returning the company we started for. This
384 works because the models that Hypothesis generates are saved in the database,
385 so we're essentially running the inner strategy purely for the side effect of
386 creating those children in the database.
387
388
389 .. _django-generating-primary-key:
390
391 Generating primary key values
392 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
393
394 If your model includes a custom primary key that you want to generate
395 using a strategy (rather than a default auto-increment primary key)
396 then Hypothesis has to deal with the possibility of a duplicate
397 primary key.
398
399 If a model strategy generates a value for the primary key field,
400 Hypothesis will create the model instance with
401 :meth:`~django:django.db.models.query.QuerySet.update_or_create`,
402 overwriting any existing instance in the database for this test case
403 with the same primary key.
404
405
406 On the subject of ``MultiValueField``
407 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
408
409 Django forms feature the :class:`~django:django.forms.MultiValueField`
410 which allows for several fields to be combined under a single named field, the
411 default example of this is the :class:`~django:django.forms.SplitDateTimeField`.
412
413 .. code:: python
414
415 class CustomerForm(forms.Form):
416 name = forms.CharField()
417 birth_date_time = forms.SplitDateTimeField()
418
419 |django.from_form| supports ``MultiValueField`` subclasses directly, however if you
420 want to define your own strategy be forewarned that Django binds data for a
421 ``MultiValueField`` in a peculiar way. Specifically each sub-field is expected
422 to have its own entry in ``data`` addressed by the field name
423 (e.g. ``birth_date_time``) and the index of the sub-field within the
424 ``MultiValueField``, so form ``data`` for the example above might look
425 like this:
426
427 .. code:: python
428
429 {
430 "name": "Samuel John",
431 "birth_date_time_0": "2018-05-19", # the date, as the first sub-field
432 "birth_date_time_1": "15:18:00", # the time, as the second sub-field
433 }
434
435 Thus, if you want to define your own strategies for such a field you must
436 address your sub-fields appropriately:
437
438 .. code:: python
439
440 from_form(CustomerForm, birth_date_time_0=just("2018-05-19"))
441
442 .. _fuzz_one_input:
443
444 External fuzzers
445 ----------------
446
447 .. autodata:: hypothesis.core.HypothesisHandle.fuzz_one_input
448
449 .. _custom-function-execution:
450
451 Custom function execution
452 -------------------------
453
454 Hypothesis provides you with a hook that lets you control how it runs examples.
455
456 This lets you do things like set up and tear down around each example, run examples in a subprocess, transform coroutine tests into normal tests, etc. For example, :class:`~hypothesis.extra.django.TransactionTestCase` in the Django extra runs each example in a separate database transaction.
457
458 The way this works is by introducing the concept of an executor. An executor is essentially a function that takes a block of code and run it. The default executor is:
459
460 .. code:: python
461
462 def default_executor(function):
463 return function()
464
465 You define executors by defining a method ``execute_example`` on a class. Any test methods on that class with |@given| used on them will use ``self.execute_example`` as an executor with which to run tests. For example, the following executor runs all its code twice:
466
467 .. code:: python
468
469 from unittest import TestCase
470
471 class TestTryReallyHard(TestCase):
472 @given(integers())
473 def test_something(self, i):
474 perform_some_unreliable_operation(i)
475
476 def execute_example(self, f):
477 f()
478 return f()
479
480 Note: The functions you use in map, etc. will run *inside* the executor. i.e. they will not be called until you invoke the function passed to ``execute_example``.
481
482 An executor must be able to handle being passed a function which returns None, otherwise it won't be able to run normal test cases. So for example the following executor is invalid:
483
484 .. code:: python
485
486 from unittest import TestCase
487
488 class TestRunTwice(TestCase):
489 def execute_example(self, f):
490 return f()()
491
492 and should be rewritten as:
493
494 .. code:: python
495
496 from unittest import TestCase
497
498 class TestRunTwice(TestCase):
499 def execute_example(self, f):
500 result = f()
501 if callable(result):
502 result = result()
503 return result
504
505 An alternative hook is provided for use by test runner extensions such as :pypi:`pytest-trio`, which cannot use the ``execute_example`` method. This is **not** recommended for end-users - it is better to write a complete test function directly, perhaps by using a decorator to perform the same transformation before applying |@given|.
506
507 .. code:: python
508
509 @given(x=integers())
510 @pytest.mark.trio
511 async def test(x): ...
512
513 # Illustrative code, inside the pytest-trio plugin
514 test.hypothesis.inner_test = lambda x: trio.run(test, x)
515
516 For authors of test runners however, assigning to the ``inner_test`` attribute of the ``hypothesis`` attribute of the test will replace the interior test.
517
518 .. note::
519 The new ``inner_test`` must accept and pass through all the ``*args``
520 and ``**kwargs`` expected by the original test.
521
522 If the end user has also specified a custom executor using the ``execute_example`` method, it - and all other execution-time logic - will be applied to the *new* inner test assigned by the test runner.
523
524 Detection
525 ---------
526
527 .. autofunction:: hypothesis.is_hypothesis_test
528 .. autofunction:: hypothesis.currently_in_test_context