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
25 from testtools
import content
, content_type
27 VALID_RESULTS
= ['success', 'successful', 'failure', 'fail', 'skip', 'knownfail', 'error', 'xfail', 'skip-testsuite', 'testsuite-failure', 'testsuite-xfail', 'testsuite-success', 'testsuite-error', 'uxsuccess']
29 class TestsuiteEnabledTestResult(testtools
.testresult
.TestResult
):
31 def start_testsuite(self
, name
):
32 raise NotImplementedError(self
.start_testsuite
)
35 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
)
114 elif result
in ("uxsuccess", ):
116 test
= open_tests
.pop(testname
)
118 statistics
['TESTS_ERROR']+=1
120 msg_ops
.addError(subunit
.RemotedTestCase(testname
), subunit
.RemoteError(u
"Test was never started"))
122 statistics
['TESTS_UNEXPECTED_OK']+=1
123 msg_ops
.addUnexpectedSuccess(test
, remote_error
)
125 elif result
in ("failure", "fail"):
127 test
= open_tests
.pop(testname
)
129 statistics
['TESTS_ERROR']+=1
131 msg_ops
.addError(subunit
.RemotedTestCase(testname
), subunit
.RemoteError(u
"Test was never started"))
133 statistics
['TESTS_UNEXPECTED_FAIL']+=1
135 msg_ops
.addFailure(test
, remote_error
)
136 elif result
== "skip":
137 statistics
['TESTS_SKIP']+=1
138 # Allow tests to be skipped without prior announcement of test
140 test
= open_tests
.pop(testname
)
142 test
= subunit
.RemotedTestCase(testname
)
143 msg_ops
.addSkip(test
, reason
)
144 elif result
== "error":
145 statistics
['TESTS_ERROR']+=1
148 test
= open_tests
.pop(testname
)
150 test
= subunit
.RemotedTestCase(testname
)
151 msg_ops
.addError(test
, remote_error
)
152 elif result
== "skip-testsuite":
153 msg_ops
.skip_testsuite(testname
)
154 elif result
== "testsuite-success":
155 msg_ops
.end_testsuite(testname
, "success", reason
)
156 elif result
== "testsuite-failure":
157 msg_ops
.end_testsuite(testname
, "failure", reason
)
159 elif result
== "testsuite-xfail":
160 msg_ops
.end_testsuite(testname
, "xfail", reason
)
161 elif result
== "testsuite-error":
162 msg_ops
.end_testsuite(testname
, "error", reason
)
165 raise AssertionError("Recognized but unhandled result %r" %
167 elif command
== "testsuite":
168 msg_ops
.start_testsuite(arg
.strip())
169 elif command
== "progress":
172 msg_ops
.progress(None, subunit
.PROGRESS_POP
)
174 msg_ops
.progress(None, subunit
.PROGRESS_PUSH
)
176 msg_ops
.progress(int(arg
), subunit
.PROGRESS_CUR
)
178 msg_ops
.progress(int(arg
), subunit
.PROGRESS_SET
)
180 msg_ops
.output_msg(l
)
183 test
= subunit
.RemotedTestCase(open_tests
.popitem()[1])
184 msg_ops
.addError(test
, subunit
.RemoteError(u
"was started but never finished!"))
185 statistics
['TESTS_ERROR']+=1
191 class SubunitOps(subunit
.TestProtocolClient
,TestsuiteEnabledTestResult
):
193 # The following are Samba extensions:
194 def start_testsuite(self
, name
):
195 self
._stream
.write("testsuite: %s\n" % name
)
197 def skip_testsuite(self
, name
, reason
=None):
199 self
._stream
.write("skip-testsuite: %s [\n%s\n]\n" % (name
, reason
))
201 self
._stream
.write("skip-testsuite: %s\n" % name
)
203 def end_testsuite(self
, name
, result
, reason
=None):
205 self
._stream
.write("testsuite-%s: %s [\n%s\n]\n" % (result
, name
, reason
))
207 self
._stream
.write("testsuite-%s: %s\n" % (result
, name
))
209 def output_msg(self
, msg
):
210 self
._stream
.write(msg
)
213 def read_test_regexes(name
):
219 if l
== "" or l
[0] == "#":
222 (regex
, reason
) = l
.split("#", 1)
223 ret
[regex
.strip()] = reason
.strip()
231 def find_in_list(regexes
, fullname
):
232 for regex
, reason
in regexes
.iteritems():
233 if re
.match(regex
, fullname
):
240 class ImmediateFail(Exception):
241 """Raised to abort immediately."""
244 super(ImmediateFail
, self
).__init
__("test failed and fail_immediately set")
247 class FilterOps(testtools
.testresult
.TestResult
):
249 def control_msg(self
, msg
):
250 pass # We regenerate control messages, so ignore this
252 def time(self
, time
):
255 def progress(self
, delta
, whence
):
256 self
._ops
.progress(delta
, whence
)
258 def output_msg(self
, msg
):
259 if self
.output
is None:
260 sys
.stdout
.write(msg
)
264 def startTest(self
, test
):
265 self
.seen_output
= True
266 test
= self
._add
_prefix
(test
)
267 if self
.strip_ok_output
:
270 self
._ops
.startTest(test
)
272 def _add_prefix(self
, test
):
273 if self
.prefix
is not None:
274 return subunit
.RemotedTestCase(self
.prefix
+ test
.id())
278 def addError(self
, test
, details
=None):
279 test
= self
._add
_prefix
(test
)
282 self
._ops
.addError(test
, details
)
284 if self
.fail_immediately
:
285 raise ImmediateFail()
287 def addSkip(self
, test
, details
=None):
288 self
.seen_output
= True
289 test
= self
._add
_prefix
(test
)
290 self
._ops
.addSkip(test
, details
)
293 def addExpectedFailure(self
, test
, details
=None):
294 test
= self
._add
_prefix
(test
)
295 self
._ops
.addExpectedFailure(test
, details
)
298 def addUnexpectedSuccess(self
, test
, details
=None):
299 test
= self
._add
_prefix
(test
)
300 self
._ops
.addUnexpectedSuccess(test
, details
)
303 def addFailure(self
, test
, details
=None):
304 test
= self
._add
_prefix
(test
)
305 xfail_reason
= find_in_list(self
.expected_failures
, test
.id())
306 if xfail_reason
is None:
307 xfail_reason
= find_in_list(self
.flapping
, test
.id())
308 if xfail_reason
is not None:
311 if details
is not None:
312 details
= subunit
.RemoteError(unicode(details
[1]) + xfail_reason
.decode("utf-8"))
314 details
= subunit
.RemoteError(xfail_reason
.decode("utf-8"))
315 self
._ops
.addExpectedFailure(test
, details
)
319 self
._ops
.addFailure(test
, details
)
321 self
._ops
.output_msg(self
.output
)
322 if self
.fail_immediately
:
323 raise ImmediateFail()
326 def addSuccess(self
, test
, details
=None):
327 test
= self
._add
_prefix
(test
)
328 xfail_reason
= find_in_list(self
.expected_failures
, test
.id())
329 if xfail_reason
is not None:
330 self
.uxsuccess_added
+= 1
331 self
.total_uxsuccess
+= 1
334 details
['reason'] = content
.Content(
335 content_type
.ContentType("text", "plain",
336 {"charset": "utf8"}), lambda: xfail_reason
)
337 self
._ops
.addUnexpectedSuccess(test
, details
)
339 self
._ops
.output_msg(self
.output
)
340 if self
.fail_immediately
:
341 raise ImmediateFail()
343 self
._ops
.addSuccess(test
, details
)
346 def skip_testsuite(self
, name
, reason
=None):
347 self
._ops
.skip_testsuite(name
, reason
)
349 def start_testsuite(self
, name
):
350 self
._ops
.start_testsuite(name
)
354 self
.uxsuccess_added
= 0
356 def end_testsuite(self
, name
, result
, reason
=None):
359 if self
.xfail_added
> 0:
361 if self
.fail_added
> 0 or self
.error_added
> 0:
364 if xfail
and result
in ("fail", "failure"):
367 if self
.fail_added
> 0 and result
!= "failure":
370 reason
= "Subunit/Filter Reason"
371 reason
+= "\n failures[%d]" % self
.fail_added
373 if self
.error_added
> 0 and result
!= "error":
376 reason
= "Subunit/Filter Reason"
377 reason
+= "\n errors[%d]" % self
.error_added
379 self
._ops
.end_testsuite(name
, result
, reason
)
381 def __init__(self
, out
, prefix
=None, expected_failures
=None,
382 strip_ok_output
=False, fail_immediately
=False,
385 self
.seen_output
= False
388 if expected_failures
is not None:
389 self
.expected_failures
= expected_failures
391 self
.expected_failures
= {}
392 if flapping
is not None:
393 self
.flapping
= flapping
396 self
.strip_ok_output
= strip_ok_output
399 self
.uxsuccess_added
= 0
403 self
.total_uxsuccess
= 0
405 self
.fail_immediately
= fail_immediately
408 class PlainFormatter(TestsuiteEnabledTestResult
):
410 def __init__(self
, verbose
, immediate
, statistics
,
412 super(PlainFormatter
, self
).__init
__()
413 self
.verbose
= verbose
414 self
.immediate
= immediate
415 self
.statistics
= statistics
416 self
.start_time
= None
417 self
.test_output
= {}
418 self
.suitesfailed
= []
423 self
._progress
_level
= 0
424 self
.totalsuites
= totaltests
425 self
.last_time
= None
428 def _format_time(delta
):
429 minutes
, seconds
= divmod(delta
.seconds
, 60)
430 hours
, minutes
= divmod(minutes
, 60)
435 ret
+= "%dm" % minutes
436 ret
+= "%ds" % seconds
439 def progress(self
, offset
, whence
):
440 if whence
== subunit
.PROGRESS_POP
:
441 self
._progress
_level
-= 1
442 elif whence
== subunit
.PROGRESS_PUSH
:
443 self
._progress
_level
+= 1
444 elif whence
== subunit
.PROGRESS_SET
:
445 if self
._progress
_level
== 0:
446 self
.totalsuites
= offset
447 elif whence
== subunit
.PROGRESS_CUR
:
448 raise NotImplementedError
451 if self
.start_time
is None:
455 def start_testsuite(self
, name
):
460 self
.test_output
[name
] = ""
462 out
= "[%d" % self
.index
463 if self
.totalsuites
is not None:
464 out
+= "/%d" % self
.totalsuites
465 if self
.start_time
is not None:
466 out
+= " in " + self
._format
_time
(self
.last_time
- self
.start_time
)
467 if self
.suitesfailed
:
468 out
+= ", %d errors" % (len(self
.suitesfailed
),)
471 sys
.stdout
.write(out
+ "\n")
473 sys
.stdout
.write(out
+ ": ")
475 def output_msg(self
, output
):
477 sys
.stdout
.write(output
)
478 elif self
.name
is not None:
479 self
.test_output
[self
.name
] += output
481 sys
.stdout
.write(output
)
483 def control_msg(self
, output
):
486 def end_testsuite(self
, name
, result
, reason
):
490 if not name
in self
.test_output
:
491 print "no output for name[%s]" % name
493 if result
in ("success", "xfail"):
496 self
.output_msg("ERROR: Testsuite[%s]\n" % name
)
497 if reason
is not None:
498 self
.output_msg("REASON: %s\n" % (reason
,))
499 self
.suitesfailed
.append(name
)
500 if self
.immediate
and not self
.verbose
and name
in self
.test_output
:
501 out
+= self
.test_output
[name
]
504 if not self
.immediate
:
508 out
+= " " + result
.upper() + "\n"
510 sys
.stdout
.write(out
)
512 def startTest(self
, test
):
515 def addSuccess(self
, test
):
516 self
.end_test(test
.id(), "success", False)
518 def addError(self
, test
, details
=None):
519 self
.end_test(test
.id(), "error", True, details
)
521 def addFailure(self
, test
, details
=None):
522 self
.end_test(test
.id(), "failure", True, details
)
524 def addSkip(self
, test
, details
=None):
525 self
.end_test(test
.id(), "skip", False, details
)
527 def addExpectedFailure(self
, test
, details
=None):
528 self
.end_test(test
.id(), "xfail", False, details
)
530 def addUnexpectedSuccess(self
, test
, details
=None):
531 self
.end_test(test
.id(), "uxsuccess", True, details
)
533 def end_test(self
, testname
, result
, unexpected
, details
=None):
535 self
.test_output
[self
.name
] = ""
536 if not self
.immediate
:
541 'success': '.'}.get(result
, "?(%s)" % result
))
544 if not self
.name
in self
.test_output
:
545 self
.test_output
[self
.name
] = ""
547 self
.test_output
[self
.name
] += "UNEXPECTED(%s): %s\n" % (result
, testname
)
548 if details
is not None:
549 self
.test_output
[self
.name
] += "REASON: %s\n" % (unicode(details
[1]).encode("utf-8").strip(),)
551 if self
.immediate
and not self
.verbose
:
552 sys
.stdout
.write(self
.test_output
[self
.name
])
553 self
.test_output
[self
.name
] = ""
555 if not self
.immediate
:
560 'success': 'S'}.get(result
, "?"))
562 def write_summary(self
, path
):
565 if self
.suitesfailed
:
566 f
.write("= Failed tests =\n")
568 for suite
in self
.suitesfailed
:
569 f
.write("== %s ==\n" % suite
)
570 if suite
in self
.test_output
:
571 f
.write(self
.test_output
[suite
]+"\n\n")
575 if not self
.immediate
and not self
.verbose
:
576 for suite
in self
.suitesfailed
:
578 print "FAIL: %s" % suite
579 if suite
in self
.test_output
:
580 print self
.test_output
[suite
]
583 f
.write("= Skipped tests =\n")
584 for reason
in self
.skips
.keys():
585 f
.write(reason
+ "\n")
586 for name
in self
.skips
[reason
]:
587 f
.write("\t%s\n" % name
)
591 if (not self
.suitesfailed
and
592 not self
.statistics
['TESTS_UNEXPECTED_FAIL'] and
593 not self
.statistics
['TESTS_UNEXPECTED_OK'] and
594 not self
.statistics
['TESTS_ERROR']):
595 ok
= (self
.statistics
['TESTS_EXPECTED_OK'] +
596 self
.statistics
['TESTS_EXPECTED_FAIL'])
597 print "\nALL OK (%d tests in %d testsuites)" % (ok
, self
.suites_ok
)
599 print "\nFAILED (%d failures, %d errors and %d unexpected successes in %d testsuites)" % (
600 self
.statistics
['TESTS_UNEXPECTED_FAIL'],
601 self
.statistics
['TESTS_ERROR'],
602 self
.statistics
['TESTS_UNEXPECTED_OK'],
603 len(self
.suitesfailed
))
605 def skip_testsuite(self
, name
, reason
="UNKNOWN"):
606 self
.skips
.setdefault(reason
, []).append(name
)