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 __all__
= ['parse_results']
23 import subunit
.iso8601
26 VALID_RESULTS
= ['success', 'successful', 'failure', 'fail', 'skip', 'knownfail', 'error', 'xfail', 'skip-testsuite', 'testsuite-failure', 'testsuite-xfail', 'testsuite-success', 'testsuite-error']
28 class TestsuiteEnabledTestResult(testtools
.testresult
.TestResult
):
30 def start_testsuite(self
, name
):
31 raise NotImplementedError(self
.start_testsuite
)
34 def parse_results(msg_ops
, statistics
, fh
):
43 parts
= l
.split(None, 1)
44 if not len(parts
) == 2 or not l
.startswith(parts
[0]):
47 command
= parts
[0].rstrip(":")
49 if command
in ("test", "testing"):
50 msg_ops
.control_msg(l
)
52 test
= subunit
.RemotedTestCase(name
)
53 if name
in open_tests
:
54 msg_ops
.addError(open_tests
.pop(name
), subunit
.RemoteError(u
"Test already running"))
55 msg_ops
.startTest(test
)
56 open_tests
[name
] = test
57 elif command
== "time":
58 msg_ops
.control_msg(l
)
60 dt
= subunit
.iso8601
.parse_date(arg
.rstrip("\n"))
62 print "Unable to parse time line: %s" % arg
.rstrip("\n")
65 elif command
in VALID_RESULTS
:
66 msg_ops
.control_msg(l
)
68 grp
= re
.match("(.*?)( \[)?([ \t]*)( multipart)?\n", arg
)
69 (testname
, hasreason
) = (grp
.group(1), grp
.group(2))
72 # reason may be specified in next lines
78 msg_ops
.control_msg(l
)
85 remote_error
= subunit
.RemoteError(reason
.decode("utf-8"))
88 statistics
['TESTS_ERROR']+=1
89 msg_ops
.addError(subunit
.RemotedTestCase(testname
), subunit
.RemoteError(u
"reason (%s) interrupted" % result
))
93 remote_error
= subunit
.RemoteError(u
"No reason specified")
94 if result
in ("success", "successful"):
96 test
= open_tests
.pop(testname
)
98 statistics
['TESTS_ERROR']+=1
100 msg_ops
.addError(subunit
.RemotedTestCase(testname
), subunit
.RemoteError(u
"Test was never started"))
102 statistics
['TESTS_EXPECTED_OK']+=1
103 msg_ops
.addSuccess(test
)
104 elif result
in ("xfail", "knownfail"):
106 test
= open_tests
.pop(testname
)
108 statistics
['TESTS_ERROR']+=1
110 msg_ops
.addError(subunit
.RemotedTestCase(testname
), subunit
.RemoteError(u
"Test was never started"))
112 statistics
['TESTS_EXPECTED_FAIL']+=1
113 msg_ops
.addExpectedFailure(test
, remote_error
)
115 elif result
in ("failure", "fail"):
117 test
= open_tests
.pop(testname
)
119 statistics
['TESTS_ERROR']+=1
121 msg_ops
.addError(subunit
.RemotedTestCase(testname
), subunit
.RemoteError(u
"Test was never started"))
123 statistics
['TESTS_UNEXPECTED_FAIL']+=1
125 msg_ops
.addFailure(test
, remote_error
)
126 elif result
== "skip":
127 statistics
['TESTS_SKIP']+=1
128 # Allow tests to be skipped without prior announcement of test
130 test
= open_tests
.pop(testname
)
132 test
= subunit
.RemotedTestCase(testname
)
133 msg_ops
.addSkip(test
, reason
)
134 elif result
== "error":
135 statistics
['TESTS_ERROR']+=1
138 test
= open_tests
.pop(testname
)
140 test
= subunit
.RemotedTestCase(testname
)
141 msg_ops
.addError(test
, remote_error
)
142 elif result
== "skip-testsuite":
143 msg_ops
.skip_testsuite(testname
)
144 elif result
== "testsuite-success":
145 msg_ops
.end_testsuite(testname
, "success", reason
)
146 elif result
== "testsuite-failure":
147 msg_ops
.end_testsuite(testname
, "failure", reason
)
149 elif result
== "testsuite-xfail":
150 msg_ops
.end_testsuite(testname
, "xfail", reason
)
151 elif result
== "testsuite-error":
152 msg_ops
.end_testsuite(testname
, "error", reason
)
155 raise AssertionError("Recognized but unhandled result %r" %
157 elif command
== "testsuite":
158 msg_ops
.start_testsuite(arg
.strip())
159 elif command
== "progress":
162 msg_ops
.progress(None, subunit
.PROGRESS_POP
)
164 msg_ops
.progress(None, subunit
.PROGRESS_PUSH
)
166 msg_ops
.progress(int(arg
), subunit
.PROGRESS_CUR
)
168 msg_ops
.progress(int(arg
), subunit
.PROGRESS_SET
)
170 msg_ops
.output_msg(l
)
173 test
= subunit
.RemotedTestCase(open_tests
.popitem()[1])
174 msg_ops
.addError(test
, subunit
.RemoteError(u
"was started but never finished!"))
175 statistics
['TESTS_ERROR']+=1
181 class SubunitOps(subunit
.TestProtocolClient
,TestsuiteEnabledTestResult
):
183 # The following are Samba extensions:
184 def start_testsuite(self
, name
):
185 self
._stream
.write("testsuite: %s\n" % name
)
187 def skip_testsuite(self
, name
, reason
=None):
189 self
._stream
.write("skip-testsuite: %s [\n%s\n]\n" % (name
, reason
))
191 self
._stream
.write("skip-testsuite: %s\n" % name
)
193 def end_testsuite(self
, name
, result
, reason
=None):
195 self
._stream
.write("testsuite-%s: %s [\n%s\n]\n" % (result
, name
, reason
))
197 self
._stream
.write("testsuite-%s: %s\n" % (result
, name
))
199 def output_msg(self
, msg
):
200 self
._stream
.write(msg
)
203 def read_test_regexes(name
):
209 if l
== "" or l
[0] == "#":
212 (regex
, reason
) = l
.split("#", 1)
213 ret
[regex
.strip()] = reason
.strip()
221 def find_in_list(regexes
, fullname
):
222 for regex
, reason
in regexes
.iteritems():
223 if re
.match(regex
, fullname
):
230 class ImmediateFail(Exception):
231 """Raised to abort immediately."""
234 super(ImmediateFail
, self
).__init
__("test failed and fail_immediately set")
237 class FilterOps(testtools
.testresult
.TestResult
):
239 def control_msg(self
, msg
):
240 pass # We regenerate control messages, so ignore this
242 def time(self
, time
):
245 def progress(self
, delta
, whence
):
246 self
._ops
.progress(delta
, whence
)
248 def output_msg(self
, msg
):
249 if self
.output
is None:
250 sys
.stdout
.write(msg
)
254 def startTest(self
, test
):
255 self
.seen_output
= True
256 test
= self
._add
_prefix
(test
)
257 if self
.strip_ok_output
:
260 self
._ops
.startTest(test
)
262 def _add_prefix(self
, test
):
263 if self
.prefix
is not None:
264 return subunit
.RemotedTestCase(self
.prefix
+ test
.id())
268 def addError(self
, test
, details
=None):
269 test
= self
._add
_prefix
(test
)
272 self
._ops
.addError(test
, details
)
274 if self
.fail_immediately
:
275 raise ImmediateFail()
277 def addSkip(self
, test
, details
=None):
278 self
.seen_output
= True
279 test
= self
._add
_prefix
(test
)
280 self
._ops
.addSkip(test
, details
)
283 def addExpectedFailure(self
, test
, details
=None):
284 test
= self
._add
_prefix
(test
)
285 self
._ops
.addExpectedFailure(test
, details
)
288 def addFailure(self
, test
, details
=None):
289 test
= self
._add
_prefix
(test
)
290 xfail_reason
= find_in_list(self
.expected_failures
, test
.id())
291 if xfail_reason
is not None:
294 if details
is not None:
295 details
= subunit
.RemoteError(unicode(details
[1]) + xfail_reason
.decode("utf-8"))
297 details
= subunit
.RemoteError(xfail_reason
.decode("utf-8"))
298 self
._ops
.addExpectedFailure(test
, details
)
302 self
._ops
.addFailure(test
, details
)
304 self
._ops
.output_msg(self
.output
)
305 if self
.fail_immediately
:
306 raise ImmediateFail()
309 def addSuccess(self
, test
, details
=None):
310 test
= self
._add
_prefix
(test
)
311 self
._ops
.addSuccess(test
, details
)
314 def skip_testsuite(self
, name
, reason
=None):
315 self
._ops
.skip_testsuite(name
, reason
)
317 def start_testsuite(self
, name
):
318 self
._ops
.start_testsuite(name
)
323 def end_testsuite(self
, name
, result
, reason
=None):
326 if self
.xfail_added
> 0:
328 if self
.fail_added
> 0 or self
.error_added
> 0:
331 if xfail
and result
in ("fail", "failure"):
334 if self
.fail_added
> 0 and result
!= "failure":
337 reason
= "Subunit/Filter Reason"
338 reason
+= "\n failures[%d]" % self
.fail_added
340 if self
.error_added
> 0 and result
!= "error":
343 reason
= "Subunit/Filter Reason"
344 reason
+= "\n errors[%d]" % self
.error_added
346 self
._ops
.end_testsuite(name
, result
, reason
)
348 def __init__(self
, out
, prefix
=None, expected_failures
=None,
349 strip_ok_output
=False, fail_immediately
=False):
351 self
.seen_output
= False
354 if expected_failures
is not None:
355 self
.expected_failures
= expected_failures
357 self
.expected_failures
= {}
358 self
.strip_ok_output
= strip_ok_output
365 self
.fail_immediately
= fail_immediately
368 class PlainFormatter(TestsuiteEnabledTestResult
):
370 def __init__(self
, verbose
, immediate
, statistics
,
372 super(PlainFormatter
, self
).__init
__()
373 self
.verbose
= verbose
374 self
.immediate
= immediate
375 self
.statistics
= statistics
376 self
.start_time
= None
377 self
.test_output
= {}
378 self
.suitesfailed
= []
383 self
._progress
_level
= 0
384 self
.totalsuites
= totaltests
385 self
.last_time
= None
388 def _format_time(delta
):
389 minutes
, seconds
= divmod(delta
.seconds
, 60)
390 hours
, minutes
= divmod(minutes
, 60)
395 ret
+= "%dm" % minutes
396 ret
+= "%ds" % seconds
399 def progress(self
, offset
, whence
):
400 if whence
== subunit
.PROGRESS_POP
:
401 self
._progress
_level
-= 1
402 elif whence
== subunit
.PROGRESS_PUSH
:
403 self
._progress
_level
+= 1
404 elif whence
== subunit
.PROGRESS_SET
:
405 if self
._progress
_level
== 0:
406 self
.totalsuites
= offset
407 elif whence
== subunit
.PROGRESS_CUR
:
408 raise NotImplementedError
411 if self
.start_time
is None:
415 def start_testsuite(self
, name
):
420 self
.test_output
[name
] = ""
422 out
= "[%d" % self
.index
423 if self
.totalsuites
is not None:
424 out
+= "/%d" % self
.totalsuites
425 if self
.start_time
is not None:
426 out
+= " in " + self
._format
_time
(self
.last_time
- self
.start_time
)
427 if self
.suitesfailed
:
428 out
+= ", %d errors" % (len(self
.suitesfailed
),)
431 sys
.stdout
.write(out
+ "\n")
433 sys
.stdout
.write(out
+ ": ")
435 def output_msg(self
, output
):
437 sys
.stdout
.write(output
)
438 elif self
.name
is not None:
439 self
.test_output
[self
.name
] += output
441 sys
.stdout
.write(output
)
443 def control_msg(self
, output
):
446 def end_testsuite(self
, name
, result
, reason
):
450 if not name
in self
.test_output
:
451 print "no output for name[%s]" % name
453 if result
in ("success", "xfail"):
456 self
.output_msg("ERROR: Testsuite[%s]\n" % name
)
457 if reason
is not None:
458 self
.output_msg("REASON: %s\n" % (reason
,))
459 self
.suitesfailed
.append(name
)
460 if self
.immediate
and not self
.verbose
and name
in self
.test_output
:
461 out
+= self
.test_output
[name
]
464 if not self
.immediate
:
468 out
+= " " + result
.upper() + "\n"
470 sys
.stdout
.write(out
)
472 def startTest(self
, test
):
475 def addSuccess(self
, test
):
476 self
.end_test(test
.id(), "success", False)
478 def addError(self
, test
, details
=None):
479 self
.end_test(test
.id(), "error", True, details
)
481 def addFailure(self
, test
, details
=None):
482 self
.end_test(test
.id(), "failure", True, details
)
484 def addSkip(self
, test
, details
=None):
485 self
.end_test(test
.id(), "skip", False, details
)
487 def addExpectedFail(self
, test
, details
=None):
488 self
.end_test(test
.id(), "xfail", False, details
)
490 def end_test(self
, testname
, result
, unexpected
, reason
=None):
492 self
.test_output
[self
.name
] = ""
493 if not self
.immediate
:
498 'success': '.'}.get(result
, "?(%s)" % result
))
501 if not self
.name
in self
.test_output
:
502 self
.test_output
[self
.name
] = ""
504 self
.test_output
[self
.name
] += "UNEXPECTED(%s): %s\n" % (result
, testname
)
505 if reason
is not None:
506 self
.test_output
[self
.name
] += "REASON: %s\n" % (unicode(reason
[1]).encode("utf-8").strip(),)
508 if self
.immediate
and not self
.verbose
:
509 print self
.test_output
[self
.name
]
510 self
.test_output
[self
.name
] = ""
512 if not self
.immediate
:
516 'success': 'S'}.get(result
, "?"))
518 def write_summary(self
, path
):
521 if self
.suitesfailed
:
522 f
.write("= Failed tests =\n")
524 for suite
in self
.suitesfailed
:
525 f
.write("== %s ==\n" % suite
)
526 if suite
in self
.test_output
:
527 f
.write(self
.test_output
[suite
]+"\n\n")
531 if not self
.immediate
and not self
.verbose
:
532 for suite
in self
.suitesfailed
:
534 print "FAIL: %s" % suite
535 if suite
in self
.test_output
:
536 print self
.test_output
[suite
]
539 f
.write("= Skipped tests =\n")
540 for reason
in self
.skips
.keys():
541 f
.write(reason
+ "\n")
542 for name
in self
.skips
[reason
]:
543 f
.write("\t%s\n" % name
)
547 if (not self
.suitesfailed
and
548 not self
.statistics
['TESTS_UNEXPECTED_FAIL'] and
549 not self
.statistics
['TESTS_ERROR']):
550 ok
= (self
.statistics
['TESTS_EXPECTED_OK'] +
551 self
.statistics
['TESTS_EXPECTED_FAIL'])
552 print "\nALL OK (%d tests in %d testsuites)" % (ok
, self
.suites_ok
)
554 print "\nFAILED (%d failures and %d errors in %d testsuites)" % (
555 self
.statistics
['TESTS_UNEXPECTED_FAIL'],
556 self
.statistics
['TESTS_ERROR'],
557 len(self
.suitesfailed
))
559 def skip_testsuite(self
, name
, reason
="UNKNOWN"):
560 self
.skips
.setdefault(reason
, []).append(name
)