subunit: Use subunit standard functions for handling time and progress.
[amitay/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(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 startTest(self, testname):
175         self._stream.write("test: %s\n" % testname)
176
177     def end_test(self, name, result, reason=None):
178         if reason:
179             self._stream.write("%s: %s [\n%s\n]\n" % (result, name, reason))
180         else:
181             self._stream.write("%s: %s\n" % (result, name))
182
183     def skip_test(self, name, reason=None):
184         self.end_test(name, "skip", reason)
185
186     def fail_test(self, name, reason=None):
187         self.end_test(name, "fail", reason)
188
189     def success_test(self, name, reason=None):
190         self.end_test(name, "success", reason)
191
192     def xfail_test(self, name, reason=None):
193         self.end_test(name, "xfail", reason)
194
195     # The following are Samba extensions:
196     def start_testsuite(self, name):
197         self._stream.write("testsuite: %s\n" % name)
198
199     def skip_testsuite(self, name, reason=None):
200         if reason:
201             self._stream.write("skip-testsuite: %s [\n%s\n]\n" % (name, reason))
202         else:
203             self._stream.write("skip-testsuite: %s\n" % name)
204
205     def end_testsuite(self, name, result, reason=None):
206         if reason:
207             self._stream.write("testsuite-%s: %s [\n%s\n]\n" % (result, name, reason))
208         else:
209             self._stream.write("testsuite-%s: %s\n" % (result, name))
210
211
212 def read_test_regexes(name):
213     ret = {}
214     f = open(name, 'r')
215     try:
216         for l in f:
217             l = l.strip()
218             if l == "" or l[0] == "#":
219                 continue
220             if "#" in l:
221                 (regex, reason) = l.split("#", 1)
222                 ret[regex.strip()] = reason.strip()
223             else:
224                 ret[l] = None
225     finally:
226         f.close()
227     return ret
228
229
230 def find_in_list(regexes, fullname):
231     for regex, reason in regexes.iteritems():
232         if re.match(regex, fullname):
233             if reason is None:
234                 return ""
235             return reason
236     return None
237
238
239 class FilterOps(testtools.testresult.TestResult):
240
241     def control_msg(self, msg):
242         pass # We regenerate control messages, so ignore this
243
244     def time(self, time):
245         self._ops.time(time)
246
247     def progress(self, delta, whence):
248         self._ops.progress(delta, whence)
249
250     def output_msg(self, msg):
251         if self.output is None:
252             sys.stdout.write(msg)
253         else:
254             self.output+=msg
255
256     def startTest(self, testname):
257         if self.prefix is not None:
258             testname = self.prefix + testname
259
260         if self.strip_ok_output:
261            self.output = ""
262
263         self._ops.startTest(testname)
264
265     def end_test(self, testname, result, unexpected, reason):
266         if self.prefix is not None:
267             testname = self.prefix + testname
268
269         if result in ("fail", "failure") and not unexpected:
270             result = "xfail"
271             self.xfail_added+=1
272             self.total_xfail+=1
273         xfail_reason = find_in_list(self.expected_failures, testname)
274         if xfail_reason is not None and result in ("fail", "failure"):
275             result = "xfail"
276             self.xfail_added+=1
277             self.total_xfail+=1
278             reason += xfail_reason
279
280         if result in ("fail", "failure"):
281             self.fail_added+=1
282             self.total_fail+=1
283
284         if result == "error":
285             self.error_added+=1
286             self.total_error+=1
287
288         if self.strip_ok_output:
289             if result not in ("success", "xfail", "skip"):
290                 print self.output
291         self.output = None
292
293         self._ops.end_test(testname, result, reason)
294
295     def skip_testsuite(self, name, reason=None):
296         self._ops.skip_testsuite(name, reason)
297
298     def start_testsuite(self, name):
299         self._ops.start_testsuite(name)
300
301         self.error_added = 0
302         self.fail_added = 0
303         self.xfail_added = 0
304
305     def end_testsuite(self, name, result, reason=None):
306         xfail = False
307
308         if self.xfail_added > 0:
309             xfail = True
310         if self.fail_added > 0 or self.error_added > 0:
311             xfail = False
312
313         if xfail and result in ("fail", "failure"):
314             result = "xfail"
315
316         if self.fail_added > 0 and result != "failure":
317             result = "failure"
318             if reason is None:
319                 reason = "Subunit/Filter Reason"
320             reason += "\n failures[%d]" % self.fail_added
321
322         if self.error_added > 0 and result != "error":
323             result = "error"
324             if reason is None:
325                 reason = "Subunit/Filter Reason"
326             reason += "\n errors[%d]" % self.error_added
327
328         self._ops.end_testsuite(name, result, reason)
329
330     def __init__(self, out, prefix, expected_failures, strip_ok_output):
331         self._ops = out
332         self.output = None
333         self.prefix = prefix
334         self.expected_failures = expected_failures
335         self.strip_ok_output = strip_ok_output
336         self.xfail_added = 0
337         self.total_xfail = 0
338         self.total_error = 0
339         self.total_fail = 0