|
| 1 | +import pathlib |
| 2 | +import signal |
| 3 | +import sys |
| 4 | +from datetime import datetime |
| 5 | +from typing import Any, Callable, NamedTuple |
| 6 | + |
| 7 | +import nbformat |
| 8 | +import pytest |
| 9 | +from nbclient.exceptions import CellExecutionError |
| 10 | +from nbconvert.preprocessors.execute import ExecutePreprocessor |
| 11 | + |
| 12 | +TEARDOWN_CELL_TAG = "teardown" |
| 13 | + |
| 14 | + |
| 15 | +class IndexedCell(NamedTuple): |
| 16 | + cell: Any |
| 17 | + index: int # type: ignore |
| 18 | + |
| 19 | + |
| 20 | +class TeardownExecutePreprocessor(ExecutePreprocessor): |
| 21 | + def __init__(self, **kw: Any): |
| 22 | + super().__init__(**kw) # type: ignore |
| 23 | + |
| 24 | + def init_notebook(self, tear_down_cells: list[IndexedCell]) -> None: |
| 25 | + self.tear_down_cells = tear_down_cells |
| 26 | + self._skip_rest = False |
| 27 | + |
| 28 | + # run the cell of a notebook |
| 29 | + def preprocess_cell(self, cell: Any, resources: Any, index: int) -> None: |
| 30 | + if index == 0: |
| 31 | + |
| 32 | + def handle_signal(sig, frame): # type: ignore |
| 33 | + print("Received SIGNAL, running tear down cells") |
| 34 | + self.teardown(resources) |
| 35 | + sys.exit(1) |
| 36 | + |
| 37 | + signal.signal(signal.SIGINT, handle_signal) |
| 38 | + signal.signal(signal.SIGTERM, handle_signal) |
| 39 | + |
| 40 | + try: |
| 41 | + if not self._skip_rest: |
| 42 | + super().preprocess_cell(cell, resources, index) # type: ignore |
| 43 | + except CellExecutionError as e: |
| 44 | + if self.tear_down_cells: |
| 45 | + print(f"Running tear down cells due to error in notebook execution: {e}") |
| 46 | + self.teardown(resources) |
| 47 | + raise e |
| 48 | + |
| 49 | + def teardown(self, resources: Any) -> None: |
| 50 | + for td_cell, td_idx in self.tear_down_cells: |
| 51 | + try: |
| 52 | + super().preprocess_cell(td_cell, resources, td_idx) # type: ignore |
| 53 | + except CellExecutionError as td_e: |
| 54 | + print(f"Error running tear down cell {td_idx}: {td_e}") |
| 55 | + |
| 56 | + |
| 57 | +class TearDownCollector(ExecutePreprocessor): |
| 58 | + def __init__(self, **kw: Any): |
| 59 | + super().__init__(**kw) # type: ignore |
| 60 | + |
| 61 | + def init_notebook(self) -> None: |
| 62 | + self._tear_down_cells: list[IndexedCell] = [] |
| 63 | + |
| 64 | + def preprocess_cell(self, cell: Any, resources: Any, index: int) -> None: |
| 65 | + if TEARDOWN_CELL_TAG in cell["metadata"].get("tags", []): |
| 66 | + self._tear_down_cells.append(IndexedCell(cell, index)) |
| 67 | + |
| 68 | + def tear_down_cells(self) -> list[IndexedCell]: |
| 69 | + return self._tear_down_cells |
| 70 | + |
| 71 | + |
| 72 | +def run_notebooks(filter_func: Callable[[str], bool]) -> None: |
| 73 | + current_dir = pathlib.Path(__file__).parent.resolve() |
| 74 | + examples_path = current_dir.parent.parent / "examples" |
| 75 | + |
| 76 | + notebook_files = [ |
| 77 | + f for f in examples_path.iterdir() if f.is_file() and f.suffix == ".ipynb" and filter_func(f.name) |
| 78 | + ] |
| 79 | + |
| 80 | + ep = TeardownExecutePreprocessor(kernel_name="python3") |
| 81 | + td_collector = TearDownCollector(kernel_name="python3") |
| 82 | + exceptions: list[RuntimeError] = [] |
| 83 | + |
| 84 | + for notebook_filename in notebook_files: |
| 85 | + now = datetime.now().strftime("%Y-%m-%d %H:%M:%S") |
| 86 | + print(f"{now}: Executing notebook {notebook_filename}", flush=True) |
| 87 | + |
| 88 | + with open(notebook_filename) as f: |
| 89 | + nb = nbformat.read(f, as_version=4) # type: ignore |
| 90 | + |
| 91 | + # Collect tear down cells |
| 92 | + td_collector.init_notebook() |
| 93 | + td_collector.preprocess(nb) |
| 94 | + |
| 95 | + ep.init_notebook(tear_down_cells=td_collector.tear_down_cells()) |
| 96 | + |
| 97 | + # run the notebook |
| 98 | + try: |
| 99 | + ep.preprocess(nb) |
| 100 | + print(f"Finished executing notebook {notebook_filename}") |
| 101 | + except CellExecutionError as e: |
| 102 | + exceptions.append(RuntimeError(f"Error executing notebook {notebook_filename}", e)) |
| 103 | + continue |
| 104 | + |
| 105 | + if exceptions: |
| 106 | + for nb_ex in exceptions: |
| 107 | + print(nb_ex) |
| 108 | + raise RuntimeError(f"{len(exceptions)} Errors occurred while executing notebooks") |
| 109 | + else: |
| 110 | + print("Finished executing notebooks") |
| 111 | + |
| 112 | + |
| 113 | +@pytest.mark.requires_neo4j_and_gds |
| 114 | +def test_neo4j(gds: Any) -> None: |
| 115 | + neo4j_notebooks = ["neo4j-nvl-example.ipynb", "gds-nvl-example.ipynb"] |
| 116 | + |
| 117 | + def filter_func(notebook: str) -> bool: |
| 118 | + return notebook in neo4j_notebooks |
| 119 | + |
| 120 | + run_notebooks(filter_func) |
| 121 | + |
| 122 | + |
| 123 | +# def test_snowflake() -> None: |
| 124 | +# snowflake_notebooks = ["snowflake-nvl-example.ipynb"] |
| 125 | +# |
| 126 | +# def filter_func(notebook: str) -> bool: |
| 127 | +# return notebook in snowflake_notebooks |
| 128 | +# |
| 129 | +# run_notebooks(filter_func) |
| 130 | +# |
| 131 | +# def test_simple() -> None: |
| 132 | +# simple_notebooks = ["simple-nvl-example.ipynb"] |
| 133 | +# |
| 134 | +# def filter_func(notebook: str) -> bool: |
| 135 | +# return notebook in simple_notebooks |
| 136 | +# |
| 137 | +# run_notebooks(filter_func) |
0 commit comments