1
1
#!/usr/bin/env python
2
2
# coding: utf-8
3
+ from datetime import datetime
4
+ startTime = datetime .now ()
3
5
4
6
import itertools
5
7
import json
8
+ import multiprocessing as mp
6
9
import os
7
- import subprocess
8
10
import sys
9
11
import time
10
12
try :
15
17
sys .exit ("""Some libraries are missing. Please install them by running `pip install -r test_requirements.txt`.""" )
16
18
17
19
# CONSTANTS
20
+ manager = mp .Manager ()
18
21
TEST_NOTEBOOKS_FILE = 'testnotebooks.txt'
19
22
TEST_CONFIG_FILE = 'testconfig.csv'
20
- SUCCESSES = 0
21
- EXCEPTIONS = 0
22
- SUCCESSFUL_EXECUTIONS = []
23
- FAILED_EXECUTIONS = []
23
+ SUCCESSES = mp . Value ( 'd' , 0 )
24
+ EXCEPTIONS = mp . Value ( 'd' , 0 )
25
+ SUCCESSFUL_EXECUTIONS = manager . list ()
26
+ FAILED_EXECUTIONS = manager . list ()
24
27
CELL_EXECUTION_TIMEOUT_SECONDS = 1200
28
+ ROOT = os .path .abspath ('.' )
29
+
30
+ jobs = []
25
31
26
32
27
33
# helper functions
28
- def run_notebook (nb_path , test_config ):
29
- dir_name = os .path .dirname (nb_path )
34
+
35
+ def execute_nb_with_params (nb_path , params ):
36
+ abs_nb_dir_path = os .path .join (ROOT , os .path .dirname (nb_path ))
30
37
nb_name = os .path .basename (nb_path )
31
38
output_nb_name = "output_{}.ipynb" .format (nb_name )
32
- os .chdir (dir_name )
39
+ os .chdir (abs_nb_dir_path )
33
40
print ("Current directory: {}" .format (os .getcwd ()))
34
- global SUCCESSES
35
- global EXCEPTIONS
36
- for i in range (len (test_config )):
37
- params = json .loads (test_config .loc [i ].to_json ())
41
+ print ("RUN: " + nb_name + " with parameters " + str (params ))
42
+ # Execute notebook
43
+ test_case = dict ({'notebook' :nb_name , 'params' :params })
44
+ try :
45
+ papermill .execute_notebook (nb_name , output_nb_name , parameters = params , execution_timeout = CELL_EXECUTION_TIMEOUT_SECONDS , log_output = True )
46
+ SUCCESSES .value += 1
47
+ SUCCESSFUL_EXECUTIONS .append (test_case )
48
+ except BaseException as error :
49
+ print ('An exception occurred: {}' .format (error ))
50
+ EXCEPTIONS .value += 1
51
+ FAILED_EXECUTIONS .append (test_case )
52
+ os .chdir (ROOT )
53
+
54
+
55
+ def test_notebook (nb_path , df_test_config ):
56
+ for i in range (len (df_test_config )):
57
+ params = json .loads (df_test_config .loc [i ].to_json ())
38
58
# Coach notebooks support only single instance training, so skip the tests with multiple EC2 instances
39
- if 'coach' in nb_name .lower () and params ['train_instance_count' ] > 1 :
59
+ if 'coach' in nb_path .lower () and params ['train_instance_count' ] > 1 :
40
60
continue
41
- print ("\n TEST: " + nb_name + " with parameters " + str (params ))
42
- process = None
43
- try :
44
- papermill .execute_notebook (nb_name , output_nb_name , parameters = params , execution_timeout = CELL_EXECUTION_TIMEOUT_SECONDS , log_output = True )
45
- SUCCESSES += 1
46
- SUCCESSFUL_EXECUTIONS .append (dict ({'notebook' :nb_name , 'params' :params }))
47
- except BaseException as error :
48
- print ('An exception occurred: {}' .format (error ))
49
- EXCEPTIONS += 1
50
- FAILED_EXECUTIONS .append (dict ({'notebook' :nb_name , 'params' :params }))
61
+ p = mp .Process (target = execute_nb_with_params , args = (nb_path , params ))
62
+ time .sleep (1 )
63
+ jobs .append (p )
64
+ p .start ()
65
+
66
+
51
67
52
68
def print_notebook_executions (nb_list_with_params ):
53
69
# This expects a list of dict type items.
@@ -65,26 +81,30 @@ def print_notebook_executions(nb_list_with_params):
65
81
print (tabulate (pd .DataFrame ([v for v in vals ], columns = keys ), showindex = False ))
66
82
67
83
84
+ if __name__ == "__main__" :
85
+ notebooks_list = open (TEST_NOTEBOOKS_FILE ).readlines ()
86
+ config = pd .read_csv (TEST_CONFIG_FILE )
87
+ # Run tests on each notebook listed in the config.
88
+ print ("Test Configuration: " )
89
+ print (config )
68
90
69
- notebooks_list = open ( TEST_NOTEBOOKS_FILE ). readlines ()
70
- config = pd . read_csv ( TEST_CONFIG_FILE )
71
- ROOT = os . path . abspath ( '.' )
91
+ for nb_path in notebooks_list :
92
+ print ( "Testing: {}" . format ( nb_path ) )
93
+ test_notebook ( nb_path . strip (), config )
72
94
73
- # Run tests on each notebook listed in the config.
74
- print ("Test Configuration: " )
75
- print (config )
76
- for nb_path in notebooks_list :
77
- os .chdir (ROOT )
78
- print ("Testing: {}" .format (nb_path ))
79
- run_notebook (nb_path .strip (), config )
80
-
81
- # Print summary of tests ran.
82
- print ("Summary: {}/{} tests passed." .format (SUCCESSES , SUCCESSES + EXCEPTIONS ))
83
- print ("Successful executions: " )
84
- print_notebook_executions (SUCCESSFUL_EXECUTIONS )
85
-
86
- # Throw exception if any test fails, so that the CodeBuild also fails.
87
- if EXCEPTIONS > 0 :
88
- print ("Failed executions: " )
89
- print_notebook_executions (FAILED_EXECUTIONS )
90
- raise Exception ("Test did not complete successfully" )
95
+ for job in jobs :
96
+ job .join ()
97
+
98
+ # Print summary of tests ran.
99
+ print ("Summary: {}/{} tests passed." .format (SUCCESSES .value , SUCCESSES .value + EXCEPTIONS .value ))
100
+ print ("Successful executions: " )
101
+ print_notebook_executions (SUCCESSFUL_EXECUTIONS )
102
+
103
+ # Throw exception if any test fails, so that the CodeBuild also fails.
104
+ if EXCEPTIONS .value > 0 :
105
+ print ("Failed executions: " )
106
+ print_notebook_executions (FAILED_EXECUTIONS )
107
+ raise Exception ("Test did not complete successfully" )
108
+
109
+ print ("Total time taken for tests: " )
110
+ print (datetime .now () - startTime )
0 commit comments