/
test_sampled_from.py
89 lines (62 loc) · 2.59 KB
/
test_sampled_from.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# coding=utf-8
#
# This file is part of Hypothesis, which may be found at
# https://github.com/HypothesisWorks/hypothesis/
#
# Most of this work is copyright (C) 2013-2019 David R. MacIver
# (david@drmaciver.com), but it contains contributions by others. See
# CONTRIBUTING.rst for a full list of people who may hold copyright, and
# consult the git log if you need to determine who owns an individual
# contribution.
#
# This Source Code Form is subject to the terms of the Mozilla Public License,
# v. 2.0. If a copy of the MPL was not distributed with this file, You can
# obtain one at https://mozilla.org/MPL/2.0/.
#
# END HEADER
from __future__ import absolute_import, division, print_function
import collections
import enum
import hypothesis.strategies as st
from hypothesis import given
from hypothesis.errors import FailedHealthCheck, InvalidArgument, Unsatisfiable
from hypothesis.internal.compat import hrange
from hypothesis.strategies import sampled_from
from tests.common.utils import checks_deprecated_behaviour, fails_with
an_enum = enum.Enum("A", "a b c")
an_ordereddict = collections.OrderedDict([("a", 1), ("b", 2), ("c", 3)])
@fails_with(InvalidArgument)
def test_cannot_sample_sets():
sampled_from(set("abc")).example()
def test_can_sample_sequence_without_warning():
sampled_from([1, 2, 3]).example()
def test_can_sample_ordereddict_without_warning():
sampled_from(an_ordereddict).example()
@given(sampled_from(an_enum))
def test_can_sample_enums(member):
assert isinstance(member, an_enum)
@checks_deprecated_behaviour
def test_sampling_empty_is_deprecated():
assert sampled_from([]).is_empty
@fails_with(FailedHealthCheck)
@given(sampled_from(hrange(10)).filter(lambda x: x < 0))
def test_unsat_filtered_sampling(x):
assert False
@fails_with(Unsatisfiable)
@given(sampled_from(hrange(2)).filter(lambda x: x < 0))
def test_unsat_filtered_sampling_in_rejection_stage(x):
# Rejecting all possible indices before we calculate the allowed indices
# takes an early exit path, so we need this test to cover that branch.
assert False
def test_easy_filtered_sampling():
x = sampled_from(hrange(100)).filter(lambda x: x == 0).example()
assert x == 0
@given(sampled_from(hrange(100)).filter(lambda x: x == 99))
def test_filtered_sampling_finds_rare_value(x):
assert x == 99
@given(st.sets(st.sampled_from(range(50)), min_size=50))
def test_efficient_sets_of_samples(x):
assert x == set(range(50))
@given(st.lists(st.sampled_from([0] * 100), unique=True))
def test_does_not_include_duplicates_even_when_duplicated_in_collection(ls):
assert len(ls) <= 1