Add package and version to the test report XML
[platform/upstream/glib.git] / glib / gtester-report
1 #! /usr/bin/env python
2 # GLib Testing Framework Utility                        -*- Mode: python; -*-
3 # Copyright (C) 2007 Imendio AB
4 # Authors: Tim Janik
5 #
6 # This library is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU Lesser General Public
8 # License as published by the Free Software Foundation; either
9 # version 2 of the License, or (at your option) any later version.
10 #
11 # This library is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 # Lesser General Public License for more details.
15 #
16 # You should have received a copy of the GNU Lesser General Public
17 # License along with this library; if not, write to the
18 # Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 # Boston, MA 02111-1307, USA.
20 import sys, re, xml.dom.minidom
21 pkginstall_configvars = {
22   #@PKGINSTALL_CONFIGVARS_IN24LINES@ # configvars are substituted upon script installation
23 }
24
25 # xml utilities
26 def find_child (node, child_name):
27   for child in node.childNodes:
28     if child.nodeName == child_name:
29       return child
30   return None
31 def list_children (node, child_name):
32   rlist = []
33   for child in node.childNodes:
34     if child.nodeName == child_name:
35       rlist += [ child ]
36   return rlist
37 def find_node (node, name = None):
38   if not node or node.nodeName == name or not name:
39     return node
40   for child in node.childNodes:
41     c = find_node (child, name)
42     if c:
43       return c
44   return None
45 def node_as_text (node, name = None):
46   if name:
47     node = find_node (node, name)
48   txt = ''
49   if node:
50     if node.nodeValue:
51       txt += node.nodeValue
52     for child in node.childNodes:
53       txt += node_as_text (child)
54   return txt
55 def attribute_as_text (node, aname, node_name = None):
56   node = find_node (node, node_name)
57   if not node:
58     return ''
59   attr = node.attributes.get (aname, '')
60   if hasattr (attr, 'value'):
61     return attr.value
62   return ''
63
64 # HTML utilities
65 def html_indent_string (n):
66   uncollapsible_space = '  ' # HTML won't compress alternating sequences of ' ' and ' '
67   string = ''
68   for i in range (0, (n + 1) / 2):
69     string += uncollapsible_space
70   return string
71
72 # TestBinary object, instantiated per test binary in the log file
73 class TestBinary:
74   def __init__ (self, name):
75     self.name = name
76     self.testcases = []
77     self.duration = 0
78     self.success_cases = 0
79     self.skipped_cases = 0
80     self.file = '???'
81     self.random_seed = ''
82
83 # base class to handle processing/traversion of XML nodes
84 class TreeProcess:
85   def __init__ (self):
86     self.nest_level = 0
87   def trampoline (self, node):
88     name = node.nodeName
89     if name == '#text':
90       self.handle_text (node)
91     else:
92       try:      method = getattr (self, 'handle_' + re.sub ('[^a-zA-Z0-9]', '_', name))
93       except:   method = None
94       if method:
95         return method (node)
96       else:
97         return self.process_recursive (name, node)
98   def process_recursive (self, node_name, node):
99     self.process_children (node)
100   def process_children (self, node):
101     self.nest_level += 1
102     for child in node.childNodes:
103       self.trampoline (child)
104     self.nest_level += 1
105
106 # test report reader, this class collects some statistics and merges duplicate test binary runs
107 class ReportReader (TreeProcess):
108   def __init__ (self):
109     TreeProcess.__init__ (self)
110     self.binary_names = []
111     self.binaries = {}
112     self.last_binary = None
113     self.info = {}
114   def binary_list (self):
115     lst = []
116     for name in self.binary_names:
117       lst += [ self.binaries[name] ]
118     return lst
119   def get_info (self):
120     return self.info
121   def handle_info (self, node):
122     dn = find_child (node, 'package')
123     self.info['package'] = node_as_text (dn)
124     dn = find_child (node, 'version')
125     self.info['version'] = node_as_text (dn)
126   def handle_testcase (self, node):
127     self.last_binary.testcases += [ node ]
128     result = attribute_as_text (node, 'result', 'status')
129     if result == 'success':
130       self.last_binary.success_cases += 1
131     if bool (int (attribute_as_text (node, 'skipped') + '0')):
132       self.last_binary.skipped_cases += 1
133   def handle_text (self, node):
134     pass
135   def handle_testbinary (self, node):
136     path = node.attributes.get ('path', None).value
137     if self.binaries.get (path, -1) == -1:
138       self.binaries[path] = TestBinary (path)
139       self.binary_names += [ path ]
140     self.last_binary = self.binaries[path]
141     dn = find_child (node, 'duration')
142     dur = node_as_text (dn)
143     try:        dur = float (dur)
144     except:     dur = 0
145     if dur:
146       self.last_binary.duration += dur
147     bin = find_child (node, 'binary')
148     if bin:
149       self.last_binary.file = attribute_as_text (bin, 'file')
150     rseed = find_child (node, 'random-seed')
151     if rseed:
152       self.last_binary.random_seed = node_as_text (rseed)
153     self.process_children (node)
154
155 # HTML report generation class
156 class ReportWriter (TreeProcess):
157   # Javascript/CSS snippet to toggle element visibility
158   cssjs = r'''
159   <style type="text/css" media="screen">
160     .VisibleSection { }
161     .HiddenSection  { display: none; }
162   </style>
163   <script language="javascript" type="text/javascript"><!--
164   function toggle_display (parentid, tagtype, idmatch, keymatch) {
165     ptag = document.getElementById (parentid);
166     tags = ptag.getElementsByTagName (tagtype);
167     for (var i = 0; i < tags.length; i++) {
168       tag = tags[i];
169       var key = tag.getAttribute ("keywords");
170       if (tag.id.indexOf (idmatch) == 0 && key && key.match (keymatch)) {
171         if (tag.className.indexOf ("HiddenSection") >= 0)
172           tag.className = "VisibleSection";
173         else
174           tag.className = "HiddenSection";
175       }
176     }
177   }
178   message_array = Array();
179   function view_testlog (wname, file, random_seed, tcase, msgtitle, msgid) {
180       txt = message_array[msgid];
181       var w = window.open ("", // URI
182                            wname,
183                            "resizable,scrollbars,status,width=790,height=400");
184       var doc = w.document;
185       doc.write ("<h2>File: " + file + "</h2>\n");
186       doc.write ("<h3>Case: " + tcase + "</h3>\n");
187       doc.write ("<strong>Random Seed:</strong> <code>" + random_seed + "</code> <br /><br />\n");
188       doc.write ("<strong>" + msgtitle + "</strong><br />\n");
189       doc.write ("<pre>");
190       doc.write (txt);
191       doc.write ("</pre>\n");
192       doc.write ("<a href=\'javascript:window.close()\'>Close Window</a>\n");
193       doc.close();
194   }
195   --></script>
196   '''
197   def __init__ (self, info, binary_list):
198     TreeProcess.__init__ (self)
199     self.info = info
200     self.binaries = binary_list
201     self.bcounter = 0
202     self.tcounter = 0
203     self.total_tcounter = 0
204     self.total_fcounter = 0
205     self.total_duration = 0
206     self.indent_depth = 0
207     self.lastchar = ''
208   def oprint (self, message):
209     sys.stdout.write (message)
210     if message:
211       self.lastchar = message[-1]
212   def handle_info (self):
213     self.oprint ('<h3>Package: %(package)s, version: %(version)s</h3>\n' % self.info)
214   def handle_text (self, node):
215     self.oprint (node.nodeValue)
216   def handle_testcase (self, node, binary):
217     skipped = bool (int (attribute_as_text (node, 'skipped') + '0'))
218     if skipped:
219       return            # skipped tests are uninteresting for HTML reports
220     path = attribute_as_text (node, 'path')
221     duration = node_as_text (node, 'duration')
222     result = attribute_as_text (node, 'result', 'status')
223     rcolor = {
224       'success': 'bgcolor="lightgreen"',
225       'failed':  'bgcolor="red"',
226     }.get (result, '')
227     if result != 'success':
228       duration = '-'    # ignore bogus durations
229     self.oprint ('<tr id="b%u_t%u_" keywords="%s all" class="HiddenSection">\n' % (self.bcounter, self.tcounter, result))
230     self.oprint ('<td>%s %s</td> <td align="right">%s</td> \n' % (html_indent_string (4), path, duration))
231     perflist = list_children (node, 'performance')
232     if result != 'success':
233       rlist = list_children (node, 'error')
234       txt = ''
235       for enode in rlist:
236         txt += node_as_text (enode)
237         if txt and txt[-1] != '\n':
238           txt += '\n'
239       txt = re.sub (r'"', r'\\"', txt)
240       txt = re.sub (r'\n', r'\\n', txt)
241       txt = re.sub (r'&', r'&amp;', txt)
242       txt = re.sub (r'<', r'&lt;', txt)
243       self.oprint ('<script language="javascript" type="text/javascript">message_array["b%u_t%u_"] = "%s";</script>\n' % (self.bcounter, self.tcounter, txt))
244       self.oprint ('<td align="center"><a href="javascript:view_testlog (\'%s\', \'%s\', \'%s\', \'%s\', \'Output:\', \'b%u_t%u_\')">Details</a></td>\n' %
245                    ('TestResultWindow', binary.file, binary.random_seed, path, self.bcounter, self.tcounter))
246     elif perflist:
247       presults = []
248       for perf in perflist:
249         pmin = bool (int (attribute_as_text (perf, 'minimize')))
250         pmax = bool (int (attribute_as_text (perf, 'maximize')))
251         pval = float (attribute_as_text (perf, 'value'))
252         txt = node_as_text (perf)
253         txt = re.sub (r'&', r'&amp;', txt)
254         txt = re.sub (r'<', r'&gt;', txt)
255         txt = '<strong>Performance(' + (pmin and '<em>minimized</em>' or '<em>maximized</em>') + '):</strong> ' + txt.strip() + '<br />\n'
256         txt = re.sub (r'"', r'\\"', txt)
257         txt = re.sub (r'\n', r'\\n', txt)
258         presults += [ (pval, txt) ]
259       presults.sort()
260       ptxt = ''.join ([e[1] for e in presults])
261       self.oprint ('<script language="javascript" type="text/javascript">message_array["b%u_t%u_"] = "%s";</script>\n' % (self.bcounter, self.tcounter, ptxt))
262       self.oprint ('<td align="center"><a href="javascript:view_testlog (\'%s\', \'%s\', \'%s\', \'%s\', \'Test Results:\', \'b%u_t%u_\')">Details</a></td>\n' %
263                    ('TestResultWindow', binary.file, binary.random_seed, path, self.bcounter, self.tcounter))
264     else:
265       self.oprint ('<td align="center">-</td>\n')
266     self.oprint ('<td align="right" %s>%s</td>\n' % (rcolor, result))
267     self.oprint ('</tr>\n')
268     self.tcounter += 1
269     self.total_tcounter += 1
270     self.total_fcounter += result != 'success'
271   def handle_binary (self, binary):
272     self.tcounter = 1
273     self.bcounter += 1
274     self.total_duration += binary.duration
275     self.oprint ('<tr><td><strong>%s</strong></td><td align="right">%f</td> <td align="center">\n' % (binary.name, binary.duration))
276     erlink, oklink = ('', '')
277     real_cases = len (binary.testcases) - binary.skipped_cases
278     if binary.success_cases < real_cases:
279       erlink = 'href="javascript:toggle_display (\'ResultTable\', \'tr\', \'b%u_\', \'failed\')"' % self.bcounter
280     if binary.success_cases:
281       oklink = 'href="javascript:toggle_display (\'ResultTable\', \'tr\', \'b%u_\', \'success\')"' % self.bcounter
282     if real_cases != 0:
283         self.oprint ('<a %s>ER</a>\n' % erlink)
284         self.oprint ('<a %s>OK</a>\n' % oklink)
285         self.oprint ('</td>\n')
286         perc = binary.success_cases * 100.0 / real_cases
287         pcolor = {
288           100 : 'bgcolor="lightgreen"',
289           0   : 'bgcolor="red"',
290         }.get (int (perc), 'bgcolor="yellow"')
291         self.oprint ('<td align="right" %s>%.2f%%</td>\n' % (pcolor, perc))
292         self.oprint ('</tr>\n')
293     else:
294         self.oprint ('Empty\n')
295         self.oprint ('</td>\n')
296         self.oprint ('</tr>\n')
297     for tc in binary.testcases:
298       self.handle_testcase (tc, binary)
299   def handle_totals (self):
300     self.oprint ('<tr>')
301     self.oprint ('<td><strong>Totals:</strong> %u Binaries, %u Tests, %u Failed, %u Succeeded</td>' %
302                  (self.bcounter, self.total_tcounter, self.total_fcounter, self.total_tcounter - self.total_fcounter))
303     self.oprint ('<td align="right">%f</td>\n' % self.total_duration)
304     self.oprint ('<td align="center">-</td>\n')
305     perc = (self.total_tcounter - self.total_fcounter) * 100.0 / self.total_tcounter
306     pcolor = {
307       100 : 'bgcolor="lightgreen"',
308       0   : 'bgcolor="red"',
309     }.get (int (perc), 'bgcolor="yellow"')
310     self.oprint ('<td align="right" %s>%.2f%%</td>\n' % (pcolor, perc))
311     self.oprint ('</tr>\n')
312   def printout (self):
313     self.oprint ('<html><head>\n')
314     self.oprint ('<title>GTester Unit Test Report</title>\n')
315     self.oprint (self.cssjs)
316     self.oprint ('</head>\n')
317     self.oprint ('<body>\n')
318     self.oprint ('<h2>GTester Unit Test Report</h2>\n')
319     self.handle_info ()
320     self.oprint ('<table id="ResultTable" width="100%" border="1">\n<tr>\n')
321     self.oprint ('<th>Program / Testcase </th>\n')
322     self.oprint ('<th style="width:8em">Duration (sec)</th>\n')
323     self.oprint ('<th style="width:5em">View</th>\n')
324     self.oprint ('<th style="width:5em">Result</th>\n')
325     self.oprint ('</tr>\n')
326     for tb in self.binaries:
327       self.handle_binary (tb)
328     self.handle_totals()
329     self.oprint ('</table>\n')
330     self.oprint ('</body>\n')
331     self.oprint ('</html>\n')
332
333 # main program handling
334 def parse_files_and_args ():
335   from sys import argv, stdin
336   files = []
337   arg_iter = sys.argv[1:].__iter__()
338   rest = len (sys.argv) - 1
339   for arg in arg_iter:
340     rest -= 1
341     if arg == '--help' or arg == '-h':
342       print_help ()
343       sys.exit (0)
344     elif arg == '--version' or arg == '-v':
345       print_help (False)
346       sys.exit (0)
347     else:
348       files = files + [ arg ]
349   return files
350
351 def print_help (with_help = True):
352   import os
353   print "gtester-report (GLib utils) version", pkginstall_configvars.get ('glib-version', '0.0-uninstalled')
354   if not with_help:
355     return
356   print "Usage: %s [OPTIONS] <gtester-log.xml>" % os.path.basename (sys.argv[0])
357   print "Generate HTML reports from the XML log files generated by gtester."
358   print "Options:"
359   print "  --help, -h                print this help message"
360   print "  --version, -v             print version info"
361
362 def main():
363   from sys import argv, stdin
364   files = parse_files_and_args()
365   if len (files) != 1:
366     print_help (True)
367     sys.exit (1)
368   xd = xml.dom.minidom.parse (files[0])
369   rr = ReportReader()
370   rr.trampoline (xd)
371   rw = ReportWriter (rr.get_info(), rr.binary_list())
372   rw.printout()
373
374 if __name__ == '__main__':
375   main()