| 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 threading |
| 12 |
from functools import partial |
| 13 |
from random import Random |
| 14 |
|
| 15 |
import pytest |
| 16 |
|
| 17 |
from hypothesis import ( |
| 18 |
HealthCheck, |
| 19 |
assume, |
| 20 |
example, |
| 21 |
given, |
| 22 |
note, |
| 23 |
settings, |
| 24 |
strategies as st, |
| 25 |
) |
| 26 |
from hypothesis.errors import InvalidArgument |
| 27 |
from hypothesis.internal.cache import GenericCache, LRUCache, LRUReusedCache |
| 28 |
|
| 29 |
from tests.common.utils import Why, skipif_emscripten, xfail_on_crosshair |
| 30 |
|
| 31 |
|
| 32 |
class LRUCacheAlternative(GenericCache): |
| 33 |
__slots__ = ("__tick",) |
| 34 |
|
| 35 |
def __init__(self, max_size): |
| 36 |
super().__init__(max_size) |
| 37 |
self.__tick = 0 |
| 38 |
|
| 39 |
def new_entry(self, key, value): |
| 40 |
return self.tick() |
| 41 |
|
| 42 |
def on_access(self, key, value, score): |
| 43 |
return self.tick() |
| 44 |
|
| 45 |
def tick(self): |
| 46 |
self.__tick += 1 |
| 47 |
return self.__tick |
| 48 |
|
| 49 |
|
| 50 |
class LFUCache(GenericCache): |
| 51 |
def new_entry(self, key, value): |
| 52 |
return 1 |
| 53 |
|
| 54 |
def on_access(self, key, value, score): |
| 55 |
return score + 1 |
| 56 |
|
| 57 |
|
| 58 |
@st.composite |
| 59 |
def write_pattern(draw, min_distinct_keys=0): |
| 60 |
keys = draw( |
| 61 |
st.lists(st.integers(0, 1000), unique=True, min_size=max(min_distinct_keys, 1)) |
| 62 |
) |
| 63 |
values = draw(st.lists(st.integers(), unique=True, min_size=1)) |
| 64 |
s = st.lists( |
| 65 |
st.tuples(st.sampled_from(keys), st.sampled_from(values)), |
| 66 |
min_size=min_distinct_keys, |
| 67 |
) |
| 68 |
if min_distinct_keys > 0: |
| 69 |
s = s.filter(lambda ls: len({k for k, _ in ls}) >= min_distinct_keys) |
| 70 |
return draw(s) |
| 71 |
|
| 72 |
|
| 73 |
class ValueScored(GenericCache): |
| 74 |
def new_entry(self, key, value): |
| 75 |
return value |
| 76 |
|
| 77 |
|
| 78 |
class RandomCache(GenericCache): |
| 79 |
def __init__(self, max_size): |
| 80 |
super().__init__(max_size) |
| 81 |
self.random = Random(0) |
| 82 |
|
| 83 |
def new_entry(self, key, value): |
| 84 |
return self.random.random() |
| 85 |
|
| 86 |
def on_access(self, key, value, score): |
| 87 |
return self.random.random() |
| 88 |
|
| 89 |
|
| 90 |
@pytest.mark.parametrize( |
| 91 |
"implementation", |
| 92 |
[LRUCache, LFUCache, LRUReusedCache, ValueScored, RandomCache, LRUCacheAlternative], |
| 93 |
) |
| 94 |
@example(writes=[(0, 0), (3, 0), (1, 0), (2, 0), (2, 0), (1, 0)], size=4) |
| 95 |
@example(writes=[(0, 0)], size=1) |
| 96 |
@example(writes=[(1, 0), (2, 0), (0, -1), (1, 0)], size=3) |
| 97 |
@given(write_pattern(), st.integers(1, 10)) |
| 98 |
def test_behaves_like_a_dict_with_losses(implementation, writes, size): |
| 99 |
model = {} |
| 100 |
target = implementation(max_size=size) |
| 101 |
|
| 102 |
for k, v in writes: |
| 103 |
try: |
| 104 |
assert model[k] == target[k] |
| 105 |
except KeyError: |
| 106 |
pass |
| 107 |
model[k] = v |
| 108 |
target[k] = v |
| 109 |
target.check_valid() |
| 110 |
assert target[k] == v |
| 111 |
for r, s in model.items(): |
| 112 |
try: |
| 113 |
assert s == target[r] |
| 114 |
except KeyError: |
| 115 |
pass |
| 116 |
assert len(target) <= min(len(model), size) |
| 117 |
|
| 118 |
|
| 119 |
@xfail_on_crosshair(Why.symbolic_outside_context, strict=False) |
| 120 |
@settings( |
| 121 |
suppress_health_check={HealthCheck.too_slow} |
| 122 |
| set(settings().suppress_health_check), |
| 123 |
deadline=None, |
| 124 |
) |
| 125 |
@given(write_pattern(min_distinct_keys=2), st.data()) |
| 126 |
def test_always_evicts_the_lowest_scoring_value(writes, data): |
| 127 |
scores = {} |
| 128 |
|
| 129 |
n_keys = len({k for k, _ in writes}) |
| 130 |
|
| 131 |
assume(n_keys > 1) |
| 132 |
|
| 133 |
size = data.draw(st.integers(1, n_keys - 1)) |
| 134 |
|
| 135 |
evicted = set() |
| 136 |
|
| 137 |
def new_score(key): |
| 138 |
scores[key] = data.draw(st.integers(0, 1000), label=f"scores[{key!r}]") |
| 139 |
return scores[key] |
| 140 |
|
| 141 |
last_entry = None |
| 142 |
|
| 143 |
class Cache(GenericCache): |
| 144 |
def new_entry(self, key, value): |
| 145 |
nonlocal last_entry |
| 146 |
last_entry = key |
| 147 |
evicted.discard(key) |
| 148 |
assert key not in scores |
| 149 |
return new_score(key) |
| 150 |
|
| 151 |
def on_access(self, key, value, score): |
| 152 |
assert key in scores |
| 153 |
return new_score(key) |
| 154 |
|
| 155 |
def on_evict(self, key, value, score): |
| 156 |
note(f"Evicted {key!r}") |
| 157 |
assert score == scores[key] |
| 158 |
del scores[key] |
| 159 |
if len(scores) > 1: |
| 160 |
assert score <= min(v for k, v in scores.items() if k != last_entry) |
| 161 |
evicted.add(key) |
| 162 |
|
| 163 |
target = Cache(max_size=size) |
| 164 |
model = {} |
| 165 |
|
| 166 |
for k, v in writes: |
| 167 |
target[k] = v |
| 168 |
model[k] = v |
| 169 |
|
| 170 |
assert evicted |
| 171 |
assert len(evicted) + len(target) == len(model) |
| 172 |
assert len(scores) == len(target) |
| 173 |
|
| 174 |
for k, v in model.items(): |
| 175 |
try: |
| 176 |
assert target[k] == v |
| 177 |
assert k not in evicted |
| 178 |
except KeyError: |
| 179 |
assert k in evicted |
| 180 |
|
| 181 |
|
| 182 |
def test_basic_access(): |
| 183 |
cache = ValueScored(max_size=2) |
| 184 |
cache[1] = 0 |
| 185 |
cache[1] = 0 |
| 186 |
cache[0] = 1 |
| 187 |
cache[2] = 0 |
| 188 |
assert cache[2] == 0 |
| 189 |
assert cache[0] == 1 |
| 190 |
assert len(cache) == 2 |
| 191 |
|
| 192 |
|
| 193 |
def test_can_clear_a_cache(): |
| 194 |
x = ValueScored(1) |
| 195 |
x[0] = 1 |
| 196 |
assert len(x) == 1 |
| 197 |
x.clear() |
| 198 |
assert len(x) == 0 |
| 199 |
|
| 200 |
|
| 201 |
def test_max_size_must_be_positive(): |
| 202 |
with pytest.raises(InvalidArgument): |
| 203 |
ValueScored(max_size=0) |
| 204 |
|
| 205 |
|
| 206 |
def test_pinning_prevents_eviction(): |
| 207 |
cache = LRUReusedCache(max_size=10) |
| 208 |
cache.pin(20, 1) |
| 209 |
for i in range(20): |
| 210 |
cache[i] = 0 |
| 211 |
assert cache[20] == 1 |
| 212 |
|
| 213 |
|
| 214 |
def test_unpinning_allows_eviction(): |
| 215 |
cache = LRUReusedCache(max_size=10) |
| 216 |
cache.pin(20, True) |
| 217 |
for i in range(20): |
| 218 |
cache[i] = False |
| 219 |
|
| 220 |
assert 20 in cache |
| 221 |
|
| 222 |
cache.unpin(20) |
| 223 |
cache[21] = False |
| 224 |
|
| 225 |
assert 20 not in cache |
| 226 |
|
| 227 |
|
| 228 |
def test_unpins_must_match_pins(): |
| 229 |
cache = LRUReusedCache(max_size=2) |
| 230 |
cache.pin(1, 1) |
| 231 |
assert cache.is_pinned(1) |
| 232 |
assert cache[1] == 1 |
| 233 |
cache.pin(1, 2) |
| 234 |
assert cache.is_pinned(1) |
| 235 |
assert cache[1] == 2 |
| 236 |
cache.unpin(1) |
| 237 |
assert cache.is_pinned(1) |
| 238 |
assert cache[1] == 2 |
| 239 |
cache.unpin(1) |
| 240 |
assert not cache.is_pinned(1) |
| 241 |
|
| 242 |
|
| 243 |
def test_will_error_instead_of_evicting_pin(): |
| 244 |
cache = LRUReusedCache(max_size=1) |
| 245 |
cache.pin(1, 1) |
| 246 |
with pytest.raises(ValueError): |
| 247 |
cache[2] = 2 |
| 248 |
|
| 249 |
assert 1 in cache |
| 250 |
assert 2 not in cache |
| 251 |
|
| 252 |
|
| 253 |
def test_will_error_for_bad_unpin(): |
| 254 |
cache = LRUReusedCache(max_size=1) |
| 255 |
cache[1] = 1 |
| 256 |
with pytest.raises(ValueError): |
| 257 |
cache.unpin(1) |
| 258 |
|
| 259 |
|
| 260 |
def test_still_inserts_if_score_is_worse(): |
| 261 |
class TC(GenericCache): |
| 262 |
def new_entry(self, key, value): |
| 263 |
return key |
| 264 |
|
| 265 |
cache = TC(1) |
| 266 |
|
| 267 |
cache[0] = 1 |
| 268 |
cache[1] = 1 |
| 269 |
|
| 270 |
assert 0 not in cache |
| 271 |
assert 1 in cache |
| 272 |
assert len(cache) == 1 |
| 273 |
|
| 274 |
|
| 275 |
def test_does_insert_if_score_is_better(): |
| 276 |
class TC(GenericCache): |
| 277 |
def new_entry(self, key, value): |
| 278 |
return value |
| 279 |
|
| 280 |
cache = TC(1) |
| 281 |
|
| 282 |
cache[0] = 1 |
| 283 |
cache[1] = 0 |
| 284 |
|
| 285 |
assert 0 not in cache |
| 286 |
assert 1 in cache |
| 287 |
assert len(cache) == 1 |
| 288 |
|
| 289 |
|
| 290 |
def test_double_pinning_does_not_add_entry(): |
| 291 |
cache = LRUReusedCache(2) |
| 292 |
cache.pin(0, 0) |
| 293 |
cache.pin(0, 1) |
| 294 |
cache[1] = 1 |
| 295 |
assert len(cache) == 2 |
| 296 |
|
| 297 |
|
| 298 |
def test_can_add_new_keys_after_unpinning(): |
| 299 |
cache = LRUReusedCache(1) |
| 300 |
cache.pin(0, 0) |
| 301 |
cache.unpin(0) |
| 302 |
cache[1] = 1 |
| 303 |
assert len(cache) == 1 |
| 304 |
assert 1 in cache |
| 305 |
|
| 306 |
|
| 307 |
def test_iterates_over_remaining_keys(): |
| 308 |
cache = LRUReusedCache(2) |
| 309 |
for i in range(3): |
| 310 |
cache[i] = "hi" |
| 311 |
assert sorted(cache) == [1, 2] |
| 312 |
|
| 313 |
|
| 314 |
def test_lru_cache_is_actually_lru(): |
| 315 |
cache = LRUCache(2) |
| 316 |
cache[1] = 1 # [1] |
| 317 |
cache[2] = 2 # [1, 2] |
| 318 |
cache[1] # [2, 1] |
| 319 |
cache[3] = 2 # [2, 1, 3] -> drop least recently used -> [1, 3] |
| 320 |
assert list(cache) == [1, 3] |
| 321 |
|
| 322 |
|
| 323 |
@skipif_emscripten |
| 324 |
def test_cache_is_threadsafe_issue_2433_regression(): |
| 325 |
errors = [] |
| 326 |
|
| 327 |
def target(): |
| 328 |
for _ in range(1000): |
| 329 |
try: |
| 330 |
st.builds(partial(str)) |
| 331 |
except Exception as exc: |
| 332 |
errors.append(exc) |
| 333 |
|
| 334 |
workers = [threading.Thread(target=target) for _ in range(4)] |
| 335 |
for worker in workers: |
| 336 |
worker.start() |
| 337 |
for worker in workers: |
| 338 |
worker.join() |
| 339 |
|
| 340 |
assert not errors |