Fix the wrong-category schema test
[glib.git] / glib / gtester-report
blob3bce548bf193acbd38c60baf516287ed6c49b90e
1 #! /usr/bin/env python
2 # GLib Testing Framework Utility -*- Mode: python; -*-
3 # Copyright (C) 2007 Imendio AB
4 # Authors: Tim Janik
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.
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.
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 datetime
21 import optparse
22 import sys, re, xml.dom.minidom
24 try:
25 import subunit
26 from subunit import iso8601
27 from testtools.content import Content, ContentType
28 mime_utf8 = ContentType('text', 'plain', {'charset': 'utf8'})
29 except ImportError:
30 subunit = None
33 pkginstall_configvars = {
34 #@PKGINSTALL_CONFIGVARS_IN24LINES@ # configvars are substituted upon script installation
37 # xml utilities
38 def find_child (node, child_name):
39 for child in node.childNodes:
40 if child.nodeName == child_name:
41 return child
42 return None
43 def list_children (node, child_name):
44 rlist = []
45 for child in node.childNodes:
46 if child.nodeName == child_name:
47 rlist += [ child ]
48 return rlist
49 def find_node (node, name = None):
50 if not node or node.nodeName == name or not name:
51 return node
52 for child in node.childNodes:
53 c = find_node (child, name)
54 if c:
55 return c
56 return None
57 def node_as_text (node, name = None):
58 if name:
59 node = find_node (node, name)
60 txt = ''
61 if node:
62 if node.nodeValue:
63 txt += node.nodeValue
64 for child in node.childNodes:
65 txt += node_as_text (child)
66 return txt
67 def attribute_as_text (node, aname, node_name = None):
68 node = find_node (node, node_name)
69 if not node:
70 return ''
71 attr = node.attributes.get (aname, '')
72 if hasattr (attr, 'value'):
73 return attr.value
74 return ''
76 # HTML utilities
77 def html_indent_string (n):
78 uncollapsible_space = '  ' # HTML won't compress alternating sequences of ' ' and ' '
79 string = ''
80 for i in range (0, (n + 1) / 2):
81 string += uncollapsible_space
82 return string
84 # TestBinary object, instantiated per test binary in the log file
85 class TestBinary:
86 def __init__ (self, name):
87 self.name = name
88 self.testcases = []
89 self.duration = 0
90 self.success_cases = 0
91 self.skipped_cases = 0
92 self.file = '???'
93 self.random_seed = ''
95 # base class to handle processing/traversion of XML nodes
96 class TreeProcess:
97 def __init__ (self):
98 self.nest_level = 0
99 def trampoline (self, node):
100 name = node.nodeName
101 if name == '#text':
102 self.handle_text (node)
103 else:
104 try: method = getattr (self, 'handle_' + re.sub ('[^a-zA-Z0-9]', '_', name))
105 except: method = None
106 if method:
107 return method (node)
108 else:
109 return self.process_recursive (name, node)
110 def process_recursive (self, node_name, node):
111 self.process_children (node)
112 def process_children (self, node):
113 self.nest_level += 1
114 for child in node.childNodes:
115 self.trampoline (child)
116 self.nest_level += 1
118 # test report reader, this class collects some statistics and merges duplicate test binary runs
119 class ReportReader (TreeProcess):
120 def __init__ (self):
121 TreeProcess.__init__ (self)
122 self.binary_names = []
123 self.binaries = {}
124 self.last_binary = None
125 self.info = {}
126 def binary_list (self):
127 lst = []
128 for name in self.binary_names:
129 lst += [ self.binaries[name] ]
130 return lst
131 def get_info (self):
132 return self.info
133 def handle_info (self, node):
134 dn = find_child (node, 'package')
135 self.info['package'] = node_as_text (dn)
136 dn = find_child (node, 'version')
137 self.info['version'] = node_as_text (dn)
138 def handle_testcase (self, node):
139 self.last_binary.testcases += [ node ]
140 result = attribute_as_text (node, 'result', 'status')
141 if result == 'success':
142 self.last_binary.success_cases += 1
143 if bool (int (attribute_as_text (node, 'skipped') + '0')):
144 self.last_binary.skipped_cases += 1
145 def handle_text (self, node):
146 pass
147 def handle_testbinary (self, node):
148 path = node.attributes.get ('path', None).value
149 if self.binaries.get (path, -1) == -1:
150 self.binaries[path] = TestBinary (path)
151 self.binary_names += [ path ]
152 self.last_binary = self.binaries[path]
153 dn = find_child (node, 'duration')
154 dur = node_as_text (dn)
155 try: dur = float (dur)
156 except: dur = 0
157 if dur:
158 self.last_binary.duration += dur
159 bin = find_child (node, 'binary')
160 if bin:
161 self.last_binary.file = attribute_as_text (bin, 'file')
162 rseed = find_child (node, 'random-seed')
163 if rseed:
164 self.last_binary.random_seed = node_as_text (rseed)
165 self.process_children (node)
168 class ReportWriter(object):
169 """Base class for reporting."""
171 def __init__(self, binary_list):
172 self.binaries = binary_list
174 def _error_text(self, node):
175 """Get a string representing the error children of node."""
176 rlist = list_children(node, 'error')
177 txt = ''
178 for enode in rlist:
179 txt += node_as_text (enode)
180 if txt and txt[-1] != '\n':
181 txt += '\n'
182 return txt
185 class HTMLReportWriter(ReportWriter):
186 # Javascript/CSS snippet to toggle element visibility
187 cssjs = r'''
188 <style type="text/css" media="screen">
189 .VisibleSection { }
190 .HiddenSection { display: none; }
191 </style>
192 <script language="javascript" type="text/javascript"><!--
193 function toggle_display (parentid, tagtype, idmatch, keymatch) {
194 ptag = document.getElementById (parentid);
195 tags = ptag.getElementsByTagName (tagtype);
196 for (var i = 0; i < tags.length; i++) {
197 tag = tags[i];
198 var key = tag.getAttribute ("keywords");
199 if (tag.id.indexOf (idmatch) == 0 && key && key.match (keymatch)) {
200 if (tag.className.indexOf ("HiddenSection") >= 0)
201 tag.className = "VisibleSection";
202 else
203 tag.className = "HiddenSection";
207 message_array = Array();
208 function view_testlog (wname, file, random_seed, tcase, msgtitle, msgid) {
209 txt = message_array[msgid];
210 var w = window.open ("", // URI
211 wname,
212 "resizable,scrollbars,status,width=790,height=400");
213 var doc = w.document;
214 doc.write ("<h2>File: " + file + "</h2>\n");
215 doc.write ("<h3>Case: " + tcase + "</h3>\n");
216 doc.write ("<strong>Random Seed:</strong> <code>" + random_seed + "</code> <br /><br />\n");
217 doc.write ("<strong>" + msgtitle + "</strong><br />\n");
218 doc.write ("<pre>");
219 doc.write (txt);
220 doc.write ("</pre>\n");
221 doc.write ("<a href=\'javascript:window.close()\'>Close Window</a>\n");
222 doc.close();
224 --></script>
226 def __init__ (self, info, binary_list):
227 ReportWriter.__init__(self, binary_list)
228 self.info = info
229 self.bcounter = 0
230 self.tcounter = 0
231 self.total_tcounter = 0
232 self.total_fcounter = 0
233 self.total_duration = 0
234 self.indent_depth = 0
235 self.lastchar = ''
236 def oprint (self, message):
237 sys.stdout.write (message)
238 if message:
239 self.lastchar = message[-1]
240 def handle_info (self):
241 self.oprint ('<h3>Package: %(package)s, version: %(version)s</h3>\n' % self.info)
242 def handle_text (self, node):
243 self.oprint (node.nodeValue)
244 def handle_testcase (self, node, binary):
245 skipped = bool (int (attribute_as_text (node, 'skipped') + '0'))
246 if skipped:
247 return # skipped tests are uninteresting for HTML reports
248 path = attribute_as_text (node, 'path')
249 duration = node_as_text (node, 'duration')
250 result = attribute_as_text (node, 'result', 'status')
251 rcolor = {
252 'success': 'bgcolor="lightgreen"',
253 'failed': 'bgcolor="red"',
254 }.get (result, '')
255 if result != 'success':
256 duration = '-' # ignore bogus durations
257 self.oprint ('<tr id="b%u_t%u_" keywords="%s all" class="HiddenSection">\n' % (self.bcounter, self.tcounter, result))
258 self.oprint ('<td>%s %s</td> <td align="right">%s</td> \n' % (html_indent_string (4), path, duration))
259 perflist = list_children (node, 'performance')
260 if result != 'success':
261 txt = self._error_text(node)
262 txt = re.sub (r'"', r'\\"', txt)
263 txt = re.sub (r'\n', r'\\n', txt)
264 txt = re.sub (r'&', r'&amp;', txt)
265 txt = re.sub (r'<', r'&lt;', txt)
266 self.oprint ('<script language="javascript" type="text/javascript">message_array["b%u_t%u_"] = "%s";</script>\n' % (self.bcounter, self.tcounter, txt))
267 self.oprint ('<td align="center"><a href="javascript:view_testlog (\'%s\', \'%s\', \'%s\', \'%s\', \'Output:\', \'b%u_t%u_\')">Details</a></td>\n' %
268 ('TestResultWindow', binary.file, binary.random_seed, path, self.bcounter, self.tcounter))
269 elif perflist:
270 presults = []
271 for perf in perflist:
272 pmin = bool (int (attribute_as_text (perf, 'minimize')))
273 pmax = bool (int (attribute_as_text (perf, 'maximize')))
274 pval = float (attribute_as_text (perf, 'value'))
275 txt = node_as_text (perf)
276 txt = re.sub (r'&', r'&amp;', txt)
277 txt = re.sub (r'<', r'&gt;', txt)
278 txt = '<strong>Performance(' + (pmin and '<em>minimized</em>' or '<em>maximized</em>') + '):</strong> ' + txt.strip() + '<br />\n'
279 txt = re.sub (r'"', r'\\"', txt)
280 txt = re.sub (r'\n', r'\\n', txt)
281 presults += [ (pval, txt) ]
282 presults.sort()
283 ptxt = ''.join ([e[1] for e in presults])
284 self.oprint ('<script language="javascript" type="text/javascript">message_array["b%u_t%u_"] = "%s";</script>\n' % (self.bcounter, self.tcounter, ptxt))
285 self.oprint ('<td align="center"><a href="javascript:view_testlog (\'%s\', \'%s\', \'%s\', \'%s\', \'Test Results:\', \'b%u_t%u_\')">Details</a></td>\n' %
286 ('TestResultWindow', binary.file, binary.random_seed, path, self.bcounter, self.tcounter))
287 else:
288 self.oprint ('<td align="center">-</td>\n')
289 self.oprint ('<td align="right" %s>%s</td>\n' % (rcolor, result))
290 self.oprint ('</tr>\n')
291 self.tcounter += 1
292 self.total_tcounter += 1
293 self.total_fcounter += result != 'success'
294 def handle_binary (self, binary):
295 self.tcounter = 1
296 self.bcounter += 1
297 self.total_duration += binary.duration
298 self.oprint ('<tr><td><strong>%s</strong></td><td align="right">%f</td> <td align="center">\n' % (binary.name, binary.duration))
299 erlink, oklink = ('', '')
300 real_cases = len (binary.testcases) - binary.skipped_cases
301 if binary.success_cases < real_cases:
302 erlink = 'href="javascript:toggle_display (\'ResultTable\', \'tr\', \'b%u_\', \'failed\')"' % self.bcounter
303 if binary.success_cases:
304 oklink = 'href="javascript:toggle_display (\'ResultTable\', \'tr\', \'b%u_\', \'success\')"' % self.bcounter
305 if real_cases != 0:
306 self.oprint ('<a %s>ER</a>\n' % erlink)
307 self.oprint ('<a %s>OK</a>\n' % oklink)
308 self.oprint ('</td>\n')
309 perc = binary.success_cases * 100.0 / real_cases
310 pcolor = {
311 100 : 'bgcolor="lightgreen"',
312 0 : 'bgcolor="red"',
313 }.get (int (perc), 'bgcolor="yellow"')
314 self.oprint ('<td align="right" %s>%.2f%%</td>\n' % (pcolor, perc))
315 self.oprint ('</tr>\n')
316 else:
317 self.oprint ('Empty\n')
318 self.oprint ('</td>\n')
319 self.oprint ('</tr>\n')
320 for tc in binary.testcases:
321 self.handle_testcase (tc, binary)
322 def handle_totals (self):
323 self.oprint ('<tr>')
324 self.oprint ('<td><strong>Totals:</strong> %u Binaries, %u Tests, %u Failed, %u Succeeded</td>' %
325 (self.bcounter, self.total_tcounter, self.total_fcounter, self.total_tcounter - self.total_fcounter))
326 self.oprint ('<td align="right">%f</td>\n' % self.total_duration)
327 self.oprint ('<td align="center">-</td>\n')
328 if self.total_tcounter != 0:
329 perc = (self.total_tcounter - self.total_fcounter) * 100.0 / self.total_tcounter
330 else:
331 perc = 0.0
332 pcolor = {
333 100 : 'bgcolor="lightgreen"',
334 0 : 'bgcolor="red"',
335 }.get (int (perc), 'bgcolor="yellow"')
336 self.oprint ('<td align="right" %s>%.2f%%</td>\n' % (pcolor, perc))
337 self.oprint ('</tr>\n')
338 def printout (self):
339 self.oprint ('<html><head>\n')
340 self.oprint ('<title>GTester Unit Test Report</title>\n')
341 self.oprint (self.cssjs)
342 self.oprint ('</head>\n')
343 self.oprint ('<body>\n')
344 self.oprint ('<h2>GTester Unit Test Report</h2>\n')
345 self.handle_info ()
346 self.oprint ('<table id="ResultTable" width="100%" border="1">\n<tr>\n')
347 self.oprint ('<th>Program / Testcase </th>\n')
348 self.oprint ('<th style="width:8em">Duration (sec)</th>\n')
349 self.oprint ('<th style="width:5em">View</th>\n')
350 self.oprint ('<th style="width:5em">Result</th>\n')
351 self.oprint ('</tr>\n')
352 for tb in self.binaries:
353 self.handle_binary (tb)
354 self.handle_totals()
355 self.oprint ('</table>\n')
356 self.oprint ('</body>\n')
357 self.oprint ('</html>\n')
360 class SubunitWriter(ReportWriter):
361 """Reporter to output a subunit stream."""
363 def printout(self):
364 reporter = subunit.TestProtocolClient(sys.stdout)
365 for binary in self.binaries:
366 for tc in binary.testcases:
367 test = GTestCase(tc, binary)
368 test.run(reporter)
371 class GTestCase(object):
372 """A representation of a gtester test result as a pyunit TestCase."""
374 def __init__(self, case, binary):
375 """Create a GTestCase for case `case` from binary program `binary`."""
376 self._case = case
377 self._binary = binary
378 # the name of the case - e.g. /dbusmenu/glib/objects/menuitem/props_boolstr
379 self._path = attribute_as_text(self._case, 'path')
381 def id(self):
382 """What test is this? Returns the gtester path for the testcase."""
383 return self._path
385 def _get_details(self):
386 """Calculate a details dict for the test - attachments etc."""
387 details = {}
388 result = attribute_as_text(self._case, 'result', 'status')
389 details['filename'] = Content(mime_utf8, lambda:[self._binary.file])
390 details['random_seed'] = Content(mime_utf8,
391 lambda:[self._binary.random_seed])
392 if self._get_outcome() == 'addFailure':
393 # Extract the error details. Skips have no details because its not
394 # skip like unittest does, instead the runner just bypasses N test.
395 txt = self._error_text(self._case)
396 details['error'] = Content(mime_utf8, lambda:[txt])
397 if self._get_outcome() == 'addSuccess':
398 # Sucessful tests may have performance metrics.
399 perflist = list_children(self._case, 'performance')
400 if perflist:
401 presults = []
402 for perf in perflist:
403 pmin = bool (int (attribute_as_text (perf, 'minimize')))
404 pmax = bool (int (attribute_as_text (perf, 'maximize')))
405 pval = float (attribute_as_text (perf, 'value'))
406 txt = node_as_text (perf)
407 txt = 'Performance(' + (pmin and 'minimized' or 'maximized'
408 ) + '): ' + txt.strip() + '\n'
409 presults += [(pval, txt)]
410 presults.sort()
411 perf_details = [e[1] for e in presults]
412 details['performance'] = Content(mime_utf8, lambda:perf_details)
413 return details
415 def _get_outcome(self):
416 if int(attribute_as_text(self._case, 'skipped') + '0'):
417 return 'addSkip'
418 outcome = attribute_as_text(self._case, 'result', 'status')
419 if outcome == 'success':
420 return 'addSuccess'
421 else:
422 return 'addFailure'
424 def run(self, result):
425 time = datetime.datetime.utcnow().replace(tzinfo=iso8601.Utc())
426 result.time(time)
427 result.startTest(self)
428 try:
429 outcome = self._get_outcome()
430 details = self._get_details()
431 # Only provide a duration IFF outcome == 'addSuccess' - the main
432 # parser claims bogus results otherwise: in that case emit time as
433 # zero perhaps.
434 if outcome == 'addSuccess':
435 duration = float(node_as_text(self._case, 'duration'))
436 duration = duration * 1000000
437 timedelta = datetime.timedelta(0, 0, duration)
438 time = time + timedelta
439 result.time(time)
440 getattr(result, outcome)(self, details=details)
441 finally:
442 result.stopTest(self)
446 # main program handling
447 def parse_opts():
448 """Parse program options.
450 :return: An options object and the program arguments.
452 parser = optparse.OptionParser()
453 parser.version = pkginstall_configvars.get ('glib-version', '0.0-uninstalled')
454 parser.usage = "%prog [OPTIONS] <gtester-log.xml>"
455 parser.description = "Generate HTML reports from the XML log files generated by gtester."
456 parser.epilog = "gtester-report (GLib utils) version %s."% (parser.version,)
457 parser.add_option("-v", "--version", action="store_true", dest="version", default=False,
458 help="Show program version.")
459 parser.add_option("-s", "--subunit", action="store_true", dest="subunit", default=False,
460 help="Output subunit [See https://launchpad.net/subunit/"
461 " Needs python-subunit]")
462 options, files = parser.parse_args()
463 if options.version:
464 print parser.epilog
465 return None, None
466 if len(files) != 1:
467 parser.error("Must supply a log file to parse.")
468 if options.subunit and subunit is None:
469 parser.error("python-subunit is not installed.")
470 return options, files
473 def main():
474 options, files = parse_opts()
475 if options is None:
476 return 0
477 xd = xml.dom.minidom.parse (files[0])
478 rr = ReportReader()
479 rr.trampoline (xd)
480 if not options.subunit:
481 HTMLReportWriter(rr.get_info(), rr.binary_list()).printout()
482 else:
483 SubunitWriter(rr.get_info(), rr.binary_list()).printout()
486 if __name__ == '__main__':
487 main()