python (3.11.7)
1 import io
2 import os
3 import sys
4 import pickle
5 import subprocess
6 from test import support
7
8 import unittest
9 from unittest.case import _Outcome
10
11 from unittest.test.support import (LoggingResult,
12 ResultWithNoStartTestRunStopTestRun)
13
14
15 def resultFactory(*_):
16 return unittest.TestResult()
17
18
19 def getRunner():
20 return unittest.TextTestRunner(resultclass=resultFactory,
21 stream=io.StringIO())
22
23
24 class ESC[4;38;5;81mCustomError(ESC[4;38;5;149mException):
25 pass
26
27 # For test output compat:
28 CustomErrorRepr = f"{__name__ + '.' if __name__ != '__main__' else ''}CustomError"
29
30
31 def runTests(*cases):
32 suite = unittest.TestSuite()
33 for case in cases:
34 tests = unittest.defaultTestLoader.loadTestsFromTestCase(case)
35 suite.addTests(tests)
36
37 runner = getRunner()
38
39 # creating a nested suite exposes some potential bugs
40 realSuite = unittest.TestSuite()
41 realSuite.addTest(suite)
42 # adding empty suites to the end exposes potential bugs
43 suite.addTest(unittest.TestSuite())
44 realSuite.addTest(unittest.TestSuite())
45 return runner.run(realSuite)
46
47
48 def cleanup(ordering, blowUp=False):
49 if not blowUp:
50 ordering.append('cleanup_good')
51 else:
52 ordering.append('cleanup_exc')
53 raise CustomError('CleanUpExc')
54
55
56 class ESC[4;38;5;81mTestCM:
57 def __init__(self, ordering, enter_result=None):
58 self.ordering = ordering
59 self.enter_result = enter_result
60
61 def __enter__(self):
62 self.ordering.append('enter')
63 return self.enter_result
64
65 def __exit__(self, *exc_info):
66 self.ordering.append('exit')
67
68
69 class ESC[4;38;5;81mLacksEnterAndExit:
70 pass
71 class ESC[4;38;5;81mLacksEnter:
72 def __exit__(self, *exc_info):
73 pass
74 class ESC[4;38;5;81mLacksExit:
75 def __enter__(self):
76 pass
77
78
79 class ESC[4;38;5;81mTestCleanUp(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
80 def testCleanUp(self):
81 class ESC[4;38;5;81mTestableTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
82 def testNothing(self):
83 pass
84
85 test = TestableTest('testNothing')
86 self.assertEqual(test._cleanups, [])
87
88 cleanups = []
89
90 def cleanup1(*args, **kwargs):
91 cleanups.append((1, args, kwargs))
92
93 def cleanup2(*args, **kwargs):
94 cleanups.append((2, args, kwargs))
95
96 test.addCleanup(cleanup1, 1, 2, 3, four='hello', five='goodbye')
97 test.addCleanup(cleanup2)
98
99 self.assertEqual(test._cleanups,
100 [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
101 (cleanup2, (), {})])
102
103 self.assertTrue(test.doCleanups())
104 self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
105
106 def testCleanUpWithErrors(self):
107 class ESC[4;38;5;81mTestableTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
108 def testNothing(self):
109 pass
110
111 test = TestableTest('testNothing')
112 result = unittest.TestResult()
113 outcome = test._outcome = _Outcome(result=result)
114
115 CleanUpExc = CustomError('foo')
116 exc2 = CustomError('bar')
117 def cleanup1():
118 raise CleanUpExc
119
120 def cleanup2():
121 raise exc2
122
123 test.addCleanup(cleanup1)
124 test.addCleanup(cleanup2)
125
126 self.assertFalse(test.doCleanups())
127 self.assertFalse(outcome.success)
128
129 (_, msg2), (_, msg1) = result.errors
130 self.assertIn('in cleanup1', msg1)
131 self.assertIn('raise CleanUpExc', msg1)
132 self.assertIn(f'{CustomErrorRepr}: foo', msg1)
133 self.assertIn('in cleanup2', msg2)
134 self.assertIn('raise exc2', msg2)
135 self.assertIn(f'{CustomErrorRepr}: bar', msg2)
136
137 def testCleanupInRun(self):
138 blowUp = False
139 ordering = []
140
141 class ESC[4;38;5;81mTestableTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
142 def setUp(self):
143 ordering.append('setUp')
144 test.addCleanup(cleanup2)
145 if blowUp:
146 raise CustomError('foo')
147
148 def testNothing(self):
149 ordering.append('test')
150 test.addCleanup(cleanup3)
151
152 def tearDown(self):
153 ordering.append('tearDown')
154
155 test = TestableTest('testNothing')
156
157 def cleanup1():
158 ordering.append('cleanup1')
159 def cleanup2():
160 ordering.append('cleanup2')
161 def cleanup3():
162 ordering.append('cleanup3')
163 test.addCleanup(cleanup1)
164
165 def success(some_test):
166 self.assertEqual(some_test, test)
167 ordering.append('success')
168
169 result = unittest.TestResult()
170 result.addSuccess = success
171
172 test.run(result)
173 self.assertEqual(ordering, ['setUp', 'test', 'tearDown', 'cleanup3',
174 'cleanup2', 'cleanup1', 'success'])
175
176 blowUp = True
177 ordering = []
178 test = TestableTest('testNothing')
179 test.addCleanup(cleanup1)
180 test.run(result)
181 self.assertEqual(ordering, ['setUp', 'cleanup2', 'cleanup1'])
182
183 def testTestCaseDebugExecutesCleanups(self):
184 ordering = []
185
186 class ESC[4;38;5;81mTestableTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
187 def setUp(self):
188 ordering.append('setUp')
189 self.addCleanup(cleanup1)
190
191 def testNothing(self):
192 ordering.append('test')
193 self.addCleanup(cleanup3)
194
195 def tearDown(self):
196 ordering.append('tearDown')
197 test.addCleanup(cleanup4)
198
199 test = TestableTest('testNothing')
200
201 def cleanup1():
202 ordering.append('cleanup1')
203 test.addCleanup(cleanup2)
204 def cleanup2():
205 ordering.append('cleanup2')
206 def cleanup3():
207 ordering.append('cleanup3')
208 def cleanup4():
209 ordering.append('cleanup4')
210
211 test.debug()
212 self.assertEqual(ordering, ['setUp', 'test', 'tearDown', 'cleanup4',
213 'cleanup3', 'cleanup1', 'cleanup2'])
214
215
216 def test_enterContext(self):
217 class ESC[4;38;5;81mTestableTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
218 def testNothing(self):
219 pass
220
221 test = TestableTest('testNothing')
222 cleanups = []
223
224 test.addCleanup(cleanups.append, 'cleanup1')
225 cm = TestCM(cleanups, 42)
226 self.assertEqual(test.enterContext(cm), 42)
227 test.addCleanup(cleanups.append, 'cleanup2')
228
229 self.assertTrue(test.doCleanups())
230 self.assertEqual(cleanups, ['enter', 'cleanup2', 'exit', 'cleanup1'])
231
232 def test_enterContext_arg_errors(self):
233 class ESC[4;38;5;81mTestableTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
234 def testNothing(self):
235 pass
236
237 test = TestableTest('testNothing')
238
239 with self.assertRaisesRegex(TypeError, 'the context manager'):
240 test.enterContext(LacksEnterAndExit())
241 with self.assertRaisesRegex(TypeError, 'the context manager'):
242 test.enterContext(LacksEnter())
243 with self.assertRaisesRegex(TypeError, 'the context manager'):
244 test.enterContext(LacksExit())
245
246 self.assertEqual(test._cleanups, [])
247
248
249 class ESC[4;38;5;81mTestClassCleanup(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
250 def test_addClassCleanUp(self):
251 class ESC[4;38;5;81mTestableTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
252 def testNothing(self):
253 pass
254 test = TestableTest('testNothing')
255 self.assertEqual(test._class_cleanups, [])
256 class_cleanups = []
257
258 def class_cleanup1(*args, **kwargs):
259 class_cleanups.append((3, args, kwargs))
260
261 def class_cleanup2(*args, **kwargs):
262 class_cleanups.append((4, args, kwargs))
263
264 TestableTest.addClassCleanup(class_cleanup1, 1, 2, 3,
265 four='hello', five='goodbye')
266 TestableTest.addClassCleanup(class_cleanup2)
267
268 self.assertEqual(test._class_cleanups,
269 [(class_cleanup1, (1, 2, 3),
270 dict(four='hello', five='goodbye')),
271 (class_cleanup2, (), {})])
272
273 TestableTest.doClassCleanups()
274 self.assertEqual(class_cleanups, [(4, (), {}), (3, (1, 2, 3),
275 dict(four='hello', five='goodbye'))])
276
277 def test_run_class_cleanUp(self):
278 ordering = []
279 blowUp = True
280
281 class ESC[4;38;5;81mTestableTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
282 @classmethod
283 def setUpClass(cls):
284 ordering.append('setUpClass')
285 cls.addClassCleanup(cleanup, ordering)
286 if blowUp:
287 raise CustomError()
288 def testNothing(self):
289 ordering.append('test')
290 @classmethod
291 def tearDownClass(cls):
292 ordering.append('tearDownClass')
293
294 runTests(TestableTest)
295 self.assertEqual(ordering, ['setUpClass', 'cleanup_good'])
296
297 ordering = []
298 blowUp = False
299 runTests(TestableTest)
300 self.assertEqual(ordering,
301 ['setUpClass', 'test', 'tearDownClass', 'cleanup_good'])
302
303 def test_run_class_cleanUp_without_tearDownClass(self):
304 ordering = []
305 blowUp = True
306
307 class ESC[4;38;5;81mTestableTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
308 @classmethod
309 def setUpClass(cls):
310 ordering.append('setUpClass')
311 cls.addClassCleanup(cleanup, ordering)
312 if blowUp:
313 raise CustomError()
314 def testNothing(self):
315 ordering.append('test')
316 @classmethod
317 @property
318 def tearDownClass(cls):
319 raise AttributeError
320
321 runTests(TestableTest)
322 self.assertEqual(ordering, ['setUpClass', 'cleanup_good'])
323
324 ordering = []
325 blowUp = False
326 runTests(TestableTest)
327 self.assertEqual(ordering,
328 ['setUpClass', 'test', 'cleanup_good'])
329
330 def test_debug_executes_classCleanUp(self):
331 ordering = []
332 blowUp = False
333
334 class ESC[4;38;5;81mTestableTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
335 @classmethod
336 def setUpClass(cls):
337 ordering.append('setUpClass')
338 cls.addClassCleanup(cleanup, ordering, blowUp=blowUp)
339 def testNothing(self):
340 ordering.append('test')
341 @classmethod
342 def tearDownClass(cls):
343 ordering.append('tearDownClass')
344
345 suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestableTest)
346 suite.debug()
347 self.assertEqual(ordering,
348 ['setUpClass', 'test', 'tearDownClass', 'cleanup_good'])
349
350 ordering = []
351 blowUp = True
352 suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestableTest)
353 with self.assertRaises(CustomError) as cm:
354 suite.debug()
355 self.assertEqual(str(cm.exception), 'CleanUpExc')
356 self.assertEqual(ordering,
357 ['setUpClass', 'test', 'tearDownClass', 'cleanup_exc'])
358
359 def test_debug_executes_classCleanUp_when_teardown_exception(self):
360 ordering = []
361 blowUp = False
362
363 class ESC[4;38;5;81mTestableTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
364 @classmethod
365 def setUpClass(cls):
366 ordering.append('setUpClass')
367 cls.addClassCleanup(cleanup, ordering, blowUp=blowUp)
368 def testNothing(self):
369 ordering.append('test')
370 @classmethod
371 def tearDownClass(cls):
372 ordering.append('tearDownClass')
373 raise CustomError('TearDownClassExc')
374
375 suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestableTest)
376 with self.assertRaises(CustomError) as cm:
377 suite.debug()
378 self.assertEqual(str(cm.exception), 'TearDownClassExc')
379 self.assertEqual(ordering, ['setUpClass', 'test', 'tearDownClass'])
380 self.assertTrue(TestableTest._class_cleanups)
381 TestableTest._class_cleanups.clear()
382
383 ordering = []
384 blowUp = True
385 suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestableTest)
386 with self.assertRaises(CustomError) as cm:
387 suite.debug()
388 self.assertEqual(str(cm.exception), 'TearDownClassExc')
389 self.assertEqual(ordering, ['setUpClass', 'test', 'tearDownClass'])
390 self.assertTrue(TestableTest._class_cleanups)
391 TestableTest._class_cleanups.clear()
392
393 def test_doClassCleanups_with_errors_addClassCleanUp(self):
394 class ESC[4;38;5;81mTestableTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
395 def testNothing(self):
396 pass
397
398 def cleanup1():
399 raise CustomError('cleanup1')
400
401 def cleanup2():
402 raise CustomError('cleanup2')
403
404 TestableTest.addClassCleanup(cleanup1)
405 TestableTest.addClassCleanup(cleanup2)
406 TestableTest.doClassCleanups()
407
408 self.assertEqual(len(TestableTest.tearDown_exceptions), 2)
409
410 e1, e2 = TestableTest.tearDown_exceptions
411 self.assertIsInstance(e1[1], CustomError)
412 self.assertEqual(str(e1[1]), 'cleanup2')
413 self.assertIsInstance(e2[1], CustomError)
414 self.assertEqual(str(e2[1]), 'cleanup1')
415
416 def test_with_errors_addCleanUp(self):
417 ordering = []
418 class ESC[4;38;5;81mTestableTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
419 @classmethod
420 def setUpClass(cls):
421 ordering.append('setUpClass')
422 cls.addClassCleanup(cleanup, ordering)
423 def setUp(self):
424 ordering.append('setUp')
425 self.addCleanup(cleanup, ordering, blowUp=True)
426 def testNothing(self):
427 pass
428 @classmethod
429 def tearDownClass(cls):
430 ordering.append('tearDownClass')
431
432 result = runTests(TestableTest)
433 self.assertEqual(result.errors[0][1].splitlines()[-1],
434 f'{CustomErrorRepr}: CleanUpExc')
435 self.assertEqual(ordering,
436 ['setUpClass', 'setUp', 'cleanup_exc',
437 'tearDownClass', 'cleanup_good'])
438
439 def test_run_with_errors_addClassCleanUp(self):
440 ordering = []
441 class ESC[4;38;5;81mTestableTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
442 @classmethod
443 def setUpClass(cls):
444 ordering.append('setUpClass')
445 cls.addClassCleanup(cleanup, ordering, blowUp=True)
446 def setUp(self):
447 ordering.append('setUp')
448 self.addCleanup(cleanup, ordering)
449 def testNothing(self):
450 ordering.append('test')
451 @classmethod
452 def tearDownClass(cls):
453 ordering.append('tearDownClass')
454
455 result = runTests(TestableTest)
456 self.assertEqual(result.errors[0][1].splitlines()[-1],
457 f'{CustomErrorRepr}: CleanUpExc')
458 self.assertEqual(ordering,
459 ['setUpClass', 'setUp', 'test', 'cleanup_good',
460 'tearDownClass', 'cleanup_exc'])
461
462 def test_with_errors_in_addClassCleanup_and_setUps(self):
463 ordering = []
464 class_blow_up = False
465 method_blow_up = False
466
467 class ESC[4;38;5;81mTestableTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
468 @classmethod
469 def setUpClass(cls):
470 ordering.append('setUpClass')
471 cls.addClassCleanup(cleanup, ordering, blowUp=True)
472 if class_blow_up:
473 raise CustomError('ClassExc')
474 def setUp(self):
475 ordering.append('setUp')
476 if method_blow_up:
477 raise CustomError('MethodExc')
478 def testNothing(self):
479 ordering.append('test')
480 @classmethod
481 def tearDownClass(cls):
482 ordering.append('tearDownClass')
483
484 result = runTests(TestableTest)
485 self.assertEqual(result.errors[0][1].splitlines()[-1],
486 f'{CustomErrorRepr}: CleanUpExc')
487 self.assertEqual(ordering,
488 ['setUpClass', 'setUp', 'test',
489 'tearDownClass', 'cleanup_exc'])
490
491 ordering = []
492 class_blow_up = True
493 method_blow_up = False
494 result = runTests(TestableTest)
495 self.assertEqual(result.errors[0][1].splitlines()[-1],
496 f'{CustomErrorRepr}: ClassExc')
497 self.assertEqual(result.errors[1][1].splitlines()[-1],
498 f'{CustomErrorRepr}: CleanUpExc')
499 self.assertEqual(ordering,
500 ['setUpClass', 'cleanup_exc'])
501
502 ordering = []
503 class_blow_up = False
504 method_blow_up = True
505 result = runTests(TestableTest)
506 self.assertEqual(result.errors[0][1].splitlines()[-1],
507 f'{CustomErrorRepr}: MethodExc')
508 self.assertEqual(result.errors[1][1].splitlines()[-1],
509 f'{CustomErrorRepr}: CleanUpExc')
510 self.assertEqual(ordering,
511 ['setUpClass', 'setUp', 'tearDownClass',
512 'cleanup_exc'])
513
514 def test_with_errors_in_tearDownClass(self):
515 ordering = []
516 class ESC[4;38;5;81mTestableTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
517 @classmethod
518 def setUpClass(cls):
519 ordering.append('setUpClass')
520 cls.addClassCleanup(cleanup, ordering)
521 def testNothing(self):
522 ordering.append('test')
523 @classmethod
524 def tearDownClass(cls):
525 ordering.append('tearDownClass')
526 raise CustomError('TearDownExc')
527
528 result = runTests(TestableTest)
529 self.assertEqual(result.errors[0][1].splitlines()[-1],
530 f'{CustomErrorRepr}: TearDownExc')
531 self.assertEqual(ordering,
532 ['setUpClass', 'test', 'tearDownClass', 'cleanup_good'])
533
534 def test_enterClassContext(self):
535 class ESC[4;38;5;81mTestableTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
536 def testNothing(self):
537 pass
538
539 cleanups = []
540
541 TestableTest.addClassCleanup(cleanups.append, 'cleanup1')
542 cm = TestCM(cleanups, 42)
543 self.assertEqual(TestableTest.enterClassContext(cm), 42)
544 TestableTest.addClassCleanup(cleanups.append, 'cleanup2')
545
546 TestableTest.doClassCleanups()
547 self.assertEqual(cleanups, ['enter', 'cleanup2', 'exit', 'cleanup1'])
548
549 def test_enterClassContext_arg_errors(self):
550 class ESC[4;38;5;81mTestableTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
551 def testNothing(self):
552 pass
553
554 with self.assertRaisesRegex(TypeError, 'the context manager'):
555 TestableTest.enterClassContext(LacksEnterAndExit())
556 with self.assertRaisesRegex(TypeError, 'the context manager'):
557 TestableTest.enterClassContext(LacksEnter())
558 with self.assertRaisesRegex(TypeError, 'the context manager'):
559 TestableTest.enterClassContext(LacksExit())
560
561 self.assertEqual(TestableTest._class_cleanups, [])
562
563 def test_run_nested_test(self):
564 ordering = []
565
566 class ESC[4;38;5;81mInnerTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
567 @classmethod
568 def setUpClass(cls):
569 ordering.append('inner setup')
570 cls.addClassCleanup(ordering.append, 'inner cleanup')
571 def test(self):
572 ordering.append('inner test')
573
574 class ESC[4;38;5;81mOuterTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
575 @classmethod
576 def setUpClass(cls):
577 ordering.append('outer setup')
578 cls.addClassCleanup(ordering.append, 'outer cleanup')
579 def test(self):
580 ordering.append('start outer test')
581 runTests(InnerTest)
582 ordering.append('end outer test')
583
584 runTests(OuterTest)
585 self.assertEqual(ordering, [
586 'outer setup', 'start outer test',
587 'inner setup', 'inner test', 'inner cleanup',
588 'end outer test', 'outer cleanup'])
589
590
591 class ESC[4;38;5;81mTestModuleCleanUp(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
592 def test_add_and_do_ModuleCleanup(self):
593 module_cleanups = []
594
595 def module_cleanup1(*args, **kwargs):
596 module_cleanups.append((3, args, kwargs))
597
598 def module_cleanup2(*args, **kwargs):
599 module_cleanups.append((4, args, kwargs))
600
601 class ESC[4;38;5;81mModule(ESC[4;38;5;149mobject):
602 unittest.addModuleCleanup(module_cleanup1, 1, 2, 3,
603 four='hello', five='goodbye')
604 unittest.addModuleCleanup(module_cleanup2)
605
606 self.assertEqual(unittest.case._module_cleanups,
607 [(module_cleanup1, (1, 2, 3),
608 dict(four='hello', five='goodbye')),
609 (module_cleanup2, (), {})])
610
611 unittest.case.doModuleCleanups()
612 self.assertEqual(module_cleanups, [(4, (), {}), (3, (1, 2, 3),
613 dict(four='hello', five='goodbye'))])
614 self.assertEqual(unittest.case._module_cleanups, [])
615
616 def test_doModuleCleanup_with_errors_in_addModuleCleanup(self):
617 module_cleanups = []
618
619 def module_cleanup_good(*args, **kwargs):
620 module_cleanups.append((3, args, kwargs))
621
622 def module_cleanup_bad(*args, **kwargs):
623 raise CustomError('CleanUpExc')
624
625 class ESC[4;38;5;81mModule(ESC[4;38;5;149mobject):
626 unittest.addModuleCleanup(module_cleanup_good, 1, 2, 3,
627 four='hello', five='goodbye')
628 unittest.addModuleCleanup(module_cleanup_bad)
629 self.assertEqual(unittest.case._module_cleanups,
630 [(module_cleanup_good, (1, 2, 3),
631 dict(four='hello', five='goodbye')),
632 (module_cleanup_bad, (), {})])
633 with self.assertRaises(CustomError) as e:
634 unittest.case.doModuleCleanups()
635 self.assertEqual(str(e.exception), 'CleanUpExc')
636 self.assertEqual(unittest.case._module_cleanups, [])
637
638 def test_addModuleCleanup_arg_errors(self):
639 cleanups = []
640 def cleanup(*args, **kwargs):
641 cleanups.append((args, kwargs))
642
643 class ESC[4;38;5;81mModule(ESC[4;38;5;149mobject):
644 unittest.addModuleCleanup(cleanup, 1, 2, function='hello')
645 with self.assertRaises(TypeError):
646 unittest.addModuleCleanup(function=cleanup, arg='hello')
647 with self.assertRaises(TypeError):
648 unittest.addModuleCleanup()
649 unittest.case.doModuleCleanups()
650 self.assertEqual(cleanups,
651 [((1, 2), {'function': 'hello'})])
652
653 def test_run_module_cleanUp(self):
654 blowUp = True
655 ordering = []
656 class ESC[4;38;5;81mModule(ESC[4;38;5;149mobject):
657 @staticmethod
658 def setUpModule():
659 ordering.append('setUpModule')
660 unittest.addModuleCleanup(cleanup, ordering)
661 if blowUp:
662 raise CustomError('setUpModule Exc')
663 @staticmethod
664 def tearDownModule():
665 ordering.append('tearDownModule')
666
667 class ESC[4;38;5;81mTestableTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
668 @classmethod
669 def setUpClass(cls):
670 ordering.append('setUpClass')
671 def testNothing(self):
672 ordering.append('test')
673 @classmethod
674 def tearDownClass(cls):
675 ordering.append('tearDownClass')
676
677 TestableTest.__module__ = 'Module'
678 sys.modules['Module'] = Module
679 result = runTests(TestableTest)
680 self.assertEqual(ordering, ['setUpModule', 'cleanup_good'])
681 self.assertEqual(result.errors[0][1].splitlines()[-1],
682 f'{CustomErrorRepr}: setUpModule Exc')
683
684 ordering = []
685 blowUp = False
686 runTests(TestableTest)
687 self.assertEqual(ordering,
688 ['setUpModule', 'setUpClass', 'test', 'tearDownClass',
689 'tearDownModule', 'cleanup_good'])
690 self.assertEqual(unittest.case._module_cleanups, [])
691
692 def test_run_multiple_module_cleanUp(self):
693 blowUp = True
694 blowUp2 = False
695 ordering = []
696 class ESC[4;38;5;81mModule1(ESC[4;38;5;149mobject):
697 @staticmethod
698 def setUpModule():
699 ordering.append('setUpModule')
700 unittest.addModuleCleanup(cleanup, ordering)
701 if blowUp:
702 raise CustomError()
703 @staticmethod
704 def tearDownModule():
705 ordering.append('tearDownModule')
706
707 class ESC[4;38;5;81mModule2(ESC[4;38;5;149mobject):
708 @staticmethod
709 def setUpModule():
710 ordering.append('setUpModule2')
711 unittest.addModuleCleanup(cleanup, ordering)
712 if blowUp2:
713 raise CustomError()
714 @staticmethod
715 def tearDownModule():
716 ordering.append('tearDownModule2')
717
718 class ESC[4;38;5;81mTestableTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
719 @classmethod
720 def setUpClass(cls):
721 ordering.append('setUpClass')
722 def testNothing(self):
723 ordering.append('test')
724 @classmethod
725 def tearDownClass(cls):
726 ordering.append('tearDownClass')
727
728 class ESC[4;38;5;81mTestableTest2(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
729 @classmethod
730 def setUpClass(cls):
731 ordering.append('setUpClass2')
732 def testNothing(self):
733 ordering.append('test2')
734 @classmethod
735 def tearDownClass(cls):
736 ordering.append('tearDownClass2')
737
738 TestableTest.__module__ = 'Module1'
739 sys.modules['Module1'] = Module1
740 TestableTest2.__module__ = 'Module2'
741 sys.modules['Module2'] = Module2
742 runTests(TestableTest, TestableTest2)
743 self.assertEqual(ordering, ['setUpModule', 'cleanup_good',
744 'setUpModule2', 'setUpClass2', 'test2',
745 'tearDownClass2', 'tearDownModule2',
746 'cleanup_good'])
747 ordering = []
748 blowUp = False
749 blowUp2 = True
750 runTests(TestableTest, TestableTest2)
751 self.assertEqual(ordering, ['setUpModule', 'setUpClass', 'test',
752 'tearDownClass', 'tearDownModule',
753 'cleanup_good', 'setUpModule2',
754 'cleanup_good'])
755
756 ordering = []
757 blowUp = False
758 blowUp2 = False
759 runTests(TestableTest, TestableTest2)
760 self.assertEqual(ordering,
761 ['setUpModule', 'setUpClass', 'test', 'tearDownClass',
762 'tearDownModule', 'cleanup_good', 'setUpModule2',
763 'setUpClass2', 'test2', 'tearDownClass2',
764 'tearDownModule2', 'cleanup_good'])
765 self.assertEqual(unittest.case._module_cleanups, [])
766
767 def test_run_module_cleanUp_without_teardown(self):
768 ordering = []
769 class ESC[4;38;5;81mModule(ESC[4;38;5;149mobject):
770 @staticmethod
771 def setUpModule():
772 ordering.append('setUpModule')
773 unittest.addModuleCleanup(cleanup, ordering)
774
775 class ESC[4;38;5;81mTestableTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
776 @classmethod
777 def setUpClass(cls):
778 ordering.append('setUpClass')
779 def testNothing(self):
780 ordering.append('test')
781 @classmethod
782 def tearDownClass(cls):
783 ordering.append('tearDownClass')
784
785 TestableTest.__module__ = 'Module'
786 sys.modules['Module'] = Module
787 runTests(TestableTest)
788 self.assertEqual(ordering, ['setUpModule', 'setUpClass', 'test',
789 'tearDownClass', 'cleanup_good'])
790 self.assertEqual(unittest.case._module_cleanups, [])
791
792 def test_run_module_cleanUp_when_teardown_exception(self):
793 ordering = []
794 class ESC[4;38;5;81mModule(ESC[4;38;5;149mobject):
795 @staticmethod
796 def setUpModule():
797 ordering.append('setUpModule')
798 unittest.addModuleCleanup(cleanup, ordering)
799 @staticmethod
800 def tearDownModule():
801 ordering.append('tearDownModule')
802 raise CustomError('CleanUpExc')
803
804 class ESC[4;38;5;81mTestableTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
805 @classmethod
806 def setUpClass(cls):
807 ordering.append('setUpClass')
808 def testNothing(self):
809 ordering.append('test')
810 @classmethod
811 def tearDownClass(cls):
812 ordering.append('tearDownClass')
813
814 TestableTest.__module__ = 'Module'
815 sys.modules['Module'] = Module
816 result = runTests(TestableTest)
817 self.assertEqual(result.errors[0][1].splitlines()[-1],
818 f'{CustomErrorRepr}: CleanUpExc')
819 self.assertEqual(ordering, ['setUpModule', 'setUpClass', 'test',
820 'tearDownClass', 'tearDownModule',
821 'cleanup_good'])
822 self.assertEqual(unittest.case._module_cleanups, [])
823
824 def test_debug_module_executes_cleanUp(self):
825 ordering = []
826 blowUp = False
827 class ESC[4;38;5;81mModule(ESC[4;38;5;149mobject):
828 @staticmethod
829 def setUpModule():
830 ordering.append('setUpModule')
831 unittest.addModuleCleanup(cleanup, ordering, blowUp=blowUp)
832 @staticmethod
833 def tearDownModule():
834 ordering.append('tearDownModule')
835
836 class ESC[4;38;5;81mTestableTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
837 @classmethod
838 def setUpClass(cls):
839 ordering.append('setUpClass')
840 def testNothing(self):
841 ordering.append('test')
842 @classmethod
843 def tearDownClass(cls):
844 ordering.append('tearDownClass')
845
846 TestableTest.__module__ = 'Module'
847 sys.modules['Module'] = Module
848 suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestableTest)
849 suite.debug()
850 self.assertEqual(ordering,
851 ['setUpModule', 'setUpClass', 'test', 'tearDownClass',
852 'tearDownModule', 'cleanup_good'])
853 self.assertEqual(unittest.case._module_cleanups, [])
854
855 ordering = []
856 blowUp = True
857 suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestableTest)
858 with self.assertRaises(CustomError) as cm:
859 suite.debug()
860 self.assertEqual(str(cm.exception), 'CleanUpExc')
861 self.assertEqual(ordering, ['setUpModule', 'setUpClass', 'test',
862 'tearDownClass', 'tearDownModule', 'cleanup_exc'])
863 self.assertEqual(unittest.case._module_cleanups, [])
864
865 def test_debug_module_cleanUp_when_teardown_exception(self):
866 ordering = []
867 blowUp = False
868 class ESC[4;38;5;81mModule(ESC[4;38;5;149mobject):
869 @staticmethod
870 def setUpModule():
871 ordering.append('setUpModule')
872 unittest.addModuleCleanup(cleanup, ordering, blowUp=blowUp)
873 @staticmethod
874 def tearDownModule():
875 ordering.append('tearDownModule')
876 raise CustomError('TearDownModuleExc')
877
878 class ESC[4;38;5;81mTestableTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
879 @classmethod
880 def setUpClass(cls):
881 ordering.append('setUpClass')
882 def testNothing(self):
883 ordering.append('test')
884 @classmethod
885 def tearDownClass(cls):
886 ordering.append('tearDownClass')
887
888 TestableTest.__module__ = 'Module'
889 sys.modules['Module'] = Module
890 suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestableTest)
891 with self.assertRaises(CustomError) as cm:
892 suite.debug()
893 self.assertEqual(str(cm.exception), 'TearDownModuleExc')
894 self.assertEqual(ordering, ['setUpModule', 'setUpClass', 'test',
895 'tearDownClass', 'tearDownModule'])
896 self.assertTrue(unittest.case._module_cleanups)
897 unittest.case._module_cleanups.clear()
898
899 ordering = []
900 blowUp = True
901 suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestableTest)
902 with self.assertRaises(CustomError) as cm:
903 suite.debug()
904 self.assertEqual(str(cm.exception), 'TearDownModuleExc')
905 self.assertEqual(ordering, ['setUpModule', 'setUpClass', 'test',
906 'tearDownClass', 'tearDownModule'])
907 self.assertTrue(unittest.case._module_cleanups)
908 unittest.case._module_cleanups.clear()
909
910 def test_addClassCleanup_arg_errors(self):
911 cleanups = []
912 def cleanup(*args, **kwargs):
913 cleanups.append((args, kwargs))
914
915 class ESC[4;38;5;81mTestableTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
916 @classmethod
917 def setUpClass(cls):
918 cls.addClassCleanup(cleanup, 1, 2, function=3, cls=4)
919 with self.assertRaises(TypeError):
920 cls.addClassCleanup(function=cleanup, arg='hello')
921 def testNothing(self):
922 pass
923
924 with self.assertRaises(TypeError):
925 TestableTest.addClassCleanup()
926 with self.assertRaises(TypeError):
927 unittest.TestCase.addCleanup(cls=TestableTest(), function=cleanup)
928 runTests(TestableTest)
929 self.assertEqual(cleanups,
930 [((1, 2), {'function': 3, 'cls': 4})])
931
932 def test_addCleanup_arg_errors(self):
933 cleanups = []
934 def cleanup(*args, **kwargs):
935 cleanups.append((args, kwargs))
936
937 class ESC[4;38;5;81mTestableTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
938 def setUp(self2):
939 self2.addCleanup(cleanup, 1, 2, function=3, self=4)
940 with self.assertRaises(TypeError):
941 self2.addCleanup(function=cleanup, arg='hello')
942 def testNothing(self):
943 pass
944
945 with self.assertRaises(TypeError):
946 TestableTest().addCleanup()
947 with self.assertRaises(TypeError):
948 unittest.TestCase.addCleanup(self=TestableTest(), function=cleanup)
949 runTests(TestableTest)
950 self.assertEqual(cleanups,
951 [((1, 2), {'function': 3, 'self': 4})])
952
953 def test_with_errors_in_addClassCleanup(self):
954 ordering = []
955
956 class ESC[4;38;5;81mModule(ESC[4;38;5;149mobject):
957 @staticmethod
958 def setUpModule():
959 ordering.append('setUpModule')
960 unittest.addModuleCleanup(cleanup, ordering)
961 @staticmethod
962 def tearDownModule():
963 ordering.append('tearDownModule')
964
965 class ESC[4;38;5;81mTestableTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
966 @classmethod
967 def setUpClass(cls):
968 ordering.append('setUpClass')
969 cls.addClassCleanup(cleanup, ordering, blowUp=True)
970 def testNothing(self):
971 ordering.append('test')
972 @classmethod
973 def tearDownClass(cls):
974 ordering.append('tearDownClass')
975
976 TestableTest.__module__ = 'Module'
977 sys.modules['Module'] = Module
978
979 result = runTests(TestableTest)
980 self.assertEqual(result.errors[0][1].splitlines()[-1],
981 f'{CustomErrorRepr}: CleanUpExc')
982 self.assertEqual(ordering,
983 ['setUpModule', 'setUpClass', 'test', 'tearDownClass',
984 'cleanup_exc', 'tearDownModule', 'cleanup_good'])
985
986 def test_with_errors_in_addCleanup(self):
987 ordering = []
988 class ESC[4;38;5;81mModule(ESC[4;38;5;149mobject):
989 @staticmethod
990 def setUpModule():
991 ordering.append('setUpModule')
992 unittest.addModuleCleanup(cleanup, ordering)
993 @staticmethod
994 def tearDownModule():
995 ordering.append('tearDownModule')
996
997 class ESC[4;38;5;81mTestableTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
998 def setUp(self):
999 ordering.append('setUp')
1000 self.addCleanup(cleanup, ordering, blowUp=True)
1001 def testNothing(self):
1002 ordering.append('test')
1003 def tearDown(self):
1004 ordering.append('tearDown')
1005
1006 TestableTest.__module__ = 'Module'
1007 sys.modules['Module'] = Module
1008
1009 result = runTests(TestableTest)
1010 self.assertEqual(result.errors[0][1].splitlines()[-1],
1011 f'{CustomErrorRepr}: CleanUpExc')
1012 self.assertEqual(ordering,
1013 ['setUpModule', 'setUp', 'test', 'tearDown',
1014 'cleanup_exc', 'tearDownModule', 'cleanup_good'])
1015
1016 def test_with_errors_in_addModuleCleanup_and_setUps(self):
1017 ordering = []
1018 module_blow_up = False
1019 class_blow_up = False
1020 method_blow_up = False
1021 class ESC[4;38;5;81mModule(ESC[4;38;5;149mobject):
1022 @staticmethod
1023 def setUpModule():
1024 ordering.append('setUpModule')
1025 unittest.addModuleCleanup(cleanup, ordering, blowUp=True)
1026 if module_blow_up:
1027 raise CustomError('ModuleExc')
1028 @staticmethod
1029 def tearDownModule():
1030 ordering.append('tearDownModule')
1031
1032 class ESC[4;38;5;81mTestableTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
1033 @classmethod
1034 def setUpClass(cls):
1035 ordering.append('setUpClass')
1036 if class_blow_up:
1037 raise CustomError('ClassExc')
1038 def setUp(self):
1039 ordering.append('setUp')
1040 if method_blow_up:
1041 raise CustomError('MethodExc')
1042 def testNothing(self):
1043 ordering.append('test')
1044 @classmethod
1045 def tearDownClass(cls):
1046 ordering.append('tearDownClass')
1047
1048 TestableTest.__module__ = 'Module'
1049 sys.modules['Module'] = Module
1050
1051 result = runTests(TestableTest)
1052 self.assertEqual(result.errors[0][1].splitlines()[-1],
1053 f'{CustomErrorRepr}: CleanUpExc')
1054 self.assertEqual(ordering,
1055 ['setUpModule', 'setUpClass', 'setUp', 'test',
1056 'tearDownClass', 'tearDownModule',
1057 'cleanup_exc'])
1058
1059 ordering = []
1060 module_blow_up = True
1061 class_blow_up = False
1062 method_blow_up = False
1063 result = runTests(TestableTest)
1064 self.assertEqual(result.errors[0][1].splitlines()[-1],
1065 f'{CustomErrorRepr}: ModuleExc')
1066 self.assertEqual(result.errors[1][1].splitlines()[-1],
1067 f'{CustomErrorRepr}: CleanUpExc')
1068 self.assertEqual(ordering, ['setUpModule', 'cleanup_exc'])
1069
1070 ordering = []
1071 module_blow_up = False
1072 class_blow_up = True
1073 method_blow_up = False
1074 result = runTests(TestableTest)
1075 self.assertEqual(result.errors[0][1].splitlines()[-1],
1076 f'{CustomErrorRepr}: ClassExc')
1077 self.assertEqual(result.errors[1][1].splitlines()[-1],
1078 f'{CustomErrorRepr}: CleanUpExc')
1079 self.assertEqual(ordering, ['setUpModule', 'setUpClass',
1080 'tearDownModule', 'cleanup_exc'])
1081
1082 ordering = []
1083 module_blow_up = False
1084 class_blow_up = False
1085 method_blow_up = True
1086 result = runTests(TestableTest)
1087 self.assertEqual(result.errors[0][1].splitlines()[-1],
1088 f'{CustomErrorRepr}: MethodExc')
1089 self.assertEqual(result.errors[1][1].splitlines()[-1],
1090 f'{CustomErrorRepr}: CleanUpExc')
1091 self.assertEqual(ordering, ['setUpModule', 'setUpClass', 'setUp',
1092 'tearDownClass', 'tearDownModule',
1093 'cleanup_exc'])
1094
1095 def test_module_cleanUp_with_multiple_classes(self):
1096 ordering =[]
1097 def cleanup1():
1098 ordering.append('cleanup1')
1099
1100 def cleanup2():
1101 ordering.append('cleanup2')
1102
1103 def cleanup3():
1104 ordering.append('cleanup3')
1105
1106 class ESC[4;38;5;81mModule(ESC[4;38;5;149mobject):
1107 @staticmethod
1108 def setUpModule():
1109 ordering.append('setUpModule')
1110 unittest.addModuleCleanup(cleanup1)
1111 @staticmethod
1112 def tearDownModule():
1113 ordering.append('tearDownModule')
1114
1115 class ESC[4;38;5;81mTestableTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
1116 def setUp(self):
1117 ordering.append('setUp')
1118 self.addCleanup(cleanup2)
1119 def testNothing(self):
1120 ordering.append('test')
1121 def tearDown(self):
1122 ordering.append('tearDown')
1123
1124 class ESC[4;38;5;81mOtherTestableTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
1125 def setUp(self):
1126 ordering.append('setUp2')
1127 self.addCleanup(cleanup3)
1128 def testNothing(self):
1129 ordering.append('test2')
1130 def tearDown(self):
1131 ordering.append('tearDown2')
1132
1133 TestableTest.__module__ = 'Module'
1134 OtherTestableTest.__module__ = 'Module'
1135 sys.modules['Module'] = Module
1136 runTests(TestableTest, OtherTestableTest)
1137 self.assertEqual(ordering,
1138 ['setUpModule', 'setUp', 'test', 'tearDown',
1139 'cleanup2', 'setUp2', 'test2', 'tearDown2',
1140 'cleanup3', 'tearDownModule', 'cleanup1'])
1141
1142 def test_enterModuleContext(self):
1143 cleanups = []
1144
1145 unittest.addModuleCleanup(cleanups.append, 'cleanup1')
1146 cm = TestCM(cleanups, 42)
1147 self.assertEqual(unittest.enterModuleContext(cm), 42)
1148 unittest.addModuleCleanup(cleanups.append, 'cleanup2')
1149
1150 unittest.case.doModuleCleanups()
1151 self.assertEqual(cleanups, ['enter', 'cleanup2', 'exit', 'cleanup1'])
1152
1153 def test_enterModuleContext_arg_errors(self):
1154 class ESC[4;38;5;81mTestableTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
1155 def testNothing(self):
1156 pass
1157
1158 with self.assertRaisesRegex(TypeError, 'the context manager'):
1159 unittest.enterModuleContext(LacksEnterAndExit())
1160 with self.assertRaisesRegex(TypeError, 'the context manager'):
1161 unittest.enterModuleContext(LacksEnter())
1162 with self.assertRaisesRegex(TypeError, 'the context manager'):
1163 unittest.enterModuleContext(LacksExit())
1164
1165 self.assertEqual(unittest.case._module_cleanups, [])
1166
1167
1168 class ESC[4;38;5;81mTest_TextTestRunner(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
1169 """Tests for TextTestRunner."""
1170
1171 def setUp(self):
1172 # clean the environment from pre-existing PYTHONWARNINGS to make
1173 # test_warnings results consistent
1174 self.pythonwarnings = os.environ.get('PYTHONWARNINGS')
1175 if self.pythonwarnings:
1176 del os.environ['PYTHONWARNINGS']
1177
1178 def tearDown(self):
1179 # bring back pre-existing PYTHONWARNINGS if present
1180 if self.pythonwarnings:
1181 os.environ['PYTHONWARNINGS'] = self.pythonwarnings
1182
1183 def test_init(self):
1184 runner = unittest.TextTestRunner()
1185 self.assertFalse(runner.failfast)
1186 self.assertFalse(runner.buffer)
1187 self.assertEqual(runner.verbosity, 1)
1188 self.assertEqual(runner.warnings, None)
1189 self.assertTrue(runner.descriptions)
1190 self.assertEqual(runner.resultclass, unittest.TextTestResult)
1191 self.assertFalse(runner.tb_locals)
1192
1193 def test_multiple_inheritance(self):
1194 class ESC[4;38;5;81mAResult(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestResult):
1195 def __init__(self, stream, descriptions, verbosity):
1196 super(AResult, self).__init__(stream, descriptions, verbosity)
1197
1198 class ESC[4;38;5;81mATextResult(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTextTestResult, ESC[4;38;5;149mAResult):
1199 pass
1200
1201 # This used to raise an exception due to TextTestResult not passing
1202 # on arguments in its __init__ super call
1203 ATextResult(None, None, 1)
1204
1205 def testBufferAndFailfast(self):
1206 class ESC[4;38;5;81mTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
1207 def testFoo(self):
1208 pass
1209 result = unittest.TestResult()
1210 runner = unittest.TextTestRunner(stream=io.StringIO(), failfast=True,
1211 buffer=True)
1212 # Use our result object
1213 runner._makeResult = lambda: result
1214 runner.run(Test('testFoo'))
1215
1216 self.assertTrue(result.failfast)
1217 self.assertTrue(result.buffer)
1218
1219 def test_locals(self):
1220 runner = unittest.TextTestRunner(stream=io.StringIO(), tb_locals=True)
1221 result = runner.run(unittest.TestSuite())
1222 self.assertEqual(True, result.tb_locals)
1223
1224 def testRunnerRegistersResult(self):
1225 class ESC[4;38;5;81mTest(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTestCase):
1226 def testFoo(self):
1227 pass
1228 originalRegisterResult = unittest.runner.registerResult
1229 def cleanup():
1230 unittest.runner.registerResult = originalRegisterResult
1231 self.addCleanup(cleanup)
1232
1233 result = unittest.TestResult()
1234 runner = unittest.TextTestRunner(stream=io.StringIO())
1235 # Use our result object
1236 runner._makeResult = lambda: result
1237
1238 self.wasRegistered = 0
1239 def fakeRegisterResult(thisResult):
1240 self.wasRegistered += 1
1241 self.assertEqual(thisResult, result)
1242 unittest.runner.registerResult = fakeRegisterResult
1243
1244 runner.run(unittest.TestSuite())
1245 self.assertEqual(self.wasRegistered, 1)
1246
1247 def test_works_with_result_without_startTestRun_stopTestRun(self):
1248 class ESC[4;38;5;81mOldTextResult(ESC[4;38;5;149mResultWithNoStartTestRunStopTestRun):
1249 separator2 = ''
1250 def printErrors(self):
1251 pass
1252
1253 class ESC[4;38;5;81mRunner(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTextTestRunner):
1254 def __init__(self):
1255 super(Runner, self).__init__(io.StringIO())
1256
1257 def _makeResult(self):
1258 return OldTextResult()
1259
1260 runner = Runner()
1261 runner.run(unittest.TestSuite())
1262
1263 def test_startTestRun_stopTestRun_called(self):
1264 class ESC[4;38;5;81mLoggingTextResult(ESC[4;38;5;149mLoggingResult):
1265 separator2 = ''
1266 def printErrors(self):
1267 pass
1268
1269 class ESC[4;38;5;81mLoggingRunner(ESC[4;38;5;149munittestESC[4;38;5;149m.ESC[4;38;5;149mTextTestRunner):
1270 def __init__(self, events):
1271 super(LoggingRunner, self).__init__(io.StringIO())
1272 self._events = events
1273
1274 def _makeResult(self):
1275 return LoggingTextResult(self._events)
1276
1277 events = []
1278 runner = LoggingRunner(events)
1279 runner.run(unittest.TestSuite())
1280 expected = ['startTestRun', 'stopTestRun']
1281 self.assertEqual(events, expected)
1282
1283 def test_pickle_unpickle(self):
1284 # Issue #7197: a TextTestRunner should be (un)pickleable. This is
1285 # required by test_multiprocessing under Windows (in verbose mode).
1286 stream = io.StringIO("foo")
1287 runner = unittest.TextTestRunner(stream)
1288 for protocol in range(2, pickle.HIGHEST_PROTOCOL + 1):
1289 s = pickle.dumps(runner, protocol)
1290 obj = pickle.loads(s)
1291 # StringIO objects never compare equal, a cheap test instead.
1292 self.assertEqual(obj.stream.getvalue(), stream.getvalue())
1293
1294 def test_resultclass(self):
1295 def MockResultClass(*args):
1296 return args
1297 STREAM = object()
1298 DESCRIPTIONS = object()
1299 VERBOSITY = object()
1300 runner = unittest.TextTestRunner(STREAM, DESCRIPTIONS, VERBOSITY,
1301 resultclass=MockResultClass)
1302 self.assertEqual(runner.resultclass, MockResultClass)
1303
1304 expectedresult = (runner.stream, DESCRIPTIONS, VERBOSITY)
1305 self.assertEqual(runner._makeResult(), expectedresult)
1306
1307 @support.requires_subprocess()
1308 def test_warnings(self):
1309 """
1310 Check that warnings argument of TextTestRunner correctly affects the
1311 behavior of the warnings.
1312 """
1313 # see #10535 and the _test_warnings file for more information
1314
1315 def get_parse_out_err(p):
1316 return [b.splitlines() for b in p.communicate()]
1317 opts = dict(stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1318 cwd=os.path.dirname(__file__))
1319 ae_msg = b'Please use assertEqual instead.'
1320 at_msg = b'Please use assertTrue instead.'
1321
1322 # no args -> all the warnings are printed, unittest warnings only once
1323 p = subprocess.Popen([sys.executable, '-E', '_test_warnings.py'], **opts)
1324 with p:
1325 out, err = get_parse_out_err(p)
1326 self.assertIn(b'OK', err)
1327 # check that the total number of warnings in the output is correct
1328 self.assertEqual(len(out), 12)
1329 # check that the numbers of the different kind of warnings is correct
1330 for msg in [b'dw', b'iw', b'uw']:
1331 self.assertEqual(out.count(msg), 3)
1332 for msg in [ae_msg, at_msg, b'rw']:
1333 self.assertEqual(out.count(msg), 1)
1334
1335 args_list = (
1336 # passing 'ignore' as warnings arg -> no warnings
1337 [sys.executable, '_test_warnings.py', 'ignore'],
1338 # -W doesn't affect the result if the arg is passed
1339 [sys.executable, '-Wa', '_test_warnings.py', 'ignore'],
1340 # -W affects the result if the arg is not passed
1341 [sys.executable, '-Wi', '_test_warnings.py']
1342 )
1343 # in all these cases no warnings are printed
1344 for args in args_list:
1345 p = subprocess.Popen(args, **opts)
1346 with p:
1347 out, err = get_parse_out_err(p)
1348 self.assertIn(b'OK', err)
1349 self.assertEqual(len(out), 0)
1350
1351
1352 # passing 'always' as warnings arg -> all the warnings printed,
1353 # unittest warnings only once
1354 p = subprocess.Popen([sys.executable, '_test_warnings.py', 'always'],
1355 **opts)
1356 with p:
1357 out, err = get_parse_out_err(p)
1358 self.assertIn(b'OK', err)
1359 self.assertEqual(len(out), 14)
1360 for msg in [b'dw', b'iw', b'uw', b'rw']:
1361 self.assertEqual(out.count(msg), 3)
1362 for msg in [ae_msg, at_msg]:
1363 self.assertEqual(out.count(msg), 1)
1364
1365 def testStdErrLookedUpAtInstantiationTime(self):
1366 # see issue 10786
1367 old_stderr = sys.stderr
1368 f = io.StringIO()
1369 sys.stderr = f
1370 try:
1371 runner = unittest.TextTestRunner()
1372 self.assertTrue(runner.stream.stream is f)
1373 finally:
1374 sys.stderr = old_stderr
1375
1376 def testSpecifiedStreamUsed(self):
1377 # see issue 10786
1378 f = io.StringIO()
1379 runner = unittest.TextTestRunner(f)
1380 self.assertTrue(runner.stream.stream is f)
1381
1382
1383 if __name__ == "__main__":
1384 unittest.main()