Search code examples
pythonpython-decoratorstype-hintingpython-hypothesis

hypothesis decorator for inferring all strategies from type hints


The Python module hypothesis has a hypothesis.given decorator, which allows passing hypothesis.infer for individual parameters to derive their strategy from the corresponding type hint. This can be tedious though as all parameters have to be repeated. Here is an example:

@given(arg1=infer, arg2=infer, arg3=infer)
def test_something(arg1: int, arg2: bytes, arg3: List[float]) -> None:
    ...

The documentation advises that infer is not used by default to retain backwards compatibility. Does hypothesis already contain a decorator given_everything_inferred that simply assumes infer for all arguments or is it easy to write one? Intended usage example:

@given_everything_inferred
def test_something(arg1: int, arg2: bytes, arg3: List[float]) -> None:
    ...

Solution

  • We don't provide this by default because it can interfere with things like Pytest fixtures, and the transition to customised strategies (e.g. only positive integers) now requires you to change the whole decorator instead of a single argument.

    It's pretty easy to write your own, though:

    def given_everything_inferred(func):
        return given(**{n: infer for n in inspect.getfullargspec(func).args})(func)
    

    Handling keyword-only arguments, or writing a version which allows you to pass some strategies and infer the rest, is an exercise for the reader (or sponsorship).