Debian Codegraph @

tests/test_cache.py

raw
1 import os
2 import re
3 import shutil
4 from textwrap import dedent
5
6 import nbformat as nbf
7 import pytest
8
9 from jupyter_cache import __version__
10 from jupyter_cache.base import NbValidityError
11 from jupyter_cache.cache.main import JupyterCacheBase
12
13 NB_PATH = os.path.join(os.path.realpath(os.path.dirname(__file__)), "notebooks")
14 ANSI_REGEX = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
15
16
17 def test_get_version(tmp_path):
18 cache = JupyterCacheBase(str(tmp_path))
19 cache.db
20 assert cache.get_version() == __version__
21
22
23 def test_basic_workflow(tmp_path):
24 cache = JupyterCacheBase(str(tmp_path))
25 with pytest.raises(NbValidityError):
26 cache.cache_notebook_file(path=os.path.join(NB_PATH, "basic.ipynb"))
27 cache.cache_notebook_file(
28 path=os.path.join(NB_PATH, "basic.ipynb"),
29 uri="basic.ipynb",
30 check_validity=False,
31 )
32 assert cache.list_cache_records()[0].uri == "basic.ipynb"
33 pk = cache.match_cache_file(path=os.path.join(NB_PATH, "basic.ipynb")).pk
34 nb_bundle = cache.get_cache_bundle(pk)
35 assert nb_bundle.nb.metadata["kernelspec"] == {
36 "display_name": "Python 3",
37 "language": "python",
38 "name": "python3",
39 }
40 assert set(nb_bundle.record.to_dict().keys()) == {
41 "pk",
42 "hashkey",
43 "uri",
44 "data",
45 "created",
46 "accessed",
47 "description",
48 }
49 # assert cache.get_cache_codecell(pk, 0).source == "a=1\nprint(a)"
50
51 path = os.path.join(NB_PATH, "basic_failing.ipynb")
52 diff = cache.diff_nbfile_with_cache(pk, path, as_str=True, use_color=False)
53 assert diff == dedent(
54 f"""\
55 nbdiff
56 --- cached pk=1
57 +++ other: {path}
58 ## inserted before nb/cells/0:
59 + code cell:
60 + source:
61 + raise Exception('oopsie!')
62
63 ## deleted nb/cells/0:
64 - code cell:
65 - execution_count: 2
66 - source:
67 - a=1
68 - print(a)
69 - outputs:
70 - output 0:
71 - output_type: stream
72 - name: stdout
73 - text:
74 - 1
75
76 """
77 )
78 cache.remove_cache(pk)
79 assert cache.list_cache_records() == []
80
81 cache.cache_notebook_file(
82 path=os.path.join(NB_PATH, "basic.ipynb"),
83 uri="basic.ipynb",
84 check_validity=False,
85 )
86 with pytest.raises(ValueError):
87 cache.add_nb_to_project(os.path.join(NB_PATH, "basic.ipynb"), assets=[""])
88 cache.add_nb_to_project(
89 os.path.join(NB_PATH, "basic.ipynb"),
90 assets=[os.path.join(NB_PATH, "basic.ipynb")],
91 )
92 assert [r.pk for r in cache.list_project_records()] == [1]
93 assert [r.pk for r in cache.list_unexecuted()] == []
94
95 cache.add_nb_to_project(os.path.join(NB_PATH, "basic_failing.ipynb"))
96 assert [r.pk for r in cache.list_project_records()] == [1, 2]
97 assert [r.pk for r in cache.list_unexecuted()] == [2]
98
99 bundle = cache.get_project_notebook(os.path.join(NB_PATH, "basic_failing.ipynb"))
100 assert bundle.nb.metadata
101
102 cache.clear_cache()
103 assert cache.list_cache_records() == []
104
105
106 def test_v4_2_to_v4_5(tmp_path):
107 """Test that caching a v4.2 notebook can be recovered,
108 if the notebook is updated to v4.5 (adding cell ids).
109 """
110 cache = JupyterCacheBase(str(tmp_path))
111 cache_record = cache.cache_notebook_file(
112 path=os.path.join(NB_PATH, "basic.ipynb"),
113 uri="basic.ipynb",
114 check_validity=False,
115 )
116 (pk, nb) = cache.merge_match_into_notebook(
117 nbf.read(os.path.join(NB_PATH, "basic_v4-5.ipynb"), nbf.NO_CONVERT)
118 )
119 assert cache_record.pk == pk
120 assert nb.nbformat_minor == 5, nb
121 assert "id" in nb.cells[1], nb
122
123
124 def test_v4_5_to_v4_2(tmp_path):
125 """Test that caching a v4.5 notebook can be recovered,
126 if the notebook is downgraded to v4.2 (removing cell ids).
127 """
128 cache = JupyterCacheBase(str(tmp_path))
129 cache_record = cache.cache_notebook_file(
130 path=os.path.join(NB_PATH, "basic_v4-5.ipynb"),
131 uri="basic_v4-5.ipynb",
132 check_validity=False,
133 )
134 (pk, nb) = cache.merge_match_into_notebook(
135 nbf.read(os.path.join(NB_PATH, "basic.ipynb"), nbf.NO_CONVERT)
136 )
137 assert cache_record.pk == pk
138 assert nb.nbformat_minor == 2, nb
139 assert "id" not in nb.cells[1], nb
140
141
142 def test_merge_match_into_notebook(tmp_path):
143 cache = JupyterCacheBase(str(tmp_path))
144 cache.cache_notebook_file(
145 path=os.path.join(NB_PATH, "basic.ipynb"), check_validity=False
146 )
147 nb = nbf.read(os.path.join(NB_PATH, "basic_unrun.ipynb"), 4)
148 pk, merged = cache.merge_match_into_notebook(nb)
149 assert merged.cells[1] == {
150 "cell_type": "code",
151 "execution_count": 2,
152 "metadata": {},
153 "outputs": [{"name": "stdout", "output_type": "stream", "text": "1\n"}],
154 "source": "a=1\nprint(a)",
155 }
156
157
158 def test_artifacts(tmp_path):
159 cache = JupyterCacheBase(str(tmp_path))
160 with pytest.raises(IOError):
161 cache.cache_notebook_file(
162 path=os.path.join(NB_PATH, "basic.ipynb"),
163 uri="basic.ipynb",
164 artifacts=(os.path.join(NB_PATH),),
165 check_validity=False,
166 )
167 cache.cache_notebook_file(
168 path=os.path.join(NB_PATH, "basic.ipynb"),
169 uri="basic.ipynb",
170 artifacts=(os.path.join(NB_PATH, "artifact_folder", "artifact.txt"),),
171 check_validity=False,
172 )
173 hashkey = cache.get_cache_record(1).hashkey
174 assert {
175 str(p.relative_to(tmp_path)) for p in tmp_path.glob("**/*") if p.is_file()
176 } == {
177 "global.db",
178 "__version__.txt",
179 f"executed/{hashkey}/base.ipynb",
180 f"executed/{hashkey}/artifacts/artifact_folder/artifact.txt",
181 }
182
183 bundle = cache.get_cache_bundle(1)
184 assert {str(p) for p in bundle.artifacts.relative_paths} == {
185 "artifact_folder/artifact.txt"
186 }
187
188 text = list(h.read().decode() for r, h in bundle.artifacts)[0]
189 assert text.rstrip() == "An artifact"
190
191 with cache.cache_artefacts_temppath(1) as path:
192 assert path.joinpath("artifact_folder").exists()
193
194
195 @pytest.mark.parametrize(
196 "executor_key", ["local-serial", "temp-serial", "local-parallel", "temp-parallel"]
197 )
198 def test_execution(tmp_path, executor_key):
199 from jupyter_cache.executors import load_executor
200
201 db = JupyterCacheBase(str(tmp_path / "cache"))
202 temp_nb_path = tmp_path / "notebooks"
203 shutil.copytree(NB_PATH, temp_nb_path)
204 db.add_nb_to_project(path=os.path.join(temp_nb_path, "basic_unrun.ipynb"))
205 db.add_nb_to_project(path=os.path.join(temp_nb_path, "basic_failing.ipynb"))
206 db.add_nb_to_project(
207 path=os.path.join(temp_nb_path, "external_output.ipynb"),
208 assets=(os.path.join(temp_nb_path, "basic.ipynb"),),
209 )
210 executor = load_executor(executor_key, db)
211 result = executor.run_and_cache()
212 # print(result)
213 json_result = result.as_json()
214 json_result["succeeded"] = list(sorted(json_result.get("succeeded", [])))
215 assert json_result == {
216 "succeeded": [
217 os.path.join(temp_nb_path, "basic_unrun.ipynb"),
218 os.path.join(temp_nb_path, "external_output.ipynb"),
219 ],
220 "excepted": [os.path.join(temp_nb_path, "basic_failing.ipynb")],
221 "errored": [],
222 }
223 assert len(db.list_cache_records()) == 2
224 cache_record = db.get_cached_project_nb(1)
225 bundle = db.get_cache_bundle(cache_record.pk)
226 assert bundle.nb.cells[0] == {
227 "cell_type": "code",
228 "execution_count": 1,
229 "metadata": {},
230 "outputs": [{"name": "stdout", "output_type": "stream", "text": "1\n"}],
231 "source": "a=1\nprint(a)",
232 }
233 assert "execution_seconds" in bundle.record.data
234
235 # TODO artifacts
236 # with db.cache_artefacts_temppath(2) as path:
237 # paths = [str(p.relative_to(path)) for p in path.glob("**/*") if p.is_file()]
238 # assert paths == ["artifact.txt"]
239 # assert path.joinpath("artifact.txt").read_text(encoding="utf8") == "hi"
240
241 project_record = db.get_project_record(2)
242 assert project_record.traceback is not None
243 assert "Exception: oopsie!" in ANSI_REGEX.sub("", project_record.traceback)
244
245
246 def test_execution_jupytext(tmp_path):
247 """Test execution with the jupytext reader."""
248 from jupyter_cache.executors import load_executor
249
250 db = JupyterCacheBase(str(tmp_path / "cache"))
251 temp_nb_path = tmp_path / "notebooks"
252 shutil.copytree(NB_PATH, temp_nb_path)
253 db.add_nb_to_project(
254 path=os.path.join(temp_nb_path, "basic.md"),
255 read_data={"name": "jupytext", "type": "plugin"},
256 )
257 executor = load_executor("local-serial", db)
258 result = executor.run_and_cache()
259 print(result)
260 assert result.as_json() == {
261 "succeeded": [
262 os.path.join(temp_nb_path, "basic.md"),
263 ],
264 "excepted": [],
265 "errored": [],
266 }
267 assert len(db.list_cache_records()) == 1
268
269
270 def test_execution_timeout_config(tmp_path):
271 """tests the timeout value passed to the executor"""
272 from jupyter_cache.executors import load_executor
273
274 db = JupyterCacheBase(str(tmp_path))
275 db.add_nb_to_project(path=os.path.join(NB_PATH, "sleep_2.ipynb"))
276 executor = load_executor("local-serial", db)
277 result = executor.run_and_cache(timeout=10)
278 assert result.as_json() == {
279 "succeeded": [os.path.join(NB_PATH, "sleep_2.ipynb")],
280 "excepted": [],
281 "errored": [],
282 }
283 db.clear_cache()
284
285 db.add_nb_to_project(path=os.path.join(NB_PATH, "sleep_2.ipynb"))
286 executor = load_executor("local-serial", db)
287 result = executor.run_and_cache(timeout=1)
288 assert result.as_json() == {
289 "succeeded": [],
290 "excepted": [os.path.join(NB_PATH, "sleep_2.ipynb")],
291 "errored": [],
292 }
293
294
295 def test_execution_timeout_metadata(tmp_path):
296 """tests the timeout metadata key in notebooks"""
297 from jupyter_cache.executors import load_executor
298
299 db = JupyterCacheBase(str(tmp_path))
300 db.add_nb_to_project(path=os.path.join(NB_PATH, "sleep_2_timeout_1.ipynb"))
301 executor = load_executor("local-serial", db)
302 result = executor.run_and_cache()
303 assert result.as_json() == {
304 "succeeded": [],
305 "excepted": [os.path.join(NB_PATH, "sleep_2_timeout_1.ipynb")],
306 "errored": [],
307 }
308
309
310 def test_execution_allow_errors_config(tmp_path):
311 """tests the timeout value passed to the executor"""
312 from jupyter_cache.executors import load_executor
313
314 db = JupyterCacheBase(str(tmp_path))
315 db.add_nb_to_project(path=os.path.join(NB_PATH, "basic_failing.ipynb"))
316 executor = load_executor("local-serial", db)
317 result = executor.run_and_cache(allow_errors=True)
318 assert result.as_json() == {
319 "succeeded": [os.path.join(NB_PATH, "basic_failing.ipynb")],
320 "excepted": [],
321 "errored": [],
322 }
323
324
325 def test_run_in_temp_false(tmp_path):
326 """tests the timeout value passed to the executor"""
327 from jupyter_cache.executors import load_executor
328
329 db = JupyterCacheBase(str(tmp_path))
330 db.add_nb_to_project(path=os.path.join(NB_PATH, "basic.ipynb"))
331 executor = load_executor("temp-serial", db)
332 result = executor.run_and_cache()
333 assert result.as_json() == {
334 "succeeded": [os.path.join(NB_PATH, "basic.ipynb")],
335 "excepted": [],
336 "errored": [],
337 }