Debian Codegraph @

hypothesis-python/src/hypothesis/extra/dpcontracts.py

raw
1 # This file is part of Hypothesis, which may be found at
2 # https://github.com/HypothesisWorks/hypothesis/
3 #
4 # Copyright the Hypothesis Authors.
5 # Individual contributors are listed in AUTHORS.rst and the git log.
6 #
7 # This Source Code Form is subject to the terms of the Mozilla Public License,
8 # v. 2.0. If a copy of the MPL was not distributed with this file, You can
9 # obtain one at https://mozilla.org/MPL/2.0/.
10
11 """
12 This module provides tools for working with the :pypi:`dpcontracts` library,
13 because `combining contracts and property-based testing works really well
14 <https://hillelwayne.com/talks/beyond-unit-tests/>`_.
15
16 It requires ``dpcontracts >= 0.4``.
17 """
18
19 from dpcontracts import PreconditionError
20
21 from hypothesis import reject
22 from hypothesis.errors import InvalidArgument
23 from hypothesis.internal.reflection import proxies
24
25
26 def fulfill(contract_func):
27 """Decorate ``contract_func`` to reject calls which violate preconditions,
28 and retry them with different arguments.
29
30 This is a convenience function for testing internal code that uses
31 :pypi:`dpcontracts`, to automatically filter out arguments that would be
32 rejected by the public interface before triggering a contract error.
33
34 This can be used as ``builds(fulfill(func), ...)`` or in the body of the
35 test e.g. ``assert fulfill(func)(*args)``.
36 """
37 if not hasattr(contract_func, "__contract_wrapped_func__"):
38 raise InvalidArgument(
39 f"{contract_func.__name__} has no dpcontracts preconditions"
40 )
41
42 @proxies(contract_func)
43 def inner(*args, **kwargs):
44 try:
45 return contract_func(*args, **kwargs)
46 except PreconditionError:
47 reject()
48
49 return inner