-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtest_notebook.py
More file actions
executable file
·105 lines (68 loc) · 2.42 KB
/
test_notebook.py
File metadata and controls
executable file
·105 lines (68 loc) · 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#!/usr/bin/env python3
"""Run Jupyter Notebooks and check for errors."""
import argparse
import ast
import os
import sys
import warnings
import matplotlib
import nbformat
from nbconvert import PythonExporter
from tests.ge_test import GeoEngineTestInstance
def eprint(*args, **kwargs):
"""Print to stderr."""
print(*args, file=sys.stderr, **kwargs)
def parse_args() -> str:
"""Parse command-line arguments."""
parser = argparse.ArgumentParser(
prog="Jupyter Test Utility",
description="Runs a Jupyter Notebook to check for errors.",
)
parser.add_argument("filename", help="The Jupyter Notebook file to run.")
parameters = parser.parse_args()
return parameters.filename
def convert_to_python(input_file: str) -> str:
"""Convert the Jupyter Notebook to a Python file."""
exporter = PythonExporter()
notebook = nbformat.read(input_file, as_version=4)
(body, _resources) = exporter.from_notebook_node(notebook)
return body
def run_script(script: str) -> bool:
"""Run the script."""
code = compile(script, "<string>", "exec", flags=ast.PyCF_ALLOW_TOP_LEVEL_AWAIT)
try:
# prevent interactive backend to pop up
matplotlib.use("AGG")
with warnings.catch_warnings(record=True):
# pylint: disable-next=exec-used
exec(code, {})
eprint("SUCCESS")
return True
except Exception as error: # pylint: disable=broad-exception-caught
eprint("ERROR:", error)
return False
def setup_geoengine_and_run_script(input_file: str) -> bool:
"""Setup Geo Engine test instance and run the script."""
python_script = convert_to_python(input_file)
eprint(f"Running script `{input_file}`", end=": ")
with GeoEngineTestInstance(port=3030) as ge_instance:
ge_instance.wait_for_ready()
return run_script(python_script)
def main():
"""Main entry point."""
input_file = parse_args()
if setup_geoengine_and_run_script(input_file):
sys.exit(0)
else:
sys.exit(1)
def test_main():
"""Run main function with pytest"""
input_file = os.getenv("INPUT_FILE")
if not input_file:
raise AssertionError("INPUT_FILE environment variable not set")
if setup_geoengine_and_run_script(input_file):
assert True, "Notebook ran successfully"
else:
raise AssertionError("Notebook failed")
if __name__ == "__main__":
main()