Skip to content

Commit

Permalink
mocks
Browse files Browse the repository at this point in the history
  • Loading branch information
alex-treebeard committed Jul 15, 2022
1 parent 0592a3f commit c85213c
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 1 deletion.
22 changes: 21 additions & 1 deletion src/nbmake/nb_run.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from pathlib import Path
from typing import Optional
from typing import Any, Dict, Optional

import nbformat
from nbclient.client import (
Expand Down Expand Up @@ -60,6 +60,26 @@ def execute(
record_timing=True,
**extra_kwargs,
)

async def apply_mocks(
cell: NotebookNode, cell_index: int, execute_reply: Dict[str, Any]
):
if c.kc is None:
raise Exception("there is no kernelclient")
mocks: Dict[str, Any] = (
cell.get("metadata", {}).get("nbmake", {}).get("mock", {})
)
for v in mocks:
if isinstance(mocks[v], str):
out = await c.kc.execute_interactive(f"{v} = '{mocks[v]}'")
else:
out = await c.kc.execute_interactive(f"{v} = {mocks[v]}")

if out["content"]["status"] != "ok":
raise Exception(f"Failed to apply mock {v}\n\n{str(out)}")

c.on_cell_executed = apply_mocks

c.execute(cwd=self.filename.parent)
except CellExecutionError:
error = self._get_error(nb)
Expand Down
42 changes: 42 additions & 0 deletions tests/resources/mock.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"nbmake": {
"mock": {
"x": 2,
"y": "fish",
"z": {
"x": 42
}
}
}
},
"outputs": [],
"source": [
"x = 5\n",
"y = 'y'"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"assert x == 2\n",
"assert y == \"fish\"\n",
"assert z == { \"x\": 42 }"
]
}
],
"metadata": {
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
6 changes: 6 additions & 0 deletions tests/test_nb_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,3 +113,9 @@ def test_when_raises_exc_tag_then_succeeds(self, testdir2: Testdir):
run = NotebookRun(nb, 300)
res: NotebookResult = run.execute()
assert res.error == None

def test_when_mock_then_succeeds(self, testdir2: Testdir):
nb = Path(__file__).parent / "resources" / "mock.ipynb"
run = NotebookRun(nb, 300)
res: NotebookResult = run.execute()
assert res.error == None

0 comments on commit c85213c

Please sign in to comment.