-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_session_cache.py
More file actions
89 lines (66 loc) · 2.29 KB
/
Copy pathtest_session_cache.py
File metadata and controls
89 lines (66 loc) · 2.29 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
"""Unit tests for utils.session_cache."""
from __future__ import annotations
import shutil
import time
from pathlib import Path
import pytest
from utils.jsonl_parser import parse_session
from utils.session_cache import clear_cache, get_cached_session, set_max_entries
FIXTURES = Path(__file__).resolve().parent / "fixtures"
SAMPLE_SESSION = FIXTURES / "session_with_tools.jsonl"
@pytest.fixture
def sample_session(tmp_path: Path) -> Path:
dest = tmp_path / "session.jsonl"
shutil.copy(SAMPLE_SESSION, dest)
return dest
@pytest.fixture(autouse=True)
def _reset_cache() -> None:
clear_cache()
set_max_entries(200)
def test_cache_returns_same_data_as_direct_parse(sample_session: Path) -> None:
path = str(sample_session)
assert get_cached_session(path) == parse_session(path)
def test_cache_hit_avoids_reparse(sample_session: Path, monkeypatch: pytest.MonkeyPatch) -> None:
path = str(sample_session)
get_cached_session(path)
calls = 0
def counting_parse(p: str):
nonlocal calls
calls += 1
return parse_session(p)
monkeypatch.setattr("utils.session_cache.parse_session", counting_parse)
get_cached_session(path)
assert calls == 0
def test_cache_invalidates_on_mtime_change(sample_session: Path) -> None:
path = str(sample_session)
first = get_cached_session(path)
time.sleep(0.05)
sample_session.touch()
second = get_cached_session(path)
assert first is not second
def test_lru_eviction(sample_session: Path, tmp_path: Path) -> None:
set_max_entries(2)
content = sample_session.read_text(encoding="utf-8")
paths = []
for name in ("a.jsonl", "b.jsonl", "c.jsonl"):
p = tmp_path / name
p.write_text(content, encoding="utf-8")
paths.append(p)
for p in paths:
get_cached_session(str(p))
calls = 0
def counting_parse(p: str):
nonlocal calls
calls += 1
return parse_session(p)
monkeypatch = pytest.MonkeyPatch()
monkeypatch.setattr("utils.session_cache.parse_session", counting_parse)
try:
get_cached_session(str(paths[2]))
assert calls == 0
get_cached_session(str(paths[1]))
assert calls == 0
get_cached_session(str(paths[0]))
assert calls == 1
finally:
monkeypatch.undo()