/
test_examples.py
86 lines (70 loc) · 2.64 KB
/
test_examples.py
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
from glob import glob
from pathlib import Path
from pytest import fixture, mark, skip
import os
import subprocess
from .conftest import patch_plots
cwd = os.getcwd()
@fixture(scope="session")
def examples_directory(tmp_path_factory):
from shutil import copytree
exdir = Path(__file__).parent.parent / "examples"
target = tmp_path_factory.getbasetemp() / "examples"
copytree(exdir, target)
return target
def example_scripts():
exdir = Path(__file__).parent.parent / "examples"
scripts = sorted([os.path.basename(f) for f in glob(str(exdir / "*.py"))])
return scripts
def example_notebooks():
exdir = Path(__file__).parent.parent / "examples" / "notebooks"
scripts = sorted([os.path.basename(f) for f in glob(str(exdir / "*.ipynb"))])
return scripts
@patch_plots
@mark.parametrize("example", example_scripts())
def test_example_scripts(example, examples_directory):
env = os.environ.copy()
env["PYTHONWARNINGS"] = "ignore"
with open(examples_directory / example) as fp:
script = "import matplotlib\nmatplotlib.use('Agg')\n" + fp.read()
process = subprocess.run(
["python", "-c", script],
capture_output=True,
cwd=str(examples_directory),
env=env,
)
if b"SpiceSolverError" in process.stderr:
skip("No SPICE solver found.")
elif b"SmartsSolverError" in process.stderr:
skip("No SMARTS solver found.")
elif b"RCWASolverError" in process.stderr:
skip("No RCWA solver found.")
elif process.stderr != b"":
raise Exception(process.stderr.decode())
@patch_plots
@mark.parametrize("example", example_notebooks())
def test_example_notebooks(example, examples_directory):
import nbconvert
import nbformat
exporter = nbconvert.PythonExporter()
notebooks_folder = examples_directory / "notebooks"
env = os.environ.copy()
env["PYTHONWARNINGS"] = "ignore"
with open(notebooks_folder / example) as fp:
nbcode = nbformat.reads(fp.read(), as_version=4)
(code, _) = exporter.from_notebook_node(nbcode)
script = "import matplotlib\nmatplotlib.use('Agg')\n" + code
process = subprocess.run(
["python", "-c", script],
capture_output=True,
cwd=str(notebooks_folder),
env=env,
)
if b"SpiceSolverError" in process.stderr:
skip("No SPICE solver found.")
elif b"SmartsSolverError" in process.stderr:
skip("No SMARTS solver found.")
elif b"RCWASolverError" in process.stderr:
skip("No RCWA solver found.")
elif process.stderr != b"":
raise Exception(process.stderr.decode())