|
| 1 | +# Copyright 2022 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +from __future__ import annotations |
| 15 | + |
| 16 | +import os |
| 17 | +import re |
| 18 | +import subprocess |
| 19 | +import sys |
| 20 | +import textwrap |
| 21 | +import uuid |
| 22 | +from collections.abc import Callable, Iterable |
| 23 | +from datetime import datetime |
| 24 | +from typing import AsyncIterator |
| 25 | + |
| 26 | +import pytest |
| 27 | +import pytest_asyncio |
| 28 | + |
| 29 | + |
| 30 | +def get_env_var(key: str) -> str: |
| 31 | + v = os.environ.get(key) |
| 32 | + if v is None: |
| 33 | + raise ValueError(f"Must set env var {key}") |
| 34 | + return v |
| 35 | + |
| 36 | + |
| 37 | +@pytest.fixture(scope="session") |
| 38 | +def table_name() -> str: |
| 39 | + return "investments" |
| 40 | + |
| 41 | + |
| 42 | +@pytest.fixture(scope="session") |
| 43 | +def cluster_name() -> str: |
| 44 | + return get_env_var("ALLOYDB_CLUSTER") |
| 45 | + |
| 46 | + |
| 47 | +@pytest.fixture(scope="session") |
| 48 | +def instance_name() -> str: |
| 49 | + return get_env_var("ALLOYDB_INSTANCE") |
| 50 | + |
| 51 | + |
| 52 | +@pytest.fixture(scope="session") |
| 53 | +def region() -> str: |
| 54 | + return get_env_var("ALLOYDB_REGION") |
| 55 | + |
| 56 | + |
| 57 | +@pytest.fixture(scope="session") |
| 58 | +def database_name() -> str: |
| 59 | + return get_env_var("ALLOYDB_DATABASE_NAME") |
| 60 | + |
| 61 | + |
| 62 | +@pytest.fixture(scope="session") |
| 63 | +def password() -> str: |
| 64 | + return get_env_var("ALLOYDB_PASSWORD") |
| 65 | + |
| 66 | + |
| 67 | +@pytest_asyncio.fixture(scope="session") |
| 68 | +def project_id() -> str: |
| 69 | + gcp_project = get_env_var("GOOGLE_CLOUD_PROJECT") |
| 70 | + run_cmd("gcloud", "config", "set", "project", gcp_project) |
| 71 | + # Since everything requires the project, let's confiugre and show some |
| 72 | + # debugging information here. |
| 73 | + run_cmd("gcloud", "version") |
| 74 | + run_cmd("gcloud", "config", "list") |
| 75 | + return gcp_project |
| 76 | + |
| 77 | + |
| 78 | +def run_cmd(*cmd: str) -> subprocess.CompletedProcess: |
| 79 | + try: |
| 80 | + print(f">> {cmd}") |
| 81 | + start = datetime.now() |
| 82 | + p = subprocess.run( |
| 83 | + cmd, |
| 84 | + check=True, |
| 85 | + stdout=subprocess.PIPE, |
| 86 | + stderr=subprocess.PIPE, |
| 87 | + ) |
| 88 | + print(p.stderr.decode("utf-8")) |
| 89 | + print(p.stdout.decode("utf-8")) |
| 90 | + elapsed = (datetime.now() - start).seconds |
| 91 | + minutes = int(elapsed / 60) |
| 92 | + seconds = elapsed - minutes * 60 |
| 93 | + print(f"Command `{cmd[0]}` finished in {minutes}m {seconds}s") |
| 94 | + return p |
| 95 | + except subprocess.CalledProcessError as e: |
| 96 | + # Include the error message from the failed command. |
| 97 | + print(e.stderr.decode("utf-8")) |
| 98 | + print(e.stdout.decode("utf-8")) |
| 99 | + raise RuntimeError(f"{e}\n\n{e.stderr.decode('utf-8')}") from e |
| 100 | + |
| 101 | + |
| 102 | +def run_notebook( |
| 103 | + ipynb_file: str, |
| 104 | + prelude: str = "", |
| 105 | + section: str = "", |
| 106 | + variables: dict = {}, |
| 107 | + replace: dict[str, str] = {}, |
| 108 | + preprocess: Callable[[str], str] = lambda source: source, |
| 109 | + skip_shell_commands: bool = False, |
| 110 | + until_end: bool = False, |
| 111 | +) -> None: |
| 112 | + import nbformat |
| 113 | + from nbclient.client import NotebookClient |
| 114 | + from nbclient.exceptions import CellExecutionError |
| 115 | + |
| 116 | + def notebook_filter_section( |
| 117 | + start: str, |
| 118 | + end: str, |
| 119 | + cells: list[nbformat.NotebookNode], |
| 120 | + until_end: bool = False, |
| 121 | + ) -> Iterable[nbformat.NotebookNode]: |
| 122 | + in_section = False |
| 123 | + for cell in cells: |
| 124 | + if cell["cell_type"] == "markdown": |
| 125 | + if not in_section and cell["source"].startswith(start): |
| 126 | + in_section = True |
| 127 | + elif in_section and not until_end and cell["source"].startswith(end): |
| 128 | + return |
| 129 | + if in_section: |
| 130 | + yield cell |
| 131 | + |
| 132 | + # Regular expression to match and remove shell commands from the notebook. |
| 133 | + # https://regex101.com/r/EHWBpT/1 |
| 134 | + shell_command_re = re.compile(r"^!((?:[^\n]+\\\n)*(?:[^\n]+))$", re.MULTILINE) |
| 135 | + # Compile regular expressions for variable substitutions. |
| 136 | + # https://regex101.com/r/e32vfW/1 |
| 137 | + compiled_substitutions = [ |
| 138 | + ( |
| 139 | + re.compile(rf"""\b{name}\s*=\s*(?:f?'[^']*'|f?"[^"]*"|\w+)"""), |
| 140 | + f"{name} = {repr(value)}", |
| 141 | + ) |
| 142 | + for name, value in variables.items() |
| 143 | + ] |
| 144 | + # Filter the section if any, otherwise use the entire notebook. |
| 145 | + nb = nbformat.read(ipynb_file, as_version=4) |
| 146 | + if section: |
| 147 | + start = section |
| 148 | + end = section.split(" ", 1)[0] + " " |
| 149 | + nb.cells = list(notebook_filter_section(start, end, nb.cells, until_end)) |
| 150 | + if len(nb.cells) == 0: |
| 151 | + raise ValueError( |
| 152 | + f"Section {repr(section)} not found in notebook {repr(ipynb_file)}" |
| 153 | + ) |
| 154 | + # Preprocess the cells. |
| 155 | + for cell in nb.cells: |
| 156 | + # Only preprocess code cells. |
| 157 | + if cell["cell_type"] != "code": |
| 158 | + continue |
| 159 | + # Run any custom preprocessing functions before. |
| 160 | + cell["source"] = preprocess(cell["source"]) |
| 161 | + # Preprocess shell commands. |
| 162 | + if skip_shell_commands: |
| 163 | + cmd = "pass" |
| 164 | + cell["source"] = shell_command_re.sub(cmd, cell["source"]) |
| 165 | + else: |
| 166 | + cell["source"] = shell_command_re.sub(r"_run(f'''\1''')", cell["source"]) |
| 167 | + # Apply variable substitutions. |
| 168 | + for regex, new_value in compiled_substitutions: |
| 169 | + cell["source"] = regex.sub(new_value, cell["source"]) |
| 170 | + # Apply replacements. |
| 171 | + for old, new in replace.items(): |
| 172 | + cell["source"] = cell["source"].replace(old, new) |
| 173 | + # Clear outputs. |
| 174 | + cell["outputs"] = [] |
| 175 | + # Prepend the prelude cell. |
| 176 | + prelude_src = textwrap.dedent( |
| 177 | + """\ |
| 178 | + def _run(cmd): |
| 179 | + import subprocess as _sp |
| 180 | + import sys as _sys |
| 181 | + _p = _sp.run(cmd, shell=True, stdout=_sp.PIPE, stderr=_sp.PIPE) |
| 182 | + _stdout = _p.stdout.decode('utf-8').strip() |
| 183 | + _stderr = _p.stderr.decode('utf-8').strip() |
| 184 | + if _stdout: |
| 185 | + print(f'➜ !{cmd}') |
| 186 | + print(_stdout) |
| 187 | + if _stderr: |
| 188 | + print(f'➜ !{cmd}', file=_sys.stderr) |
| 189 | + print(_stderr, file=_sys.stderr) |
| 190 | + if _p.returncode: |
| 191 | + raise RuntimeError('\\n'.join([ |
| 192 | + f"Command returned non-zero exit status {_p.returncode}.", |
| 193 | + f"-------- command --------", |
| 194 | + f"{cmd}", |
| 195 | + f"-------- stderr --------", |
| 196 | + f"{_stderr}", |
| 197 | + f"-------- stdout --------", |
| 198 | + f"{_stdout}", |
| 199 | + ])) |
| 200 | + """ |
| 201 | + + prelude |
| 202 | + ) |
| 203 | + nb.cells = [nbformat.v4.new_code_cell(prelude_src)] + nb.cells |
| 204 | + # Run the notebook. |
| 205 | + error = "" |
| 206 | + client = NotebookClient(nb) |
| 207 | + try: |
| 208 | + client.execute() |
| 209 | + except CellExecutionError as e: |
| 210 | + # Remove colors and other escape characters to make it easier to read in the logs. |
| 211 | + # https://stackoverflow.com/a/33925425 |
| 212 | + color_chars = re.compile(r"(\x9B|\x1B\[)[0-?]*[ -\/]*[@-~]") |
| 213 | + error = color_chars.sub("", str(e)) |
| 214 | + for cell in nb.cells: |
| 215 | + if cell["cell_type"] != "code": |
| 216 | + continue |
| 217 | + for output in cell["outputs"]: |
| 218 | + if output.get("name") == "stdout": |
| 219 | + print(color_chars.sub("", output["text"])) |
| 220 | + elif output.get("name") == "stderr": |
| 221 | + print(color_chars.sub("", output["text"]), file=sys.stderr) |
| 222 | + if error: |
| 223 | + raise RuntimeError( |
| 224 | + f"Error on {repr(ipynb_file)}, section {repr(section)}: {error}" |
| 225 | + ) |
0 commit comments