1 # Python module for parsing and generating the Subunit protocol
3 # Copyright (C) 2008-2009 Jelmer Vernooij <jelmer@samba.org>
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 from __future__ import print_function
19 __all__ = ['parse_results']
25 from samba import subunit
26 from samba.subunit.run import TestProtocolClient
29 from dateutil.parser import isoparse as iso_parse_date
32 from iso8601 import parse_date as iso_parse_date;
34 print('Install either python-dateutil >= 2.7.1 or python-iso8601')
37 VALID_RESULTS = set(['success', 'successful', 'failure', 'fail', 'skip',
38 'knownfail', 'error', 'xfail', 'skip-testsuite',
39 'testsuite-failure', 'testsuite-xfail',
40 'testsuite-success', 'testsuite-error',
41 'uxsuccess', 'testsuite-uxsuccess'])
44 class TestsuiteEnabledTestResult(unittest.TestResult):
46 def start_testsuite(self, name):
47 raise NotImplementedError(self.start_testsuite)
50 def parse_results(msg_ops, statistics, fh):
55 parts = l.split(None, 1)
56 if not len(parts) == 2 or not l.startswith(parts[0]):
59 command = parts[0].rstrip(":")
61 if command in ("test", "testing"):
62 msg_ops.control_msg(l)
64 test = subunit.RemotedTestCase(name)
65 if name in open_tests:
66 msg_ops.addError(open_tests.pop(name), subunit.RemoteError(u"Test already running"))
67 msg_ops.startTest(test)
68 open_tests[name] = test
69 elif command == "time":
70 msg_ops.control_msg(l)
72 dt = iso_parse_date(arg.rstrip("\n"))
73 except TypeError as e:
74 print("Unable to parse time line: %s" % arg.rstrip("\n"))
77 elif command in VALID_RESULTS:
78 msg_ops.control_msg(l)
80 grp = re.match("(.*?)( \[)?([ \t]*)( multipart)?\n", arg)
81 (testname, hasreason) = (grp.group(1), grp.group(2))
84 # reason may be specified in next lines
87 msg_ops.control_msg(l)
94 if isinstance(reason, bytes):
95 remote_error = subunit.RemoteError(reason.decode("utf-8"))
97 remote_error = subunit.RemoteError(reason)
100 statistics['TESTS_ERROR'] += 1
101 msg_ops.addError(subunit.RemotedTestCase(testname),
102 subunit.RemoteError(u"result (%s) reason (%s) interrupted" % (result, reason)))
106 remote_error = subunit.RemoteError(u"No reason specified")
107 if result in ("success", "successful"):
109 test = open_tests.pop(testname)
111 statistics['TESTS_ERROR'] += 1
113 msg_ops.addError(subunit.RemotedTestCase(testname), subunit.RemoteError(u"Test was never started"))
115 statistics['TESTS_EXPECTED_OK'] += 1
116 msg_ops.addSuccess(test)
117 elif result in ("xfail", "knownfail"):
119 test = open_tests.pop(testname)
121 statistics['TESTS_ERROR'] += 1
123 msg_ops.addError(subunit.RemotedTestCase(testname), subunit.RemoteError(u"Test was never started"))
125 statistics['TESTS_EXPECTED_FAIL'] += 1
126 msg_ops.addExpectedFailure(test, remote_error)
127 elif result in ("uxsuccess", ):
129 test = open_tests.pop(testname)
131 statistics['TESTS_ERROR'] += 1
133 msg_ops.addError(subunit.RemotedTestCase(testname), subunit.RemoteError(u"Test was never started"))
135 statistics['TESTS_UNEXPECTED_OK'] += 1
136 msg_ops.addUnexpectedSuccess(test)
138 elif result in ("failure", "fail"):
140 test = open_tests.pop(testname)
142 statistics['TESTS_ERROR'] += 1
144 msg_ops.addError(subunit.RemotedTestCase(testname), subunit.RemoteError(u"Test was never started"))
146 statistics['TESTS_UNEXPECTED_FAIL'] += 1
148 msg_ops.addFailure(test, remote_error)
149 elif result == "skip":
150 statistics['TESTS_SKIP'] += 1
151 # Allow tests to be skipped without prior announcement of test
153 test = open_tests.pop(testname)
155 test = subunit.RemotedTestCase(testname)
156 msg_ops.addSkip(test, reason)
157 elif result == "error":
158 statistics['TESTS_ERROR'] += 1
161 test = open_tests.pop(testname)
163 test = subunit.RemotedTestCase(testname)
164 msg_ops.addError(test, remote_error)
165 elif result == "skip-testsuite":
166 msg_ops.skip_testsuite(testname)
167 elif result == "testsuite-success":
168 msg_ops.end_testsuite(testname, "success", reason)
169 elif result == "testsuite-failure":
170 msg_ops.end_testsuite(testname, "failure", reason)
172 elif result == "testsuite-xfail":
173 msg_ops.end_testsuite(testname, "xfail", reason)
174 elif result == "testsuite-uxsuccess":
175 msg_ops.end_testsuite(testname, "uxsuccess", reason)
177 elif result == "testsuite-error":
178 msg_ops.end_testsuite(testname, "error", reason)
181 raise AssertionError("Recognized but unhandled result %r" %
183 elif command == "testsuite":
184 msg_ops.start_testsuite(arg.strip())
185 elif command == "progress":
188 msg_ops.progress(None, subunit.PROGRESS_POP)
190 msg_ops.progress(None, subunit.PROGRESS_PUSH)
192 msg_ops.progress(int(arg), subunit.PROGRESS_CUR)
194 msg_ops.progress(int(arg), subunit.PROGRESS_SET)
196 msg_ops.output_msg(l)
199 test = subunit.RemotedTestCase(open_tests.popitem()[1])
200 msg_ops.addError(test, subunit.RemoteError(u"was started but never finished!"))
201 statistics['TESTS_ERROR'] += 1
207 class SubunitOps(TestProtocolClient, TestsuiteEnabledTestResult):
209 def progress(self, count, whence):
210 if whence == subunit.PROGRESS_POP:
211 self._stream.write("progress: pop\n")
212 elif whence == subunit.PROGRESS_PUSH:
213 self._stream.write("progress: push\n")
214 elif whence == subunit.PROGRESS_SET:
215 self._stream.write("progress: %d\n" % count)
216 elif whence == subunit.PROGRESS_CUR:
217 raise NotImplementedError
219 # The following are Samba extensions:
220 def start_testsuite(self, name):
221 self._stream.write("testsuite: %s\n" % name)
223 def skip_testsuite(self, name, reason=None):
225 self._stream.write("skip-testsuite: %s [\n%s\n]\n" % (name, reason))
227 self._stream.write("skip-testsuite: %s\n" % name)
229 def end_testsuite(self, name, result, reason=None):
231 self._stream.write("testsuite-%s: %s [\n%s\n]\n" % (result, name, reason))
233 self._stream.write("testsuite-%s: %s\n" % (result, name))
235 def output_msg(self, msg):
236 self._stream.write(msg)
239 def read_test_regexes(*names):
243 # if we are given a directory, we read all the files it contains
244 # (except the ones that end with "~").
245 if os.path.isdir(name):
246 files.extend([os.path.join(name, x)
247 for x in os.listdir(name)
252 for filename in files:
253 with open(filename, 'r') as f:
256 if l == "" or l[0] == "#":
259 (regex, reason) = l.split("#", 1)
260 ret[regex.strip()] = reason.strip()
267 def find_in_list(regexes, fullname):
268 for regex, reason in regexes.items():
269 if re.match(regex, fullname):
276 class ImmediateFail(Exception):
277 """Raised to abort immediately."""
280 super(ImmediateFail, self).__init__("test failed and fail_immediately set")
283 class FilterOps(unittest.TestResult):
285 def control_msg(self, msg):
286 pass # We regenerate control messages, so ignore this
288 def time(self, time):
291 def progress(self, delta, whence):
292 self._ops.progress(delta, whence)
294 def output_msg(self, msg):
295 if self.output is None:
296 sys.stdout.write(msg)
300 def startTest(self, test):
301 self.seen_output = True
302 test = self._add_prefix(test)
303 if self.strip_ok_output:
306 self._ops.startTest(test)
308 def _add_prefix(self, test):
309 return subunit.RemotedTestCase(self.prefix + test.id() + self.suffix)
311 def addError(self, test, err=None):
312 test = self._add_prefix(test)
313 self.error_added += 1
314 self.total_error += 1
315 self._ops.addError(test, err)
317 if self.fail_immediately:
318 raise ImmediateFail()
320 def addSkip(self, test, reason=None):
321 self.seen_output = True
322 test = self._add_prefix(test)
323 self._ops.addSkip(test, reason)
326 def addExpectedFailure(self, test, err=None):
327 test = self._add_prefix(test)
328 self._ops.addExpectedFailure(test, err)
331 def addUnexpectedSuccess(self, test):
332 test = self._add_prefix(test)
333 self.uxsuccess_added += 1
334 self.total_uxsuccess += 1
335 self._ops.addUnexpectedSuccess(test)
337 self._ops.output_msg(self.output)
339 if self.fail_immediately:
340 raise ImmediateFail()
342 def addFailure(self, test, err=None):
343 test = self._add_prefix(test)
344 xfail_reason = find_in_list(self.expected_failures, test.id())
345 if xfail_reason is None:
346 xfail_reason = find_in_list(self.flapping, test.id())
347 if xfail_reason is not None:
348 self.xfail_added += 1
349 self.total_xfail += 1
350 self._ops.addExpectedFailure(test, err)
354 self._ops.addFailure(test, err)
356 self._ops.output_msg(self.output)
357 if self.fail_immediately:
358 raise ImmediateFail()
361 def addSuccess(self, test):
362 test = self._add_prefix(test)
363 xfail_reason = find_in_list(self.expected_failures, test.id())
364 if xfail_reason is not None:
365 self.uxsuccess_added += 1
366 self.total_uxsuccess += 1
367 self._ops.addUnexpectedSuccess(test)
369 self._ops.output_msg(self.output)
370 if self.fail_immediately:
371 raise ImmediateFail()
373 self._ops.addSuccess(test)
376 def skip_testsuite(self, name, reason=None):
377 self._ops.skip_testsuite(name, reason)
379 def start_testsuite(self, name):
380 self._ops.start_testsuite(name)
384 self.uxsuccess_added = 0
386 def end_testsuite(self, name, result, reason=None):
389 if self.xfail_added > 0:
391 if self.fail_added > 0 or self.error_added > 0 or self.uxsuccess_added > 0:
394 if xfail and result in ("fail", "failure"):
397 if self.uxsuccess_added > 0 and result != "uxsuccess":
400 reason = "Subunit/Filter Reason"
401 reason += "\n uxsuccess[%d]" % self.uxsuccess_added
403 if self.fail_added > 0 and result != "failure":
406 reason = "Subunit/Filter Reason"
407 reason += "\n failures[%d]" % self.fail_added
409 if self.error_added > 0 and result != "error":
412 reason = "Subunit/Filter Reason"
413 reason += "\n errors[%d]" % self.error_added
415 self._ops.end_testsuite(name, result, reason)
416 if result not in ("success", "xfail"):
418 self._ops.output_msg(self.output)
419 if self.fail_immediately:
420 raise ImmediateFail()
423 def __init__(self, out, prefix=None, suffix=None, expected_failures=None,
424 strip_ok_output=False, fail_immediately=False,
427 self.seen_output = False
431 if expected_failures is not None:
432 self.expected_failures = expected_failures
434 self.expected_failures = {}
435 if flapping is not None:
436 self.flapping = flapping
439 self.strip_ok_output = strip_ok_output
442 self.uxsuccess_added = 0
446 self.total_uxsuccess = 0
448 self.fail_immediately = fail_immediately
451 class PerfFilterOps(unittest.TestResult):
453 def progress(self, delta, whence):
456 def output_msg(self, msg):
459 def control_msg(self, msg):
462 def skip_testsuite(self, name, reason=None):
463 self._ops.skip_testsuite(name, reason)
465 def start_testsuite(self, name):
466 self.suite_has_time = False
468 def end_testsuite(self, name, result, reason=None):
471 def _add_prefix(self, test):
472 return subunit.RemotedTestCase(self.prefix + test.id() + self.suffix)
474 def time(self, time):
475 self.latest_time = time
476 #self._ops.output_msg("found time %s\n" % time)
477 self.suite_has_time = True
480 if self.suite_has_time:
481 return self.latest_time
482 return datetime.datetime.utcnow()
484 def startTest(self, test):
485 self.seen_output = True
486 test = self._add_prefix(test)
487 self.starts[test.id()] = self.get_time()
489 def addSuccess(self, test):
490 test = self._add_prefix(test)
492 if tid not in self.starts:
493 self._ops.addError(test, "%s succeeded without ever starting!" % tid)
494 delta = self.get_time() - self.starts[tid]
495 self._ops.output_msg("elapsed-time: %s: %f\n" % (tid, delta.total_seconds()))
497 def addFailure(self, test, err=''):
499 delta = self.get_time() - self.starts[tid]
500 self._ops.output_msg("failure: %s failed after %f seconds (%s)\n" %
501 (tid, delta.total_seconds(), err))
503 def addError(self, test, err=''):
505 delta = self.get_time() - self.starts[tid]
506 self._ops.output_msg("error: %s failed after %f seconds (%s)\n" %
507 (tid, delta.total_seconds(), err))
509 def __init__(self, out, prefix='', suffix=''):
511 self.prefix = prefix or ''
512 self.suffix = suffix or ''
514 self.seen_output = False
515 self.suite_has_time = False
518 class PlainFormatter(TestsuiteEnabledTestResult):
520 def __init__(self, verbose, immediate, statistics,
522 super(PlainFormatter, self).__init__()
523 self.verbose = verbose
524 self.immediate = immediate
525 self.statistics = statistics
526 self.start_time = None
527 self.test_output = {}
528 self.suitesfailed = []
533 self._progress_level = 0
534 self.totalsuites = totaltests
535 self.last_time = None
538 def _format_time(delta):
539 minutes, seconds = divmod(delta.seconds, 60)
540 hours, minutes = divmod(minutes, 60)
545 ret += "%dm" % minutes
546 ret += "%ds" % seconds
549 def progress(self, offset, whence):
550 if whence == subunit.PROGRESS_POP:
551 self._progress_level -= 1
552 elif whence == subunit.PROGRESS_PUSH:
553 self._progress_level += 1
554 elif whence == subunit.PROGRESS_SET:
555 if self._progress_level == 0:
556 self.totalsuites = offset
557 elif whence == subunit.PROGRESS_CUR:
558 raise NotImplementedError
561 if self.start_time is None:
565 def start_testsuite(self, name):
570 self.test_output[name] = ""
572 total_tests = (self.statistics['TESTS_EXPECTED_OK'] +
573 self.statistics['TESTS_EXPECTED_FAIL'] +
574 self.statistics['TESTS_ERROR'] +
575 self.statistics['TESTS_UNEXPECTED_FAIL'] +
576 self.statistics['TESTS_UNEXPECTED_OK'])
578 out = "[%d(%d)" % (self.index, total_tests)
579 if self.totalsuites is not None:
580 out += "/%d" % self.totalsuites
581 if self.start_time is not None:
582 out += " at " + self._format_time(self.last_time - self.start_time)
583 if self.suitesfailed:
584 out += ", %d errors" % (len(self.suitesfailed),)
587 sys.stdout.write(out + "\n")
589 sys.stdout.write(out + ": ")
591 def output_msg(self, output):
593 sys.stdout.write(output)
594 elif self.name is not None:
595 self.test_output[self.name] += output
597 sys.stdout.write(output)
599 def control_msg(self, output):
602 def end_testsuite(self, name, result, reason):
606 if name not in self.test_output:
607 print("no output for name[%s]" % name)
609 if result in ("success", "xfail"):
612 self.output_msg("ERROR: Testsuite[%s]\n" % name)
613 if reason is not None:
614 self.output_msg("REASON: %s\n" % (reason,))
615 self.suitesfailed.append(name)
616 if self.immediate and not self.verbose and name in self.test_output:
617 out += self.test_output[name]
620 if not self.immediate:
624 out += " " + result.upper() + "\n"
626 sys.stdout.write(out)
628 def startTest(self, test):
631 def addSuccess(self, test):
632 self.end_test(test.id(), "success", False)
634 def addError(self, test, err=None):
635 self.end_test(test.id(), "error", True, err)
637 def addFailure(self, test, err=None):
638 self.end_test(test.id(), "failure", True, err)
640 def addSkip(self, test, reason=None):
641 self.end_test(test.id(), "skip", False, reason)
643 def addExpectedFailure(self, test, err=None):
644 self.end_test(test.id(), "xfail", False, err)
646 def addUnexpectedSuccess(self, test):
647 self.end_test(test.id(), "uxsuccess", True)
649 def end_test(self, testname, result, unexpected, err=None):
651 self.test_output[self.name] = ""
652 if not self.immediate:
657 'success': '.'}.get(result, "?(%s)" % result))
660 if self.name not in self.test_output:
661 self.test_output[self.name] = ""
663 self.test_output[self.name] += "UNEXPECTED(%s): %s\n" % (result, testname)
665 self.test_output[self.name] += "REASON: %s\n" % str(err[1]).strip()
667 if self.immediate and not self.verbose:
668 sys.stdout.write(self.test_output[self.name])
669 self.test_output[self.name] = ""
671 if not self.immediate:
676 'success': 'S'}.get(result, "?"))
678 def write_summary(self, path):
681 if self.suitesfailed:
682 f.write("= Failed tests =\n")
684 for suite in self.suitesfailed:
685 f.write("== %s ==\n" % suite)
686 if suite in self.test_output:
687 f.write(self.test_output[suite] + "\n\n")
691 if not self.immediate and not self.verbose:
692 for suite in self.suitesfailed:
694 print("FAIL: %s" % suite)
695 if suite in self.test_output:
696 print(self.test_output[suite])
699 f.write("= Skipped tests =\n")
700 for reason in self.skips.keys():
701 f.write(reason + "\n")
702 for name in self.skips[reason]:
703 f.write("\t%s\n" % name)
707 if (not self.suitesfailed and
708 not self.statistics['TESTS_UNEXPECTED_FAIL'] and
709 not self.statistics['TESTS_UNEXPECTED_OK'] and
710 not self.statistics['TESTS_ERROR']):
711 ok = (self.statistics['TESTS_EXPECTED_OK'] +
712 self.statistics['TESTS_EXPECTED_FAIL'])
713 print("\nALL OK (%d tests in %d testsuites)" % (ok, self.suites_ok))
715 print("\nFAILED (%d failures, %d errors and %d unexpected successes in %d testsuites)" % (
716 self.statistics['TESTS_UNEXPECTED_FAIL'],
717 self.statistics['TESTS_ERROR'],
718 self.statistics['TESTS_UNEXPECTED_OK'],
719 len(self.suitesfailed)))
721 def skip_testsuite(self, name, reason="UNKNOWN"):
722 self.skips.setdefault(reason, []).append(name)
724 self.totalsuites -= 1