Debian Codegraph @

hypothesis-python/tests/nocover/test_conjecture_utils.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 sys
12 from collections import Counter
13
14 from hypothesis import assume, example, given, settings, strategies as st, target
15 from hypothesis.internal.conjecture import utils as cu
16 from hypothesis.internal.conjecture.engine import BUFFER_SIZE
17 from hypothesis.internal.conjecture.provider_conformance import integer_weights
18
19 from tests.conjecture.common import fresh_data
20
21
22 @given(integer_weights(), st.randoms(use_true_random=True))
23 @settings(max_examples=3)
24 def test_sampler_matches_distribution(weights, random):
25 # if we randomly sample from Sampler(weights), the resulting distribution
26 # should match the weights (to some tolerance).
27
28 weights = weights.values()
29 sampler = cu.Sampler(weights)
30 counter = Counter()
31 for _ in range(10_000):
32 cd = fresh_data(random=random)
33 n = sampler.sample(cd)
34 counter[n] += 1
35
36 # if we ever pull in scipy to our test suite, we should do a chi squared
37 # test here instead.
38 expected = [w / sum(weights) for w in weights]
39 counter_total = sum(counter.values()) # Counter.total() new in py3.10
40 actual = [counter[i] / counter_total for i in range(len(weights))]
41 for p1, p2 in zip(expected, actual, strict=True):
42 assert abs(p1 - p2) < 0.05, (expected, actual)
43
44
45 @example(0, 1)
46 @example(0, float("inf"))
47 @example(cu.SMALLEST_POSITIVE_FLOAT, 2 * cu.SMALLEST_POSITIVE_FLOAT)
48 @example(cu.SMALLEST_POSITIVE_FLOAT, 1)
49 @example(cu.SMALLEST_POSITIVE_FLOAT, float("inf"))
50 @example(sys.float_info.min, 1)
51 @example(sys.float_info.min, float("inf"))
52 @example(10, 10)
53 @example(10, float("inf"))
54 # BUFFER_SIZE divided by (2bytes coin + 0byte element) gives the
55 # maximum number of elements that we would ever be able to generate.
56 @given(st.floats(0, BUFFER_SIZE // 2), st.integers(0, BUFFER_SIZE // 2))
57 def test_p_continue(average_size, max_size):
58 assume(average_size <= max_size)
59 p = cu._calc_p_continue(average_size, max_size)
60 assert 0 <= target(p, label="p") <= 1
61 assert 0 < target(p, label="-p") or average_size < 1e-5
62 abs_err = abs(average_size - cu._p_continue_to_avg(p, max_size))
63 assert target(abs_err, label="abs_err") < 0.01
64
65
66 @example(1.1, 10)
67 @given(st.floats(0, 1), st.integers(0, BUFFER_SIZE // 2))
68 def test_p_continue_to_average(p_continue, max_size):
69 average = cu._p_continue_to_avg(p_continue, max_size)
70 assert 0 <= average <= max_size