Debian Codegraph @

hypothesis-python/tests/nocover/test_filtering.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 import pytest
12
13 from hypothesis import given, strategies as st
14 from hypothesis.strategies import integers, lists
15
16
17 @pytest.mark.parametrize(
18 ("specifier", "condition"),
19 [(integers(), lambda x: x > 1), (lists(integers()), bool)],
20 )
21 def test_filter_correctly(specifier, condition):
22 @given(specifier.filter(condition))
23 def test_is_filtered(x):
24 assert condition(x)
25
26 test_is_filtered()
27
28
29 # A variety of strategies that generate the integers 1-20 inclusive, but might
30 # differ in their support for special-case filtering.
31 one_to_twenty_strategies = [
32 st.integers(1, 20),
33 st.integers(0, 19).map(lambda x: x + 1),
34 st.sampled_from(range(1, 21)),
35 st.sampled_from(range(20)).map(lambda x: x + 1),
36 ]
37
38
39 @pytest.mark.parametrize("base", one_to_twenty_strategies)
40 @given(
41 data=st.data(),
42 forbidden_values=st.lists(st.integers(1, 20), max_size=19, unique=True),
43 )
44 def test_chained_filters_agree(data, forbidden_values, base):
45 def forbid(s, forbidden):
46 """Helper function to avoid Python variable scoping issues."""
47 return s.filter(lambda x: x != forbidden)
48
49 s = base
50 for forbidden in forbidden_values:
51 s = forbid(s, forbidden)
52
53 x = data.draw(s)
54 assert 1 <= x <= 20
55 assert x not in forbidden_values
56
57
58 @pytest.mark.parametrize("base", one_to_twenty_strategies)
59 def test_chained_filters_repr(base):
60 def foo(x):
61 return x != 0
62
63 def bar(x):
64 return x != 2
65
66 filtered = base.filter(foo)
67 chained = filtered.filter(bar)
68 assert repr(chained) == f"{base!r}.filter(foo).filter(bar)"
69 assert repr(filtered) == f"{base!r}.filter(foo)"