Merge remote branch 'gvdb/master'
[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   def binary_list (self):
114     lst = []
115     for name in self.binary_names:
116       lst += [ self.binaries[name] ]
117     return lst
118   def handle_testcase (self, node):
119     self.last_binary.testcases += [ node ]
120     result = attribute_as_text (node, 'result', 'status')
121     if result == 'success':
122       self.last_binary.success_cases += 1
123     if bool (int (attribute_as_text (node, 'skipped') + '0')):
124       self.last_binary.skipped_cases += 1
125   def handle_text (self, node):
126     pass
127   def handle_testbinary (self, node):
128     path = node.attributes.get ('path', None).value
129     if self.binaries.get (path, -1) == -1:
130       self.binaries[path] = TestBinary (path)
131       self.binary_names += [ path ]
132     self.last_binary = self.binaries[path]
133     dn = find_child (node, 'duration')
134     dur = node_as_text (dn)
135     try:        dur = float (dur)
136     except:     dur = 0
137     if dur:
138       self.last_binary.duration += dur
139     bin = find_child (node, 'binary')
140     if bin:
141       self.last_binary.file = attribute_as_text (bin, 'file')
142     rseed = find_child (node, 'random-seed')
143     if rseed:
144       self.last_binary.random_seed = node_as_text (rseed)
145     self.process_children (node)
146
147 # HTML report generation class
148 class ReportWriter (TreeProcess):
149   # Javascript/CSS snippet to toggle element visibility
150   cssjs = r'''
151   <style type="text/css" media="screen">
152     .VisibleSection { }
153     .HiddenSection  { display: none; }
154   </style>
155   <script language="javascript" type="text/javascript"><!--
156   function toggle_display (parentid, tagtype, idmatch, keymatch) {
157     ptag = document.getElementById (parentid);
158     tags = ptag.getElementsByTagName (tagtype);
159     for (var i = 0; i < tags.length; i++) {
160       tag = tags[i];
161       var key = tag.getAttribute ("keywords");
162       if (tag.id.indexOf (idmatch) == 0 && key && key.match (keymatch)) {
163         if (tag.className.indexOf ("HiddenSection") >= 0)
164           tag.className = "VisibleSection";
165         else
166           tag.className = "HiddenSection";
167       }
168     }
169   }
170   message_array = Array();
171   function view_testlog (wname, file, random_seed, tcase, msgtitle, msgid) {
172       txt = message_array[msgid];
173       var w = window.open ("", // URI
174                            wname,
175                            "resizable,scrollbars,status,width=790,height=400");
176       var doc = w.document;
177       doc.write ("<h2>File: " + file + "</h2>\n");
178       doc.write ("<h3>Case: " + tcase + "</h3>\n");
179       doc.write ("<strong>Random Seed:</strong> <code>" + random_seed + "</code> <br /><br />\n");
180       doc.write ("<strong>" + msgtitle + "</strong><br />\n");
181       doc.write ("<pre>");
182       doc.write (txt);
183       doc.write ("</pre>\n");
184       doc.write ("<a href=\'javascript:window.close()\'>Close Window</a>\n");
185       doc.close();
186   }
187   --></script>
188   '''
189   def __init__ (self, binary_list):
190     TreeProcess.__init__ (self)
191     self.binaries = binary_list
192     self.bcounter = 0
193     self.tcounter = 0
194     self.total_tcounter = 0
195     self.total_fcounter = 0
196     self.total_duration = 0
197     self.indent_depth = 0
198     self.lastchar = ''
199   def oprint (self, message):
200     sys.stdout.write (message)
201     if message:
202       self.lastchar = message[-1]
203   def handle_text (self, node):
204     self.oprint (node.nodeValue)
205   def handle_testcase (self, node, binary):
206     skipped = bool (int (attribute_as_text (node, 'skipped') + '0'))
207     if skipped:
208       return            # skipped tests are uninteresting for HTML reports
209     path = attribute_as_text (node, 'path')
210     duration = node_as_text (node, 'duration')
211     result = attribute_as_text (node, 'result', 'status')
212     rcolor = {
213       'success': 'bgcolor="lightgreen"',
214       'failed':  'bgcolor="red"',
215     }.get (result, '')
216     if result != 'success':
217       duration = '-'    # ignore bogus durations
218     self.oprint ('<tr id="b%u_t%u_" keywords="%s all" class="HiddenSection">\n' % (self.bcounter, self.tcounter, result))
219     self.oprint ('<td>%s %s</td> <td align="right">%s</td> \n' % (html_indent_string (4), path, duration))
220     perflist = list_children (node, 'performance')
221     if result != 'success':
222       rlist = list_children (node, 'error')
223       txt = ''
224       for enode in rlist:
225         txt += node_as_text (enode)
226         if txt and txt[-1] != '\n':
227           txt += '\n'
228       txt = re.sub (r'"', r'\\"', txt)
229       txt = re.sub (r'\n', r'\\n', txt)
230       txt = re.sub (r'&', r'&amp;', txt)
231       txt = re.sub (r'<', r'&lt;', txt)
232       self.oprint ('<script language="javascript" type="text/javascript">message_array["b%u_t%u_"] = "%s";</script>\n' % (self.bcounter, self.tcounter, txt))
233       self.oprint ('<td align="center"><a href="javascript:view_testlog (\'%s\', \'%s\', \'%s\', \'%s\', \'Output:\', \'b%u_t%u_\')">Details</a></td>\n' %
234                    ('TestResultWindow', binary.file, binary.random_seed, path, self.bcounter, self.tcounter))
235     elif perflist:
236       presults = []
237       for perf in perflist:
238         pmin = bool (int (attribute_as_text (perf, 'minimize')))
239         pmax = bool (int (attribute_as_text (perf, 'maximize')))
240         pval = float (attribute_as_text (perf, 'value'))
241         txt = node_as_text (perf)
242         txt = re.sub (r'&', r'&amp;', txt)
243         txt = re.sub (r'<', r'&gt;', txt)
244         txt = '<strong>Performance(' + (pmin and '<em>minimized</em>' or '<em>maximized</em>') + '):</strong> ' + txt.strip() + '<br />\n'
245         txt = re.sub (r'"', r'\\"', txt)
246         txt = re.sub (r'\n', r'\\n', txt)
247         presults += [ (pval, txt) ]
248       presults.sort()
249       ptxt = ''.join ([e[1] for e in presults])
250       self.oprint ('<script language="javascript" type="text/javascript">message_array["b%u_t%u_"] = "%s";</script>\n' % (self.bcounter, self.tcounter, ptxt))
251       self.oprint ('<td align="center"><a href="javascript:view_testlog (\'%s\', \'%s\', \'%s\', \'%s\', \'Test Results:\', \'b%u_t%u_\')">Details</a></td>\n' %
252                    ('TestResultWindow', binary.file, binary.random_seed, path, self.bcounter, self.tcounter))
253     else:
254       self.oprint ('<td align="center">-</td>\n')
255     self.oprint ('<td align="right" %s>%s</td>\n' % (rcolor, result))
256     self.oprint ('</tr>\n')
257     self.tcounter += 1
258     self.total_tcounter += 1
259     self.total_fcounter += result != 'success'
260   def handle_binary (self, binary):
261     self.tcounter = 1
262     self.bcounter += 1
263     self.total_duration += binary.duration
264     self.oprint ('<tr><td><strong>%s</strong></td><td align="right">%f</td> <td align="center">\n' % (binary.name, binary.duration))
265     erlink, oklink = ('', '')
266     real_cases = len (binary.testcases) - binary.skipped_cases
267     if binary.success_cases < real_cases:
268       erlink = 'href="javascript:toggle_display (\'ResultTable\', \'tr\', \'b%u_\', \'failed\')"' % self.bcounter
269     if binary.success_cases:
270       oklink = 'href="javascript:toggle_display (\'ResultTable\', \'tr\', \'b%u_\', \'success\')"' % self.bcounter
271     if real_cases != 0:
272         self.oprint ('<a %s>ER</a>\n' % erlink)
273         self.oprint ('<a %s>OK</a>\n' % oklink)
274         self.oprint ('</td>\n')
275         perc = binary.success_cases * 100.0 / real_cases
276         pcolor = {
277           100 : 'bgcolor="lightgreen"',
278           0   : 'bgcolor="red"',
279         }.get (int (perc), 'bgcolor="yellow"')
280         self.oprint ('<td align="right" %s>%.2f%%</td>\n' % (pcolor, perc))
281         self.oprint ('</tr>\n')
282     else:
283         self.oprint ('Empty\n')
284         self.oprint ('</td>\n')
285         self.oprint ('</tr>\n')
286     for tc in binary.testcases:
287       self.handle_testcase (tc, binary)
288   def handle_totals (self):
289     self.oprint ('<tr>')
290     self.oprint ('<td><strong>Totals:</strong> %u Binaries, %u Tests, %u Failed, %u Succeeded</td>' %
291                  (self.bcounter, self.total_tcounter, self.total_fcounter, self.total_tcounter - self.total_fcounter))
292     self.oprint ('<td align="right">%f</td>\n' % self.total_duration)
293     self.oprint ('<td align="center">-</td>\n')
294     perc = (self.total_tcounter - self.total_fcounter) * 100.0 / self.total_tcounter
295     pcolor = {
296       100 : 'bgcolor="lightgreen"',
297       0   : 'bgcolor="red"',
298     }.get (int (perc), 'bgcolor="yellow"')
299     self.oprint ('<td align="right" %s>%.2f%%</td>\n' % (pcolor, perc))
300     self.oprint ('</tr>\n')
301   def printout (self):
302     self.oprint ('<html><head>\n')
303     self.oprint ('<title>GTester Unit Test Report</title>\n')
304     self.oprint (self.cssjs)
305     self.oprint ('</head>\n')
306     self.oprint ('<body>\n')
307     self.oprint ('<h2>GTester Unit Test Report</h2>\n')
308     self.oprint ('<table id="ResultTable" width="100%" border="1">\n<tr>\n')
309     self.oprint ('<th>Program / Testcase </th>\n')
310     self.oprint ('<th style="width:8em">Duration (sec)</th>\n')
311     self.oprint ('<th style="width:5em">View</th>\n')
312     self.oprint ('<th style="width:5em">Result</th>\n')
313     self.oprint ('</tr>\n')
314     for tb in self.binaries:
315       self.handle_binary (tb)
316     self.handle_totals()
317     self.oprint ('</table>\n')
318     self.oprint ('</body>\n')
319     self.oprint ('</html>\n')
320
321 # main program handling
322 def parse_files_and_args ():
323   from sys import argv, stdin
324   files = []
325   arg_iter = sys.argv[1:].__iter__()
326   rest = len (sys.argv) - 1
327   for arg in arg_iter:
328     rest -= 1
329     if arg == '--help' or arg == '-h':
330       print_help ()
331       sys.exit (0)
332     elif arg == '--version' or arg == '-v':
333       print_help (False)
334       sys.exit (0)
335     else:
336       files = files + [ arg ]
337   return files
338
339 def print_help (with_help = True):
340   import os
341   print "gtester-report (GLib utils) version", pkginstall_configvars.get ('glib-version', '0.0-uninstalled')
342   if not with_help:
343     return
344   print "Usage: %s [OPTIONS] <gtester-log.xml>" % os.path.basename (sys.argv[0])
345   print "Generate HTML reports from the XML log files generated by gtester."
346   print "Options:"
347   print "  --help, -h                print this help message"
348   print "  --version, -v             print version info"
349
350 def main():
351   from sys import argv, stdin
352   files = parse_files_and_args()
353   if len (files) != 1:
354     print_help (True)
355     sys.exit (1)
356   xd = xml.dom.minidom.parse (files[0])
357   rr = ReportReader()
358   rr.trampoline (xd)
359   rw = ReportWriter (rr.binary_list())
360   rw.printout()
361
362 if __name__ == '__main__':
363   main()