xref: /petsc/config/report_tests.py (revision 6e5deea7f77aba86209a155046f38ed8ba4e1fc1)
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 get_test_data(directory):
116    """
117    Create dictionary structure with test data
118    """
119    startdir= os.getcwd()
120    try:
121        os.chdir(directory)
122    except OSError:
123        print('# No tests run')
124        return
125    # loop over *.counts files for all the problems tested in the test suite
126    testdata = {}
127    for cfile in glob.glob('*.counts'):
128        # first we get rid of the .counts extension, then we split the name in two
129        # to recover the problem name and the package it belongs to
130        fname = cfile.split('.')[0]
131        testname = fname.split('-')
132        probname = ''
133        for i in range(1,len(testname)):
134            probname += testname[i]
135        # we split the package into its subcomponents of PETSc module (e.g.: snes)
136        # and test type (e.g.: tutorial)
137        testname_list = testname[0].split('_')
138        pkgname = testname_list[0]
139        testtype = testname_list[-1]
140        # in order to correct assemble the folder path for problem outputs, we
141        # iterate over any possible subpackage names and test suffixes
142        testname_short = testname_list[:-1]
143        prob_subdir = os.path.join('', *testname_short)
144        probfolder = 'run%s'%probname
145        probdir = os.path.join('..', prob_subdir, 'examples', testtype, probfolder)
146        if not os.path.exists(probdir):
147            probfolder = probfolder.split('_')[0]
148            probdir = os.path.join('..', prob_subdir, 'examples', testtype, probfolder)
149        # assemble the final full folder path for problem outputs and read the files
150        try:
151            with open('%s/diff-%s.out'%(probdir, probfolder),'r') as probdiff:
152                difflines = probdiff.readlines()
153        except IOError:
154            difflines = []
155        try:
156            with open('%s/%s.err'%(probdir, probfolder),'r') as probstderr:
157                stderrlines = probstderr.readlines()
158        except IOError:
159            stderrlines = []
160        try:
161            with open('%s/%s.tmp'%(probdir, probname), 'r') as probstdout:
162                stdoutlines = probstdout.readlines()
163        except IOError:
164            stdoutlines = []
165        # join the package, subpackage and problem type names into a "class"
166        classname = pkgname
167        for item in testname_list[1:]:
168            classname += '.%s'%item
169        # if this is the first time we see this package, initialize its dict
170        if pkgname not in testdata.keys():
171            testdata[pkgname] = {
172                'total':0,
173                'success':0,
174                'failed':0,
175                'errors':0,
176                'todo':0,
177                'skip':0,
178                'time':0,
179                'problems':{}
180            }
181        # add the dict for the problem into the dict for the package
182        testdata[pkgname]['problems'][probname] = {
183            'classname':classname,
184            'time':0,
185            'failed':False,
186            'skipped':False,
187            'diff':difflines,
188            'stdout':stdoutlines,
189            'stderr':stderrlines
190        }
191        # process the *.counts file and increment problem status trackers
192        if len(testdata[pkgname]['problems'][probname]['stderr'])>0:
193            testdata[pkgname]['errors'] += 1
194        with open(cfile, 'r') as f:
195            for line in f:
196                l = line.split()
197                if l[0] == 'failed':
198                    testdata[pkgname]['problems'][probname][l[0]] = True
199                    testdata[pkgname][l[0]] += 1
200                elif l[0] == 'time':
201                    if len(l)==1: continue
202                    testdata[pkgname]['problems'][probname][l[0]] = float(l[1])
203                    testdata[pkgname][l[0]] += float(l[1])
204                elif l[0] == 'skip':
205                    testdata[pkgname]['problems'][probname][l[0]] = True
206                    testdata[pkgname][l[0]] += 1
207                elif l[0] not in testdata[pkgname].keys():
208                    continue
209                else:
210                    testdata[pkgname][l[0]] += 1
211    os.chdir(startdir)  # Keep function in good state
212    return testdata
213
214def show_fail(testdata):
215    """ Show the failures and commands to run them
216    """
217    for pkg in testdata.keys():
218        testsuite = testdata[pkg]
219        for prob in testsuite['problems'].keys():
220            p = testsuite['problems'][prob]
221            if p['skipped']:
222                # if we got here, the TAP output shows a skipped test
223                pass
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                print(p)
228                pass
229            elif len(p['diff'])>0:
230                # if we got here, the test output did not match the stored output file
231                # we show the diff between new output and old output under <failure>
232                print(p)
233                pass
234    return
235
236def generate_xml(testdata,directory):
237    """ write testdata information into a jUnit formatted XLM file
238    """
239    startdir= os.getcwd()
240    try:
241        os.chdir(directory)
242    except OSError:
243        print('# No tests run')
244        return
245    junit = open('../testresults.xml', 'w')
246    junit.write('<?xml version="1.0" ?>\n')
247    junit.write('<testsuites>\n')
248    for pkg in testdata.keys():
249        testsuite = testdata[pkg]
250        junit.write('  <testsuite errors="%i" failures="%i" name="%s" tests="%i">\n'%(
251            testsuite['errors'], testsuite['failed'], pkg, testsuite['total']))
252        for prob in testsuite['problems'].keys():
253            p = testsuite['problems'][prob]
254            junit.write('    <testcase classname="%s" name="%s" time="%f">\n'%(
255                p['classname'], prob, p['time']))
256            if p['skipped']:
257                # if we got here, the TAP output shows a skipped test
258                junit.write('      <skipped/>\n')
259            elif len(p['stderr'])>0:
260                # if we got here, the test crashed with an error
261                # we show the stderr output under <error>
262                junit.write('      <error type="crash">\n')
263                junit.write("<![CDATA[\n") # CDATA is necessary to preserve whitespace
264                for line in p['stderr']:
265                    junit.write("%s\n"%line.rstrip())
266                junit.write("]]>")
267                junit.write('      </error>\n')
268            elif len(p['diff'])>0:
269                # if we got here, the test output did not match the stored output file
270                # we show the diff between new output and old output under <failure>
271                junit.write('      <failure type="output">\n')
272                junit.write("<![CDATA[\n") # CDATA is necessary to preserve whitespace
273                for line in p['diff']:
274                    junit.write("%s\n"%line.rstrip())
275                junit.write("]]>")
276                junit.write('      </failure>\n')
277            elif len(p['stdout'])>0:
278                # if we got here, the test succeeded so we just show the stdout
279                # for manual sanity-checks
280                junit.write('      <system-out>\n')
281                junit.write("<![CDATA[\n") # CDATA is necessary to preserve whitespace
282                count = 0
283                for line in p['stdout']:
284                    junit.write("%s\n"%line.rstrip())
285                    count += 1
286                    if count >= 1024:
287                        break
288                junit.write("]]>")
289                junit.write('      </system-out>\n')
290            junit.write('    </testcase>\n')
291        junit.write('  </testsuite>\n')
292    junit.write('</testsuites>')
293    junit.close()
294    os.chdir(startdir)
295    return
296
297def main():
298    parser = optparse.OptionParser(usage="%prog [options]")
299    parser.add_option('-d', '--directory', dest='directory',
300                      help='Directory containing results of petsc test system',
301                      default=os.path.join(os.environ.get('PETSC_ARCH',''),
302                                           'tests','counts'))
303    parser.add_option('-e', '--elapsed_time', dest='elapsed_time',
304                      help='Report elapsed time in output',
305                      default=None)
306    parser.add_option('-m', '--make', dest='make',
307                      help='make executable to report in summary',
308                      default='make')
309    parser.add_option('-t', '--time', dest='time',
310                      help='-t n: Report on the n number expensive jobs',
311                      default=0)
312    parser.add_option('-f', '--fail', dest='show_fail', action="store_true",
313                      help='Show the failed tests and how to run them')
314    options, args = parser.parse_args()
315
316    # Process arguments
317    if len(args) > 0:
318      parser.print_usage()
319      return
320
321
322    if not options.show_fail:
323      summarize_results(options.directory,options.make,int(options.time),options.elapsed_time)
324    testresults=get_test_data(options.directory)
325
326    if options.show_fail:
327      show_fail(testresults)
328    else:
329      generate_xml(testresults, options.directory)
330
331if __name__ == "__main__":
332        main()
333