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