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