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