11import os
22import subprocess
3+ import tempfile
34
45import nbformat
5- import pytest
6-
76
87_TEST_DIR = os .path .abspath (os .path .dirname (__file__ ))
98_EXCLUDE = ["Python_intro.ipynb" , "animate-landlab-output.ipynb" ]
109
1110
12- def all_notebooks ():
11+ def all_notebooks (path = "." ):
1312 notebooks = []
14- for root , dirs , files in os .walk (_TEST_DIR ):
13+ for root , dirs , files in os .walk (path ):
14+ if ".ipynb_checkpoints" in root :
15+ continue
1516 for file in files :
16- if (
17- file .endswith (".ipynb" )
18- and (file not in _EXCLUDE )
19- and ("checkpoint" not in file )
20- ):
17+ if file .endswith (".ipynb" ) and (file not in _EXCLUDE ):
2118 notebooks .append (os .path .join (root , file ))
2219 return notebooks
2320
2421
2522def pytest_generate_tests (metafunc ):
2623 if "notebook" in metafunc .fixturenames :
27- metafunc .parametrize ("notebook" , all_notebooks ())
24+ metafunc .parametrize ("notebook" , all_notebooks (_TEST_DIR ))
2825
2926
3027def _notebook_run (path ):
3128 """Execute a notebook via nbconvert and collect output.
3229 :returns (parsed nb object, execution errors)
3330 """
34- dirname , __ = os .path .split (path )
35- os .chdir (dirname )
36-
37- in_fn = os .path .split (path )[- 1 ].split ("." )[0 ]
38- temp_file_prefix = "output_" + in_fn
39- temp_file_out = temp_file_prefix + ".ipynb"
40-
41- args = [
42- "jupyter" ,
43- "nbconvert" ,
44- "--to" ,
45- "notebook" ,
46- "--execute" ,
47- "--ExecutePreprocessor.kernel_name=python" ,
48- "--ExecutePreprocessor.timeout=None" ,
49- "--output" ,
50- temp_file_prefix ,
51- path ,
52- ]
53- subprocess .check_call (args )
54-
55- nb = nbformat .read (temp_file_out , nbformat .current_nbformat , encoding = "UTF-8" )
31+ _ , notebook = os .path .split (path )
32+ base , ext = os .path .splitext (notebook )
33+
34+ with tempfile .NamedTemporaryFile ("w" , suffix = ".ipynb" ) as fp :
35+ args = [
36+ "jupyter" ,
37+ "nbconvert" ,
38+ "--to" ,
39+ "notebook" ,
40+ "--execute" ,
41+ "--ExecutePreprocessor.kernel_name=python" ,
42+ "--ExecutePreprocessor.timeout=None" ,
43+ "--output" ,
44+ fp .name ,
45+ "--output-dir=." ,
46+ path ,
47+ ]
48+ subprocess .check_call (args )
49+
50+ nb = nbformat .read (fp .name , nbformat .current_nbformat , encoding = "UTF-8" )
5651
5752 errors = [
5853 output
@@ -61,7 +56,6 @@ def _notebook_run(path):
6156 for output in cell ["outputs" ]
6257 if output .output_type == "error"
6358 ]
64- os .remove (temp_file_out )
6559
6660 return nb , errors
6761
0 commit comments