From 2f9f36aa1fb7e2217754c4095c770ef504b3bf93 Mon Sep 17 00:00:00 2001 From: Frank Harkins Date: Wed, 15 May 2024 09:32:13 +0100 Subject: [PATCH] Check for errors when executing initialization code (#1373) 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> --- .../qiskit_docs_notebook_tester/__init__.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/scripts/nb-tester/qiskit_docs_notebook_tester/__init__.py b/scripts/nb-tester/qiskit_docs_notebook_tester/__init__.py index ac5cc037ecd..7bf23a8905e 100644 --- a/scripts/nb-tester/qiskit_docs_notebook_tester/__init__.py +++ b/scripts/nb-tester/qiskit_docs_notebook_tester/__init__.py @@ -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 @@ -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: @@ -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,