subunit: Use standard subunit test protocol client, use standard name for startTest.
[bbaumbach/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 testtools
24 import time
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             msg_ops.startTest(arg.rstrip())
51             open_tests.append(arg.rstrip())
52         elif command == "time":
53             msg_ops.control_msg(l)
54             grp = re.match(
55                 '(\d+)-(\d+)-(\d+) (\d+):(\d+):([.0-9]+)\n', arg)
56             if grp is None:
57                 grp = re.match(
58                     '(\d+)-(\d+)-(\d+) (\d+):(\d+):([.0-9]+)Z\n', arg)
59                 if grp is None:
60                     print "Unable to parse time line: %s" % arg
61             if grp is not None:
62                 msg_ops.report_time(time.mktime((int(grp.group(1)), int(grp.group(2)), int(grp.group(3)), int(grp.group(4)), int(grp.group(5)), int(float(grp.group(6))), 0, 0, 0)))
63         elif command in VALID_RESULTS:
64             msg_ops.control_msg(l)
65             result = command
66             grp = re.match("(.*?)( \[)?([ \t]*)( multipart)?\n", arg)
67             (testname, hasreason) = (grp.group(1), grp.group(2))
68             if hasreason:
69                 reason = ""
70                 # reason may be specified in next lines
71                 terminated = False
72                 while fh:
73                     l = fh.readline()
74                     if l == "":
75                         break
76                     msg_ops.control_msg(l)
77                     if l == "]\n":
78                         terminated = True
79                         break
80                     else:
81                         reason += l
82
83                 if not terminated:
84                     statistics['TESTS_ERROR']+=1
85                     msg_ops.end_test(testname, "error", True, 
86                                        "reason (%s) interrupted" % result)
87                     return 1
88             else:
89                 reason = None
90             if result in ("success", "successful"):
91                 try:
92                     open_tests.remove(testname)
93                 except ValueError:
94                     statistics['TESTS_ERROR']+=1
95                     msg_ops.end_test(testname, "error", True, 
96                             "Test was never started")
97                 else:
98                     statistics['TESTS_EXPECTED_OK']+=1
99                     msg_ops.end_test(testname, "success", False, reason)
100             elif result in ("xfail", "knownfail"):
101                 try:
102                     open_tests.remove(testname)
103                 except ValueError:
104                     statistics['TESTS_ERROR']+=1
105                     msg_ops.end_test(testname, "error", True, 
106                             "Test was never started")
107                 else:
108                     statistics['TESTS_EXPECTED_FAIL']+=1
109                     msg_ops.end_test(testname, "xfail", False, reason)
110                     expected_fail+=1
111             elif result in ("failure", "fail"):
112                 try:
113                     open_tests.remove(testname)
114                 except ValueError:
115                     statistics['TESTS_ERROR']+=1
116                     msg_ops.end_test(testname, "error", True, 
117                             "Test was never started")
118                 else:
119                     statistics['TESTS_UNEXPECTED_FAIL']+=1
120                     msg_ops.end_test(testname, "failure", True, reason)
121             elif result == "skip":
122                 statistics['TESTS_SKIP']+=1
123                 # Allow tests to be skipped without prior announcement of test
124                 last = open_tests.pop()
125                 if last is not None and last != testname:
126                     open_tests.append(testname)
127                 msg_ops.end_test(testname, "skip", False, reason)
128             elif result == "error":
129                 statistics['TESTS_ERROR']+=1
130                 try:
131                     open_tests.remove(testname)
132                 except ValueError:
133                     pass
134                 msg_ops.end_test(testname, "error", True, reason)
135             elif result == "skip-testsuite":
136                 msg_ops.skip_testsuite(testname)
137             elif result == "testsuite-success":
138                 msg_ops.end_testsuite(testname, "success", reason)
139             elif result == "testsuite-failure":
140                 msg_ops.end_testsuite(testname, "failure", reason)
141             elif result == "testsuite-xfail":
142                 msg_ops.end_testsuite(testname, "xfail", reason)
143             elif result == "testsuite-error":
144                 msg_ops.end_testsuite(testname, "error", reason)
145             else:
146                 raise AssertionError("Recognized but unhandled result %r" %
147                     result)
148         elif command == "testsuite":
149             msg_ops.start_testsuite(arg.strip())
150         elif command == "progress":
151             arg = arg.strip()
152             if arg == "pop":
153                 msg_ops.progress(None, subunit.PROGRESS_POP)
154             elif arg == "push":
155                 msg_ops.progress(None, subunit.PROGRESS_PUSH)
156             elif arg[0] in '+-':
157                 msg_ops.progress(int(arg), subunit.PROGRESS_CUR)
158             else:
159                 msg_ops.progress(int(arg), subunit.PROGRESS_SET)
160         else:
161             msg_ops.output_msg(l)
162
163     while open_tests:
164         msg_ops.end_test(open_tests.pop(), "error", True,
165                    "was started but never finished!")
166         statistics['TESTS_ERROR']+=1
167
168     if statistics['TESTS_ERROR'] > 0:
169         return 1
170     if statistics['TESTS_UNEXPECTED_FAIL'] > 0:
171         return 1 
172     return 0
173
174
175 class SubunitOps(subunit.TestProtocolClient,TestsuiteEnabledTestResult):
176
177     def startTest(self, testname):
178         self._stream.write("test: %s\n" % testname)
179
180     def end_test(self, name, result, reason=None):
181         if reason:
182             self._stream.write("%s: %s [\n%s\n]\n" % (result, name, reason))
183         else:
184             self._stream.write("%s: %s\n" % (result, name))
185
186     def skip_test(self, name, reason=None):
187         self.end_test(name, "skip", reason)
188
189     def fail_test(self, name, reason=None):
190         self.end_test(name, "fail", reason)
191
192     def success_test(self, name, reason=None):
193         self.end_test(name, "success", reason)
194
195     def xfail_test(self, name, reason=None):
196         self.end_test(name, "xfail", reason)
197
198     def report_time(self, t):
199         (year, mon, mday, hour, min, sec, wday, yday, isdst) = time.localtime(t)
200         self._stream.write("time: %04d-%02d-%02d %02d:%02d:%02d\n" % (year, mon, mday, hour, min, sec))
201
202     def progress(self, offset, whence):
203         if whence == subunit.PROGRESS_CUR and offset > -1:
204             prefix = "+"
205         elif whence == subunit.PROGRESS_PUSH:
206             prefix = ""
207             offset = "push"
208         elif whence == subunit.PROGRESS_POP:
209             prefix = ""
210             offset = "pop"
211         else:
212             prefix = ""
213         self._stream.write("progress: %s%s\n" % (prefix, offset))
214
215     # The following are Samba extensions:
216     def start_testsuite(self, name):
217         self._stream.write("testsuite: %s\n" % name)
218
219     def skip_testsuite(self, name, reason=None):
220         if reason:
221             self._stream.write("skip-testsuite: %s [\n%s\n]\n" % (name, reason))
222         else:
223             self._stream.write("skip-testsuite: %s\n" % name)
224
225     def end_testsuite(self, name, result, reason=None):
226         if reason:
227             self._stream.write("testsuite-%s: %s [\n%s\n]\n" % (result, name, reason))
228         else:
229             self._stream.write("testsuite-%s: %s\n" % (result, name))
230
231
232 def read_test_regexes(name):
233     ret = {}
234     f = open(name, 'r')
235     try:
236         for l in f:
237             l = l.strip()
238             if l == "" or l[0] == "#":
239                 continue
240             if "#" in l:
241                 (regex, reason) = l.split("#", 1)
242                 ret[regex.strip()] = reason.strip()
243             else:
244                 ret[l] = None
245     finally:
246         f.close()
247     return ret
248
249
250 def find_in_list(regexes, fullname):
251     for regex, reason in regexes.iteritems():
252         if re.match(regex, fullname):
253             if reason is None:
254                 return ""
255             return reason
256     return None
257
258
259 class FilterOps(testtools.testresult.TestResult):
260
261     def control_msg(self, msg):
262         pass # We regenerate control messages, so ignore this
263
264     def report_time(self, time):
265         self._ops.report_time(time)
266
267     def progress(self, delta, whence):
268         self._ops.progress(delta, whence)
269
270     def output_msg(self, msg):
271         if self.output is None:
272             sys.stdout.write(msg)
273         else:
274             self.output+=msg
275
276     def startTest(self, testname):
277         if self.prefix is not None:
278             testname = self.prefix + testname
279
280         if self.strip_ok_output:
281            self.output = ""
282
283         self._ops.startTest(testname)
284
285     def end_test(self, testname, result, unexpected, reason):
286         if self.prefix is not None:
287             testname = self.prefix + testname
288
289         if result in ("fail", "failure") and not unexpected:
290             result = "xfail"
291             self.xfail_added+=1
292             self.total_xfail+=1
293         xfail_reason = find_in_list(self.expected_failures, testname)
294         if xfail_reason is not None and result in ("fail", "failure"):
295             result = "xfail"
296             self.xfail_added+=1
297             self.total_xfail+=1
298             reason += xfail_reason
299
300         if result in ("fail", "failure"):
301             self.fail_added+=1
302             self.total_fail+=1
303
304         if result == "error":
305             self.error_added+=1
306             self.total_error+=1
307
308         if self.strip_ok_output:
309             if result not in ("success", "xfail", "skip"):
310                 print self.output
311         self.output = None
312
313         self._ops.end_test(testname, result, reason)
314
315     def skip_testsuite(self, name, reason=None):
316         self._ops.skip_testsuite(name, reason)
317
318     def start_testsuite(self, name):
319         self._ops.start_testsuite(name)
320
321         self.error_added = 0
322         self.fail_added = 0
323         self.xfail_added = 0
324
325     def end_testsuite(self, name, result, reason=None):
326         xfail = False
327
328         if self.xfail_added > 0:
329             xfail = True
330         if self.fail_added > 0 or self.error_added > 0:
331             xfail = False
332
333         if xfail and result in ("fail", "failure"):
334             result = "xfail"
335
336         if self.fail_added > 0 and result != "failure":
337             result = "failure"
338             if reason is None:
339                 reason = "Subunit/Filter Reason"
340             reason += "\n failures[%d]" % self.fail_added
341
342         if self.error_added > 0 and result != "error":
343             result = "error"
344             if reason is None:
345                 reason = "Subunit/Filter Reason"
346             reason += "\n errors[%d]" % self.error_added
347
348         self._ops.end_testsuite(name, result, reason)
349
350     def __init__(self, out, prefix, expected_failures, strip_ok_output):
351         self._ops = out
352         self.output = None
353         self.prefix = prefix
354         self.expected_failures = expected_failures
355         self.strip_ok_output = strip_ok_output
356         self.xfail_added = 0
357         self.total_xfail = 0
358         self.total_error = 0
359         self.total_fail = 0