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