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('cmd-','', 79 re.sub('diff-','',failstr+' ')) 80 ) 81 print(fail_targets) 82 # Strip off characters from subtests 83 fail_list=[] 84 for failure in fail_targets.split(): 85 if failure.split('-')[1].count('_')>1: 86 froot=failure.split('-')[0] 87 flabel='_'.join(failure.split('-')[1].split('_')[0:1]) 88 fail_list.append(froot+'-'+flabel+'_*') 89 elif failure.count('-')>1: 90 fail_list.append('-'.join(failure.split('-')[:-1])) 91 else: 92 fail_list.append(failure) 93 fail_list=list(set(fail_list)) 94 fail_targets=' '.join(fail_list) 95 96 #Make the message nice 97 makefile="gmakefile.test" if inInstallDir() else "gmakefile" 98 99 print("#\n# To rerun failed tests: ") 100 print("# "+make+" -f "+makefile+" test globsearch='" + fail_targets.strip()+"'") 101 102 if ntime>0: 103 print("#\n# Timing summary (actual test time / total CPU time): ") 104 timelist=list(set(timelist)) 105 timelist.sort(reverse=True) 106 nlim=(ntime if ntime<len(timelist) else len(timelist)) 107 # Do a double loop to sort in order 108 for timelimit in timelist[0:nlim]: 109 for cf in timesummary: 110 if timesummary[cf] == timelimit: 111 print("# %s: %.2f sec / %.2f sec" % (re.sub('.counts','',cf), timesummary[cf], cputimesummary[cf])) 112 os.chdir(startdir) 113 return 114 115def generate_xml(directory): 116 startdir= os.getcwd() 117 try: 118 os.chdir(directory) 119 except OSError: 120 print('# No tests run') 121 return 122 # loop over *.counts files for all the problems tested in the test suite 123 testdata = {} 124 for cfile in glob.glob('*.counts'): 125 # first we get rid of the .counts extension, then we split the name in two 126 # to recover the problem name and the package it belongs to 127 fname = cfile.split('.')[0] 128 testname = fname.split('-') 129 probname = '' 130 for i in range(1,len(testname)): 131 probname += testname[i] 132 # we split the package into its subcomponents of PETSc module (e.g.: snes) 133 # and test type (e.g.: tutorial) 134 testname_list = testname[0].split('_') 135 pkgname = testname_list[0] 136 testtype = testname_list[-1] 137 # in order to correct assemble the folder path for problem outputs, we 138 # iterate over any possible subpackage names and test suffixes 139 testname_short = testname_list[:-1] 140 prob_subdir = os.path.join('', *testname_short) 141 probfolder = 'run%s'%probname 142 probdir = os.path.join('..', prob_subdir, 'examples', testtype, probfolder) 143 if not os.path.exists(probdir): 144 probfolder = probfolder.split('_')[0] 145 probdir = os.path.join('..', prob_subdir, 'examples', testtype, probfolder) 146 # assemble the final full folder path for problem outputs and read the files 147 try: 148 with open('%s/diff-%s.out'%(probdir, probfolder),'r') as probdiff: 149 difflines = probdiff.readlines() 150 except IOError: 151 difflines = [] 152 try: 153 with open('%s/%s.err'%(probdir, probfolder),'r') as probstderr: 154 stderrlines = probstderr.readlines() 155 except IOError: 156 stderrlines = [] 157 try: 158 with open('%s/%s.tmp'%(probdir, probname), 'r') as probstdout: 159 stdoutlines = probstdout.readlines() 160 except IOError: 161 stdoutlines = [] 162 # join the package, subpackage and problem type names into a "class" 163 classname = pkgname 164 for item in testname_list[1:]: 165 classname += '.%s'%item 166 # if this is the first time we see this package, initialize its dict 167 if pkgname not in testdata.keys(): 168 testdata[pkgname] = { 169 'total':0, 170 'success':0, 171 'failed':0, 172 'errors':0, 173 'todo':0, 174 'skip':0, 175 'time':0, 176 'problems':{} 177 } 178 # add the dict for the problem into the dict for the package 179 testdata[pkgname]['problems'][probname] = { 180 'classname':classname, 181 'time':0, 182 'failed':False, 183 'skipped':False, 184 'diff':difflines, 185 'stdout':stdoutlines, 186 'stderr':stderrlines 187 } 188 # process the *.counts file and increment problem status trackers 189 if len(testdata[pkgname]['problems'][probname]['stderr'])>0: 190 testdata[pkgname]['errors'] += 1 191 with open(cfile, 'r') as f: 192 for line in f: 193 l = line.split() 194 if l[0] == 'failed': 195 testdata[pkgname]['problems'][probname][l[0]] = True 196 testdata[pkgname][l[0]] += 1 197 elif l[0] == 'time': 198 if len(l)==1: continue 199 testdata[pkgname]['problems'][probname][l[0]] = float(l[1]) 200 testdata[pkgname][l[0]] += float(l[1]) 201 elif l[0] == 'skip': 202 testdata[pkgname]['problems'][probname][l[0]] = True 203 testdata[pkgname][l[0]] += 1 204 elif l[0] not in testdata[pkgname].keys(): 205 continue 206 else: 207 testdata[pkgname][l[0]] += 1 208 # at this point we have the complete test results in dictionary structures 209 # we can now write this information into a jUnit formatted XLM file 210 junit = open('../testresults.xml', 'w') 211 junit.write('<?xml version="1.0" ?>\n') 212 junit.write('<testsuites>\n') 213 for pkg in testdata.keys(): 214 testsuite = testdata[pkg] 215 junit.write(' <testsuite errors="%i" failures="%i" name="%s" tests="%i">\n'%( 216 testsuite['errors'], testsuite['failed'], pkg, testsuite['total'])) 217 for prob in testsuite['problems'].keys(): 218 p = testsuite['problems'][prob] 219 junit.write(' <testcase classname="%s" name="%s" time="%f">\n'%( 220 p['classname'], prob, p['time'])) 221 if p['skipped']: 222 # if we got here, the TAP output shows a skipped test 223 junit.write(' <skipped/>\n') 224 elif len(p['stderr'])>0: 225 # if we got here, the test crashed with an error 226 # we show the stderr output under <error> 227 junit.write(' <error type="crash">\n') 228 junit.write("<![CDATA[\n") # CDATA is necessary to preserve whitespace 229 for line in p['stderr']: 230 junit.write("%s\n"%line.rstrip()) 231 junit.write("]]>") 232 junit.write(' </error>\n') 233 elif len(p['diff'])>0: 234 # if we got here, the test output did not match the stored output file 235 # we show the diff between new output and old output under <failure> 236 junit.write(' <failure type="output">\n') 237 junit.write("<![CDATA[\n") # CDATA is necessary to preserve whitespace 238 for line in p['diff']: 239 junit.write("%s\n"%line.rstrip()) 240 junit.write("]]>") 241 junit.write(' </failure>\n') 242 elif len(p['stdout'])>0: 243 # if we got here, the test succeeded so we just show the stdout 244 # for manual sanity-checks 245 junit.write(' <system-out>\n') 246 junit.write("<![CDATA[\n") # CDATA is necessary to preserve whitespace 247 count = 0 248 for line in p['stdout']: 249 junit.write("%s\n"%line.rstrip()) 250 count += 1 251 if count >= 1024: 252 break 253 junit.write("]]>") 254 junit.write(' </system-out>\n') 255 junit.write(' </testcase>\n') 256 junit.write(' </testsuite>\n') 257 junit.write('</testsuites>') 258 junit.close() 259 os.chdir(startdir) 260 return 261 262def main(): 263 parser = optparse.OptionParser(usage="%prog [options]") 264 parser.add_option('-d', '--directory', dest='directory', 265 help='Directory containing results of petsc test system', 266 default=os.path.join(os.environ.get('PETSC_ARCH',''), 267 'tests','counts')) 268 parser.add_option('-e', '--elapsed_time', dest='elapsed_time', 269 help='Report elapsed time in output', 270 default=None) 271 parser.add_option('-m', '--make', dest='make', 272 help='make executable to report in summary', 273 default='make') 274 parser.add_option('-t', '--time', dest='time', 275 help='-t n: Report on the n number expensive jobs', 276 default=0) 277 options, args = parser.parse_args() 278 279 # Process arguments 280 if len(args) > 0: 281 parser.print_usage() 282 return 283 284 summarize_results(options.directory,options.make,int(options.time),options.elapsed_time) 285 286 generate_xml(options.directory) 287 288if __name__ == "__main__": 289 main() 290