1#  _______________________________________________________________________
2#
3#  PECOS: Parallel Environment for Creation Of Stochastics
4#  Copyright (c) 2011, Sandia National Laboratories.
5#  This software is distributed under the GNU Lesser General Public License.
6#  For more information, see the README file in the top Pecos directory.
7#  _______________________________________________________________________
8
9import os, glob, subprocess, tempfile, nbformat
10
11def run_notebook(path):
12    """
13    Execute a notebook via nbconvert and collect the output.
14
15    Parameters
16    ----------
17    path : string
18        The full filename (including path) of the notebook
19
20    Returns
21    -------
22    notebook : notebook object
23        The parsed notebook
24
25    errors : list
26        errors found whilst executing notebook
27    """
28    dirname, __ = os.path.split(path)
29    #print dirname == None
30    #os.chdir(dirname)
31    with tempfile.NamedTemporaryFile(suffix=".ipynb") as fout:
32        args = ["jupyter", "nbconvert", "--to", "notebook", "--execute",
33          "--ExecutePreprocessor.timeout=60",
34          "--ExecutePreprocessor.kernel_name=python",
35          "--ExecutePreprocessor.allow_errors=True",
36          "--output", fout.name, path]
37        subprocess.call(args)
38
39        fout.seek(0)
40        notebook = nbformat.read(fout,nbformat.current_nbformat)
41
42    errors = [output for cell in notebook.cells if "outputs" in cell
43                     for output in cell["outputs"]\
44                     if output.output_type == "error"]
45
46    return notebook, errors
47
48if __name__== '__main__':
49
50    filenames = ['Multivariate Function Approximation With Dakota.ipynb']
51    for filename in filenames:
52        # Test if any Exceptions or assert violations were thrown
53        notebook, errors = run_notebook(filename)
54        assert errors == []
55