-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathtest_cache.py
More file actions
92 lines (68 loc) · 2.71 KB
/
Copy pathtest_cache.py
File metadata and controls
92 lines (68 loc) · 2.71 KB
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
90
91
92
from collections import defaultdict
from pathlib import Path
import pytest
from docstub import _cache
def test_directory_size():
assert _cache._directory_size(Path(__file__).parent) > 0
with pytest.raises(FileNotFoundError, match="doesn't exist, can't determine size"):
_cache._directory_size(Path("i/don't/exist"))
def test_create_cache(tmp_path):
cache_dir = tmp_path / ".test_cache_dir"
assert not cache_dir.exists()
_cache.create_cache(cache_dir)
assert cache_dir.is_dir()
# Check CACHEDIR.TAG file
cache_tag_path = cache_dir / "CACHEDIR.TAG"
assert cache_tag_path.is_file()
with cache_tag_path.open("r") as fp:
cache_tag_content = fp.read()
assert cache_tag_content.startswith("Signature: 8a477f597d28d172789f06886806bc55\n")
# Check. gitignore
gitignore_path = cache_dir / ".gitignore"
assert gitignore_path.is_file()
with gitignore_path.open("r") as fp:
gitignore_content = fp.read()
assert "\n*\n" in gitignore_content
# Check that calling it a second time doesn't raise an error
_cache.create_cache(cache_dir)
class Test_FileCache:
def test_basic(self, tmp_path):
class Serializer:
suffix = ".txt"
def hash_args(self, arg: int) -> str:
return str(hash(arg))
def serialize(self, data: int) -> bytes:
return str(data).encode()
def deserialize(self, raw: bytes) -> int:
return int(raw.decode())
counter = defaultdict(lambda: 0)
def square(x):
counter[x] += 1
return x * x
cached_square = _cache.FileCache(
func=square, serializer=Serializer(), cache_dir=tmp_path, name="test"
)
assert cached_square(3) == 9
assert counter[3] == 1
# Result was cached
entry_name = f"{Serializer().hash_args(3)!s}{Serializer.suffix}"
cached_file = tmp_path / "test" / entry_name
assert cached_file.is_file()
# With the square(3) cached, the counter no longer increases
assert cached_square(3) == 9
assert counter[3] == 1
# Using another FileCache will use the existing cache
cached_square_2 = _cache.FileCache(
func=square, serializer=Serializer(), cache_dir=tmp_path, name="test"
)
assert cached_square_2(3) == 9
assert counter[3] == 1
# But using another FileCache with a different name will not hit existing cache
cached_square_3 = _cache.FileCache(
func=square,
serializer=Serializer(),
cache_dir=tmp_path,
name="test2",
)
assert cached_square_3(3) == 9
assert counter[3] == 2