Debian Codegraph @

tests/functional_tests/test_cache.py

raw
1 import pickle
2 from pathlib import Path
3 from typing import List
4
5 import pytest
6 from textual.widgets.text_area import Selection
7
8 from harlequin import Harlequin
9 from harlequin.editor_cache import (
10 BufferState,
11 Cache,
12 get_cache_file,
13 get_recovery_file,
14 load_cache,
15 write_cache,
16 )
17 from tests.functional_tests.helpers import wait_for_editor
18
19
20 @pytest.fixture
21 def buffer_states() -> List[BufferState]:
22 return [
23 BufferState(
24 selection=Selection((0, 3), (0, 3)),
25 text="select 1\n",
26 ),
27 BufferState(
28 selection=Selection((0, 0), (0, 0)),
29 text="",
30 ),
31 BufferState(
32 selection=Selection((0, 0), (1, 0)),
33 text="select\n*\nfrom\nfoo\n",
34 ),
35 ]
36
37
38 @pytest.fixture
39 def cache(buffer_states: List[BufferState]) -> Cache:
40 return Cache(focus_index=1, buffers=buffer_states)
41
42
43 @pytest.fixture(autouse=True)
44 def mock_user_cache_dir(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path:
45 monkeypatch.setattr("harlequin.editor_cache.user_cache_dir", lambda **_: tmp_path)
46 return tmp_path
47
48
49 @pytest.mark.use_cache
50 def test_cache_ops(mock_user_cache_dir: Path, cache: Cache) -> None:
51 assert mock_user_cache_dir.exists()
52 assert len(list(mock_user_cache_dir.iterdir())) == 0
53 write_cache(cache)
54 children = list(mock_user_cache_dir.iterdir())
55 assert len(children) == 1
56 assert children[0].suffix == ".pickle"
57 assert get_cache_file() == children[0]
58 loaded_cache = load_cache()
59 assert loaded_cache == cache
60
61
62 @pytest.mark.use_cache
63 @pytest.mark.asyncio
64 async def test_harlequin_loads_cache(
65 cache: Cache,
66 app: Harlequin,
67 ) -> None:
68 write_cache(cache)
69 async with app.run_test() as pilot:
70 await wait_for_editor(pilot, app)
71 assert app.editor_collection is not None
72 assert app.editor is not None
73 assert app.editor_collection.tab_count == len(cache.buffers)
74 assert [buffer.text for buffer in app.editor_collection.buffers] == [
75 buffer.text for buffer in cache.buffers
76 ]
77 # the buffer that was active when the cache was written is active again
78 assert app.editor_collection.active_buffer_index == cache.focus_index
79 assert app.editor.text == cache.buffers[cache.focus_index].text
80
81
82 @pytest.mark.use_cache
83 @pytest.mark.asyncio
84 async def test_harlequin_writes_cache(
85 app: Harlequin,
86 ) -> None:
87 cache_path = get_cache_file()
88 assert not cache_path.exists()
89 async with app.run_test() as pilot:
90 editor = await wait_for_editor(pilot, app)
91 assert app.editor_collection.tab_count == 1
92 editor.text = "first"
93 await pilot.press("ctrl+n")
94 await pilot.pause()
95 editor.text = "second"
96 await pilot.press("ctrl+q")
97 assert cache_path.exists()
98 with open(cache_path, "rb") as f:
99 cache = pickle.load(f)
100 assert isinstance(cache, Cache)
101 assert [buffer.text for buffer in cache.buffers] == ["first", "second"]
102 assert cache.focus_index == 1
103
104
105 @pytest.mark.use_cache
106 @pytest.mark.asyncio
107 async def test_harlequin_recovers_buffers(
108 cache: Cache,
109 app: Harlequin,
110 ) -> None:
111 """A recovered session started from the cache, so it wins over one."""
112 write_cache(Cache(focus_index=0, buffers=[BufferState(Selection(), "stale\n")]))
113 recovery_file = get_cache_file().with_name("recovered-20260904T120000Z-99.pickle")
114 recovery_file.write_bytes(pickle.dumps(cache))
115
116 async with app.run_test() as pilot:
117 await wait_for_editor(pilot, app)
118 assert app.editor_collection is not None
119 assert [buffer.text for buffer in app.editor_collection.buffers] == [
120 buffer.text for buffer in cache.buffers
121 ]
122
123 # the poisoned-buffer guard: replayed once, whatever happened during the replay
124 assert not recovery_file.exists()
125 assert recovery_file.with_suffix(".replayed").exists()
126
127
128 @pytest.mark.use_cache
129 @pytest.mark.asyncio
130 async def test_harlequin_clears_its_recovery_file_on_quit(
131 app: Harlequin,
132 ) -> None:
133 recovery_file = get_recovery_file()
134 recovery_file.parent.mkdir(parents=True, exist_ok=True)
135 recovery_file.write_bytes(pickle.dumps(Cache(focus_index=0, buffers=[])))
136
137 async with app.run_test() as pilot:
138 await wait_for_editor(pilot, app)
139 await pilot.press("ctrl+q")
140
141 assert not recovery_file.exists()
142 assert get_cache_file().exists()
143
144
145 @pytest.mark.use_cache
146 @pytest.mark.asyncio
147 async def test_harlequin_checkpoints_buffers(
148 app: Harlequin,
149 ) -> None:
150 recovery_file = get_recovery_file()
151 async with app.run_test() as pilot:
152 editor = await wait_for_editor(pilot, app)
153 app._checkpoint_editor_cache()
154 # a blank buffer is not work, so there is nothing to save yet
155 assert not recovery_file.exists()
156
157 editor.text = "select 1"
158 app._checkpoint_editor_cache()
159 assert pickle.loads(recovery_file.read_bytes()).buffers[0].text == "select 1"
160
161 # and an idle session does not rewrite what it already wrote
162 written_at = recovery_file.stat().st_mtime_ns
163 app._checkpoint_editor_cache()
164 assert recovery_file.stat().st_mtime_ns == written_at
165
166 # a blank buffer cannot destroy a good checkpoint, either
167 editor.text = ""
168 app._checkpoint_editor_cache()
169 assert pickle.loads(recovery_file.read_bytes()).buffers[0].text == "select 1"