|
| 1 | +# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 |
| 2 | +# For details: https://github.com/coveragepy/coveragepy/blob/main/NOTICE.txt |
| 3 | + |
| 4 | +"""Hypothesis strategies for use in tests.""" |
| 5 | + |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | +from hypothesis import strategies as st |
| 9 | + |
| 10 | + |
| 11 | +# Leaf types, all hashable. Some are limited to the kinds of values coverage |
| 12 | +# deals with, to focus Hypothesis. |
| 13 | +hashable_leaves = [ |
| 14 | + st.none(), |
| 15 | + st.booleans(), |
| 16 | + st.integers(min_value=-1000, max_value=10_000_000), |
| 17 | + st.floats(min_value=-100, max_value=100, allow_nan=False, allow_infinity=False).map( |
| 18 | + lambda x: 0.0 if x == 0.0 else x |
| 19 | + ), |
| 20 | + st.text(max_size=10), |
| 21 | + st.binary(max_size=10), |
| 22 | +] |
| 23 | + |
| 24 | + |
| 25 | +def tuples_of(strat: st.SearchStrategy) -> st.SearchStrategy: |
| 26 | + """Make a strategy for tuples of some other strategy.""" |
| 27 | + return st.lists(strat, max_size=3).map(tuple) |
| 28 | + |
| 29 | + |
| 30 | +# List of strategies that produce hashable data. |
| 31 | +hashable = hashable_leaves + [tuples_of(s) for s in hashable_leaves] |
| 32 | + |
| 33 | + |
| 34 | +def nested_dicts_of(s: st.SearchStrategy) -> st.SearchStrategy: |
| 35 | + """Make a strategy to produce recursive dicts with leaves from the `s` strategy.""" |
| 36 | + return st.recursive( |
| 37 | + s, |
| 38 | + lambda children: st.dictionaries(st.text(max_size=10), children, max_size=3), |
| 39 | + max_leaves=10, |
| 40 | + ) |
| 41 | + |
| 42 | + |
| 43 | +# Schema: a strategy that generates strategies for nested data. |
| 44 | +nested_data_schemas = st.recursive( |
| 45 | + st.sampled_from(hashable), |
| 46 | + lambda children: st.one_of( |
| 47 | + children.map(lambda s: st.lists(s, max_size=5)), |
| 48 | + children.map(tuples_of), |
| 49 | + st.sampled_from(hashable).map(lambda s: st.sets(s, max_size=10)), |
| 50 | + children.map(nested_dicts_of), |
| 51 | + ), |
| 52 | + max_leaves=3, |
| 53 | +) |
| 54 | + |
| 55 | +if __name__ == "__main__": |
| 56 | + import warnings |
| 57 | + from hypothesis.errors import NonInteractiveExampleWarning |
| 58 | + |
| 59 | + warnings.filterwarnings("ignore", category=NonInteractiveExampleWarning) |
| 60 | + |
| 61 | + for _ in range(50): |
| 62 | + print(repr(nested_data_schemas.example().example())) |
0 commit comments