test_runner.py 49 KB

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