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