Debian Codegraph @

hypothesis-python/docs/extensions.rst

raw
1 Third-party extensions
2 ======================
3
4 There are a number of open-source community libraries that extend Hypothesis. This page lists some of them; you can find more by searching PyPI `by keyword <https://pypi.org/search/?q=hypothesis>`_ or `by framework classifier <https://pypi.org/search/?c=Framework+%3A%3A+Hypothesis>`_.
5
6 If there's something missing which you think should be here, let us know!
7
8 .. note::
9 Being listed on this page does not imply that the Hypothesis
10 maintainers endorse a package.
11
12 External strategies
13 -------------------
14
15 Some packages provide strategies directly:
16
17 * :pypi:`hypothesis-fspaths` - strategy to generate filesystem paths.
18 * :pypi:`hypothesis-geojson` - strategy to generate `GeoJson <https://geojson.org/>`_.
19 * :pypi:`hypothesis-geometry` - strategies to generate geometric objects.
20 * :pypi:`hs-dbus-signature` - strategy to generate arbitrary
21 `D-Bus signatures <https://www.freedesktop.org/wiki/Software/dbus/>`_.
22 * :pypi:`hypothesis-sqlalchemy` - strategies to generate :pypi:`SQLAlchemy` objects.
23 * :pypi:`hypothesis-ros` - strategies to generate messages and parameters for the `Robot Operating System <https://www.ros.org/>`_.
24 * :pypi:`hypothesis-csv` - strategy to generate CSV files.
25 * :pypi:`hypothesis-networkx` - strategy to generate :pypi:`networkx` graphs.
26 * :pypi:`hypothesis-bio` - strategies for bioinformatics data, such as DNA, codons, FASTA, and FASTQ formats.
27 * :pypi:`hypothesis-rdkit` - strategies to generate RDKit molecules and representations such as SMILES and mol blocks
28 * :pypi:`hypothesmith` - strategy to generate syntatically-valid Python code.
29 * :pypi:`hypothesis-torch` - strategy to generate various `Pytorch <https://pytorch.org/>`_ structures (including tensors and modules).
30
31 Others provide a function to infer a strategy from some other schema:
32
33 * :pypi:`hypothesis-jsonschema` - infer strategies from `JSON schemas <https://json-schema.org/>`_.
34 * :pypi:`lollipop-hypothesis` - infer strategies from :pypi:`lollipop` schemas.
35 * :pypi:`hypothesis-drf` - infer strategies from a :pypi:`djangorestframework` serialiser.
36 * :pypi:`hypothesis-graphql` - infer strategies from `GraphQL schemas <https://graphql.org/>`_.
37 * :pypi:`hypothesis-mongoengine` - infer strategies from a :pypi:`mongoengine` model.
38 * :pypi:`hypothesis-pb` - infer strategies from `Protocol Buffer
39 <https://protobuf.dev/>`_ schemas.
40
41 Or some other custom integration, such as a :ref:`"hypothesis" entry point <entry-points>`:
42
43 * :pypi:`deal` is a design-by-contract library with built-in Hypothesis support.
44 * :pypi:`icontract-hypothesis` infers strategies from :pypi:`icontract` code contracts.
45 * :pypi:`pandera` schemas all have a ``.strategy()`` method, which returns a strategy for
46 matching :class:`~pandas:pandas.DataFrame`\ s.
47 * :pypi:`Pydantic <pydantic>` automatically registers constrained types - so
48 :func:`~hypothesis.strategies.builds` and :func:`~hypothesis.strategies.from_type`
49 "just work" regardless of the underlying implementation.
50
51 Other cool things
52 -----------------
53
54 `Tyche <https://marketplace.visualstudio.com/items?itemName=HarrisonGoldstein.tyche>`__
55 (`source <https://github.com/tyche-pbt>`__) is a VSCode extension which provides live
56 insights into your property-based tests, including the distribution of generated inputs
57 and the resulting code coverage. You can `read the research paper here
58 <https://harrisongoldste.in/papers/uist23.pdf>`__.
59
60 :pypi:`schemathesis` is a tool for testing web applications built with `Open API / Swagger specifications <https://swagger.io/>`_.
61 It reads the schema and generates test cases which will ensure that the application is compliant with its schema.
62 The application under test could be written in any language, the only thing you need is a valid API schema in a supported format.
63 Includes CLI and convenient :pypi:`pytest` integration.
64 Powered by Hypothesis and :pypi:`hypothesis-jsonschema`, inspired by the earlier :pypi:`swagger-conformance` library.
65
66 `Trio <https://trio.readthedocs.io/>`_ is an async framework with "an obsessive
67 focus on usability and correctness", so naturally it works with Hypothesis!
68 :pypi:`pytest-trio` includes :ref:`a custom hook <custom-function-execution>`
69 that allows ``@given(...)`` to work with Trio-style async test functions, and
70 :pypi:`hypothesis-trio` includes stateful testing extensions to support
71 concurrent programs.
72
73 :pypi:`pymtl3` is "an open-source Python-based hardware generation, simulation,
74 and verification framework with multi-level hardware modeling support", which
75 ships with Hypothesis integrations to check that all of those levels are
76 equivalent, from function-level to register-transfer level and even to hardware.
77
78 :pypi:`battle-tested` is a fuzzing tool that will show you how your code can
79 fail - by trying all kinds of inputs and reporting whatever happens.
80
81 :pypi:`pytest-subtesthack` functions as a workaround for :issue:`377`.
82
83 :pypi:`returns` uses Hypothesis to verify that Higher Kinded Types correctly
84 implement functor, applicative, monad, and other laws; allowing a declarative
85 approach to be combined with traditional pythonic code.
86
87 :pypi:`icontract-hypothesis` includes a :ref:`ghostwriter <ghostwriter>` for test files
88 and IDE integrations such as `icontract-hypothesis-vim <https://github.com/mristin/icontract-hypothesis-vim>`_,
89 `icontract-hypothesis-pycharm <https://github.com/mristin/icontract-hypothesis-pycharm>`_,
90 and
91 `icontract-hypothesis-vscode <https://github.com/mristin/icontract-hypothesis-vscode>`_ -
92 you can run a quick 'smoke test' with only a few keystrokes for any type-annotated
93 function, even if it doesn't have any contracts!
94
95 Writing an extension
96 --------------------
97
98 .. note::
99
100 See :gh-file:`CONTRIBUTING.rst` for more information.
101
102 New strategies can be added to Hypothesis, or published as an external package
103 on PyPI - either is fine for most strategies. If in doubt, ask!
104
105 It's generally much easier to get things working outside, because there's more
106 freedom to experiment and fewer requirements in stability and API style. We're
107 happy to review and help with external packages as well as pull requests!
108
109 If you're thinking about writing an extension, please name it
110 ``hypothesis-{something}`` - a standard prefix makes the community more
111 visible and searching for extensions easier. And make sure you use the
112 ``Framework :: Hypothesis`` trove classifier!
113
114 On the other hand, being inside gets you access to some deeper implementation
115 features (if you need them) and better long-term guarantees about maintenance.
116 We particularly encourage pull requests for new composable primitives that
117 make implementing other strategies easier, or for widely used types in the
118 standard library. Strategies for other things are also welcome; anything with
119 external dependencies just goes in ``hypothesis.extra``.
120
121 Tools such as assertion helpers may also need to check whether the current
122 test is using Hypothesis. For that, see |currently_in_test_context|.
123
124 .. _entry-points:
125
126 Hypothesis integration via entry points
127 ---------------------------------------
128
129 If you would like to ship Hypothesis strategies for a custom type - either as
130 part of the upstream library, or as a third-party extension, there's a catch:
131 |st.from_type| only works after the corresponding
132 call to |st.register_type_strategy|, and you'll have
133 the same problem with |register_random|. This means that
134 either
135
136 - you have to try importing Hypothesis to register the strategy when *your*
137 library is imported, though that's only useful at test time, or
138 - the user has to call a 'register the strategies' helper that you provide
139 before running their tests
140
141 `Entry points <https://setuptools.pypa.io/en/latest/userguide/entry_point.html>`__
142 are Python's standard way of automating the latter: when you register a
143 ``"hypothesis"`` entry point in your ``pyproject.toml``, we'll import and run it
144 automatically when *hypothesis* is imported. Nothing happens unless Hypothesis
145 is already in use, and it's totally seamless for downstream users!
146
147 Let's look at an example. You start by adding a function somewhere in your
148 package that does all the Hypothesis-related setup work:
149
150 .. code-block:: python
151
152 # mymodule.py
153
154 class MyCustomType:
155 def __init__(self, x: int):
156 assert x >= 0, f"got {x}, but only positive numbers are allowed"
157 self.x = x
158
159 def _hypothesis_setup_hook():
160 import hypothesis.strategies as st
161
162 st.register_type_strategy(MyCustomType, st.integers(min_value=0))
163
164 and then declare this as your ``"hypothesis"`` entry point:
165
166 .. code-block:: toml
167
168 # pyproject.toml
169
170 # You can list a module to import by dotted name
171 [project.entry-points.hypothesis]
172 _ = "mymodule.a_submodule"
173
174 # Or name a specific function, and Hypothesis will call it for you
175 [project.entry-points.hypothesis]
176 _ = "mymodule:_hypothesis_setup_hook"
177
178 And that's all it takes!
179
180 .. envvar:: HYPOTHESIS_NO_PLUGINS
181
182 If set, disables automatic loading of all hypothesis plugins. This is probably only
183 useful for our own self-tests, but documented in case it might help narrow down
184 any particularly weird bugs in complex environments.
185
186
187 Interaction with :pypi:`pytest-cov`
188 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
189
190 Because pytest does not load plugins from entrypoints in any particular order,
191 using the Hypothesis entrypoint may import your module before :pypi:`pytest-cov`
192 starts. `This is a known issue <https://github.com/pytest-dev/pytest/issues/935>`__,
193 but there are workarounds.
194
195 You can use :command:`coverage run pytest ...` instead of :command:`pytest --cov ...`,
196 opting out of the pytest plugin entirely. Alternatively, you can ensure that Hypothesis
197 is loaded after coverage measurement is started by disabling the entrypoint, and
198 loading our pytest plugin from your ``conftest.py`` instead::
199
200 echo "pytest_plugins = ['hypothesis.extra.pytestplugin']\n" > tests/conftest.py
201 pytest -p "no:hypothesispytest" ...
202
203 Another alternative, which we in fact use in our CI self-tests because it works
204 well also with parallel tests, is to automatically start coverage early for all
205 new processes if an environment variable is set.
206 This automatic starting is set up by the PyPi package :pypi:`coverage_enable_subprocess`.
207
208 This means all configuration must be done in ``.coveragerc``, and not on the
209 command line::
210
211 [run]
212 parallel = True
213 source = ...
214
215 Then, set the relevant environment variable and run normally::
216
217 python -m pip install coverage_enable_subprocess
218 export COVERAGE_PROCESS_START=$PATH/.coveragerc
219 pytest [-n auto] ...
220 coverage combine
221 coverage report
222
223
224 .. _alternative-backends:
225
226 Alternative backends for Hypothesis
227 -----------------------------------
228
229 .. seealso::
230
231 See also the :ref:`Alternative backends interface <alternative-backends-internals>` for details on implementing your own alternative backend.
232
233 Hypothesis supports alternative backends, which tells Hypothesis how to generate primitive
234 types. This enables powerful generation techniques which are compatible with all parts of
235 Hypothesis, including the database and shrinking.
236
237 Hypothesis includes the following backends:
238
239 hypothesis
240 The default backend.
241 hypothesis-urandom
242 The same as the default backend, but uses ``/dev/urandom`` as its source of randomness,
243 instead of the standard PRNG in |random.Random|. The only reason to use this backend over the default ``backend="hypothesis"`` is if you are also
244 using `Antithesis <https://antithesis.com/>`_, in which case this allows Antithesis
245 mutation of ``/dev/urandom`` to control the values generated by Hypothesis.
246
247 ``/dev/urandom`` is not available on Windows, so we emit a warning and fall back to the
248 hypothesis backend there.
249 hypofuzz
250 Generates inputs using coverage-guided fuzzing. See `HypoFuzz <https://hypofuzz.com/>`_ for details.
251
252 Requires ``pip install hypofuzz``.
253 crosshair
254 Generates inputs using SMT solvers like z3, which is particularly effective at satisfying
255 difficult checks in your code, like ``if`` or ``==`` statements.
256
257 Requires ``pip install hypothesis[crosshair]``.
258
259 You can change the backend for a test with the |settings.backend| setting. For instance, after
260 ``pip install hypothesis[crosshair]``, you can use :pypi:`crosshair <crosshair-tool>` to
261 generate inputs with SMT via the :pypi:`hypothesis-crosshair` backend:
262
263 .. code-block:: python
264
265 from hypothesis import given, settings, strategies as st
266
267 @settings(backend="crosshair") # pip install hypothesis[crosshair]
268 @given(st.integers())
269 def test_needs_solver(x):
270 assert x != 123456789
271
272 Failures found by alternative backends are saved to the database and shrink just like normally
273 generated inputs, and in general interact with every feature of Hypothesis as you would expect.