| 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 gc |
| 12 |
import random |
| 13 |
import sys |
| 14 |
|
| 15 |
import pytest |
| 16 |
|
| 17 |
from hypothesis import ( |
| 18 |
Phase, |
| 19 |
core, |
| 20 |
find, |
| 21 |
given, |
| 22 |
register_random, |
| 23 |
settings, |
| 24 |
strategies as st, |
| 25 |
) |
| 26 |
from hypothesis.errors import HypothesisWarning, InvalidArgument |
| 27 |
from hypothesis.internal import entropy |
| 28 |
from hypothesis.internal.compat import GRAALPY, PYPY |
| 29 |
from hypothesis.internal.entropy import deterministic_PRNG |
| 30 |
|
| 31 |
from tests.common.utils import skipif_threading, xfail_if_gil_disabled |
| 32 |
|
| 33 |
|
| 34 |
def gc_collect(): |
| 35 |
# CPython uses reference counting, so objects (without circular refs) |
| 36 |
# are collected immediately on `del`, breaking weak references. |
| 37 |
# Python implementations with other garbage collection strategies may |
| 38 |
# or may not, so we use this function in tests before counting the |
| 39 |
# surviving references to ensure that they're deterministic. |
| 40 |
if PYPY or GRAALPY: |
| 41 |
gc.collect() |
| 42 |
|
| 43 |
|
| 44 |
def test_can_seed_random(): |
| 45 |
@settings(phases=(Phase.generate, Phase.shrink)) |
| 46 |
@given(st.random_module()) |
| 47 |
def test(r): |
| 48 |
raise AssertionError |
| 49 |
|
| 50 |
with pytest.raises(AssertionError) as err: |
| 51 |
test() |
| 52 |
assert "RandomSeeder(0)" in "\n".join(err.value.__notes__) |
| 53 |
|
| 54 |
|
| 55 |
@given(st.random_module(), st.random_module()) |
| 56 |
def test_seed_random_twice(r, r2): |
| 57 |
assert repr(r) == repr(r2) |
| 58 |
|
| 59 |
|
| 60 |
# ideally we would actually raise the global random warning here, but random_module |
| 61 |
# calls seed_all and restore_all inside the deprecate_random_in_strategy context |
| 62 |
# manager, which never sees the global random interference. |
| 63 |
# |
| 64 |
# But it can sometimes see it under multithreading depending on timing. Until |
| 65 |
# we fix this to also warn in this case, just skip on threading. |
| 66 |
@skipif_threading |
| 67 |
@given(st.random_module()) |
| 68 |
def test_does_not_fail_health_check_if_randomness_is_used(r): |
| 69 |
random.getrandbits(128) |
| 70 |
|
| 71 |
|
| 72 |
def test_cannot_register_non_Random(): |
| 73 |
with pytest.raises(InvalidArgument): |
| 74 |
register_random("not a Random instance") |
| 75 |
|
| 76 |
|
| 77 |
@skipif_threading |
| 78 |
def test_registering_a_Random_is_idempotent(): |
| 79 |
gc_collect() |
| 80 |
n_registered = len(entropy.RANDOMS_TO_MANAGE) |
| 81 |
# on 3.14+, python introduced the LOAD_FAST_BORROW opcode, which does |
| 82 |
# not increment the refcount. Passing a bare r to register_random here on 3.14+ |
| 83 |
# would use LOAD_FAST_BORROW and entropy.py would see a non-increasing refcount |
| 84 |
# and hard-error. On 3.13 and earlier, this is a warning instead. |
| 85 |
# |
| 86 |
# For compatibility with both versions, this test forces a refcount increment |
| 87 |
# with a redundant container. |
| 88 |
container = [random.Random()] |
| 89 |
r = container[0] |
| 90 |
register_random(r) |
| 91 |
register_random(r) |
| 92 |
assert len(entropy.RANDOMS_TO_MANAGE) == n_registered + 1 |
| 93 |
del container |
| 94 |
del r |
| 95 |
gc_collect() |
| 96 |
assert len(entropy.RANDOMS_TO_MANAGE) == n_registered |
| 97 |
|
| 98 |
|
| 99 |
def test_manages_registered_Random_instance(): |
| 100 |
r = random.Random() |
| 101 |
register_random(r) |
| 102 |
state = r.getstate() |
| 103 |
result = [] |
| 104 |
|
| 105 |
@given(st.integers()) |
| 106 |
def inner(x): |
| 107 |
v = r.random() |
| 108 |
if result: |
| 109 |
assert v == result[0] |
| 110 |
else: |
| 111 |
result.append(v) |
| 112 |
|
| 113 |
inner() |
| 114 |
assert state == r.getstate() |
| 115 |
|
| 116 |
|
| 117 |
def test_registered_Random_is_seeded_by_random_module_strategy(): |
| 118 |
r = random.Random() |
| 119 |
register_random(r) |
| 120 |
state = r.getstate() |
| 121 |
results = set() |
| 122 |
count = 0 |
| 123 |
|
| 124 |
@given(st.integers()) |
| 125 |
def inner(x): |
| 126 |
nonlocal count |
| 127 |
results.add(r.random()) |
| 128 |
count += 1 |
| 129 |
|
| 130 |
inner() |
| 131 |
assert count > len(results) * 0.9, "too few unique random numbers" |
| 132 |
assert state == r.getstate() |
| 133 |
|
| 134 |
|
| 135 |
@given(st.random_module()) |
| 136 |
@skipif_threading # writing to global random state |
| 137 |
def test_will_actually_use_the_random_seed(rnd): |
| 138 |
a = random.randint(0, 100) |
| 139 |
b = random.randint(0, 100) |
| 140 |
random.seed(rnd.seed) |
| 141 |
assert a == random.randint(0, 100) |
| 142 |
assert b == random.randint(0, 100) |
| 143 |
|
| 144 |
|
| 145 |
def test_given_does_not_pollute_state(): |
| 146 |
with deterministic_PRNG(): |
| 147 |
|
| 148 |
@given(st.random_module()) |
| 149 |
def test(r): |
| 150 |
pass |
| 151 |
|
| 152 |
test() |
| 153 |
state_a = random.getstate() |
| 154 |
state_a2 = core.threadlocal._hypothesis_global_random.getstate() |
| 155 |
|
| 156 |
test() |
| 157 |
state_b = random.getstate() |
| 158 |
state_b2 = core.threadlocal._hypothesis_global_random.getstate() |
| 159 |
|
| 160 |
assert state_a == state_b |
| 161 |
assert state_a2 != state_b2 |
| 162 |
|
| 163 |
|
| 164 |
@skipif_threading # modifying global random state |
| 165 |
def test_find_does_not_pollute_state(): |
| 166 |
with deterministic_PRNG(): |
| 167 |
find(st.random_module(), lambda r: True) |
| 168 |
state_a = random.getstate() |
| 169 |
state_a2 = core.threadlocal._hypothesis_global_random.getstate() |
| 170 |
|
| 171 |
find(st.random_module(), lambda r: True) |
| 172 |
state_b = random.getstate() |
| 173 |
state_b2 = core.threadlocal._hypothesis_global_random.getstate() |
| 174 |
|
| 175 |
assert state_a == state_b |
| 176 |
assert state_a2 != state_b2 |
| 177 |
|
| 178 |
|
| 179 |
@skipif_threading # we assume we're the only writer to entropy.RANDOMS_TO_MANAGE |
| 180 |
def test_evil_prng_registration_nonsense(): |
| 181 |
# my guess is that other tests may register randoms that are then marked for |
| 182 |
# deletion (but not actually gc'd yet). Therefore, depending on the order tests |
| 183 |
# are run, RANDOMS_TO_MANAGE may start with more entries than after a gc. To |
| 184 |
# force a clean slate for this test, unconditionally gc. |
| 185 |
gc.collect() |
| 186 |
# The first test to call deterministic_PRNG registers a new random instance. |
| 187 |
# If that's this test, it will throw off our n_registered count in the middle. |
| 188 |
# start with a no-op to ensure this registration has occurred. |
| 189 |
with deterministic_PRNG(): |
| 190 |
pass |
| 191 |
|
| 192 |
n_registered = len(entropy.RANDOMS_TO_MANAGE) |
| 193 |
# put inside a list to increment ref count and avoid our warning/error about no |
| 194 |
# referrers |
| 195 |
c1, c2, c3 = [random.Random(1)], [random.Random(2)], [random.Random(3)] |
| 196 |
r1, r2, r3 = c1[0], c2[0], c3[0] |
| 197 |
s2 = r2.getstate() |
| 198 |
|
| 199 |
# We're going to be totally evil here: register two randoms, then |
| 200 |
# drop one and add another, and finally check that we reset only |
| 201 |
# the states that we collected before we started |
| 202 |
register_random(r1) |
| 203 |
k = max(entropy.RANDOMS_TO_MANAGE) # get a handle to check if r1 still exists |
| 204 |
register_random(r2) |
| 205 |
assert len(entropy.RANDOMS_TO_MANAGE) == n_registered + 2 |
| 206 |
|
| 207 |
with deterministic_PRNG(): |
| 208 |
del r1 |
| 209 |
del c1 |
| 210 |
gc_collect() |
| 211 |
assert k not in entropy.RANDOMS_TO_MANAGE, "r1 has been garbage-collected" |
| 212 |
assert len(entropy.RANDOMS_TO_MANAGE) == n_registered + 1 |
| 213 |
|
| 214 |
r2.seed(4) |
| 215 |
register_random(r3) |
| 216 |
r3.seed(4) |
| 217 |
s4 = r3.getstate() |
| 218 |
|
| 219 |
# Implicit check, no exception was raised in __exit__ |
| 220 |
assert r2.getstate() == s2, "reset previously registered random state" |
| 221 |
assert r3.getstate() == s4, "retained state when registered within the context" |
| 222 |
|
| 223 |
|
| 224 |
@pytest.mark.skipif( |
| 225 |
PYPY, reason="We can't guard against bad no-reference patterns in pypy." |
| 226 |
) |
| 227 |
def test_passing_unreferenced_instance_raises(): |
| 228 |
with pytest.raises(ReferenceError): |
| 229 |
register_random(random.Random(0)) |
| 230 |
|
| 231 |
|
| 232 |
@xfail_if_gil_disabled |
| 233 |
@pytest.mark.skipif( |
| 234 |
PYPY, reason="We can't guard against bad no-reference patterns in pypy." |
| 235 |
) |
| 236 |
def test_passing_unreferenced_instance_within_function_scope_raises(): |
| 237 |
def f(): |
| 238 |
register_random(random.Random(0)) |
| 239 |
|
| 240 |
with pytest.raises(ReferenceError): |
| 241 |
f() |
| 242 |
|
| 243 |
# we have two error paths for register_random: one which warns and one which |
| 244 |
# errors. We use an alias to bump the refcount while not adding a gc referrer, |
| 245 |
# which covers the warning path. |
| 246 |
def f(): |
| 247 |
r = random.Random(0) |
| 248 |
_r2 = r |
| 249 |
register_random(r) |
| 250 |
|
| 251 |
with pytest.warns( |
| 252 |
HypothesisWarning, |
| 253 |
match="It looks like `register_random` was passed an object that could be" |
| 254 |
" garbage collected", |
| 255 |
): |
| 256 |
f() |
| 257 |
|
| 258 |
|
| 259 |
@xfail_if_gil_disabled |
| 260 |
@pytest.mark.skipif( |
| 261 |
PYPY, reason="We can't guard against bad no-reference patterns in pypy." |
| 262 |
) |
| 263 |
@pytest.mark.skipif( |
| 264 |
sys.version_info[:2] < (3, 14), |
| 265 |
reason="warns instead of raises on 3.13 or earlier due to gc changes", |
| 266 |
) |
| 267 |
def test_passing_referenced_instance_within_function_scope_raises(): |
| 268 |
def f(): |
| 269 |
r = random.Random(0) |
| 270 |
register_random(r) |
| 271 |
|
| 272 |
with pytest.raises( |
| 273 |
ReferenceError, |
| 274 |
match=r"`register_random` was passed .* which will be garbage collected", |
| 275 |
): |
| 276 |
f() |
| 277 |
|
| 278 |
|
| 279 |
@pytest.mark.skipif( |
| 280 |
PYPY, reason="We can't guard against bad no-reference patterns in pypy." |
| 281 |
) |
| 282 |
@skipif_threading # we assume we're the only writer to entropy.RANDOMS_TO_MANAGE |
| 283 |
def test_register_random_within_nested_function_scope(): |
| 284 |
n_registered = len(entropy.RANDOMS_TO_MANAGE) |
| 285 |
|
| 286 |
def f(): |
| 287 |
# put inside a list to increment ref count and avoid our warning/error about no |
| 288 |
# referrers |
| 289 |
container = [random.Random()] |
| 290 |
r = container[0] |
| 291 |
register_random(r) |
| 292 |
assert len(entropy.RANDOMS_TO_MANAGE) == n_registered + 1 |
| 293 |
|
| 294 |
f() |
| 295 |
gc_collect() |
| 296 |
assert len(entropy.RANDOMS_TO_MANAGE) == n_registered |