Skip to content

Commit

Permalink
Check for errors when executing initialization code (#1373)
Browse files Browse the repository at this point in the history
We run some code before notebook execution to silence some warnings and
set up mock backends. At the moment, errors are ignored and the kernel
continues, often leading to unexpected behaviour.

This PR explicitly checks for errors when running the initialization
code and exits early if needed.

---------

Co-authored-by: Eric Arellano <14852634+Eric-Arellano@users.noreply.github.com>
  • Loading branch information
frankharkins and Eric-Arellano authored May 15, 2024
1 parent f170d21 commit 2f9f36a
Showing 1 changed file with 9 additions and 3 deletions.
12 changes: 9 additions & 3 deletions scripts/nb-tester/qiskit_docs_notebook_tester/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
import nbclient
import nbformat
import tomli
from jupyter_client.manager import start_new_async_kernel
from jupyter_client.manager import start_new_async_kernel, AsyncKernelClient
from qiskit_ibm_runtime import QiskitRuntimeService
from squeaky import clean_notebook

Expand Down Expand Up @@ -226,6 +226,12 @@ async def execute_notebook(path: Path, config: Config) -> bool:
print(f"✅ No problems in {path} (written)")
return True

async def _execute_in_kernel(kernel: AsyncKernelClient, code: str) -> None:
"""Execute code in kernel and raise if it fails"""
response = await kernel.execute_interactive(code, store_history=False)
if response.get("content", {}).get("status", "") == "error":
raise Exception("Error running initialization code")

async def _execute_notebook(filepath: Path, config: Config) -> nbformat.NotebookNode:
"""
Use nbclient to execute notebook. The steps are:
Expand All @@ -242,9 +248,9 @@ async def _execute_notebook(filepath: Path, config: Config) -> nbformat.Notebook
extra_arguments=["--InlineBackend.figure_format='svg'"],
)

kernel.execute(PRE_EXECUTE_CODE, store_history=False)
await _execute_in_kernel(kernel, PRE_EXECUTE_CODE)
if config.should_patch(filepath):
kernel.execute(MOCKING_CODE, store_history=False)
await _execute_in_kernel(kernel, MOCKING_CODE)

notebook_client = nbclient.NotebookClient(
nb=nb,
Expand Down

0 comments on commit 2f9f36a

Please sign in to comment.