Debian Codegraph @

python/tests/test_test_results.py

raw
1 #
2 # subunit: extensions to Python unittest to get test results from subprocesses.
3 # Copyright (C) 2009 Robert Collins <[email protected]>
4 #
5 # Licensed under either the Apache License, Version 2.0 or the BSD 3-clause
6 # license at the users choice. A copy of both licenses are available in the
7 # project source as Apache-2.0 and BSD. You may not use this file except in
8 # compliance with one of these two licences.
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under these licenses is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # license you chose for the specific language governing permissions and
14 # limitations under that license.
15 #
16
17 import csv
18 import datetime
19 import sys
20 import unittest
21 from io import StringIO
22
23 import testtools
24 from testtools import TestCase
25 from testtools.content import TracebackContent, text_content
26 from testtools.testresult.doubles import ExtendedTestResult
27
28 import subunit
29 import iso8601
30 import subunit.test_results
31
32
33 class LoggingDecorator(subunit.test_results.HookedTestResultDecorator):
34 def __init__(self, decorated):
35 self._calls = 0
36 super().__init__(decorated)
37
38 def _before_event(self):
39 self._calls += 1
40
41
42 class AssertBeforeTestResult(LoggingDecorator):
43 """A TestResult for checking preconditions."""
44
45 def __init__(self, decorated, test):
46 self.test = test
47 super().__init__(decorated)
48
49 def _before_event(self):
50 self.test.assertEqual(1, self.earlier._calls)
51 super()._before_event()
52
53
54 class TimeCapturingResult(unittest.TestResult):
55 def __init__(self):
56 super().__init__()
57 self._calls = []
58 self.failfast = False
59
60 def time(self, a_datetime):
61 self._calls.append(a_datetime)
62
63 def progress(self, offset, whence):
64 pass
65
66 def addDuration(self, test, duration):
67 """Called to add a test duration.
68
69 :param test: The test that completed.
70 :param duration: The duration of the test as a float in seconds.
71 """
72 pass
73
74
75 class TestHookedTestResultDecorator(unittest.TestCase):
76 def setUp(self):
77 # An end to the chain
78 terminal = unittest.TestResult()
79 # Asserts that the call was made to self.result before asserter was
80 # called.
81 asserter = AssertBeforeTestResult(terminal, self)
82 # The result object we call, which much increase its call count.
83 self.result = LoggingDecorator(asserter)
84 asserter.earlier = self.result
85 self.decorated = asserter
86
87 def tearDown(self):
88 # The hook in self.result must have been called
89 self.assertEqual(1, self.result._calls)
90 # The hook in asserter must have been called too, otherwise the
91 # assertion about ordering won't have completed.
92 self.assertEqual(1, self.decorated._calls)
93
94 def test_startTest(self):
95 self.result.startTest(self)
96
97 def test_startTestRun(self):
98 self.result.startTestRun()
99
100 def test_stopTest(self):
101 self.result.stopTest(self)
102
103 def test_stopTestRun(self):
104 self.result.stopTestRun()
105
106 def test_addError(self):
107 self.result.addError(self, subunit.RemoteError())
108
109 def test_addError_details(self):
110 self.result.addError(self, details={})
111
112 def test_addFailure(self):
113 self.result.addFailure(self, subunit.RemoteError())
114
115 def test_addFailure_details(self):
116 self.result.addFailure(self, details={})
117
118 def test_addSuccess(self):
119 self.result.addSuccess(self)
120
121 def test_addSuccess_details(self):
122 self.result.addSuccess(self, details={})
123
124 def test_addSkip(self):
125 self.result.addSkip(self, "foo")
126
127 def test_addSkip_details(self):
128 self.result.addSkip(self, details={})
129
130 def test_addExpectedFailure(self):
131 self.result.addExpectedFailure(self, subunit.RemoteError())
132
133 def test_addExpectedFailure_details(self):
134 self.result.addExpectedFailure(self, details={})
135
136 def test_addUnexpectedSuccess(self):
137 self.result.addUnexpectedSuccess(self)
138
139 def test_addUnexpectedSuccess_details(self):
140 self.result.addUnexpectedSuccess(self, details={})
141
142 def test_progress(self):
143 self.result.progress(1, subunit.PROGRESS_SET)
144
145 def test_wasSuccessful(self):
146 self.result.wasSuccessful()
147
148 def test_shouldStop(self):
149 self.result.shouldStop
150
151 def test_stop(self):
152 self.result.stop()
153
154 def test_time(self):
155 self.result.time(None)
156
157 def test_addDuration(self):
158 self.result.addDuration(self, 1.5)
159
160
161 class TestAutoTimingTestResultDecorator(unittest.TestCase):
162 def setUp(self):
163 # And end to the chain which captures time events.
164 terminal = TimeCapturingResult()
165 # The result object under test.
166 self.result = subunit.test_results.AutoTimingTestResultDecorator(terminal)
167 self.decorated = terminal
168
169 def test_without_time_calls_time_is_called_and_not_None(self):
170 self.result.startTest(self)
171 self.assertEqual(1, len(self.decorated._calls))
172 self.assertNotEqual(None, self.decorated._calls[0])
173
174 def test_no_time_from_progress(self):
175 self.result.progress(1, subunit.PROGRESS_CUR)
176 self.assertEqual(0, len(self.decorated._calls))
177
178 def test_no_time_from_shouldStop(self):
179 self.decorated.stop()
180 self.result.shouldStop
181 self.assertEqual(0, len(self.decorated._calls))
182
183 def test_calling_time_inhibits_automatic_time(self):
184 # Calling time() outputs a time signal immediately and prevents
185 # automatically adding one when other methods are called.
186 time = datetime.datetime(2009, 10, 11, 12, 13, 14, 15, iso8601.UTC)
187 self.result.time(time)
188 self.result.startTest(self)
189 self.result.stopTest(self)
190 self.assertEqual(1, len(self.decorated._calls))
191 self.assertEqual(time, self.decorated._calls[0])
192
193 def test_calling_time_None_enables_automatic_time(self):
194 time = datetime.datetime(2009, 10, 11, 12, 13, 14, 15, iso8601.UTC)
195 self.result.time(time)
196 self.assertEqual(1, len(self.decorated._calls))
197 self.assertEqual(time, self.decorated._calls[0])
198 # Calling None passes the None through, in case other results care.
199 self.result.time(None)
200 self.assertEqual(2, len(self.decorated._calls))
201 self.assertEqual(None, self.decorated._calls[1])
202 # Calling other methods doesn't generate an automatic time event.
203 self.result.startTest(self)
204 self.assertEqual(3, len(self.decorated._calls))
205 self.assertNotEqual(None, self.decorated._calls[2])
206
207 def test_set_failfast_True(self):
208 self.assertFalse(self.decorated.failfast)
209 self.result.failfast = True
210 self.assertTrue(self.decorated.failfast)
211
212
213 class TestTagCollapsingDecorator(TestCase):
214 def test_tags_collapsed_outside_of_tests(self):
215 result = ExtendedTestResult()
216 tag_collapser = subunit.test_results.TagCollapsingDecorator(result)
217 tag_collapser.tags({"a"}, set())
218 tag_collapser.tags({"b"}, set())
219 tag_collapser.startTest(self)
220 self.assertEqual(
221 [
222 ("tags", {"a", "b"}, set()),
223 ("startTest", self),
224 ],
225 result._events,
226 )
227
228 def test_tags_collapsed_outside_of_tests_are_flushed(self):
229 result = ExtendedTestResult()
230 tag_collapser = subunit.test_results.TagCollapsingDecorator(result)
231 tag_collapser.startTestRun()
232 tag_collapser.tags({"a"}, set())
233 tag_collapser.tags({"b"}, set())
234 tag_collapser.startTest(self)
235 tag_collapser.addSuccess(self)
236 tag_collapser.stopTest(self)
237 tag_collapser.stopTestRun()
238 self.assertEqual(
239 [
240 ("startTestRun",),
241 ("tags", {"a", "b"}, set()),
242 ("startTest", self),
243 ("addSuccess", self),
244 ("stopTest", self),
245 ("stopTestRun",),
246 ],
247 result._events,
248 )
249
250 def test_tags_forwarded_after_tests(self):
251 test = subunit.RemotedTestCase("foo")
252 result = ExtendedTestResult()
253 tag_collapser = subunit.test_results.TagCollapsingDecorator(result)
254 tag_collapser.startTestRun()
255 tag_collapser.startTest(test)
256 tag_collapser.addSuccess(test)
257 tag_collapser.stopTest(test)
258 tag_collapser.tags({"a"}, {"b"})
259 tag_collapser.stopTestRun()
260 self.assertEqual(
261 [
262 ("startTestRun",),
263 ("startTest", test),
264 ("addSuccess", test),
265 ("stopTest", test),
266 ("tags", {"a"}, {"b"}),
267 ("stopTestRun",),
268 ],
269 result._events,
270 )
271
272 def test_tags_collapsed_inside_of_tests(self):
273 result = ExtendedTestResult()
274 tag_collapser = subunit.test_results.TagCollapsingDecorator(result)
275 test = subunit.RemotedTestCase("foo")
276 tag_collapser.startTest(test)
277 tag_collapser.tags({"a"}, set())
278 tag_collapser.tags({"b"}, {"a"})
279 tag_collapser.tags({"c"}, set())
280 tag_collapser.stopTest(test)
281 self.assertEqual([("startTest", test), ("tags", {"b", "c"}, {"a"}), ("stopTest", test)], result._events)
282
283 def test_tags_collapsed_inside_of_tests_different_ordering(self):
284 result = ExtendedTestResult()
285 tag_collapser = subunit.test_results.TagCollapsingDecorator(result)
286 test = subunit.RemotedTestCase("foo")
287 tag_collapser.startTest(test)
288 tag_collapser.tags(set(), {"a"})
289 tag_collapser.tags({"a", "b"}, set())
290 tag_collapser.tags({"c"}, set())
291 tag_collapser.stopTest(test)
292 self.assertEqual([("startTest", test), ("tags", {"a", "b", "c"}, set()), ("stopTest", test)], result._events)
293
294 def test_tags_sent_before_result(self):
295 # Because addSuccess and friends tend to send subunit output
296 # immediately, and because 'tags:' before a result line means
297 # something different to 'tags:' after a result line, we need to be
298 # sure that tags are emitted before 'addSuccess' (or whatever).
299 result = ExtendedTestResult()
300 tag_collapser = subunit.test_results.TagCollapsingDecorator(result)
301 test = subunit.RemotedTestCase("foo")
302 tag_collapser.startTest(test)
303 tag_collapser.tags({"a"}, set())
304 tag_collapser.addSuccess(test)
305 tag_collapser.stopTest(test)
306 self.assertEqual(
307 [("startTest", test), ("tags", {"a"}, set()), ("addSuccess", test), ("stopTest", test)], result._events
308 )
309
310
311 class TestTimeCollapsingDecorator(TestCase):
312 def make_time(self):
313 # Heh heh.
314 return datetime.datetime(2000, 1, self.getUniqueInteger(), tzinfo=iso8601.UTC)
315
316 def test_initial_time_forwarded(self):
317 # We always forward the first time event we see.
318 result = ExtendedTestResult()
319 tag_collapser = subunit.test_results.TimeCollapsingDecorator(result)
320 a_time = self.make_time()
321 tag_collapser.time(a_time)
322 self.assertEqual([("time", a_time)], result._events)
323
324 def test_time_collapsed_to_first_and_last(self):
325 # If there are many consecutive time events, only the first and last
326 # are sent through.
327 result = ExtendedTestResult()
328 tag_collapser = subunit.test_results.TimeCollapsingDecorator(result)
329 times = [self.make_time() for i in range(5)]
330 for a_time in times:
331 tag_collapser.time(a_time)
332 tag_collapser.startTest(subunit.RemotedTestCase("foo"))
333 self.assertEqual([("time", times[0]), ("time", times[-1])], result._events[:-1])
334
335 def test_only_one_time_sent(self):
336 # If we receive a single time event followed by a non-time event, we
337 # send exactly one time event.
338 result = ExtendedTestResult()
339 tag_collapser = subunit.test_results.TimeCollapsingDecorator(result)
340 a_time = self.make_time()
341 tag_collapser.time(a_time)
342 tag_collapser.startTest(subunit.RemotedTestCase("foo"))
343 self.assertEqual([("time", a_time)], result._events[:-1])
344
345 def test_duplicate_times_not_sent(self):
346 # Many time events with the exact same time are collapsed into one
347 # time event.
348 result = ExtendedTestResult()
349 tag_collapser = subunit.test_results.TimeCollapsingDecorator(result)
350 a_time = self.make_time()
351 for i in range(5):
352 tag_collapser.time(a_time)
353 tag_collapser.startTest(subunit.RemotedTestCase("foo"))
354 self.assertEqual([("time", a_time)], result._events[:-1])
355
356 def test_no_times_inserted(self):
357 result = ExtendedTestResult()
358 tag_collapser = subunit.test_results.TimeCollapsingDecorator(result)
359 a_time = self.make_time()
360 tag_collapser.time(a_time)
361 foo = subunit.RemotedTestCase("foo")
362 tag_collapser.startTest(foo)
363 tag_collapser.addSuccess(foo)
364 tag_collapser.stopTest(foo)
365 self.assertEqual([("time", a_time), ("startTest", foo), ("addSuccess", foo), ("stopTest", foo)], result._events)
366
367
368 class TestByTestResultTests(testtools.TestCase):
369 def setUp(self):
370 super().setUp()
371 self.log = []
372 self.result = subunit.test_results.TestByTestResult(self.on_test)
373 self.result._now = iter(range(5)).__next__
374
375 def assertCalled(self, **kwargs):
376 defaults = {
377 "test": self,
378 "tags": set(),
379 "details": None,
380 "start_time": 0,
381 "stop_time": 1,
382 }
383 defaults.update(kwargs)
384 self.assertEqual([defaults], self.log)
385
386 def on_test(self, **kwargs):
387 self.log.append(kwargs)
388
389 def test_no_tests_nothing_reported(self):
390 self.result.startTestRun()
391 self.result.stopTestRun()
392 self.assertEqual([], self.log)
393
394 def test_add_success(self):
395 self.result.startTest(self)
396 self.result.addSuccess(self)
397 self.result.stopTest(self)
398 self.assertCalled(status="success")
399
400 def test_add_success_details(self):
401 self.result.startTest(self)
402 details = {"foo": "bar"}
403 self.result.addSuccess(self, details=details)
404 self.result.stopTest(self)
405 self.assertCalled(status="success", details=details)
406
407 def test_tags(self):
408 if not getattr(self.result, "tags", None):
409 self.skipTest("No tags in testtools")
410 self.result.tags(["foo"], [])
411 self.result.startTest(self)
412 self.result.addSuccess(self)
413 self.result.stopTest(self)
414 self.assertCalled(status="success", tags={"foo"})
415
416 def test_add_error(self):
417 self.result.startTest(self)
418 try:
419 1 / 0
420 except ZeroDivisionError:
421 error = sys.exc_info()
422 self.result.addError(self, error)
423 self.result.stopTest(self)
424 self.assertCalled(status="error", details={"traceback": TracebackContent(error, self)})
425
426 def test_add_error_details(self):
427 self.result.startTest(self)
428 details = {"foo": text_content("bar")}
429 self.result.addError(self, details=details)
430 self.result.stopTest(self)
431 self.assertCalled(status="error", details=details)
432
433 def test_add_failure(self):
434 self.result.startTest(self)
435 try:
436 self.fail("intentional failure")
437 except self.failureException:
438 failure = sys.exc_info()
439 self.result.addFailure(self, failure)
440 self.result.stopTest(self)
441 self.assertCalled(status="failure", details={"traceback": TracebackContent(failure, self)})
442
443 def test_add_failure_details(self):
444 self.result.startTest(self)
445 details = {"foo": text_content("bar")}
446 self.result.addFailure(self, details=details)
447 self.result.stopTest(self)
448 self.assertCalled(status="failure", details=details)
449
450 def test_add_xfail(self):
451 self.result.startTest(self)
452 try:
453 1 / 0
454 except ZeroDivisionError:
455 error = sys.exc_info()
456 self.result.addExpectedFailure(self, error)
457 self.result.stopTest(self)
458 self.assertCalled(status="xfail", details={"traceback": TracebackContent(error, self)})
459
460 def test_add_xfail_details(self):
461 self.result.startTest(self)
462 details = {"foo": text_content("bar")}
463 self.result.addExpectedFailure(self, details=details)
464 self.result.stopTest(self)
465 self.assertCalled(status="xfail", details=details)
466
467 def test_add_unexpected_success(self):
468 self.result.startTest(self)
469 details = {"foo": "bar"}
470 self.result.addUnexpectedSuccess(self, details=details)
471 self.result.stopTest(self)
472 self.assertCalled(status="success", details=details)
473
474 def test_add_skip_reason(self):
475 self.result.startTest(self)
476 reason = self.getUniqueString()
477 self.result.addSkip(self, reason)
478 self.result.stopTest(self)
479 self.assertCalled(status="skip", details={"reason": text_content(reason)})
480
481 def test_add_skip_details(self):
482 self.result.startTest(self)
483 details = {"foo": "bar"}
484 self.result.addSkip(self, details=details)
485 self.result.stopTest(self)
486 self.assertCalled(status="skip", details=details)
487
488 def test_twice(self):
489 self.result.startTest(self)
490 self.result.addSuccess(self, details={"foo": "bar"})
491 self.result.stopTest(self)
492 self.result.startTest(self)
493 self.result.addSuccess(self)
494 self.result.stopTest(self)
495 self.assertEqual(
496 [
497 {
498 "test": self,
499 "status": "success",
500 "start_time": 0,
501 "stop_time": 1,
502 "tags": set(),
503 "details": {"foo": "bar"},
504 },
505 {"test": self, "status": "success", "start_time": 2, "stop_time": 3, "tags": set(), "details": None},
506 ],
507 self.log,
508 )
509
510
511 class TestCsvResult(testtools.TestCase):
512 def parse_stream(self, stream):
513 stream.seek(0)
514 reader = csv.reader(stream)
515 return list(reader)
516
517 def test_csv_output(self):
518 stream = StringIO()
519 result = subunit.test_results.CsvResult(stream)
520 result._now = iter(range(5)).__next__
521 result.startTestRun()
522 result.startTest(self)
523 result.addSuccess(self)
524 result.stopTest(self)
525 result.stopTestRun()
526 self.assertEqual(
527 [
528 ["test", "status", "start_time", "stop_time"],
529 [self.id(), "success", "0", "1"],
530 ],
531 self.parse_stream(stream),
532 )
533
534 def test_just_header_when_no_tests(self):
535 stream = StringIO()
536 result = subunit.test_results.CsvResult(stream)
537 result.startTestRun()
538 result.stopTestRun()
539 self.assertEqual([["test", "status", "start_time", "stop_time"]], self.parse_stream(stream))
540
541 def test_no_output_before_events(self):
542 stream = StringIO()
543 subunit.test_results.CsvResult(stream)
544 self.assertEqual([], self.parse_stream(stream))
545
546
547 class TestTestIdPrintingResult(testtools.TestCase):
548 def setUp(self):
549 super().setUp()
550 self.stream = StringIO()
551 self.result = subunit.test_results.TestIdPrintingResult(self.stream)
552
553 def test_addDuration(self):
554 # addDuration should not raise an exception
555 test = subunit.RemotedTestCase("foo")
556 self.result.addDuration(test, 2.5)
557 # TestIdPrintingResult doesn't output anything for addDuration
558 self.assertEqual("", self.stream.getvalue())