# AUTOGENERATED! DO NOT EDIT! File to edit: notebooks/02_tests.ipynb (unless otherwise specified).

__all__ = ['test_notebooks']

# Cell
import os
import subprocess

from fastcore.script import *
from nbdev.test import *
from nbdev.test import nbglob, num_cpus, parallel, _test_one, Path
from kicad_helpers import get_git_root, setup_test_repo, get_project_name, get_schematic_path, get_bom_path
from .core import _set_root

# Cell
@call_parse
def test_notebooks(fname:Param("A notebook name or glob to convert", str)=None,
                   flags:Param("Space separated list of flags", str)=None,
                   n_workers:Param("Number of workers to use", int)=None,
                   verbose:Param("Print errors along the way", bool_arg)=True,
                   timing:Param("Timing each notebook to see the ones are slow", bool)=False,
                   pause:Param("Pause time (in secs) between notebooks to avoid race conditions", float)=0.5,
                   root:Param("project root directory", str)="."):
    "Test in parallel the notebooks matching `fname`, passing along `flags`"
    root = _set_root(root)
    if flags is not None: flags = flags.split(' ')
    if fname is None:
        fname = os.path.join(root, "tests", "*.ipynb")
    files = nbglob(fname, recursive=False)
    files = [Path(f).absolute() for f in sorted(files)]
    assert len(files) > 0, "No files to test found."
    if n_workers is None: n_workers = 0 if len(files)==1 else min(num_cpus(), 8)
    # make sure we are inside the tests folder
    os.chdir(os.path.join(root, "tests"))
    results = parallel(_test_one, files, flags=flags, verbose=verbose, n_workers=n_workers, pause=pause)
    passed,times = [r[0] for r in results],[r[1] for r in results]
    if all(passed): print("All tests are passing!")
    else:
        msg = "The following notebooks failed:\n"
        raise Exception(msg + '\n'.join([f.name for p,f in zip(passed,files) if not p]))
    if timing:
        for i,t in sorted(enumerate(times), key=lambda o:o[1], reverse=True):
            print(f"Notebook {files[i].name} took {int(t)} seconds")