11import os
2- from pathlib import Path
2+ from pathlib import Path , PurePath
33
44import pytest
55
66NOTEBOOK_EXT = '.ipynb'
77ROOT_DIR = 'jupyter-notebooks'
88
9- # do not look for notebooks in .ipynb_checkpoints dir
10- SKIP_DIRECTORIES = ['.ipynb_checkpoints' ]
9+ # do not run notebooks in these directories or sub-directories
10+ SKIP_DIRECTORIES = set ( ['.ipynb_checkpoints' ])
1111
1212def pytest_addoption (parser ):
1313 parser .addoption ("--path" , action = "store" ,
@@ -30,13 +30,15 @@ def pytest_generate_tests(metafunc):
3030
3131 if 'notebook_path' in metafunc .fixturenames :
3232 if notebooks :
33- notebook_paths = notebooks
33+ notebook_paths = [ Path ( n ) for n in notebooks ]
3434 else :
3535 root_path = normalize_path (option_path )
36- notebook_paths = find_notebooks (root_path )
36+ notebook_paths = get_all_paths (root_path )
3737
38+ notebook_paths = valid_notebooks (notebook_paths )
3839 metafunc .parametrize (['notebook_path' , 'do_skip' ],
39- zip (notebook_paths , [do_skip ] * len (notebook_paths )))
40+ zip ([str (p ) for p in notebook_paths ],
41+ [do_skip ] * len (notebook_paths )))
4042
4143
4244def normalize_path (path ):
@@ -48,24 +50,29 @@ def normalize_path(path):
4850 return os .path .join (* path_parts )
4951
5052
51- def find_notebooks (root_dir ):
52- '''Find all of the notebooks within the root directory.
53+ def get_all_paths (root_dir ):
54+ paths = []
55+ for path , _ , files in os .walk (root_dir ):
56+ for name in files :
57+ paths .append (PurePath (path , name ))
58+ return paths
5359
54- Skip notebooks and subdirectories of any directory with 'norun' file
55- '''
56- print ('finding notebooks in {}...' .format (root_dir ))
57- notebooks = []
5860
59- for (dirpath , dirnames , filenames ) in os .walk (root_dir ):
60- # modify in place to filter subdirectories in walk()
61- # https://stackoverflow.com/questions/19859840/excluding-directories-in-os-walk
62- dirnames [:] = [n for n in dirnames if n not in SKIP_DIRECTORIES ]
61+ def valid_notebooks (paths ):
62+ '''Filters a list of paths to only include valid notebooks.
63+
64+ Removes paths that include skip directories and paths that do not end
65+ in notebook extension, .ipynb'''
66+ valid_paths = [p for p in paths if not _in_skip_dir (p ) and _is_notebook (p )]
67+ print (' {} out of {} paths are valid' .format (len (valid_paths ), len (paths )))
68+ return valid_paths
6369
64- for name in filenames :
65- ext = os .path .splitext (name )[1 ]
66- if ext == NOTEBOOK_EXT :
67- # convert to string so test displays the path
68- notebook_name = str (os .path .join (dirpath , name ))
69- notebooks .append (notebook_name )
70- print ('found {} notebooks' .format (len (notebooks )))
71- return notebooks
70+
71+ def _in_skip_dir (path ):
72+ '''path is a Path object'''
73+ return len (SKIP_DIRECTORIES .intersection (path .parts )) > 0
74+
75+
76+ def _is_notebook (path ):
77+ '''path is a Path object'''
78+ return path .suffix == NOTEBOOK_EXT
0 commit comments