blob: 8f5cd2e428a94fde4e4b515f009e23143235626c [file] [log] [blame]
Michael Foord2560e5c2010-03-27 12:34:21 +00001import io
Ezio Melotti60901872010-12-01 00:56:10 +00002import os
3import sys
Michael Foord2560e5c2010-03-27 12:34:21 +00004import pickle
Ezio Melotti60901872010-12-01 00:56:10 +00005import subprocess
Michael Foord2560e5c2010-03-27 12:34:21 +00006
7import unittest
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +01008from unittest.case import _Outcome
Michael Foord2560e5c2010-03-27 12:34:21 +00009
10from .support import LoggingResult, ResultWithNoStartTestRunStopTestRun
11
12
13class TestCleanUp(unittest.TestCase):
14
15 def testCleanUp(self):
16 class TestableTest(unittest.TestCase):
17 def testNothing(self):
18 pass
19
20 test = TestableTest('testNothing')
21 self.assertEqual(test._cleanups, [])
22
23 cleanups = []
24
25 def cleanup1(*args, **kwargs):
26 cleanups.append((1, args, kwargs))
27
28 def cleanup2(*args, **kwargs):
29 cleanups.append((2, args, kwargs))
30
31 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
32 test.addCleanup(cleanup2)
33
34 self.assertEqual(test._cleanups,
35 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
36 (cleanup2, (), {})])
37
Michael Foordb3468f72010-12-19 03:19:47 +000038 self.assertTrue(test.doCleanups())
Michael Foord2560e5c2010-03-27 12:34:21 +000039 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
40
41 def testCleanUpWithErrors(self):
42 class TestableTest(unittest.TestCase):
43 def testNothing(self):
44 pass
45
Michael Foord2560e5c2010-03-27 12:34:21 +000046 test = TestableTest('testNothing')
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +010047 outcome = test._outcome = _Outcome()
Michael Foord2560e5c2010-03-27 12:34:21 +000048
49 exc1 = Exception('foo')
50 exc2 = Exception('bar')
51 def cleanup1():
52 raise exc1
53
54 def cleanup2():
55 raise exc2
56
57 test.addCleanup(cleanup1)
58 test.addCleanup(cleanup2)
59
60 self.assertFalse(test.doCleanups())
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +010061 self.assertFalse(outcome.success)
Michael Foord2560e5c2010-03-27 12:34:21 +000062
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +010063 ((_, (Type1, instance1, _)),
64 (_, (Type2, instance2, _))) = reversed(outcome.errors)
Michael Foordb3468f72010-12-19 03:19:47 +000065 self.assertEqual((Type1, instance1), (Exception, exc1))
66 self.assertEqual((Type2, instance2), (Exception, exc2))
Michael Foord2560e5c2010-03-27 12:34:21 +000067
68 def testCleanupInRun(self):
69 blowUp = False
70 ordering = []
71
72 class TestableTest(unittest.TestCase):
73 def setUp(self):
74 ordering.append('setUp')
75 if blowUp:
76 raise Exception('foo')
77
78 def testNothing(self):
79 ordering.append('test')
80
81 def tearDown(self):
82 ordering.append('tearDown')
83
84 test = TestableTest('testNothing')
85
86 def cleanup1():
87 ordering.append('cleanup1')
88 def cleanup2():
89 ordering.append('cleanup2')
90 test.addCleanup(cleanup1)
91 test.addCleanup(cleanup2)
92
93 def success(some_test):
94 self.assertEqual(some_test, test)
95 ordering.append('success')
96
97 result = unittest.TestResult()
98 result.addSuccess = success
99
100 test.run(result)
101 self.assertEqual(ordering, ['setUp', 'test', 'tearDown',
102 'cleanup2', 'cleanup1', 'success'])
103
104 blowUp = True
105 ordering = []
106 test = TestableTest('testNothing')
107 test.addCleanup(cleanup1)
108 test.run(result)
109 self.assertEqual(ordering, ['setUp', 'cleanup1'])
110
Michael Foordb8748742010-06-10 16:16:08 +0000111 def testTestCaseDebugExecutesCleanups(self):
112 ordering = []
113
114 class TestableTest(unittest.TestCase):
115 def setUp(self):
116 ordering.append('setUp')
117 self.addCleanup(cleanup1)
118
119 def testNothing(self):
120 ordering.append('test')
121
122 def tearDown(self):
123 ordering.append('tearDown')
124
125 test = TestableTest('testNothing')
126
127 def cleanup1():
128 ordering.append('cleanup1')
129 test.addCleanup(cleanup2)
130 def cleanup2():
131 ordering.append('cleanup2')
132
133 test.debug()
134 self.assertEqual(ordering, ['setUp', 'test', 'tearDown', 'cleanup1', 'cleanup2'])
135
Michael Foord2560e5c2010-03-27 12:34:21 +0000136
137class Test_TextTestRunner(unittest.TestCase):
138 """Tests for TextTestRunner."""
139
Michael Foord56fdb752010-05-07 16:00:30 +0000140 def test_init(self):
141 runner = unittest.TextTestRunner()
142 self.assertFalse(runner.failfast)
143 self.assertFalse(runner.buffer)
144 self.assertEqual(runner.verbosity, 1)
Ezio Melotti60901872010-12-01 00:56:10 +0000145 self.assertEqual(runner.warnings, None)
Michael Foord56fdb752010-05-07 16:00:30 +0000146 self.assertTrue(runner.descriptions)
147 self.assertEqual(runner.resultclass, unittest.TextTestResult)
148
149
Michael Foord7a1901f2012-09-28 14:14:03 +0100150 def test_multiple_inheritance(self):
151 class AResult(unittest.TestResult):
152 def __init__(self, stream, descriptions, verbosity):
153 super(AResult, self).__init__(stream, descriptions, verbosity)
154
155 class ATextResult(unittest.TextTestResult, AResult):
156 pass
157
158 # This used to raise an exception due to TextTestResult not passing
159 # on arguments in its __init__ super call
160 ATextResult(None, None, 1)
161
162
Michael Foord56fdb752010-05-07 16:00:30 +0000163 def testBufferAndFailfast(self):
164 class Test(unittest.TestCase):
165 def testFoo(self):
166 pass
167 result = unittest.TestResult()
168 runner = unittest.TextTestRunner(stream=io.StringIO(), failfast=True,
169 buffer=True)
170 # Use our result object
171 runner._makeResult = lambda: result
172 runner.run(Test('testFoo'))
173
174 self.assertTrue(result.failfast)
175 self.assertTrue(result.buffer)
176
177 def testRunnerRegistersResult(self):
178 class Test(unittest.TestCase):
179 def testFoo(self):
180 pass
181 originalRegisterResult = unittest.runner.registerResult
182 def cleanup():
183 unittest.runner.registerResult = originalRegisterResult
184 self.addCleanup(cleanup)
185
186 result = unittest.TestResult()
187 runner = unittest.TextTestRunner(stream=io.StringIO())
188 # Use our result object
189 runner._makeResult = lambda: result
190
191 self.wasRegistered = 0
192 def fakeRegisterResult(thisResult):
193 self.wasRegistered += 1
194 self.assertEqual(thisResult, result)
195 unittest.runner.registerResult = fakeRegisterResult
196
197 runner.run(unittest.TestSuite())
198 self.assertEqual(self.wasRegistered, 1)
199
Michael Foord2560e5c2010-03-27 12:34:21 +0000200 def test_works_with_result_without_startTestRun_stopTestRun(self):
201 class OldTextResult(ResultWithNoStartTestRunStopTestRun):
202 separator2 = ''
203 def printErrors(self):
204 pass
205
206 class Runner(unittest.TextTestRunner):
207 def __init__(self):
208 super(Runner, self).__init__(io.StringIO())
209
210 def _makeResult(self):
211 return OldTextResult()
212
213 runner = Runner()
214 runner.run(unittest.TestSuite())
215
216 def test_startTestRun_stopTestRun_called(self):
217 class LoggingTextResult(LoggingResult):
218 separator2 = ''
219 def printErrors(self):
220 pass
221
222 class LoggingRunner(unittest.TextTestRunner):
223 def __init__(self, events):
224 super(LoggingRunner, self).__init__(io.StringIO())
225 self._events = events
226
227 def _makeResult(self):
228 return LoggingTextResult(self._events)
229
230 events = []
231 runner = LoggingRunner(events)
232 runner.run(unittest.TestSuite())
233 expected = ['startTestRun', 'stopTestRun']
234 self.assertEqual(events, expected)
235
236 def test_pickle_unpickle(self):
237 # Issue #7197: a TextTestRunner should be (un)pickleable. This is
238 # required by test_multiprocessing under Windows (in verbose mode).
239 stream = io.StringIO("foo")
240 runner = unittest.TextTestRunner(stream)
241 for protocol in range(2, pickle.HIGHEST_PROTOCOL + 1):
242 s = pickle.dumps(runner, protocol)
243 obj = pickle.loads(s)
244 # StringIO objects never compare equal, a cheap test instead.
245 self.assertEqual(obj.stream.getvalue(), stream.getvalue())
246
247 def test_resultclass(self):
248 def MockResultClass(*args):
249 return args
250 STREAM = object()
251 DESCRIPTIONS = object()
252 VERBOSITY = object()
253 runner = unittest.TextTestRunner(STREAM, DESCRIPTIONS, VERBOSITY,
254 resultclass=MockResultClass)
255 self.assertEqual(runner.resultclass, MockResultClass)
256
257 expectedresult = (runner.stream, DESCRIPTIONS, VERBOSITY)
258 self.assertEqual(runner._makeResult(), expectedresult)
Ezio Melotti60901872010-12-01 00:56:10 +0000259
260 def test_warnings(self):
261 """
262 Check that warnings argument of TextTestRunner correctly affects the
263 behavior of the warnings.
264 """
265 # see #10535 and the _test_warnings file for more information
266
267 def get_parse_out_err(p):
268 return [b.splitlines() for b in p.communicate()]
269 opts = dict(stdout=subprocess.PIPE, stderr=subprocess.PIPE,
270 cwd=os.path.dirname(__file__))
271 ae_msg = b'Please use assertEqual instead.'
272 at_msg = b'Please use assertTrue instead.'
273
274 # no args -> all the warnings are printed, unittest warnings only once
275 p = subprocess.Popen([sys.executable, '_test_warnings.py'], **opts)
276 out, err = get_parse_out_err(p)
Ezio Melottif10c4002010-12-01 01:45:53 +0000277 self.assertIn(b'OK', err)
Ezio Melotti60901872010-12-01 00:56:10 +0000278 # check that the total number of warnings in the output is correct
279 self.assertEqual(len(out), 12)
280 # check that the numbers of the different kind of warnings is correct
281 for msg in [b'dw', b'iw', b'uw']:
282 self.assertEqual(out.count(msg), 3)
283 for msg in [ae_msg, at_msg, b'rw']:
284 self.assertEqual(out.count(msg), 1)
285
286 args_list = (
287 # passing 'ignore' as warnings arg -> no warnings
288 [sys.executable, '_test_warnings.py', 'ignore'],
289 # -W doesn't affect the result if the arg is passed
290 [sys.executable, '-Wa', '_test_warnings.py', 'ignore'],
291 # -W affects the result if the arg is not passed
292 [sys.executable, '-Wi', '_test_warnings.py']
293 )
294 # in all these cases no warnings are printed
295 for args in args_list:
296 p = subprocess.Popen(args, **opts)
297 out, err = get_parse_out_err(p)
Ezio Melottif10c4002010-12-01 01:45:53 +0000298 self.assertIn(b'OK', err)
Ezio Melotti60901872010-12-01 00:56:10 +0000299 self.assertEqual(len(out), 0)
300
301
302 # passing 'always' as warnings arg -> all the warnings printed,
303 # unittest warnings only once
304 p = subprocess.Popen([sys.executable, '_test_warnings.py', 'always'],
305 **opts)
306 out, err = get_parse_out_err(p)
Ezio Melottif10c4002010-12-01 01:45:53 +0000307 self.assertIn(b'OK', err)
Ezio Melotti60901872010-12-01 00:56:10 +0000308 self.assertEqual(len(out), 14)
309 for msg in [b'dw', b'iw', b'uw', b'rw']:
310 self.assertEqual(out.count(msg), 3)
311 for msg in [ae_msg, at_msg]:
312 self.assertEqual(out.count(msg), 1)
Michael Foord6f17e2d2010-12-30 19:36:29 +0000313
314 def testStdErrLookedUpAtInstantiationTime(self):
315 # see issue 10786
316 old_stderr = sys.stderr
317 f = io.StringIO()
318 sys.stderr = f
319 try:
320 runner = unittest.TextTestRunner()
321 self.assertTrue(runner.stream.stream is f)
322 finally:
323 sys.stderr = old_stderr
324
325 def testSpecifiedStreamUsed(self):
326 # see issue 10786
327 f = io.StringIO()
328 runner = unittest.TextTestRunner(f)
329 self.assertTrue(runner.stream.stream is f)