| 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 collections |
| 12 |
import enum |
| 13 |
import operator |
| 14 |
|
| 15 |
import pytest |
| 16 |
|
| 17 |
from hypothesis import given, settings, strategies as st |
| 18 |
from hypothesis.errors import ( |
| 19 |
FailedHealthCheck, |
| 20 |
InvalidArgument, |
| 21 |
StopTest, |
| 22 |
Unsatisfiable, |
| 23 |
) |
| 24 |
from hypothesis.internal.conjecture.data import ConjectureData |
| 25 |
from hypothesis.strategies import sampled_from |
| 26 |
from hypothesis.strategies._internal.misc import JustStrategy |
| 27 |
from hypothesis.strategies._internal.strategies import ( |
| 28 |
FilteredStrategy, |
| 29 |
filter_not_satisfied, |
| 30 |
) |
| 31 |
|
| 32 |
from tests.common.debug import ( |
| 33 |
assert_all_examples, |
| 34 |
assert_simple_property, |
| 35 |
check_can_generate_examples, |
| 36 |
) |
| 37 |
from tests.common.utils import fails_with |
| 38 |
|
| 39 |
an_enum = enum.Enum("A", "a b c") |
| 40 |
a_flag = enum.Flag("A", "a b c") |
| 41 |
# named zero state is required for empty flags from around py3.11/3.12 |
| 42 |
an_empty_flag = enum.Flag("EmptyFlag", {"a": 0}) |
| 43 |
|
| 44 |
an_ordereddict = collections.OrderedDict([("a", 1), ("b", 2), ("c", 3)]) |
| 45 |
|
| 46 |
|
| 47 |
@fails_with(InvalidArgument) |
| 48 |
def test_cannot_sample_sets(): |
| 49 |
check_can_generate_examples(sampled_from(set("abc"))) |
| 50 |
|
| 51 |
|
| 52 |
def test_can_sample_sequence_without_warning(): |
| 53 |
check_can_generate_examples(sampled_from([1, 2, 3])) |
| 54 |
|
| 55 |
|
| 56 |
def test_can_sample_ordereddict_without_warning(): |
| 57 |
check_can_generate_examples(sampled_from(an_ordereddict)) |
| 58 |
|
| 59 |
|
| 60 |
@pytest.mark.parametrize("enum_class", [an_enum, a_flag, an_empty_flag]) |
| 61 |
def test_can_sample_enums(enum_class): |
| 62 |
assert_all_examples(sampled_from(enum_class), lambda x: isinstance(x, enum_class)) |
| 63 |
|
| 64 |
|
| 65 |
@fails_with(FailedHealthCheck) |
| 66 |
@settings(suppress_health_check=[]) |
| 67 |
@given(sampled_from(range(10)).filter(lambda x: x < 0)) |
| 68 |
def test_unsat_filtered_sampling(x): |
| 69 |
raise AssertionError |
| 70 |
|
| 71 |
|
| 72 |
@fails_with(Unsatisfiable) |
| 73 |
@settings(suppress_health_check=[]) |
| 74 |
@given(sampled_from(range(2)).filter(lambda x: x < 0)) |
| 75 |
def test_unsat_filtered_sampling_in_rejection_stage(x): |
| 76 |
# Rejecting all possible indices before we calculate the allowed indices |
| 77 |
# takes an early exit path, so we need this test to cover that branch. |
| 78 |
raise AssertionError |
| 79 |
|
| 80 |
|
| 81 |
def test_easy_filtered_sampling(): |
| 82 |
assert_simple_property( |
| 83 |
sampled_from(range(100)).filter(lambda x: x == 0), lambda x: x == 0 |
| 84 |
) |
| 85 |
|
| 86 |
|
| 87 |
@given(sampled_from(range(100)).filter(lambda x: x == 99)) |
| 88 |
def test_filtered_sampling_finds_rare_value(x): |
| 89 |
assert x == 99 |
| 90 |
|
| 91 |
|
| 92 |
@given(st.sets(st.sampled_from(range(50)), min_size=50)) |
| 93 |
def test_efficient_sets_of_samples(x): |
| 94 |
assert x == set(range(50)) |
| 95 |
|
| 96 |
|
| 97 |
@given(st.dictionaries(keys=st.sampled_from(range(50)), values=st.none(), min_size=50)) |
| 98 |
def test_efficient_dicts_with_sampled_keys(x): |
| 99 |
assert set(x) == set(range(50)) |
| 100 |
|
| 101 |
|
| 102 |
@pytest.mark.skipif( |
| 103 |
settings.get_current_profile_name() == "crosshair", |
| 104 |
reason="takes 3-5 mins and raises Unsatisfiable", |
| 105 |
) |
| 106 |
@pytest.mark.parametrize( |
| 107 |
"fn", [lambda asdf: asdf[0], (operator.itemgetter(0), lambda x: x[0])] |
| 108 |
) |
| 109 |
@given(st.data()) |
| 110 |
def test_efficient_lists_of_tuples_first_element_sampled_from(fn, data): |
| 111 |
elems = st.tuples(st.sampled_from(range(20)), st.builds(list)) |
| 112 |
x = data.draw(st.lists(elems, min_size=20, unique_by=fn)) |
| 113 |
assert {first for first, *_ in x} == set(range(20)) |
| 114 |
|
| 115 |
|
| 116 |
@given(st.lists(st.sampled_from([0] * 100), unique=True)) |
| 117 |
def test_does_not_include_duplicates_even_when_duplicated_in_collection(ls): |
| 118 |
assert len(ls) <= 1 |
| 119 |
|
| 120 |
|
| 121 |
@given( |
| 122 |
st.sets( |
| 123 |
st.sampled_from(range(50)) |
| 124 |
.map(lambda x: x * 2) |
| 125 |
.filter(lambda x: x % 3) |
| 126 |
.map(lambda x: x // 2), |
| 127 |
min_size=33, |
| 128 |
) |
| 129 |
) |
| 130 |
def test_efficient_sets_of_samples_with_chained_transformations(x): |
| 131 |
assert x == {x for x in range(50) if (x * 2) % 3} |
| 132 |
|
| 133 |
|
| 134 |
@st.composite |
| 135 |
def stupid_sampled_sets(draw): |
| 136 |
result = set() |
| 137 |
s = st.sampled_from(range(20)).filter(lambda x: x % 3).map(lambda x: x * 2) |
| 138 |
while len(result) < 13: |
| 139 |
result.add(draw(s.filter(lambda x: x not in result))) |
| 140 |
return result |
| 141 |
|
| 142 |
|
| 143 |
@given(stupid_sampled_sets()) |
| 144 |
def test_efficient_sets_of_samples_with_chained_transformations_slow_path(x): |
| 145 |
# This deliberately exercises the standard filtering logic without going |
| 146 |
# through the special-case handling of UniqueSampledListStrategy. |
| 147 |
assert x == {x * 2 for x in range(20) if x % 3} |
| 148 |
|
| 149 |
|
| 150 |
@fails_with(Unsatisfiable) |
| 151 |
@given(FilteredStrategy(st.sampled_from([None, False, ""]), conditions=(bool,))) |
| 152 |
def test_unsatisfiable_explicit_filteredstrategy_sampled(x): |
| 153 |
raise AssertionError("Unreachable because there are no valid examples") |
| 154 |
|
| 155 |
|
| 156 |
@fails_with(Unsatisfiable) |
| 157 |
@given(FilteredStrategy(st.none(), conditions=(bool,))) |
| 158 |
def test_unsatisfiable_explicit_filteredstrategy_just(x): |
| 159 |
raise AssertionError("Unreachable because there are no valid examples") |
| 160 |
|
| 161 |
|
| 162 |
def test_transformed_just_strategy(): |
| 163 |
data = ConjectureData.for_choices([]) |
| 164 |
s = JustStrategy([1]).map(lambda x: x * 2) |
| 165 |
assert s.do_draw(data) == 2 |
| 166 |
sf = s.filter(lambda x: False) |
| 167 |
assert isinstance(sf, JustStrategy) |
| 168 |
assert sf.do_filtered_draw(data) == filter_not_satisfied |
| 169 |
with pytest.raises(StopTest): |
| 170 |
sf.do_draw(data) |
| 171 |
|
| 172 |
|
| 173 |
@given(st.lists(st.sampled_from(range(100)), max_size=3, unique=True)) |
| 174 |
def test_max_size_is_respected_with_unique_sampled_from(ls): |
| 175 |
assert len(ls) <= 3 |
| 176 |
|
| 177 |
|
| 178 |
@given(st.lists(st.sampled_from([0, 0.0]), unique=True, min_size=1)) |
| 179 |
def test_issue_2247_regression(ls): |
| 180 |
assert len(ls) == 1 |
| 181 |
|
| 182 |
|
| 183 |
@given(st.data()) |
| 184 |
def test_mutability_1(data): |
| 185 |
# See https://github.com/HypothesisWorks/hypothesis/issues/2507 |
| 186 |
x = [1] |
| 187 |
s = st.sampled_from(x) |
| 188 |
x.append(2) |
| 189 |
assert data.draw(s) != 2 |
| 190 |
|
| 191 |
|
| 192 |
@given(st.data()) |
| 193 |
def test_mutability_2(data): |
| 194 |
x = [1] |
| 195 |
s = st.sampled_from(x) |
| 196 |
assert data.draw(s) != 2 |
| 197 |
x.append(2) |
| 198 |
assert data.draw(s) != 2 |
| 199 |
|
| 200 |
|
| 201 |
class AnnotationsInsteadOfElements(enum.Enum): |
| 202 |
a: "int" |
| 203 |
|
| 204 |
|
| 205 |
def test_suggests_elements_instead_of_annotations(): |
| 206 |
with pytest.raises(InvalidArgument, match=r"Cannot sample.*annotations.*dataclass"): |
| 207 |
check_can_generate_examples(st.sampled_from(AnnotationsInsteadOfElements)) |
| 208 |
|
| 209 |
|
| 210 |
class TestErrorNoteBehavior3819: |
| 211 |
elements = (st.booleans(), st.decimals(), st.integers(), st.text()) |
| 212 |
|
| 213 |
@staticmethod |
| 214 |
@given(st.data()) |
| 215 |
def direct_without_error(data): |
| 216 |
data.draw(st.sampled_from((st.floats(), st.binary()))) |
| 217 |
|
| 218 |
@staticmethod |
| 219 |
@given(st.data()) |
| 220 |
def direct_with_non_type_error(data): |
| 221 |
data.draw(st.sampled_from(st.characters(), st.floats())) |
| 222 |
raise Exception("Contains SearchStrategy, but no note addition!") |
| 223 |
|
| 224 |
@staticmethod |
| 225 |
@given(st.data()) |
| 226 |
def direct_with_type_error_without_substring(data): |
| 227 |
data.draw(st.sampled_from(st.booleans(), st.binary())) |
| 228 |
raise TypeError("Substring not in message!") |
| 229 |
|
| 230 |
@staticmethod |
| 231 |
@given(st.data()) |
| 232 |
def direct_with_type_error_with_substring_but_not_all_strategies(data): |
| 233 |
data.draw(st.sampled_from(st.booleans(), False, True)) |
| 234 |
raise TypeError("Contains SearchStrategy, but no note addition!") |
| 235 |
|
| 236 |
@staticmethod |
| 237 |
@given(st.data()) |
| 238 |
def direct_all_strategies_with_type_error_with_substring(data): |
| 239 |
data.draw(st.sampled_from((st.dates(), st.datetimes()))) |
| 240 |
raise TypeError("This message contains SearchStrategy as substring!") |
| 241 |
|
| 242 |
@staticmethod |
| 243 |
@given(st.lists(st.sampled_from(elements))) |
| 244 |
def indirect_without_error(_): |
| 245 |
return |
| 246 |
|
| 247 |
@staticmethod |
| 248 |
@given(st.lists(st.sampled_from(elements))) |
| 249 |
def indirect_with_non_type_error(_): |
| 250 |
raise Exception("Contains SearchStrategy, but no note addition!") |
| 251 |
|
| 252 |
@staticmethod |
| 253 |
@given(st.lists(st.sampled_from(elements))) |
| 254 |
def indirect_with_type_error_without_substring(_): |
| 255 |
raise TypeError("Substring not in message!") |
| 256 |
|
| 257 |
@staticmethod |
| 258 |
@given(st.lists(st.sampled_from((*elements, False, True)))) |
| 259 |
def indirect_with_type_error_with_substring_but_not_all_strategies(_): |
| 260 |
raise TypeError("Contains SearchStrategy, but no note addition!") |
| 261 |
|
| 262 |
@staticmethod |
| 263 |
@given(st.lists(st.sampled_from(elements), min_size=1)) |
| 264 |
def indirect_all_strategies_with_type_error_with_substring(objs): |
| 265 |
raise TypeError("Contains SearchStrategy in message, trigger note!") |
| 266 |
|
| 267 |
@pytest.mark.parametrize( |
| 268 |
["func_to_call", "exp_err_cls", "should_exp_msg"], |
| 269 |
[ |
| 270 |
pytest.param(f.__func__, err, msg_exp, id=f.__func__.__name__) |
| 271 |
for f, err, msg_exp in [ |
| 272 |
(f, TypeError, True) |
| 273 |
for f in ( |
| 274 |
direct_all_strategies_with_type_error_with_substring, |
| 275 |
indirect_all_strategies_with_type_error_with_substring, |
| 276 |
) |
| 277 |
] |
| 278 |
+ [ |
| 279 |
(f, TypeError, False) |
| 280 |
for f in ( |
| 281 |
direct_with_type_error_without_substring, |
| 282 |
direct_with_type_error_with_substring_but_not_all_strategies, |
| 283 |
indirect_with_type_error_without_substring, |
| 284 |
indirect_with_type_error_with_substring_but_not_all_strategies, |
| 285 |
) |
| 286 |
] |
| 287 |
+ [ |
| 288 |
(f, Exception, False) |
| 289 |
for f in ( |
| 290 |
direct_with_non_type_error, |
| 291 |
indirect_with_non_type_error, |
| 292 |
) |
| 293 |
] |
| 294 |
+ [ |
| 295 |
(f, None, False) |
| 296 |
for f in ( |
| 297 |
direct_without_error, |
| 298 |
indirect_without_error, |
| 299 |
) |
| 300 |
] |
| 301 |
], |
| 302 |
) |
| 303 |
def test_error_appropriate_error_note_3819( |
| 304 |
self, func_to_call, exp_err_cls, should_exp_msg |
| 305 |
): |
| 306 |
if exp_err_cls is None: |
| 307 |
# Here we only care that no exception was raised, so nothing to assert. |
| 308 |
func_to_call() |
| 309 |
else: |
| 310 |
with pytest.raises(exp_err_cls) as err_ctx: |
| 311 |
func_to_call() |
| 312 |
notes = getattr(err_ctx.value, "__notes__", []) |
| 313 |
matching_messages = [ |
| 314 |
n |
| 315 |
for n in notes |
| 316 |
if n.startswith("sampled_from was given a collection of strategies") |
| 317 |
and n.endswith("Was one_of intended?") |
| 318 |
] |
| 319 |
assert len(matching_messages) == (1 if should_exp_msg else 0) |