1#!/usr/bin/env python 2from __future__ import print_function 3import glob, os, re 4import optparse 5import inspect 6 7""" 8Quick script for parsing the output of the test system and summarizing the results. 9""" 10 11def inInstallDir(): 12 """ 13 When petsc is installed then this file in installed in: 14 <PREFIX>/share/petsc/examples/config/gmakegentest.py 15 otherwise the path is: 16 <PETSC_DIR>/config/gmakegentest.py 17 We use this difference to determine if we are in installdir 18 """ 19 thisscriptdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) 20 dirlist=thisscriptdir.split(os.path.sep) 21 if len(dirlist)>4: 22 lastfour=os.path.sep.join(dirlist[len(dirlist)-4:]) 23 if lastfour==os.path.join('share','petsc','examples','config'): 24 return True 25 else: 26 return False 27 else: 28 return False 29 30def summarize_results(directory,make,ntime,etime): 31 ''' Loop over all of the results files and summarize the results''' 32 startdir = os.getcwd() 33 try: 34 os.chdir(directory) 35 except OSError: 36 print('# No tests run') 37 return 38 summary={'total':0,'success':0,'failed':0,'failures':[],'todo':0,'skip':0, 39 'time':0, 'cputime':0} 40 timesummary={} 41 cputimesummary={} 42 timelist=[] 43 for cfile in glob.glob('*.counts'): 44 with open(cfile, 'r') as f: 45 for line in f: 46 l = line.split() 47 if l[0] == 'failures': 48 if len(l)>1: 49 summary[l[0]] += l[1:] 50 elif l[0] == 'time': 51 if len(l)==1: continue 52 summary[l[0]] += float(l[1]) 53 summary['cputime'] += float(l[2]) 54 timesummary[cfile]=float(l[1]) 55 cputimesummary[cfile]=float(l[2]) 56 timelist.append(float(l[1])) 57 elif l[0] not in summary: 58 continue 59 else: 60 summary[l[0]] += int(l[1]) 61 62 failstr=' '.join(summary['failures']) 63 print("\n# -------------") 64 print("# Summary ") 65 print("# -------------") 66 if failstr.strip(): print("# FAILED " + failstr) 67 68 for t in "success failed todo skip".split(): 69 percent=summary[t]/float(summary['total'])*100 70 print("# %s %d/%d tests (%3.1f%%)" % (t, summary[t], summary['total'], percent)) 71 print("#") 72 if etime: 73 print("# Wall clock time for tests: %s sec"% etime) 74 print("# Approximate CPU time (not incl. build time): %s sec"% summary['cputime']) 75 76 if failstr.strip(): 77 fail_targets=( 78 re.sub('(?<=[0-9]_\w)_.*','', 79 re.sub('cmd-','', 80 re.sub('diff-','',failstr+' '))) 81 ) 82 # Strip off characters from subtests 83 fail_list=[] 84 for failure in fail_targets.split(): 85 if failure.count('-')>1: 86 fail_list.append('-'.join(failure.split('-')[:-1])) 87 else: 88 fail_list.append(failure) 89 fail_list=list(set(fail_list)) 90 fail_targets=' '.join(fail_list) 91 92 #Make the message nice 93 makefile="gmakefile.test" if inInstallDir() else "gmakefile" 94 95 print("#\n# To rerun failed tests: ") 96 print("# "+make+" -f "+makefile+" test search='" + fail_targets.strip()+"'") 97 98 if ntime>0: 99 print("#\n# Timing summary (actual test time / total CPU time): ") 100 timelist=list(set(timelist)) 101 timelist.sort(reverse=True) 102 nlim=(ntime if ntime<len(timelist) else len(timelist)) 103 # Do a double loop to sort in order 104 for timelimit in timelist[0:nlim]: 105 for cf in timesummary: 106 if timesummary[cf] == timelimit: 107 print("# %s: %.2f sec / %.2f sec" % (re.sub('.counts','',cf), timesummary[cf], cputimesummary[cf])) 108 os.chdir(startdir) 109 return 110 111def generate_xml(directory): 112 startdir= os.getcwd() 113 try: 114 os.chdir(directory) 115 except OSError: 116 print('# No tests run') 117 return 118 # loop over *.counts files for all the problems tested in the test suite 119 testdata = {} 120 for cfile in glob.glob('*.counts'): 121 # first we get rid of the .counts extension, then we split the name in two 122 # to recover the problem name and the package it belongs to 123 fname = cfile.split('.')[0] 124 testname = fname.split('-') 125 probname = testname[1] 126 # we split the package into its subcomponents of PETSc module (e.g.: snes) 127 # and test type (e.g.: tutorial) 128 testname_list = testname[0].split('_') 129 pkgname = testname_list[0] 130 testtype = testname_list[-1] 131 # in order to correct assemble the folder path for problem outputs, we 132 # iterate over any possible subpackage names 133 probfolder = 'run%s'%probname 134 if probfolder.split('_')[1] == '1': 135 probfolder = probfolder.split('_')[0] 136 testname_short = testname_list[:-1] 137 prob_subdir = os.path.join(*testname_short) 138 # assemble the final full folder path for problem outputs and read the files 139 probdir = os.path.join('..', prob_subdir, 'examples', testtype, probfolder) 140 try: 141 with open('%s/diff-%s.out'%(probdir, probfolder),'r') as probdiff: 142 difflines = probdiff.readlines() 143 except IOError: 144 difflines = [] 145 try: 146 with open('%s/%s.err'%(probdir, probfolder),'r') as probstderr: 147 stderrlines = probstderr.readlines() 148 except IOError: 149 stderrlines = [] 150 try: 151 with open('%s/%s.tmp'%(probdir, probname), 'r') as probstdout: 152 stdoutlines = probstdout.readlines() 153 except IOError: 154 stdoutlines = [] 155 # join the package, subpackage and problem type names into a "class" 156 classname = pkgname 157 for item in testname_list[1:]: 158 classname += '.%s'%item 159 # if this is the first time we see this package, initialize its dict 160 if pkgname not in testdata.keys(): 161 testdata[pkgname] = { 162 'total':0, 163 'success':0, 164 'failed':0, 165 'errors':0, 166 'todo':0, 167 'skip':0, 168 'time':0, 169 'problems':{} 170 } 171 # add the dict for the problem into the dict for the package 172 testdata[pkgname]['problems'][probname] = { 173 'classname':classname, 174 'time':0, 175 'failed':False, 176 'skipped':False, 177 'diff':difflines, 178 'stdout':stdoutlines, 179 'stderr':stderrlines 180 } 181 # process the *.counts file and increment problem status trackers 182 if len(testdata[pkgname]['problems'][probname]['stderr'])>0: 183 testdata[pkgname]['errors'] += 1 184 with open(cfile, 'r') as f: 185 for line in f: 186 l = line.split() 187 if l[0] == 'failed': 188 testdata[pkgname]['problems'][probname][l[0]] = True 189 testdata[pkgname][l[0]] += 1 190 elif l[0] == 'time': 191 if len(l)==1: continue 192 testdata[pkgname]['problems'][probname][l[0]] = float(l[1]) 193 testdata[pkgname][l[0]] += float(l[1]) 194 elif l[0] == 'skip': 195 testdata[pkgname]['problems'][probname][l[0]] = True 196 testdata[pkgname][l[0]] += 1 197 elif l[0] not in testdata[pkgname].keys(): 198 continue 199 else: 200 testdata[pkgname][l[0]] += 1 201 # at this point we have the complete test results in dictionary structures 202 # we can now write this information into a jUnit formatted XLM file 203 junit = open('../testresults.xml', 'w') 204 junit.write('<?xml version="1.0" ?>\n') 205 junit.write('<testsuites>\n') 206 for pkg in testdata.keys(): 207 testsuite = testdata[pkg] 208 junit.write(' <testsuite errors="%i" failures="%i" name="%s" tests="%i">\n'%( 209 testsuite['errors'], testsuite['failed'], pkg, testsuite['total'])) 210 for prob in testsuite['problems'].keys(): 211 p = testsuite['problems'][prob] 212 junit.write(' <testcase classname="%s" name="%s" time="%f">\n'%( 213 p['classname'], prob, p['time'])) 214 if p['skipped']: 215 # if we got here, the TAP output shows a skipped test 216 junit.write(' <skipped/>\n') 217 elif len(p['stderr'])>0: 218 # if we got here, the test crashed with an error 219 # we show the stderr output under <error> 220 junit.write(' <error type="crash">\n') 221 junit.write("<![CDATA[\n") # CDATA is necessary to preserve whitespace 222 for line in p['stderr']: 223 junit.write("%s\n"%line.rstrip()) 224 junit.write("]]>") 225 junit.write(' </error>\n') 226 elif len(p['diff'])>0: 227 # if we got here, the test output did not match the stored output file 228 # we show the diff between new output and old output under <failure> 229 junit.write(' <failure type="output">\n') 230 junit.write("<![CDATA[\n") # CDATA is necessary to preserve whitespace 231 for line in p['diff']: 232 junit.write("%s\n"%line.rstrip()) 233 junit.write("]]>") 234 junit.write(' </failure>\n') 235 elif len(p['stdout'])>0: 236 # if we got here, the test succeeded so we just show the stdout 237 # for manual sanity-checks 238 junit.write(' <system-out>\n') 239 junit.write("<![CDATA[\n") # CDATA is necessary to preserve whitespace 240 count = 0 241 for line in p['stdout']: 242 junit.write("%s\n"%line.rstrip()) 243 count += 1 244 if count >= 1024: 245 break 246 junit.write("]]>") 247 junit.write(' </system-out>\n') 248 junit.write(' </testcase>\n') 249 junit.write(' </testsuite>\n') 250 junit.write('</testsuites>') 251 junit.close() 252 os.chdir(startdir) 253 return 254 255def main(): 256 parser = optparse.OptionParser(usage="%prog [options]") 257 parser.add_option('-d', '--directory', dest='directory', 258 help='Directory containing results of petsc test system', 259 default=os.path.join(os.environ.get('PETSC_ARCH',''), 260 'tests','counts')) 261 parser.add_option('-e', '--elapsed_time', dest='elapsed_time', 262 help='Report elapsed time in output', 263 default=None) 264 parser.add_option('-m', '--make', dest='make', 265 help='make executable to report in summary', 266 default='make') 267 parser.add_option('-t', '--time', dest='time', 268 help='-t n: Report on the n number expensive jobs', 269 default=0) 270 options, args = parser.parse_args() 271 272 # Process arguments 273 if len(args) > 0: 274 parser.print_usage() 275 return 276 277 summarize_results(options.directory,options.make,int(options.time),options.elapsed_time) 278 279 generate_xml(options.directory) 280 281if __name__ == "__main__": 282 main() 283