| 1 |
import hashlib |
| 2 |
import os |
| 3 |
from time import sleep |
| 4 |
from unittest.mock import Mock |
| 5 |
from unittest.mock import patch |
| 6 |
|
| 7 |
import pytest |
| 8 |
from clear import ClearTests |
| 9 |
from common import CommonTests |
| 10 |
from has import HasTests |
| 11 |
from serializer import SerializerTests |
| 12 |
|
| 13 |
from cachelib import FileSystemCache |
| 14 |
from cachelib.serializers import BaseSerializer |
| 15 |
|
| 16 |
|
| 17 |
class SillySerializer(BaseSerializer): |
| 18 |
"""A pointless serializer only for testing""" |
| 19 |
|
| 20 |
def dump(self, value, fs): |
| 21 |
fs.write(f"{repr(value)}{os.linesep}".encode()) |
| 22 |
|
| 23 |
def load(self, fs): |
| 24 |
try: |
| 25 |
loaded = eval(fs.readline().decode()) |
| 26 |
# When all file content has been read eval will |
| 27 |
# turn the EOFError into SyntaxError which is not |
| 28 |
# handled by cachelib |
| 29 |
except SyntaxError as e: |
| 30 |
raise EOFError from e |
| 31 |
return loaded |
| 32 |
|
| 33 |
|
| 34 |
class CustomSerializerCache(FileSystemCache): |
| 35 |
"""Our custom cache client with non-default serializer""" |
| 36 |
|
| 37 |
# overwrite serializer |
| 38 |
serializer = SillySerializer() |
| 39 |
|
| 40 |
def __init__(self, *args, **kwargs): |
| 41 |
super().__init__(*args, **kwargs) |
| 42 |
|
| 43 |
|
| 44 |
class CustomHashingMethodCache(FileSystemCache): |
| 45 |
def __init__(self, *args, **kwargs): |
| 46 |
super().__init__(*args, hash_method=hashlib.sha256, **kwargs) |
| 47 |
|
| 48 |
|
| 49 |
@pytest.fixture( |
| 50 |
autouse=True, |
| 51 |
params=[ |
| 52 |
FileSystemCache, |
| 53 |
CustomSerializerCache, |
| 54 |
CustomHashingMethodCache, |
| 55 |
], |
| 56 |
) |
| 57 |
def cache_factory(request, tmpdir): |
| 58 |
def _factory(self, *args, **kwargs): |
| 59 |
client = request.param(tmpdir, *args, **kwargs) |
| 60 |
return client |
| 61 |
|
| 62 |
request.cls.cache_factory = _factory |
| 63 |
|
| 64 |
|
| 65 |
class TestFileSystemCache(CommonTests, ClearTests, HasTests, SerializerTests): |
| 66 |
# override parent sample since these must implement buffer interface |
| 67 |
sample_pairs = { |
| 68 |
"bacon": "eggs", |
| 69 |
"sausage": "spam", |
| 70 |
"brandy": "lobster", |
| 71 |
"truffle": "wine", |
| 72 |
"sauce": "truffle pate", |
| 73 |
"cravettes": "mournay sauce", |
| 74 |
} |
| 75 |
|
| 76 |
def test_EOFError(self, caplog): |
| 77 |
cache = self.cache_factory(threshold=1) |
| 78 |
assert cache.set_many(self.sample_pairs) |
| 79 |
file_names = [cache._get_filename(k) for k in self.sample_pairs.keys()] |
| 80 |
# truncate files to erase content |
| 81 |
for fpath in file_names: |
| 82 |
open(fpath, "w").close() |
| 83 |
assert cache.set("test", "EOFError") |
| 84 |
assert "Exception raised" in caplog.text |
| 85 |
|
| 86 |
def test_threshold(self): |
| 87 |
threshold = len(self.sample_pairs) // 2 |
| 88 |
cache = self.cache_factory(threshold=threshold) |
| 89 |
assert cache.set_many(self.sample_pairs) |
| 90 |
assert cache._file_count == 4 |
| 91 |
# due to autouse=True a single tmpdir is used |
| 92 |
# for each test so we need to clear it |
| 93 |
assert cache.clear() |
| 94 |
cache = self.cache_factory(threshold=0) |
| 95 |
assert cache.set_many(self.sample_pairs) |
| 96 |
assert not cache._file_count |
| 97 |
|
| 98 |
def test_file_counting(self): |
| 99 |
cache = self.cache_factory() |
| 100 |
assert cache.set_many(self.sample_pairs) |
| 101 |
assert cache._file_count == len(self.sample_pairs) |
| 102 |
assert cache.clear() |
| 103 |
assert cache._file_count == 0 |
| 104 |
|
| 105 |
def test_file_counting_on_override(self): |
| 106 |
cache = self.cache_factory() |
| 107 |
assert cache.set_many(self.sample_pairs) |
| 108 |
assert cache._file_count == len(self.sample_pairs) |
| 109 |
assert cache.set_many(self.sample_pairs) |
| 110 |
# count should remain the same |
| 111 |
assert cache._file_count == len(self.sample_pairs) |
| 112 |
|
| 113 |
def test_prune_old_entries(self): |
| 114 |
threshold = 2 * len(self.sample_pairs) - 1 |
| 115 |
cache = self.cache_factory(threshold=threshold) |
| 116 |
for k, v in self.sample_pairs.items(): |
| 117 |
assert cache.set(f"{k}-t1", v, timeout=1) |
| 118 |
assert cache.set(f"{k}-t10", v, timeout=10) |
| 119 |
sleep(3) |
| 120 |
for k, v in self.sample_pairs.items(): |
| 121 |
assert cache.set(k, v) |
| 122 |
assert cache.has(f"{k}-t10") |
| 123 |
assert not cache.has(f"{k}-t1") |
| 124 |
|
| 125 |
def test_run_safely_succeeds_on_first_try(self): |
| 126 |
"""_run_safely returns the function's result when no error is raised.""" |
| 127 |
cache = self.cache_factory() |
| 128 |
result = cache._run_safely(lambda: 42) |
| 129 |
assert result == 42 |
| 130 |
|
| 131 |
def test_run_safely_retries_on_permission_error(self): |
| 132 |
""" |
| 133 |
_run_safely retries when PermissionError is raised |
| 134 |
(e.g. Windows NTFS race). |
| 135 |
""" |
| 136 |
cache = self.cache_factory() |
| 137 |
flaky = Mock( |
| 138 |
side_effect=[PermissionError("locked"), PermissionError("locked"), "ok"] |
| 139 |
) |
| 140 |
|
| 141 |
with patch("cachelib.file.sleep") as mock_sleep: |
| 142 |
result = cache._run_safely(flaky) |
| 143 |
|
| 144 |
assert result == "ok" |
| 145 |
assert flaky.call_count == 3 |
| 146 |
assert mock_sleep.call_count == 2 |
| 147 |
|
| 148 |
def test_run_safely_exhausts_retries_and_returns_none(self): |
| 149 |
""" |
| 150 |
_run_safely returns None when PermissionError persists |
| 151 |
beyond max_sleep_time. |
| 152 |
""" |
| 153 |
cache = self.cache_factory() |
| 154 |
|
| 155 |
def always_fails(): |
| 156 |
raise PermissionError("locked") |
| 157 |
|
| 158 |
with patch("cachelib.file.sleep"): |
| 159 |
result = cache._run_safely(always_fails) |
| 160 |
|
| 161 |
assert result is None |
| 162 |
|
| 163 |
def test_run_safely_does_not_retry_other_errors(self): |
| 164 |
"""_run_safely does not catch non-PermissionError exceptions.""" |
| 165 |
cache = self.cache_factory() |
| 166 |
|
| 167 |
def raises_file_not_found(): |
| 168 |
raise FileNotFoundError("missing") |
| 169 |
|
| 170 |
with pytest.raises(FileNotFoundError): |
| 171 |
cache._run_safely(raises_file_not_found) |
| 172 |
|
| 173 |
def test_run_safely_exponential_backoff(self): |
| 174 |
"""_run_safely doubles the wait_step on each retry.""" |
| 175 |
cache = self.cache_factory() |
| 176 |
flaky = Mock( |
| 177 |
side_effect=[ |
| 178 |
PermissionError("locked"), |
| 179 |
PermissionError("locked"), |
| 180 |
PermissionError("locked"), |
| 181 |
"ok", |
| 182 |
] |
| 183 |
) |
| 184 |
|
| 185 |
with patch("cachelib.file.sleep") as mock_sleep: |
| 186 |
cache._run_safely(flaky) |
| 187 |
|
| 188 |
sleep_calls = [c.args[0] for c in mock_sleep.call_args_list] |
| 189 |
# Each wait should double the previous |
| 190 |
assert sleep_calls[1] == sleep_calls[0] * 2 |
| 191 |
assert sleep_calls[2] == sleep_calls[1] * 2 |
| 192 |
|
| 193 |
def test_mgmt_element_set_not_counted(self, tmpdir): |
| 194 |
"""set with mgmt_element=True should not affect _file_count.""" |
| 195 |
cache = FileSystemCache(tmpdir) |
| 196 |
before = cache._file_count |
| 197 |
cache.set("__internal_key", 42, mgmt_element=True) |
| 198 |
assert cache._file_count == before |
| 199 |
|
| 200 |
def test_mgmt_element_delete_not_counted(self, tmpdir): |
| 201 |
"""delete with mgmt_element=True should not affect _file_count.""" |
| 202 |
cache = FileSystemCache(tmpdir) |
| 203 |
cache.set("__internal_key", 42, mgmt_element=True) |
| 204 |
before = cache._file_count |
| 205 |
cache.delete("__internal_key", mgmt_element=True) |
| 206 |
assert cache._file_count == before |
| 207 |
|
| 208 |
def test_has_on_expired_key_returns_false(self, tmpdir): |
| 209 |
from time import sleep |
| 210 |
|
| 211 |
cache = FileSystemCache(tmpdir) |
| 212 |
cache.set("expiring", "value", timeout=1) |
| 213 |
sleep(2) |
| 214 |
assert cache.has("expiring") is False |