subunithelper: Fix format time.
[sfrench/samba-autobuild/.git] / selftest / subunithelper.py
1 # Python module for parsing and generating the Subunit protocol
2 # (Samba-specific)
3 # Copyright (C) 2008-2009 Jelmer Vernooij <jelmer@samba.org>
4 #
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.
9
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.
14
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/>.
17
18 __all__ = ['parse_results']
19
20 import re
21 import sys
22 import subunit
23 import subunit.iso8601
24 import testtools
25
26 VALID_RESULTS = ['success', 'successful', 'failure', 'fail', 'skip', 'knownfail', 'error', 'xfail', 'skip-testsuite', 'testsuite-failure', 'testsuite-xfail', 'testsuite-success', 'testsuite-error']
27
28 class TestsuiteEnabledTestResult(testtools.testresult.TestResult):
29
30     def start_testsuite(self, name):
31         raise NotImplementedError(self.start_testsuite)
32
33
34 def parse_results(msg_ops, statistics, fh):
35     expected_fail = 0
36     open_tests = {}
37
38     while fh:
39         l = fh.readline()
40         if l == "":
41             break
42         parts = l.split(None, 1)
43         if not len(parts) == 2 or not l.startswith(parts[0]):
44             msg_ops.output_msg(l)
45             continue
46         command = parts[0].rstrip(":")
47         arg = parts[1]
48         if command in ("test", "testing"):
49             msg_ops.control_msg(l)
50             name = arg.rstrip()
51             test = subunit.RemotedTestCase(name)
52             if name in open_tests:
53                 msg_ops.addError(open_tests.pop(name), subunit.RemoteError(u"Test already running"))
54             msg_ops.startTest(test)
55             open_tests[name] = test
56         elif command == "time":
57             msg_ops.control_msg(l)
58             try:
59                 dt = subunit.iso8601.parse_date(arg.rstrip("\n"))
60             except TypeError, e:
61                 print "Unable to parse time line: %s" % arg.rstrip("\n")
62             else:
63                 msg_ops.time(dt)
64         elif command in VALID_RESULTS:
65             msg_ops.control_msg(l)
66             result = command
67             grp = re.match("(.*?)( \[)?([ \t]*)( multipart)?\n", arg)
68             (testname, hasreason) = (grp.group(1), grp.group(2))
69             if hasreason:
70                 reason = ""
71                 # reason may be specified in next lines
72                 terminated = False
73                 while fh:
74                     l = fh.readline()
75                     if l == "":
76                         break
77                     msg_ops.control_msg(l)
78                     if l == "]\n":
79                         terminated = True
80                         break
81                     else:
82                         reason += l
83
84                 remote_error = subunit.RemoteError(reason.decode("utf-8"))
85
86                 if not terminated:
87                     statistics['TESTS_ERROR']+=1
88                     msg_ops.addError(subunit.RemotedTestCase(testname), subunit.RemoteError(u"reason (%s) interrupted" % result))
89                     return 1
90             else:
91                 reason = None
92                 remote_error = subunit.RemoteError(u"No reason specified")
93             if result in ("success", "successful"):
94                 try:
95                     test = open_tests.pop(testname)
96                 except KeyError:
97                     statistics['TESTS_ERROR']+=1
98                     msg_ops.addError(subunit.RemotedTestCase(testname), subunit.RemoteError(u"Test was never started"))
99                 else:
100                     statistics['TESTS_EXPECTED_OK']+=1
101                     msg_ops.addSuccess(test)
102             elif result in ("xfail", "knownfail"):
103                 try:
104                     test = open_tests.pop(testname)
105                 except KeyError:
106                     statistics['TESTS_ERROR']+=1
107                     msg_ops.addError(subunit.RemotedTestCase(testname), subunit.RemoteError(u"Test was never started"))
108                 else:
109                     statistics['TESTS_EXPECTED_FAIL']+=1
110                     msg_ops.addExpectedFailure(test, remote_error)
111                     expected_fail+=1
112             elif result in ("failure", "fail"):
113                 try:
114                     test = open_tests.pop(testname)
115                 except KeyError:
116                     statistics['TESTS_ERROR']+=1
117                     msg_ops.addError(subunit.RemotedTestCase(testname), subunit.RemoteError(u"Test was never started"))
118                 else:
119                     statistics['TESTS_UNEXPECTED_FAIL']+=1
120                     msg_ops.addFailure(test, remote_error)
121             elif result == "skip":
122                 statistics['TESTS_SKIP']+=1
123                 # Allow tests to be skipped without prior announcement of test
124                 try:
125                     test = open_tests.pop(testname)
126                 except KeyError:
127                     test = subunit.RemotedTestCase(testname)
128                 msg_ops.addSkip(test, reason)
129             elif result == "error":
130                 statistics['TESTS_ERROR']+=1
131                 try:
132                     test = open_tests.pop(testname)
133                 except KeyError:
134                     test = subunit.RemotedTestCase(testname)
135                 msg_ops.addError(test, remote_error)
136             elif result == "skip-testsuite":
137                 msg_ops.skip_testsuite(testname)
138             elif result == "testsuite-success":
139                 msg_ops.end_testsuite(testname, "success", reason)
140             elif result == "testsuite-failure":
141                 msg_ops.end_testsuite(testname, "failure", reason)
142             elif result == "testsuite-xfail":
143                 msg_ops.end_testsuite(testname, "xfail", reason)
144             elif result == "testsuite-error":
145                 msg_ops.end_testsuite(testname, "error", reason)
146             else:
147                 raise AssertionError("Recognized but unhandled result %r" %
148                     result)
149         elif command == "testsuite":
150             msg_ops.start_testsuite(arg.strip())
151         elif command == "progress":
152             arg = arg.strip()
153             if arg == "pop":
154                 msg_ops.progress(None, subunit.PROGRESS_POP)
155             elif arg == "push":
156                 msg_ops.progress(None, subunit.PROGRESS_PUSH)
157             elif arg[0] in '+-':
158                 msg_ops.progress(int(arg), subunit.PROGRESS_CUR)
159             else:
160                 msg_ops.progress(int(arg), subunit.PROGRESS_SET)
161         else:
162             msg_ops.output_msg(l)
163
164     while open_tests:
165         test = subunit.RemotedTestCase(open_tests.popitem()[1])
166         msg_ops.addError(test, subunit.RemoteError(u"was started but never finished!"))
167         statistics['TESTS_ERROR']+=1
168
169     if statistics['TESTS_ERROR'] > 0:
170         return 1
171     if statistics['TESTS_UNEXPECTED_FAIL'] > 0:
172         return 1
173     return 0
174
175
176 class SubunitOps(subunit.TestProtocolClient,TestsuiteEnabledTestResult):
177
178     # The following are Samba extensions:
179     def start_testsuite(self, name):
180         self._stream.write("testsuite: %s\n" % name)
181
182     def skip_testsuite(self, name, reason=None):
183         if reason:
184             self._stream.write("skip-testsuite: %s [\n%s\n]\n" % (name, reason))
185         else:
186             self._stream.write("skip-testsuite: %s\n" % name)
187
188     def end_testsuite(self, name, result, reason=None):
189         if reason:
190             self._stream.write("testsuite-%s: %s [\n%s\n]\n" % (result, name, reason))
191         else:
192             self._stream.write("testsuite-%s: %s\n" % (result, name))
193
194     def output_msg(self, msg):
195         self._stream.write(msg)
196
197
198 def read_test_regexes(name):
199     ret = {}
200     f = open(name, 'r')
201     try:
202         for l in f:
203             l = l.strip()
204             if l == "" or l[0] == "#":
205                 continue
206             if "#" in l:
207                 (regex, reason) = l.split("#", 1)
208                 ret[regex.strip()] = reason.strip()
209             else:
210                 ret[l] = None
211     finally:
212         f.close()
213     return ret
214
215
216 def find_in_list(regexes, fullname):
217     for regex, reason in regexes.iteritems():
218         if re.match(regex, fullname):
219             if reason is None:
220                 return ""
221             return reason
222     return None
223
224
225 class ImmediateFail(Exception):
226     """Raised to abort immediately."""
227
228     def __init__(self):
229         super(ImmediateFail, self).__init__("test failed and fail_immediately set")
230
231
232 class FilterOps(testtools.testresult.TestResult):
233
234     def control_msg(self, msg):
235         pass # We regenerate control messages, so ignore this
236
237     def time(self, time):
238         self._ops.time(time)
239
240     def progress(self, delta, whence):
241         self._ops.progress(delta, whence)
242
243     def output_msg(self, msg):
244         if self.output is None:
245             sys.stdout.write(msg)
246         else:
247             self.output+=msg
248
249     def startTest(self, test):
250         test = self._add_prefix(test)
251         if self.strip_ok_output:
252            self.output = ""
253
254         self._ops.startTest(test)
255
256     def _add_prefix(self, test):
257         if self.prefix is not None:
258             return subunit.RemotedTestCase(self.prefix + test.id())
259         else:
260             return test
261
262     def addError(self, test, details=None):
263         test = self._add_prefix(test)
264         self.error_added+=1
265         self.total_error+=1
266         self._ops.addError(test, details)
267         self.output = None
268         if self.fail_immediately:
269             raise ImmediateFail()
270
271     def addSkip(self, test, details=None):
272         test = self._add_prefix(test)
273         self._ops.addSkip(test, details)
274         self.output = None
275
276     def addExpectedFailure(self, test, details=None):
277         test = self._add_prefix(test)
278         self._ops.addExpectedFailure(test, details)
279         self.output = None
280
281     def addFailure(self, test, details=None):
282         test = self._add_prefix(test)
283         xfail_reason = find_in_list(self.expected_failures, test.id())
284         if xfail_reason is not None:
285             self.xfail_added+=1
286             self.total_xfail+=1
287             if details is not None:
288                 details = subunit.RemoteError(unicode(details[1]) + xfail_reason.decode("utf-8"))
289             else:
290                 details = subunit.RemoteError(xfail_reason.decode("utf-8"))
291             self._ops.addExpectedFailure(test, details)
292         else:
293             self.fail_added+=1
294             self.total_fail+=1
295             self._ops.addFailure(test, details)
296             if self.output:
297                 self._ops.output_msg(self.output)
298             if self.fail_immediately:
299                 raise ImmediateFail()
300         self.output = None
301
302     def addSuccess(self, test, details=None):
303         test = self._add_prefix(test)
304         self._ops.addSuccess(test, details)
305         self.output = None
306
307     def skip_testsuite(self, name, reason=None):
308         self._ops.skip_testsuite(name, reason)
309
310     def start_testsuite(self, name):
311         self._ops.start_testsuite(name)
312         self.error_added = 0
313         self.fail_added = 0
314         self.xfail_added = 0
315
316     def end_testsuite(self, name, result, reason=None):
317         xfail = False
318
319         if self.xfail_added > 0:
320             xfail = True
321         if self.fail_added > 0 or self.error_added > 0:
322             xfail = False
323
324         if xfail and result in ("fail", "failure"):
325             result = "xfail"
326
327         if self.fail_added > 0 and result != "failure":
328             result = "failure"
329             if reason is None:
330                 reason = "Subunit/Filter Reason"
331             reason += "\n failures[%d]" % self.fail_added
332
333         if self.error_added > 0 and result != "error":
334             result = "error"
335             if reason is None:
336                 reason = "Subunit/Filter Reason"
337             reason += "\n errors[%d]" % self.error_added
338
339         self._ops.end_testsuite(name, result, reason)
340
341     def __init__(self, out, prefix=None, expected_failures=None,
342                  strip_ok_output=False, fail_immediately=False):
343         self._ops = out
344         self.output = None
345         self.prefix = prefix
346         if expected_failures is not None:
347             self.expected_failures = expected_failures
348         else:
349             self.expected_failures = {}
350         self.strip_ok_output = strip_ok_output
351         self.xfail_added = 0
352         self.fail_added = 0
353         self.total_xfail = 0
354         self.total_error = 0
355         self.total_fail = 0
356         self.error_added = 0
357         self.fail_immediately = fail_immediately
358
359
360 class PlainFormatter(TestsuiteEnabledTestResult):
361
362     def __init__(self, verbose, immediate, statistics,
363             totaltests=None):
364         super(PlainFormatter, self).__init__()
365         self.verbose = verbose
366         self.immediate = immediate
367         self.statistics = statistics
368         self.start_time = None
369         self.test_output = {}
370         self.suitesfailed = []
371         self.suites_ok = 0
372         self.skips = {}
373         self.index = 0
374         self.name = None
375         self._progress_level = 0
376         self.totalsuites = totaltests
377         self.last_time = None
378
379     @staticmethod
380     def _format_time(delta):
381         minutes, seconds = divmod(delta.seconds, 60)
382         hours, minutes = divmod(minutes, 60)
383         ret = ""
384         if hours:
385             ret += "%dh" % hours
386         if minutes:
387             ret += "%dm" % minutes
388         ret += "%ds" % seconds
389         return ret
390
391     def progress(self, offset, whence):
392         if whence == subunit.PROGRESS_POP:
393             self._progress_level -= 1
394         elif whence == subunit.PROGRESS_PUSH:
395             self._progress_level += 1
396         elif whence == subunit.PROGRESS_SET:
397             if self._progress_level == 0:
398                 self.totalsuites = offset
399         elif whence == subunit.PROGRESS_CUR:
400             raise NotImplementedError
401
402     def time(self, dt):
403         if self.start_time is None:
404             self.start_time = dt
405         self.last_time = dt
406
407     def start_testsuite(self, name):
408         self.index += 1
409         self.name = name
410
411         if not self.verbose:
412             self.test_output[name] = ""
413
414         out = "[%d" % self.index
415         if self.totalsuites is not None:
416             out += "/%d" % self.totalsuites
417         if self.start_time is not None:
418             out += " in " + self._format_time(self.last_time - self.start_time)
419         if self.suitesfailed:
420             out += ", %d errors" % (len(self.suitesfailed),)
421         out += "] %s" % name
422         if self.immediate:
423             sys.stdout.write(out + "\n")
424         else:
425             sys.stdout.write(out + ": ")
426
427     def output_msg(self, output):
428         if self.verbose:
429             sys.stdout.write(output)
430         elif self.name is not None:
431             self.test_output[self.name] += output
432         else:
433             sys.stdout.write(output)
434
435     def control_msg(self, output):
436         pass
437
438     def end_testsuite(self, name, result, reason):
439         out = ""
440         unexpected = False
441
442         if not name in self.test_output:
443             print "no output for name[%s]" % name
444
445         if result in ("success", "xfail"):
446             self.suites_ok+=1
447         else:
448             self.output_msg("ERROR: Testsuite[%s]\n" % name)
449             if reason is not None:
450                 self.output_msg("REASON: %s\n" % (reason,))
451             self.suitesfailed.append(name)
452             if self.immediate and not self.verbose and name in self.test_output:
453                 out += self.test_output[name]
454             unexpected = True
455
456         if not self.immediate:
457             if not unexpected:
458                 out += " ok\n"
459             else:
460                 out += " " + result.upper() + "\n"
461
462         sys.stdout.write(out)
463
464     def startTest(self, test):
465         pass
466
467     def addSuccess(self, test):
468         self.end_test(test.id(), "success", False)
469
470     def addError(self, test, details=None):
471         self.end_test(test.id(), "error", True, details)
472
473     def addFailure(self, test, details=None):
474         self.end_test(test.id(), "failure", True, details)
475
476     def addSkip(self, test, details=None):
477         self.end_test(test.id(), "skip", False, details)
478
479     def addExpectedFail(self, test, details=None):
480         self.end_test(test.id(), "xfail", False, details)
481
482     def end_test(self, testname, result, unexpected, reason=None):
483         if not unexpected:
484             self.test_output[self.name] = ""
485             if not self.immediate:
486                 sys.stdout.write({
487                     'failure': 'f',
488                     'xfail': 'X',
489                     'skip': 's',
490                     'success': '.'}.get(result, "?(%s)" % result))
491             return
492
493         if not self.name in self.test_output:
494             self.test_output[self.name] = ""
495
496         self.test_output[self.name] += "UNEXPECTED(%s): %s\n" % (result, testname)
497         if reason is not None:
498             self.test_output[self.name] += "REASON: %s\n" % (reason[1].message.encode("utf-8").strip(),)
499
500         if self.immediate and not self.verbose:
501             print self.test_output[self.name]
502             self.test_output[self.name] = ""
503
504         if not self.immediate:
505             sys.stdout.write({
506                'error': 'E',
507                'failure': 'F',
508                'success': 'S'}.get(result, "?"))
509
510     def write_summary(self, path):
511         f = open(path, 'w+')
512
513         if self.suitesfailed:
514             f.write("= Failed tests =\n")
515
516             for suite in self.suitesfailed:
517                 f.write("== %s ==\n" % suite)
518                 if suite in self.test_output:
519                     f.write(self.test_output[suite]+"\n\n")
520
521             f.write("\n")
522
523         if not self.immediate and not self.verbose:
524             for suite in self.suitesfailed:
525                 print "=" * 78
526                 print "FAIL: %s" % suite
527                 if suite in self.test_output:
528                     print self.test_output[suite]
529                 print ""
530
531         f.write("= Skipped tests =\n")
532         for reason in self.skips.keys():
533             f.write(reason + "\n")
534             for name in self.skips[reason]:
535                 f.write("\t%s\n" % name)
536             f.write("\n")
537         f.close()
538
539         if (not self.suitesfailed and
540             not self.statistics['TESTS_UNEXPECTED_FAIL'] and
541             not self.statistics['TESTS_ERROR']):
542             ok = (self.statistics['TESTS_EXPECTED_OK'] +
543                   self.statistics['TESTS_EXPECTED_FAIL'])
544             print "\nALL OK (%d tests in %d testsuites)" % (ok, self.suites_ok)
545         else:
546             print "\nFAILED (%d failures and %d errors in %d testsuites)" % (
547                 self.statistics['TESTS_UNEXPECTED_FAIL'],
548                 self.statistics['TESTS_ERROR'],
549                 len(self.suitesfailed))
550
551     def skip_testsuite(self, name, reason="UNKNOWN"):
552         self.skips.setdefault(reason, []).append(name)
553         if self.totalsuites:
554             self.totalsuites-=1
555
556
557 class TestProtocolServer(subunit.TestProtocolServer):