Debian Codegraph @

hypothesis-python/docs/reference/integrations.rst

raw
1 Integrations Reference
2 ======================
3
4 Reference for Hypothesis features with a defined interface, but no code API.
5
6 .. _ghostwriter:
7
8 Ghostwriter
9 -----------
10
11 .. automodule:: hypothesis.extra.ghostwriter
12 :members:
13
14 A note for test-generation researchers
15 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
16
17 Ghostwritten tests are intended as a *starting point for human authorship*,
18 to demonstrate best practice, help novices past blank-page paralysis, and save time
19 for experts. They *may* be ready-to-run, or include placeholders and ``# TODO:``
20 comments to fill in strategies for unknown types. In either case, improving tests
21 for their own code gives users a well-scoped and immediately rewarding context in
22 which to explore property-based testing.
23
24 By contrast, most test-generation tools aim to produce ready-to-run test suites...
25 and implicitly assume that the current behavior is the desired behavior.
26 However, the code might contain bugs, and we want our tests to fail if it does!
27 Worse, tools require that the code to be tested is finished and executable,
28 making it impossible to generate tests as part of the development process.
29
30 `Fraser 2013`_ found that evolving a high-coverage test suite (e.g. Randoop_, EvoSuite_, Pynguin_)
31 "leads to clear improvements in commonly applied quality metrics such as code coverage
32 [but] no measurable improvement in the number of bugs actually found by developers"
33 and that "generating a set of test cases, even high coverage test cases,
34 does not necessarily improve our ability to test software".
35 Invariant detection (famously Daikon_; in PBT see e.g. `Alonso 2022`_,
36 QuickSpec_, Speculate_) relies on code execution. Program slicing (e.g. FUDGE_,
37 FuzzGen_, WINNIE_) requires downstream consumers of the code to test.
38
39 Ghostwriter inspects the function name, argument names and types, and docstrings.
40 It can be used on buggy or incomplete code, runs in a few seconds, and produces
41 a single semantically-meaningful test per function or group of functions.
42 Rather than detecting regressions, these tests check semantic properties such as
43 `encode/decode or save/load round-trips <https://zhd.dev/ghostwriter/?q=gzip.compress>`__,
44 for `commutative, associative, and distributive operations
45 <https://zhd.dev/ghostwriter/?q=operator.mul>`__,
46 `equivalence between methods <https://zhd.dev/ghostwriter/?q=operator.add+numpy.add>`__,
47 `array shapes <https://zhd.dev/ghostwriter/?q=numpy.matmul>`__,
48 and idempotence. Where no property is detected, we simply check for
49 'no error on valid input' and allow the user to supply their own invariants.
50
51 Evaluations such as the SBFT24_ competition_ measure performance on a task which
52 the Ghostwriter is not intended to perform. I'd love to see qualitative user
53 studies, such as `PBT in Practice`_ for test generation, which could check
54 whether the Ghostwriter is onto something or tilting at windmills.
55 If you're interested in similar questions, `drop me an email`_!
56
57 .. _Daikon: https://plse.cs.washington.edu/daikon/pubs/
58 .. _Alonso 2022: https://doi.org/10.1145/3540250.3559080
59 .. _QuickSpec: http://www.cse.chalmers.se/~nicsma/papers/quickspec2.pdf
60 .. _Speculate: https://matela.com.br/speculate.pdf
61 .. _FUDGE: https://research.google/pubs/pub48314/
62 .. _FuzzGen: https://www.usenix.org/conference/usenixsecurity20/presentation/ispoglou
63 .. _WINNIE: https://www.ndss-symposium.org/wp-content/uploads/2021-334-paper.pdf
64 .. _Fraser 2013: https://doi.org/10.1145/2483760.2483774
65 .. _Randoop: https://homes.cs.washington.edu/~mernst/pubs/feedback-testgen-icse2007.pdf
66 .. _EvoSuite: https://www.evosuite.org/wp-content/papercite-data/pdf/esecfse11.pdf
67 .. _Pynguin: https://arxiv.org/abs/2007.14049
68 .. _SBFT24: https://arxiv.org/abs/2401.15189
69 .. _competition: https://github.com/ThunderKey/python-tool-competition-2024
70 .. _PBT in Practice: https://harrisongoldste.in/papers/icse24-pbt-in-practice.pdf
71 .. _drop me an email: mailto:[email protected]?subject=Hypothesis%20Ghostwriter%20research
72
73 .. _observability:
74
75 Observability
76 -------------
77
78 .. note::
79
80 The `Tyche <https://github.com/tyche-pbt/tyche-extension>`__ VSCode extension provides an in-editor UI for observability results generated by Hypothesis. If you want to *view* observability results, rather than programmatically consume or display them, we recommend using Tyche.
81
82 .. warning::
83
84 This feature is experimental, and could have breaking changes or even be removed
85 without notice. Try it out, let us know what you think, but don't rely on it
86 just yet!
87
88
89 Motivation
90 ~~~~~~~~~~
91
92 Understanding what your code is doing - for example, why your test failed - is often
93 a frustrating exercise in adding some more instrumentation or logging (or ``print()`` calls)
94 and running it again. The idea of :wikipedia:`observability <Observability_(software)>`
95 is to let you answer questions you didn't think of in advance. In slogan form,
96
97 *Debugging should be a data analysis problem.*
98
99 By default, Hypothesis only reports the minimal failing example... but sometimes you might
100 want to know something about *all* the examples. Printing them to the terminal by increasing
101 |Verbosity| might be nice, but isn't always enough.
102 This feature gives you an analysis-ready dataframe with useful columns and one row
103 per test case, with columns from arguments to code coverage to pass/fail status.
104
105 This is deliberately a much lighter-weight and task-specific system than e.g.
106 `OpenTelemetry <https://opentelemetry.io/>`__. It's also less detailed than time-travel
107 debuggers such as `rr <https://rr-project.org/>`__ or `pytrace <https://pytrace.com/>`__,
108 because there's no good way to compare multiple traces from these tools and their
109 Python support is relatively immature.
110
111
112 Configuration
113 ~~~~~~~~~~~~~
114
115 If you set the ``HYPOTHESIS_EXPERIMENTAL_OBSERVABILITY`` environment variable,
116 Hypothesis will log various observations to jsonlines files in the
117 ``.hypothesis/observed/`` directory. You can load and explore these with e.g.
118 :func:`pd.read_json(".hypothesis/observed/*_testcases.jsonl", lines=True) <pandas.read_json>`,
119 or by using the :pypi:`sqlite-utils` and :pypi:`datasette` libraries::
120
121 sqlite-utils insert testcases.db testcases .hypothesis/observed/*_testcases.jsonl --nl --flatten
122 datasette serve testcases.db
123
124 If you are experiencing a significant slow-down, you can try setting
125 ``HYPOTHESIS_EXPERIMENTAL_OBSERVABILITY_NOCOVER`` instead; this will disable coverage information
126 collection. This should not be necessary on Python 3.12 or later, where coverage collection is very fast.
127
128
129 Collecting more information
130 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
131
132 If you want to record more information about your test cases than the arguments and
133 outcome - for example, was ``x`` a binary tree? what was the difference between the
134 expected and the actual value? how many queries did it take to find a solution? -
135 Hypothesis makes this easy.
136
137 :func:`~hypothesis.event` accepts a string label, and optionally a string or int or
138 float observation associated with it. All events are collected and summarized in
139 :ref:`statistics`, as well as included on a per-test-case basis in our observations.
140
141 :func:`~hypothesis.target` is a special case of numeric-valued events: as well as
142 recording them in observations, Hypothesis will try to maximize the targeted value.
143 Knowing that, you can use this to guide the search for failing inputs.
144
145
146 Data Format
147 ~~~~~~~~~~~
148
149 We dump observations in `json lines format <https://jsonlines.org/>`__, with each line
150 describing either a test case or an information message. The tables below are derived
151 from :download:`this machine-readable JSON schema <schema_observations.json>`, to
152 provide both readable and verifiable specifications.
153
154 Note that we use :func:`python:json.dumps` and can therefore emit non-standard JSON
155 which includes infinities and NaN. This is valid in `JSON5 <https://json5.org/>`__,
156 and supported by `some JSON parsers <https://evanhahn.com/pythons-nonstandard-json-encoding/>`__
157 including Gson in Java, ``JSON.parse()`` in Ruby, and of course in Python.
158
159 Information message
160 ^^^^^^^^^^^^^^^^^^^
161
162 .. jsonschema:: ./schema_observations.json#/oneOf/1
163 :hide_key: /additionalProperties, /type
164
165 Test case
166 ^^^^^^^^^
167
168 .. jsonschema:: ./schema_observations.json#/oneOf/0
169 :hide_key: /additionalProperties, /type
170
171 .. _observability-hypothesis-metadata:
172
173 Hypothesis metadata
174 +++++++++++++++++++
175
176 While the observability format is agnostic to the property-based testing library which generated it, Hypothesis includes specific values in the ``metadata`` key for test cases. You may rely on these being present if and only if the observation was generated by Hypothesis.
177
178 .. jsonschema:: ./schema_metadata.json
179 :hide_key: /additionalProperties, /type
180
181 Choices metadata
182 ++++++++++++++++
183
184 These additional metadata elements are included in ``metadata`` (as e.g. ``metadata["choice_nodes"]`` or ``metadata["choice_spans"]``), if and only if |OBSERVABILITY_CHOICES| is set.
185
186 .. jsonschema:: ./schema_metadata_choices.json
187 :hide_key: /additionalProperties, /type
188
189 .. _pytest-plugin:
190
191 The Hypothesis pytest plugin
192 ----------------------------
193
194 Hypothesis includes a tiny plugin to improve integration with :pypi:`pytest`, which is activated by default (but does not affect other test runners). It aims to improve the integration between Hypothesis and Pytest by providing extra information and convenient access to config options.
195
196 - ``pytest --hypothesis-show-statistics`` can be used to :ref:`display test and data generation statistics <statistics>`.
197 - ``pytest --hypothesis-profile=<profile name>`` can be used to load a settings profile (as in |settings.load_profile|).
198 - ``pytest --hypothesis-verbosity=<level name>`` can be used to override the current |Verbosity| setting.
199 - ``pytest --hypothesis-seed=<an int>`` can be used to reproduce a failure with a particular seed (as in |@seed|).
200 - ``pytest --hypothesis-explain`` can be used to temporarily enable |Phase.explain|.
201
202 Finally, all tests that are defined with Hypothesis automatically have ``@pytest.mark.hypothesis`` applied to them. See :ref:`here for information on working with markers <pytest:mark examples>`.
203
204 .. note::
205 Pytest will load the plugin automatically if Hypothesis is installed. You don't need to do anything at all to use it.
206
207 If this causes problems, you can avoid loading the plugin with the ``-p no:hypothesispytest`` option.
208
209 .. _statistics:
210
211 Test statistics
212 ~~~~~~~~~~~~~~~
213
214 .. note::
215
216 While test statistics are only available under pytest, you can use the :ref:`observability <observability>` interface to view similar information about your tests.
217
218 You can see a number of statistics about executed tests by passing the command line argument ``--hypothesis-show-statistics``. This will include some general statistics about the test:
219
220 For example if you ran the following with ``--hypothesis-show-statistics``:
221
222 .. code-block:: python
223
224 from hypothesis import given, strategies as st
225
226 @given(st.integers())
227 def test_integers(i):
228 pass
229
230 You would see:
231
232 .. code-block:: none
233
234 - during generate phase (0.06 seconds):
235 - Typical runtimes: < 1ms, ~ 47% in data generation
236 - 100 passing examples, 0 failing examples, 0 invalid examples
237 - Stopped because settings.max_examples=100
238
239 The final "Stopped because" line tells you why Hypothesis stopped generating new examples. This is typically because we hit |max_examples|, but occasionally because we exhausted the search space or because shrinking was taking a very long time. This can be useful for understanding the behaviour of your tests.
240
241 In some cases (such as filtered and recursive strategies) you will see events mentioned which describe some aspect of the data generation:
242
243 .. code-block:: python
244
245 from hypothesis import given, strategies as st
246
247 @given(st.integers().filter(lambda x: x % 2 == 0))
248 def test_even_integers(i):
249 pass
250
251 You would see something like:
252
253 .. code-block:: none
254
255 test_even_integers:
256
257 - during generate phase (0.08 seconds):
258 - Typical runtimes: < 1ms, ~ 57% in data generation
259 - 100 passing examples, 0 failing examples, 12 invalid examples
260 - Events:
261 * 51.79%, Retried draw from integers().filter(lambda x: x % 2 == 0) to satisfy filter
262 * 10.71%, Aborted test because unable to satisfy integers().filter(lambda x: x % 2 == 0)
263 - Stopped because settings.max_examples=100
264
265 .. _hypothesis-cli:
266
267 hypothesis[cli]
268 ----------------
269
270 .. note::
271
272 This feature requires the ``hypothesis[cli]`` :doc:`extra </extras>`, via ``pip install hypothesis[cli]``.
273
274 .. automodule:: hypothesis.extra.cli
275
276 .. _codemods:
277
278 hypothesis[codemods]
279 --------------------
280
281 .. note::
282
283 This feature requires the ``hypothesis[codemods]`` :doc:`extra </extras>`, via ``pip install hypothesis[codemods]``.
284
285 .. automodule:: hypothesis.extra.codemods
286
287 .. _hypothesis-dpcontracts:
288
289 hypothesis[dpcontracts]
290 -----------------------
291
292 .. note::
293
294 This feature requires the ``hypothesis[dpcontracts]`` :doc:`extra </extras>`, via ``pip install hypothesis[dpcontracts]``.
295
296 .. tip::
297
298 For new projects, we recommend using either :pypi:`deal` or :pypi:`icontract`
299 and :pypi:`icontract-hypothesis` over :pypi:`dpcontracts`.
300 They're generally more powerful tools for design-by-contract programming,
301 and have substantially nicer Hypothesis integration too!
302
303 .. automodule:: hypothesis.extra.dpcontracts
304 :members: