2 # GLib Testing Framework Utility -*- Mode: python; -*-
3 # Copyright (C) 2007 Imendio AB
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, see <http://www.gnu.org/licenses/>.
20 import sys
, re
, xml
.dom
.minidom
24 from subunit
import iso8601
25 from testtools
.content
import Content
, ContentType
26 mime_utf8
= ContentType('text', 'plain', {'charset': 'utf8'})
31 pkginstall_configvars
= {
32 #@PKGINSTALL_CONFIGVARS_IN24LINES@ # configvars are substituted upon script installation
36 def find_child (node
, child_name
):
37 for child
in node
.childNodes
:
38 if child
.nodeName
== child_name
:
41 def list_children (node
, child_name
):
43 for child
in node
.childNodes
:
44 if child
.nodeName
== child_name
:
47 def find_node (node
, name
= None):
48 if not node
or node
.nodeName
== name
or not name
:
50 for child
in node
.childNodes
:
51 c
= find_node (child
, name
)
55 def node_as_text (node
, name
= None):
57 node
= find_node (node
, name
)
62 for child
in node
.childNodes
:
63 txt
+= node_as_text (child
)
65 def attribute_as_text (node
, aname
, node_name
= None):
66 node
= find_node (node
, node_name
)
69 attr
= node
.attributes
.get (aname
, '')
70 if hasattr (attr
, 'value'):
75 def html_indent_string (n
):
76 uncollapsible_space
= ' ' # HTML won't compress alternating sequences of ' ' and ' '
78 for i
in range (0, (n
+ 1) / 2):
79 string
+= uncollapsible_space
82 # TestBinary object, instantiated per test binary in the log file
84 def __init__ (self
, name
):
88 self
.success_cases
= 0
89 self
.skipped_cases
= 0
93 # base class to handle processing/traversion of XML nodes
97 def trampoline (self
, node
):
100 self
.handle_text (node
)
102 try: method
= getattr (self
, 'handle_' + re
.sub ('[^a-zA-Z0-9]', '_', name
))
103 except: method
= None
107 return self
.process_recursive (name
, node
)
108 def process_recursive (self
, node_name
, node
):
109 self
.process_children (node
)
110 def process_children (self
, node
):
112 for child
in node
.childNodes
:
113 self
.trampoline (child
)
116 # test report reader, this class collects some statistics and merges duplicate test binary runs
117 class ReportReader (TreeProcess
):
119 TreeProcess
.__init
__ (self
)
120 self
.binary_names
= []
122 self
.last_binary
= None
124 def binary_list (self
):
126 for name
in self
.binary_names
:
127 lst
+= [ self
.binaries
[name
] ]
131 def handle_info (self
, node
):
132 dn
= find_child (node
, 'package')
133 self
.info
['package'] = node_as_text (dn
)
134 dn
= find_child (node
, 'version')
135 self
.info
['version'] = node_as_text (dn
)
136 dn
= find_child (node
, 'revision')
138 self
.info
['revision'] = node_as_text (dn
)
139 def handle_testcase (self
, node
):
140 self
.last_binary
.testcases
+= [ node
]
141 result
= attribute_as_text (node
, 'result', 'status')
142 if result
== 'success':
143 self
.last_binary
.success_cases
+= 1
144 if bool (int (attribute_as_text (node
, 'skipped') + '0')):
145 self
.last_binary
.skipped_cases
+= 1
146 def handle_text (self
, node
):
148 def handle_testbinary (self
, node
):
149 path
= node
.attributes
.get ('path', None).value
150 if self
.binaries
.get (path
, -1) == -1:
151 self
.binaries
[path
] = TestBinary (path
)
152 self
.binary_names
+= [ path
]
153 self
.last_binary
= self
.binaries
[path
]
154 dn
= find_child (node
, 'duration')
155 dur
= node_as_text (dn
)
156 try: dur
= float (dur
)
159 self
.last_binary
.duration
+= dur
160 bin
= find_child (node
, 'binary')
162 self
.last_binary
.file = attribute_as_text (bin
, 'file')
163 rseed
= find_child (node
, 'random-seed')
165 self
.last_binary
.random_seed
= node_as_text (rseed
)
166 self
.process_children (node
)
169 class ReportWriter(object):
170 """Base class for reporting."""
172 def __init__(self
, binary_list
):
173 self
.binaries
= binary_list
175 def _error_text(self
, node
):
176 """Get a string representing the error children of node."""
177 rlist
= list_children(node
, 'error')
180 txt
+= node_as_text (enode
)
181 if txt
and txt
[-1] != '\n':
186 class HTMLReportWriter(ReportWriter
):
187 # Javascript/CSS snippet to toggle element visibility
189 <style type="text/css" media="screen">
191 .HiddenSection { display: none; }
193 <script language="javascript" type="text/javascript"><!--
194 function toggle_display (parentid, tagtype, idmatch, keymatch) {
195 ptag = document.getElementById (parentid);
196 tags = ptag.getElementsByTagName (tagtype);
197 for (var i = 0; i < tags.length; i++) {
199 var key = tag.getAttribute ("keywords");
200 if (tag.id.indexOf (idmatch) == 0 && key && key.match (keymatch)) {
201 if (tag.className.indexOf ("HiddenSection") >= 0)
202 tag.className = "VisibleSection";
204 tag.className = "HiddenSection";
208 message_array = Array();
209 function view_testlog (wname, file, random_seed, tcase, msgtitle, msgid) {
210 txt = message_array[msgid];
211 var w = window.open ("", // URI
213 "resizable,scrollbars,status,width=790,height=400");
214 var doc = w.document;
215 doc.write ("<h2>File: " + file + "</h2>\n");
216 doc.write ("<h3>Case: " + tcase + "</h3>\n");
217 doc.write ("<strong>Random Seed:</strong> <code>" + random_seed + "</code> <br /><br />\n");
218 doc.write ("<strong>" + msgtitle + "</strong><br />\n");
221 doc.write ("</pre>\n");
222 doc.write ("<a href=\'javascript
:window
.close()\'>Close Window
</a
>\n");
227 def __init__ (self, info, binary_list):
228 ReportWriter.__init__(self, binary_list)
232 self.total_tcounter = 0
233 self.total_fcounter = 0
234 self.total_duration = 0
235 self.indent_depth = 0
237 def oprint (self, message):
238 sys.stdout.write (message)
240 self.lastchar = message[-1]
241 def handle_info (self):
242 self.oprint ('<h3>Package: %(package)s, version: %(version)s</h3>\n' % self.info)
243 if self.info['revision']:
244 self.oprint ('<h5>Report generated from: %(revision)s</h5>\n' % self.info)
245 def handle_text (self, node):
246 self.oprint (node.nodeValue)
247 def handle_testcase (self, node, binary):
248 skipped = bool (int (attribute_as_text (node, 'skipped') + '0'))
250 return # skipped tests are uninteresting for HTML reports
251 path = attribute_as_text (node, 'path')
252 duration = node_as_text (node, 'duration')
253 result = attribute_as_text (node, 'result', 'status')
255 'success': 'bgcolor="lightgreen
"',
256 'failed': 'bgcolor="red
"',
258 if result != 'success':
259 duration = '-' # ignore bogus durations
260 self.oprint ('<tr id="b
%u_t
%u_" keywords="%s all
" class="HiddenSection
">\n' % (self.bcounter, self.tcounter, result))
261 self.oprint ('<td>%s %s</td> <td align="right
">%s</td> \n' % (html_indent_string (4), path, duration))
262 perflist = list_children (node, 'performance')
263 if result != 'success':
264 txt = self._error_text(node)
265 txt = re.sub (r'"', r'\\"', txt)
266 txt = re.sub (r'\n', r'\\n', txt)
267 txt = re.sub (r'&', r'&', txt)
268 txt = re.sub (r'<', r'<', txt)
269 self.oprint ('<script language="javascript
" type="text
/javascript
">message_array["b
%u_t
%u_"] = "%s";</script>\n' % (self.bcounter, self.tcounter, txt))
270 self.oprint ('<td align="center
"><a href="javascript
:view_testlog (\'%s\', \'%s\', \'%s\', \'%s\', \'Output
:\', \'b
%u_t
%u_\')">Details</a></td>\n' %
271 ('TestResultWindow', binary.file, binary.random_seed, path, self.bcounter, self.tcounter))
274 for perf in perflist:
275 pmin = bool (int (attribute_as_text (perf, 'minimize')))
276 pmax = bool (int (attribute_as_text (perf, 'maximize')))
277 pval = float (attribute_as_text (perf, 'value'))
278 txt = node_as_text (perf)
279 txt = re.sub (r'&', r'&', txt)
280 txt = re.sub (r'<', r'>', txt)
281 txt = '<strong>Performance(' + (pmin and '<em>minimized</em>' or '<em>maximized</em>') + '):</strong> ' + txt.strip() + '<br />\n'
282 txt = re.sub (r'"', r'\\"', txt)
283 txt = re.sub (r'\n', r'\\n', txt)
284 presults += [ (pval, txt) ]
286 ptxt = ''.join ([e[1] for e in presults])
287 self.oprint ('<script language="javascript
" type="text
/javascript
">message_array["b
%u_t
%u_"] = "%s";</script>\n' % (self.bcounter, self.tcounter, ptxt))
288 self.oprint ('<td align="center
"><a href="javascript
:view_testlog (\'%s\', \'%s\', \'%s\', \'%s\', \'Test Results
:\', \'b
%u_t
%u_\')">Details</a></td>\n' %
289 ('TestResultWindow', binary.file, binary.random_seed, path, self.bcounter, self.tcounter))
291 self.oprint ('<td align="center
">-</td>\n')
292 self.oprint ('<td align="right
" %s>%s</td>\n' % (rcolor, result))
293 self.oprint ('</tr>\n')
295 self.total_tcounter += 1
296 self.total_fcounter += result != 'success'
297 def handle_binary (self, binary):
300 self.total_duration += binary.duration
301 self.oprint ('<tr><td><strong>%s</strong></td><td align="right
">%f</td> <td align="center
">\n' % (binary.name, binary.duration))
302 erlink, oklink = ('', '')
303 real_cases = len (binary.testcases) - binary.skipped_cases
304 if binary.success_cases < real_cases:
305 erlink = 'href="javascript
:toggle_display (\'ResultTable
\', \'tr
\', \'b
%u_\', \'failed
\')"' % self.bcounter
306 if binary.success_cases:
307 oklink = 'href="javascript
:toggle_display (\'ResultTable
\', \'tr
\', \'b
%u_\', \'success
\')"' % self.bcounter
309 self.oprint ('<a %s>ER</a>\n' % erlink)
310 self.oprint ('<a %s>OK</a>\n' % oklink)
311 self.oprint ('</td>\n')
312 perc = binary.success_cases * 100.0 / real_cases
314 100 : 'bgcolor="lightgreen
"',
316 }.get (int (perc), 'bgcolor="yellow
"')
317 self.oprint ('<td align="right
" %s>%.2f%%</td>\n' % (pcolor, perc))
318 self.oprint ('</tr>\n')
320 self.oprint ('Empty\n')
321 self.oprint ('</td>\n')
322 self.oprint ('</tr>\n')
323 for tc in binary.testcases:
324 self.handle_testcase (tc, binary)
325 def handle_totals (self):
327 self.oprint ('<td><strong>Totals:</strong> %u Binaries, %u Tests, %u Failed, %u Succeeded</td>' %
328 (self.bcounter, self.total_tcounter, self.total_fcounter, self.total_tcounter - self.total_fcounter))
329 self.oprint ('<td align="right
">%f</td>\n' % self.total_duration)
330 self.oprint ('<td align="center
">-</td>\n')
331 if self.total_tcounter != 0:
332 perc = (self.total_tcounter - self.total_fcounter) * 100.0 / self.total_tcounter
336 100 : 'bgcolor="lightgreen
"',
338 }.get (int (perc), 'bgcolor="yellow
"')
339 self.oprint ('<td align="right
" %s>%.2f%%</td>\n' % (pcolor, perc))
340 self.oprint ('</tr>\n')
342 self.oprint ('<html><head>\n')
343 self.oprint ('<title>GTester Unit Test Report</title>\n')
344 self.oprint (self.cssjs)
345 self.oprint ('</head>\n')
346 self.oprint ('<body>\n')
347 self.oprint ('<h2>GTester Unit Test Report</h2>\n')
349 self.oprint ('<table id="ResultTable
" width="100%" border="1">\n<tr>\n')
350 self.oprint ('<th>Program / Testcase </th>\n')
351 self.oprint ('<th style="width
:8em
">Duration (sec)</th>\n')
352 self.oprint ('<th style="width
:5em
">View</th>\n')
353 self.oprint ('<th style="width
:5em
">Result</th>\n')
354 self.oprint ('</tr>\n')
355 for tb in self.binaries:
356 self.handle_binary (tb)
358 self.oprint ('</table>\n')
359 self.oprint ('</body>\n')
360 self.oprint ('</html>\n')
363 class SubunitWriter(ReportWriter):
364 """Reporter to output a subunit stream."""
367 reporter = subunit.TestProtocolClient(sys.stdout)
368 for binary in self.binaries:
369 for tc in binary.testcases:
370 test = GTestCase(tc, binary)
374 class GTestCase(object):
375 """A representation of a gtester test result as a pyunit TestCase."""
377 def __init__(self, case, binary):
378 """Create a GTestCase for case 'case' from binary program 'binary'."""
380 self._binary = binary
381 # the name of the case - e.g. /dbusmenu/glib/objects/menuitem/props_boolstr
382 self._path = attribute_as_text(self._case, 'path')
385 """What test is this? Returns the gtester path for the testcase."""
388 def _get_details(self):
389 """Calculate a details dict for the test - attachments etc."""
391 result = attribute_as_text(self._case, 'result', 'status')
392 details['filename'] = Content(mime_utf8, lambda:[self._binary.file])
393 details['random_seed'] = Content(mime_utf8,
394 lambda:[self._binary.random_seed])
395 if self._get_outcome() == 'addFailure':
396 # Extract the error details. Skips have no details because its not
397 # skip like unittest does, instead the runner just bypasses N test.
398 txt = self._error_text(self._case)
399 details['error'] = Content(mime_utf8, lambda:[txt])
400 if self._get_outcome() == 'addSuccess':
401 # Sucessful tests may have performance metrics.
402 perflist = list_children(self._case, 'performance')
405 for perf in perflist:
406 pmin = bool (int (attribute_as_text (perf, 'minimize')))
407 pmax = bool (int (attribute_as_text (perf, 'maximize')))
408 pval = float (attribute_as_text (perf, 'value'))
409 txt = node_as_text (perf)
410 txt = 'Performance(' + (pmin and 'minimized' or 'maximized'
411 ) + '): ' + txt.strip() + '\n'
412 presults += [(pval, txt)]
414 perf_details = [e[1] for e in presults]
415 details['performance'] = Content(mime_utf8, lambda:perf_details)
418 def _get_outcome(self):
419 if int(attribute_as_text(self._case, 'skipped') + '0'):
421 outcome = attribute_as_text(self._case, 'result', 'status')
422 if outcome == 'success':
427 def run(self, result):
428 time = datetime.datetime.utcnow().replace(tzinfo=iso8601.Utc())
430 result.startTest(self)
432 outcome = self._get_outcome()
433 details = self._get_details()
434 # Only provide a duration IFF outcome == 'addSuccess' - the main
435 # parser claims bogus results otherwise: in that case emit time as
437 if outcome == 'addSuccess':
438 duration = float(node_as_text(self._case, 'duration'))
439 duration = duration * 1000000
440 timedelta = datetime.timedelta(0, 0, duration)
441 time = time + timedelta
443 getattr(result, outcome)(self, details=details)
445 result.stopTest(self)
449 # main program handling
451 """Parse program options.
453 :return: An options object and the program arguments.
455 parser = optparse.OptionParser()
456 parser.version = pkginstall_configvars.get ('glib-version', '0.0-uninstalled')
457 parser.usage = "%prog
[OPTIONS
] <gtester
-log
.xml
>"
458 parser.description = "Generate HTML reports
from the XML log files generated by gtester
."
459 parser.epilog = "gtester
-report (GLib utils
) version
%s."% (parser.version,)
460 parser.add_option("-v
", "--version
", action="store_true
", dest="version
", default=False,
461 help="Show program version
.")
462 parser.add_option("-s
", "--subunit
", action="store_true
", dest="subunit
", default=False,
463 help="Output subunit
[See https
://launchpad
.net
/subunit
/"
464 " Needs python
-subunit
]")
465 options, files = parser.parse_args()
470 parser.error("Must supply a log
file to parse
.")
471 if options.subunit and subunit is None:
472 parser.error("python
-subunit
is not installed
.")
473 return options, files
477 options, files = parse_opts()
480 xd = xml.dom.minidom.parse (files[0])
483 if not options.subunit:
484 HTMLReportWriter(rr.get_info(), rr.binary_list()).printout()
486 SubunitWriter(rr.get_info(), rr.binary_list()).printout()
489 if __name__ == '__main__':