Skip to content

Commit c85213c

Browse files
mocks
1 parent 0592a3f commit c85213c

File tree

3 files changed

+69
-1
lines changed

3 files changed

+69
-1
lines changed

src/nbmake/nb_run.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from pathlib import Path
2-
from typing import Optional
2+
from typing import Any, Dict, Optional
33

44
import nbformat
55
from nbclient.client import (
@@ -60,6 +60,26 @@ def execute(
6060
record_timing=True,
6161
**extra_kwargs,
6262
)
63+
64+
async def apply_mocks(
65+
cell: NotebookNode, cell_index: int, execute_reply: Dict[str, Any]
66+
):
67+
if c.kc is None:
68+
raise Exception("there is no kernelclient")
69+
mocks: Dict[str, Any] = (
70+
cell.get("metadata", {}).get("nbmake", {}).get("mock", {})
71+
)
72+
for v in mocks:
73+
if isinstance(mocks[v], str):
74+
out = await c.kc.execute_interactive(f"{v} = '{mocks[v]}'")
75+
else:
76+
out = await c.kc.execute_interactive(f"{v} = {mocks[v]}")
77+
78+
if out["content"]["status"] != "ok":
79+
raise Exception(f"Failed to apply mock {v}\n\n{str(out)}")
80+
81+
c.on_cell_executed = apply_mocks
82+
6383
c.execute(cwd=self.filename.parent)
6484
except CellExecutionError:
6585
error = self._get_error(nb)

tests/resources/mock.ipynb

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "code",
5+
"execution_count": null,
6+
"metadata": {
7+
"nbmake": {
8+
"mock": {
9+
"x": 2,
10+
"y": "fish",
11+
"z": {
12+
"x": 42
13+
}
14+
}
15+
}
16+
},
17+
"outputs": [],
18+
"source": [
19+
"x = 5\n",
20+
"y = 'y'"
21+
]
22+
},
23+
{
24+
"cell_type": "code",
25+
"execution_count": null,
26+
"metadata": {},
27+
"outputs": [],
28+
"source": [
29+
"assert x == 2\n",
30+
"assert y == \"fish\"\n",
31+
"assert z == { \"x\": 42 }"
32+
]
33+
}
34+
],
35+
"metadata": {
36+
"language_info": {
37+
"name": "python"
38+
}
39+
},
40+
"nbformat": 4,
41+
"nbformat_minor": 2
42+
}

tests/test_nb_run.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,3 +113,9 @@ def test_when_raises_exc_tag_then_succeeds(self, testdir2: Testdir):
113113
run = NotebookRun(nb, 300)
114114
res: NotebookResult = run.execute()
115115
assert res.error == None
116+
117+
def test_when_mock_then_succeeds(self, testdir2: Testdir):
118+
nb = Path(__file__).parent / "resources" / "mock.ipynb"
119+
run = NotebookRun(nb, 300)
120+
res: NotebookResult = run.execute()
121+
assert res.error == None

0 commit comments

Comments
 (0)