test_case.py 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988
  1. import contextlib
  2. import difflib
  3. import pprint
  4. import pickle
  5. import re
  6. import sys
  7. import logging
  8. import warnings
  9. import weakref
  10. import inspect
  11. import types
  12. from copy import deepcopy
  13. from test import support
  14. import unittest
  15. from unittest.test.support import (
  16. TestEquality, TestHashing, LoggingResult, LegacyLoggingResult,
  17. ResultWithNoStartTestRunStopTestRun
  18. )
  19. from test.support import captured_stderr, gc_collect
  20. log_foo = logging.getLogger('foo')
  21. log_foobar = logging.getLogger('foo.bar')
  22. log_quux = logging.getLogger('quux')
  23. class Test(object):
  24. "Keep these TestCase classes out of the main namespace"
  25. class Foo(unittest.TestCase):
  26. def runTest(self): pass
  27. def test1(self): pass
  28. class Bar(Foo):
  29. def test2(self): pass
  30. class LoggingTestCase(unittest.TestCase):
  31. """A test case which logs its calls."""
  32. def __init__(self, events):
  33. super(Test.LoggingTestCase, self).__init__('test')
  34. self.events = events
  35. def setUp(self):
  36. self.events.append('setUp')
  37. def test(self):
  38. self.events.append('test')
  39. def tearDown(self):
  40. self.events.append('tearDown')
  41. class Test_TestCase(unittest.TestCase, TestEquality, TestHashing):
  42. ### Set up attributes used by inherited tests
  43. ################################################################
  44. # Used by TestHashing.test_hash and TestEquality.test_eq
  45. eq_pairs = [(Test.Foo('test1'), Test.Foo('test1'))]
  46. # Used by TestEquality.test_ne
  47. ne_pairs = [(Test.Foo('test1'), Test.Foo('runTest')),
  48. (Test.Foo('test1'), Test.Bar('test1')),
  49. (Test.Foo('test1'), Test.Bar('test2'))]
  50. ################################################################
  51. ### /Set up attributes used by inherited tests
  52. # "class TestCase([methodName])"
  53. # ...
  54. # "Each instance of TestCase will run a single test method: the
  55. # method named methodName."
  56. # ...
  57. # "methodName defaults to "runTest"."
  58. #
  59. # Make sure it really is optional, and that it defaults to the proper
  60. # thing.
  61. def test_init__no_test_name(self):
  62. class Test(unittest.TestCase):
  63. def runTest(self): raise MyException()
  64. def test(self): pass
  65. self.assertEqual(Test().id()[-13:], '.Test.runTest')
  66. # test that TestCase can be instantiated with no args
  67. # primarily for use at the interactive interpreter
  68. test = unittest.TestCase()
  69. test.assertEqual(3, 3)
  70. with test.assertRaises(test.failureException):
  71. test.assertEqual(3, 2)
  72. with self.assertRaises(AttributeError):
  73. test.run()
  74. # "class TestCase([methodName])"
  75. # ...
  76. # "Each instance of TestCase will run a single test method: the
  77. # method named methodName."
  78. def test_init__test_name__valid(self):
  79. class Test(unittest.TestCase):
  80. def runTest(self): raise MyException()
  81. def test(self): pass
  82. self.assertEqual(Test('test').id()[-10:], '.Test.test')
  83. # "class TestCase([methodName])"
  84. # ...
  85. # "Each instance of TestCase will run a single test method: the
  86. # method named methodName."
  87. def test_init__test_name__invalid(self):
  88. class Test(unittest.TestCase):
  89. def runTest(self): raise MyException()
  90. def test(self): pass
  91. try:
  92. Test('testfoo')
  93. except ValueError:
  94. pass
  95. else:
  96. self.fail("Failed to raise ValueError")
  97. # "Return the number of tests represented by the this test object. For
  98. # TestCase instances, this will always be 1"
  99. def test_countTestCases(self):
  100. class Foo(unittest.TestCase):
  101. def test(self): pass
  102. self.assertEqual(Foo('test').countTestCases(), 1)
  103. # "Return the default type of test result object to be used to run this
  104. # test. For TestCase instances, this will always be
  105. # unittest.TestResult; subclasses of TestCase should
  106. # override this as necessary."
  107. def test_defaultTestResult(self):
  108. class Foo(unittest.TestCase):
  109. def runTest(self):
  110. pass
  111. result = Foo().defaultTestResult()
  112. self.assertEqual(type(result), unittest.TestResult)
  113. # "When a setUp() method is defined, the test runner will run that method
  114. # prior to each test. Likewise, if a tearDown() method is defined, the
  115. # test runner will invoke that method after each test. In the example,
  116. # setUp() was used to create a fresh sequence for each test."
  117. #
  118. # Make sure the proper call order is maintained, even if setUp() raises
  119. # an exception.
  120. def test_run_call_order__error_in_setUp(self):
  121. events = []
  122. result = LoggingResult(events)
  123. class Foo(Test.LoggingTestCase):
  124. def setUp(self):
  125. super(Foo, self).setUp()
  126. raise RuntimeError('raised by Foo.setUp')
  127. Foo(events).run(result)
  128. expected = ['startTest', 'setUp', 'addError', 'stopTest']
  129. self.assertEqual(events, expected)
  130. # "With a temporary result stopTestRun is called when setUp errors.
  131. def test_run_call_order__error_in_setUp_default_result(self):
  132. events = []
  133. class Foo(Test.LoggingTestCase):
  134. def defaultTestResult(self):
  135. return LoggingResult(self.events)
  136. def setUp(self):
  137. super(Foo, self).setUp()
  138. raise RuntimeError('raised by Foo.setUp')
  139. Foo(events).run()
  140. expected = ['startTestRun', 'startTest', 'setUp', 'addError',
  141. 'stopTest', 'stopTestRun']
  142. self.assertEqual(events, expected)
  143. # "When a setUp() method is defined, the test runner will run that method
  144. # prior to each test. Likewise, if a tearDown() method is defined, the
  145. # test runner will invoke that method after each test. In the example,
  146. # setUp() was used to create a fresh sequence for each test."
  147. #
  148. # Make sure the proper call order is maintained, even if the test raises
  149. # an error (as opposed to a failure).
  150. def test_run_call_order__error_in_test(self):
  151. events = []
  152. result = LoggingResult(events)
  153. class Foo(Test.LoggingTestCase):
  154. def test(self):
  155. super(Foo, self).test()
  156. raise RuntimeError('raised by Foo.test')
  157. expected = ['startTest', 'setUp', 'test',
  158. 'addError', 'tearDown', 'stopTest']
  159. Foo(events).run(result)
  160. self.assertEqual(events, expected)
  161. # "With a default result, an error in the test still results in stopTestRun
  162. # being called."
  163. def test_run_call_order__error_in_test_default_result(self):
  164. events = []
  165. class Foo(Test.LoggingTestCase):
  166. def defaultTestResult(self):
  167. return LoggingResult(self.events)
  168. def test(self):
  169. super(Foo, self).test()
  170. raise RuntimeError('raised by Foo.test')
  171. expected = ['startTestRun', 'startTest', 'setUp', 'test',
  172. 'addError', 'tearDown', 'stopTest', 'stopTestRun']
  173. Foo(events).run()
  174. self.assertEqual(events, expected)
  175. # "When a setUp() method is defined, the test runner will run that method
  176. # prior to each test. Likewise, if a tearDown() method is defined, the
  177. # test runner will invoke that method after each test. In the example,
  178. # setUp() was used to create a fresh sequence for each test."
  179. #
  180. # Make sure the proper call order is maintained, even if the test signals
  181. # a failure (as opposed to an error).
  182. def test_run_call_order__failure_in_test(self):
  183. events = []
  184. result = LoggingResult(events)
  185. class Foo(Test.LoggingTestCase):
  186. def test(self):
  187. super(Foo, self).test()
  188. self.fail('raised by Foo.test')
  189. expected = ['startTest', 'setUp', 'test',
  190. 'addFailure', 'tearDown', 'stopTest']
  191. Foo(events).run(result)
  192. self.assertEqual(events, expected)
  193. # "When a test fails with a default result stopTestRun is still called."
  194. def test_run_call_order__failure_in_test_default_result(self):
  195. class Foo(Test.LoggingTestCase):
  196. def defaultTestResult(self):
  197. return LoggingResult(self.events)
  198. def test(self):
  199. super(Foo, self).test()
  200. self.fail('raised by Foo.test')
  201. expected = ['startTestRun', 'startTest', 'setUp', 'test',
  202. 'addFailure', 'tearDown', 'stopTest', 'stopTestRun']
  203. events = []
  204. Foo(events).run()
  205. self.assertEqual(events, expected)
  206. # "When a setUp() method is defined, the test runner will run that method
  207. # prior to each test. Likewise, if a tearDown() method is defined, the
  208. # test runner will invoke that method after each test. In the example,
  209. # setUp() was used to create a fresh sequence for each test."
  210. #
  211. # Make sure the proper call order is maintained, even if tearDown() raises
  212. # an exception.
  213. def test_run_call_order__error_in_tearDown(self):
  214. events = []
  215. result = LoggingResult(events)
  216. class Foo(Test.LoggingTestCase):
  217. def tearDown(self):
  218. super(Foo, self).tearDown()
  219. raise RuntimeError('raised by Foo.tearDown')
  220. Foo(events).run(result)
  221. expected = ['startTest', 'setUp', 'test', 'tearDown', 'addError',
  222. 'stopTest']
  223. self.assertEqual(events, expected)
  224. # "When tearDown errors with a default result stopTestRun is still called."
  225. def test_run_call_order__error_in_tearDown_default_result(self):
  226. class Foo(Test.LoggingTestCase):
  227. def defaultTestResult(self):
  228. return LoggingResult(self.events)
  229. def tearDown(self):
  230. super(Foo, self).tearDown()
  231. raise RuntimeError('raised by Foo.tearDown')
  232. events = []
  233. Foo(events).run()
  234. expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
  235. 'addError', 'stopTest', 'stopTestRun']
  236. self.assertEqual(events, expected)
  237. # "TestCase.run() still works when the defaultTestResult is a TestResult
  238. # that does not support startTestRun and stopTestRun.
  239. def test_run_call_order_default_result(self):
  240. class Foo(unittest.TestCase):
  241. def defaultTestResult(self):
  242. return ResultWithNoStartTestRunStopTestRun()
  243. def test(self):
  244. pass
  245. Foo('test').run()
  246. def test_deprecation_of_return_val_from_test(self):
  247. # Issue 41322 - deprecate return of value that is not None from a test
  248. class Nothing:
  249. def __eq__(self, o):
  250. return o is None
  251. class Foo(unittest.TestCase):
  252. def test1(self):
  253. return 1
  254. def test2(self):
  255. yield 1
  256. def test3(self):
  257. return Nothing()
  258. with self.assertWarns(DeprecationWarning) as w:
  259. Foo('test1').run()
  260. self.assertIn('It is deprecated to return a value that is not None', str(w.warning))
  261. self.assertIn('test1', str(w.warning))
  262. self.assertEqual(w.filename, __file__)
  263. with self.assertWarns(DeprecationWarning) as w:
  264. Foo('test2').run()
  265. self.assertIn('It is deprecated to return a value that is not None', str(w.warning))
  266. self.assertIn('test2', str(w.warning))
  267. self.assertEqual(w.filename, __file__)
  268. with self.assertWarns(DeprecationWarning) as w:
  269. Foo('test3').run()
  270. self.assertIn('It is deprecated to return a value that is not None', str(w.warning))
  271. self.assertIn('test3', str(w.warning))
  272. self.assertEqual(w.filename, __file__)
  273. def _check_call_order__subtests(self, result, events, expected_events):
  274. class Foo(Test.LoggingTestCase):
  275. def test(self):
  276. super(Foo, self).test()
  277. for i in [1, 2, 3]:
  278. with self.subTest(i=i):
  279. if i == 1:
  280. self.fail('failure')
  281. for j in [2, 3]:
  282. with self.subTest(j=j):
  283. if i * j == 6:
  284. raise RuntimeError('raised by Foo.test')
  285. 1 / 0
  286. # Order is the following:
  287. # i=1 => subtest failure
  288. # i=2, j=2 => subtest success
  289. # i=2, j=3 => subtest error
  290. # i=3, j=2 => subtest error
  291. # i=3, j=3 => subtest success
  292. # toplevel => error
  293. Foo(events).run(result)
  294. self.assertEqual(events, expected_events)
  295. def test_run_call_order__subtests(self):
  296. events = []
  297. result = LoggingResult(events)
  298. expected = ['startTest', 'setUp', 'test',
  299. 'addSubTestFailure', 'addSubTestSuccess',
  300. 'addSubTestFailure', 'addSubTestFailure',
  301. 'addSubTestSuccess', 'addError', 'tearDown', 'stopTest']
  302. self._check_call_order__subtests(result, events, expected)
  303. def test_run_call_order__subtests_legacy(self):
  304. # With a legacy result object (without an addSubTest method),
  305. # text execution stops after the first subtest failure.
  306. events = []
  307. result = LegacyLoggingResult(events)
  308. expected = ['startTest', 'setUp', 'test',
  309. 'addFailure', 'tearDown', 'stopTest']
  310. self._check_call_order__subtests(result, events, expected)
  311. def _check_call_order__subtests_success(self, result, events, expected_events):
  312. class Foo(Test.LoggingTestCase):
  313. def test(self):
  314. super(Foo, self).test()
  315. for i in [1, 2]:
  316. with self.subTest(i=i):
  317. for j in [2, 3]:
  318. with self.subTest(j=j):
  319. pass
  320. Foo(events).run(result)
  321. self.assertEqual(events, expected_events)
  322. def test_run_call_order__subtests_success(self):
  323. events = []
  324. result = LoggingResult(events)
  325. # The 6 subtest successes are individually recorded, in addition
  326. # to the whole test success.
  327. expected = (['startTest', 'setUp', 'test']
  328. + 6 * ['addSubTestSuccess']
  329. + ['tearDown', 'addSuccess', 'stopTest'])
  330. self._check_call_order__subtests_success(result, events, expected)
  331. def test_run_call_order__subtests_success_legacy(self):
  332. # With a legacy result, only the whole test success is recorded.
  333. events = []
  334. result = LegacyLoggingResult(events)
  335. expected = ['startTest', 'setUp', 'test', 'tearDown',
  336. 'addSuccess', 'stopTest']
  337. self._check_call_order__subtests_success(result, events, expected)
  338. def test_run_call_order__subtests_failfast(self):
  339. events = []
  340. result = LoggingResult(events)
  341. result.failfast = True
  342. class Foo(Test.LoggingTestCase):
  343. def test(self):
  344. super(Foo, self).test()
  345. with self.subTest(i=1):
  346. self.fail('failure')
  347. with self.subTest(i=2):
  348. self.fail('failure')
  349. self.fail('failure')
  350. expected = ['startTest', 'setUp', 'test',
  351. 'addSubTestFailure', 'tearDown', 'stopTest']
  352. Foo(events).run(result)
  353. self.assertEqual(events, expected)
  354. def test_subtests_failfast(self):
  355. # Ensure proper test flow with subtests and failfast (issue #22894)
  356. events = []
  357. class Foo(unittest.TestCase):
  358. def test_a(self):
  359. with self.subTest():
  360. events.append('a1')
  361. events.append('a2')
  362. def test_b(self):
  363. with self.subTest():
  364. events.append('b1')
  365. with self.subTest():
  366. self.fail('failure')
  367. events.append('b2')
  368. def test_c(self):
  369. events.append('c')
  370. result = unittest.TestResult()
  371. result.failfast = True
  372. suite = unittest.TestLoader().loadTestsFromTestCase(Foo)
  373. suite.run(result)
  374. expected = ['a1', 'a2', 'b1']
  375. self.assertEqual(events, expected)
  376. def test_subtests_debug(self):
  377. # Test debug() with a test that uses subTest() (bpo-34900)
  378. events = []
  379. class Foo(unittest.TestCase):
  380. def test_a(self):
  381. events.append('test case')
  382. with self.subTest():
  383. events.append('subtest 1')
  384. Foo('test_a').debug()
  385. self.assertEqual(events, ['test case', 'subtest 1'])
  386. # "This class attribute gives the exception raised by the test() method.
  387. # If a test framework needs to use a specialized exception, possibly to
  388. # carry additional information, it must subclass this exception in
  389. # order to ``play fair'' with the framework. The initial value of this
  390. # attribute is AssertionError"
  391. def test_failureException__default(self):
  392. class Foo(unittest.TestCase):
  393. def test(self):
  394. pass
  395. self.assertIs(Foo('test').failureException, AssertionError)
  396. # "This class attribute gives the exception raised by the test() method.
  397. # If a test framework needs to use a specialized exception, possibly to
  398. # carry additional information, it must subclass this exception in
  399. # order to ``play fair'' with the framework."
  400. #
  401. # Make sure TestCase.run() respects the designated failureException
  402. def test_failureException__subclassing__explicit_raise(self):
  403. events = []
  404. result = LoggingResult(events)
  405. class Foo(unittest.TestCase):
  406. def test(self):
  407. raise RuntimeError()
  408. failureException = RuntimeError
  409. self.assertIs(Foo('test').failureException, RuntimeError)
  410. Foo('test').run(result)
  411. expected = ['startTest', 'addFailure', 'stopTest']
  412. self.assertEqual(events, expected)
  413. # "This class attribute gives the exception raised by the test() method.
  414. # If a test framework needs to use a specialized exception, possibly to
  415. # carry additional information, it must subclass this exception in
  416. # order to ``play fair'' with the framework."
  417. #
  418. # Make sure TestCase.run() respects the designated failureException
  419. def test_failureException__subclassing__implicit_raise(self):
  420. events = []
  421. result = LoggingResult(events)
  422. class Foo(unittest.TestCase):
  423. def test(self):
  424. self.fail("foo")
  425. failureException = RuntimeError
  426. self.assertIs(Foo('test').failureException, RuntimeError)
  427. Foo('test').run(result)
  428. expected = ['startTest', 'addFailure', 'stopTest']
  429. self.assertEqual(events, expected)
  430. # "The default implementation does nothing."
  431. def test_setUp(self):
  432. class Foo(unittest.TestCase):
  433. def runTest(self):
  434. pass
  435. # ... and nothing should happen
  436. Foo().setUp()
  437. # "The default implementation does nothing."
  438. def test_tearDown(self):
  439. class Foo(unittest.TestCase):
  440. def runTest(self):
  441. pass
  442. # ... and nothing should happen
  443. Foo().tearDown()
  444. # "Return a string identifying the specific test case."
  445. #
  446. # Because of the vague nature of the docs, I'm not going to lock this
  447. # test down too much. Really all that can be asserted is that the id()
  448. # will be a string (either 8-byte or unicode -- again, because the docs
  449. # just say "string")
  450. def test_id(self):
  451. class Foo(unittest.TestCase):
  452. def runTest(self):
  453. pass
  454. self.assertIsInstance(Foo().id(), str)
  455. # "If result is omitted or None, a temporary result object is created,
  456. # used, and is made available to the caller. As TestCase owns the
  457. # temporary result startTestRun and stopTestRun are called.
  458. def test_run__uses_defaultTestResult(self):
  459. events = []
  460. defaultResult = LoggingResult(events)
  461. class Foo(unittest.TestCase):
  462. def test(self):
  463. events.append('test')
  464. def defaultTestResult(self):
  465. return defaultResult
  466. # Make run() find a result object on its own
  467. result = Foo('test').run()
  468. self.assertIs(result, defaultResult)
  469. expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
  470. 'stopTest', 'stopTestRun']
  471. self.assertEqual(events, expected)
  472. # "The result object is returned to run's caller"
  473. def test_run__returns_given_result(self):
  474. class Foo(unittest.TestCase):
  475. def test(self):
  476. pass
  477. result = unittest.TestResult()
  478. retval = Foo('test').run(result)
  479. self.assertIs(retval, result)
  480. # "The same effect [as method run] may be had by simply calling the
  481. # TestCase instance."
  482. def test_call__invoking_an_instance_delegates_to_run(self):
  483. resultIn = unittest.TestResult()
  484. resultOut = unittest.TestResult()
  485. class Foo(unittest.TestCase):
  486. def test(self):
  487. pass
  488. def run(self, result):
  489. self.assertIs(result, resultIn)
  490. return resultOut
  491. retval = Foo('test')(resultIn)
  492. self.assertIs(retval, resultOut)
  493. def testShortDescriptionWithoutDocstring(self):
  494. self.assertIsNone(self.shortDescription())
  495. @unittest.skipIf(sys.flags.optimize >= 2,
  496. "Docstrings are omitted with -O2 and above")
  497. def testShortDescriptionWithOneLineDocstring(self):
  498. """Tests shortDescription() for a method with a docstring."""
  499. self.assertEqual(
  500. self.shortDescription(),
  501. 'Tests shortDescription() for a method with a docstring.')
  502. @unittest.skipIf(sys.flags.optimize >= 2,
  503. "Docstrings are omitted with -O2 and above")
  504. def testShortDescriptionWithMultiLineDocstring(self):
  505. """Tests shortDescription() for a method with a longer docstring.
  506. This method ensures that only the first line of a docstring is
  507. returned used in the short description, no matter how long the
  508. whole thing is.
  509. """
  510. self.assertEqual(
  511. self.shortDescription(),
  512. 'Tests shortDescription() for a method with a longer '
  513. 'docstring.')
  514. @unittest.skipIf(sys.flags.optimize >= 2,
  515. "Docstrings are omitted with -O2 and above")
  516. def testShortDescriptionWhitespaceTrimming(self):
  517. """
  518. Tests shortDescription() whitespace is trimmed, so that the first
  519. line of nonwhite-space text becomes the docstring.
  520. """
  521. self.assertEqual(
  522. self.shortDescription(),
  523. 'Tests shortDescription() whitespace is trimmed, so that the first')
  524. def testAddTypeEqualityFunc(self):
  525. class SadSnake(object):
  526. """Dummy class for test_addTypeEqualityFunc."""
  527. s1, s2 = SadSnake(), SadSnake()
  528. self.assertFalse(s1 == s2)
  529. def AllSnakesCreatedEqual(a, b, msg=None):
  530. return type(a) == type(b) == SadSnake
  531. self.addTypeEqualityFunc(SadSnake, AllSnakesCreatedEqual)
  532. self.assertEqual(s1, s2)
  533. # No this doesn't clean up and remove the SadSnake equality func
  534. # from this TestCase instance but since it's local nothing else
  535. # will ever notice that.
  536. def testAssertIs(self):
  537. thing = object()
  538. self.assertIs(thing, thing)
  539. self.assertRaises(self.failureException, self.assertIs, thing, object())
  540. def testAssertIsNot(self):
  541. thing = object()
  542. self.assertIsNot(thing, object())
  543. self.assertRaises(self.failureException, self.assertIsNot, thing, thing)
  544. def testAssertIsInstance(self):
  545. thing = []
  546. self.assertIsInstance(thing, list)
  547. self.assertRaises(self.failureException, self.assertIsInstance,
  548. thing, dict)
  549. def testAssertNotIsInstance(self):
  550. thing = []
  551. self.assertNotIsInstance(thing, dict)
  552. self.assertRaises(self.failureException, self.assertNotIsInstance,
  553. thing, list)
  554. def testAssertIn(self):
  555. animals = {'monkey': 'banana', 'cow': 'grass', 'seal': 'fish'}
  556. self.assertIn('a', 'abc')
  557. self.assertIn(2, [1, 2, 3])
  558. self.assertIn('monkey', animals)
  559. self.assertNotIn('d', 'abc')
  560. self.assertNotIn(0, [1, 2, 3])
  561. self.assertNotIn('otter', animals)
  562. self.assertRaises(self.failureException, self.assertIn, 'x', 'abc')
  563. self.assertRaises(self.failureException, self.assertIn, 4, [1, 2, 3])
  564. self.assertRaises(self.failureException, self.assertIn, 'elephant',
  565. animals)
  566. self.assertRaises(self.failureException, self.assertNotIn, 'c', 'abc')
  567. self.assertRaises(self.failureException, self.assertNotIn, 1, [1, 2, 3])
  568. self.assertRaises(self.failureException, self.assertNotIn, 'cow',
  569. animals)
  570. def testAssertDictContainsSubset(self):
  571. with warnings.catch_warnings():
  572. warnings.simplefilter("ignore", DeprecationWarning)
  573. self.assertDictContainsSubset({}, {})
  574. self.assertDictContainsSubset({}, {'a': 1})
  575. self.assertDictContainsSubset({'a': 1}, {'a': 1})
  576. self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
  577. self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
  578. with self.assertRaises(self.failureException):
  579. self.assertDictContainsSubset({1: "one"}, {})
  580. with self.assertRaises(self.failureException):
  581. self.assertDictContainsSubset({'a': 2}, {'a': 1})
  582. with self.assertRaises(self.failureException):
  583. self.assertDictContainsSubset({'c': 1}, {'a': 1})
  584. with self.assertRaises(self.failureException):
  585. self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
  586. with self.assertRaises(self.failureException):
  587. self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
  588. one = ''.join(chr(i) for i in range(255))
  589. # this used to cause a UnicodeDecodeError constructing the failure msg
  590. with self.assertRaises(self.failureException):
  591. self.assertDictContainsSubset({'foo': one}, {'foo': '\uFFFD'})
  592. def testAssertEqual(self):
  593. equal_pairs = [
  594. ((), ()),
  595. ({}, {}),
  596. ([], []),
  597. (set(), set()),
  598. (frozenset(), frozenset())]
  599. for a, b in equal_pairs:
  600. # This mess of try excepts is to test the assertEqual behavior
  601. # itself.
  602. try:
  603. self.assertEqual(a, b)
  604. except self.failureException:
  605. self.fail('assertEqual(%r, %r) failed' % (a, b))
  606. try:
  607. self.assertEqual(a, b, msg='foo')
  608. except self.failureException:
  609. self.fail('assertEqual(%r, %r) with msg= failed' % (a, b))
  610. try:
  611. self.assertEqual(a, b, 'foo')
  612. except self.failureException:
  613. self.fail('assertEqual(%r, %r) with third parameter failed' %
  614. (a, b))
  615. unequal_pairs = [
  616. ((), []),
  617. ({}, set()),
  618. (set([4,1]), frozenset([4,2])),
  619. (frozenset([4,5]), set([2,3])),
  620. (set([3,4]), set([5,4]))]
  621. for a, b in unequal_pairs:
  622. self.assertRaises(self.failureException, self.assertEqual, a, b)
  623. self.assertRaises(self.failureException, self.assertEqual, a, b,
  624. 'foo')
  625. self.assertRaises(self.failureException, self.assertEqual, a, b,
  626. msg='foo')
  627. def testEquality(self):
  628. self.assertListEqual([], [])
  629. self.assertTupleEqual((), ())
  630. self.assertSequenceEqual([], ())
  631. a = [0, 'a', []]
  632. b = []
  633. self.assertRaises(unittest.TestCase.failureException,
  634. self.assertListEqual, a, b)
  635. self.assertRaises(unittest.TestCase.failureException,
  636. self.assertListEqual, tuple(a), tuple(b))
  637. self.assertRaises(unittest.TestCase.failureException,
  638. self.assertSequenceEqual, a, tuple(b))
  639. b.extend(a)
  640. self.assertListEqual(a, b)
  641. self.assertTupleEqual(tuple(a), tuple(b))
  642. self.assertSequenceEqual(a, tuple(b))
  643. self.assertSequenceEqual(tuple(a), b)
  644. self.assertRaises(self.failureException, self.assertListEqual,
  645. a, tuple(b))
  646. self.assertRaises(self.failureException, self.assertTupleEqual,
  647. tuple(a), b)
  648. self.assertRaises(self.failureException, self.assertListEqual, None, b)
  649. self.assertRaises(self.failureException, self.assertTupleEqual, None,
  650. tuple(b))
  651. self.assertRaises(self.failureException, self.assertSequenceEqual,
  652. None, tuple(b))
  653. self.assertRaises(self.failureException, self.assertListEqual, 1, 1)
  654. self.assertRaises(self.failureException, self.assertTupleEqual, 1, 1)
  655. self.assertRaises(self.failureException, self.assertSequenceEqual,
  656. 1, 1)
  657. self.assertDictEqual({}, {})
  658. c = { 'x': 1 }
  659. d = {}
  660. self.assertRaises(unittest.TestCase.failureException,
  661. self.assertDictEqual, c, d)
  662. d.update(c)
  663. self.assertDictEqual(c, d)
  664. d['x'] = 0
  665. self.assertRaises(unittest.TestCase.failureException,
  666. self.assertDictEqual, c, d, 'These are unequal')
  667. self.assertRaises(self.failureException, self.assertDictEqual, None, d)
  668. self.assertRaises(self.failureException, self.assertDictEqual, [], d)
  669. self.assertRaises(self.failureException, self.assertDictEqual, 1, 1)
  670. def testAssertSequenceEqualMaxDiff(self):
  671. self.assertEqual(self.maxDiff, 80*8)
  672. seq1 = 'a' + 'x' * 80**2
  673. seq2 = 'b' + 'x' * 80**2
  674. diff = '\n'.join(difflib.ndiff(pprint.pformat(seq1).splitlines(),
  675. pprint.pformat(seq2).splitlines()))
  676. # the +1 is the leading \n added by assertSequenceEqual
  677. omitted = unittest.case.DIFF_OMITTED % (len(diff) + 1,)
  678. self.maxDiff = len(diff)//2
  679. try:
  680. self.assertSequenceEqual(seq1, seq2)
  681. except self.failureException as e:
  682. msg = e.args[0]
  683. else:
  684. self.fail('assertSequenceEqual did not fail.')
  685. self.assertLess(len(msg), len(diff))
  686. self.assertIn(omitted, msg)
  687. self.maxDiff = len(diff) * 2
  688. try:
  689. self.assertSequenceEqual(seq1, seq2)
  690. except self.failureException as e:
  691. msg = e.args[0]
  692. else:
  693. self.fail('assertSequenceEqual did not fail.')
  694. self.assertGreater(len(msg), len(diff))
  695. self.assertNotIn(omitted, msg)
  696. self.maxDiff = None
  697. try:
  698. self.assertSequenceEqual(seq1, seq2)
  699. except self.failureException as e:
  700. msg = e.args[0]
  701. else:
  702. self.fail('assertSequenceEqual did not fail.')
  703. self.assertGreater(len(msg), len(diff))
  704. self.assertNotIn(omitted, msg)
  705. def testTruncateMessage(self):
  706. self.maxDiff = 1
  707. message = self._truncateMessage('foo', 'bar')
  708. omitted = unittest.case.DIFF_OMITTED % len('bar')
  709. self.assertEqual(message, 'foo' + omitted)
  710. self.maxDiff = None
  711. message = self._truncateMessage('foo', 'bar')
  712. self.assertEqual(message, 'foobar')
  713. self.maxDiff = 4
  714. message = self._truncateMessage('foo', 'bar')
  715. self.assertEqual(message, 'foobar')
  716. def testAssertDictEqualTruncates(self):
  717. test = unittest.TestCase('assertEqual')
  718. def truncate(msg, diff):
  719. return 'foo'
  720. test._truncateMessage = truncate
  721. try:
  722. test.assertDictEqual({}, {1: 0})
  723. except self.failureException as e:
  724. self.assertEqual(str(e), 'foo')
  725. else:
  726. self.fail('assertDictEqual did not fail')
  727. def testAssertMultiLineEqualTruncates(self):
  728. test = unittest.TestCase('assertEqual')
  729. def truncate(msg, diff):
  730. return 'foo'
  731. test._truncateMessage = truncate
  732. try:
  733. test.assertMultiLineEqual('foo', 'bar')
  734. except self.failureException as e:
  735. self.assertEqual(str(e), 'foo')
  736. else:
  737. self.fail('assertMultiLineEqual did not fail')
  738. def testAssertEqual_diffThreshold(self):
  739. # check threshold value
  740. self.assertEqual(self._diffThreshold, 2**16)
  741. # disable madDiff to get diff markers
  742. self.maxDiff = None
  743. # set a lower threshold value and add a cleanup to restore it
  744. old_threshold = self._diffThreshold
  745. self._diffThreshold = 2**5
  746. self.addCleanup(lambda: setattr(self, '_diffThreshold', old_threshold))
  747. # under the threshold: diff marker (^) in error message
  748. s = 'x' * (2**4)
  749. with self.assertRaises(self.failureException) as cm:
  750. self.assertEqual(s + 'a', s + 'b')
  751. self.assertIn('^', str(cm.exception))
  752. self.assertEqual(s + 'a', s + 'a')
  753. # over the threshold: diff not used and marker (^) not in error message
  754. s = 'x' * (2**6)
  755. # if the path that uses difflib is taken, _truncateMessage will be
  756. # called -- replace it with explodingTruncation to verify that this
  757. # doesn't happen
  758. def explodingTruncation(message, diff):
  759. raise SystemError('this should not be raised')
  760. old_truncate = self._truncateMessage
  761. self._truncateMessage = explodingTruncation
  762. self.addCleanup(lambda: setattr(self, '_truncateMessage', old_truncate))
  763. s1, s2 = s + 'a', s + 'b'
  764. with self.assertRaises(self.failureException) as cm:
  765. self.assertEqual(s1, s2)
  766. self.assertNotIn('^', str(cm.exception))
  767. self.assertEqual(str(cm.exception), '%r != %r' % (s1, s2))
  768. self.assertEqual(s + 'a', s + 'a')
  769. def testAssertEqual_shorten(self):
  770. # set a lower threshold value and add a cleanup to restore it
  771. old_threshold = self._diffThreshold
  772. self._diffThreshold = 0
  773. self.addCleanup(lambda: setattr(self, '_diffThreshold', old_threshold))
  774. s = 'x' * 100
  775. s1, s2 = s + 'a', s + 'b'
  776. with self.assertRaises(self.failureException) as cm:
  777. self.assertEqual(s1, s2)
  778. c = 'xxxx[35 chars]' + 'x' * 61
  779. self.assertEqual(str(cm.exception), "'%sa' != '%sb'" % (c, c))
  780. self.assertEqual(s + 'a', s + 'a')
  781. p = 'y' * 50
  782. s1, s2 = s + 'a' + p, s + 'b' + p
  783. with self.assertRaises(self.failureException) as cm:
  784. self.assertEqual(s1, s2)
  785. c = 'xxxx[85 chars]xxxxxxxxxxx'
  786. self.assertEqual(str(cm.exception), "'%sa%s' != '%sb%s'" % (c, p, c, p))
  787. p = 'y' * 100
  788. s1, s2 = s + 'a' + p, s + 'b' + p
  789. with self.assertRaises(self.failureException) as cm:
  790. self.assertEqual(s1, s2)
  791. c = 'xxxx[91 chars]xxxxx'
  792. d = 'y' * 40 + '[56 chars]yyyy'
  793. self.assertEqual(str(cm.exception), "'%sa%s' != '%sb%s'" % (c, d, c, d))
  794. def testAssertCountEqual(self):
  795. a = object()
  796. self.assertCountEqual([1, 2, 3], [3, 2, 1])
  797. self.assertCountEqual(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
  798. self.assertCountEqual([a, a, 2, 2, 3], (a, 2, 3, a, 2))
  799. self.assertCountEqual([1, "2", "a", "a"], ["a", "2", True, "a"])
  800. self.assertRaises(self.failureException, self.assertCountEqual,
  801. [1, 2] + [3] * 100, [1] * 100 + [2, 3])
  802. self.assertRaises(self.failureException, self.assertCountEqual,
  803. [1, "2", "a", "a"], ["a", "2", True, 1])
  804. self.assertRaises(self.failureException, self.assertCountEqual,
  805. [10], [10, 11])
  806. self.assertRaises(self.failureException, self.assertCountEqual,
  807. [10, 11], [10])
  808. self.assertRaises(self.failureException, self.assertCountEqual,
  809. [10, 11, 10], [10, 11])
  810. # Test that sequences of unhashable objects can be tested for sameness:
  811. self.assertCountEqual([[1, 2], [3, 4], 0], [False, [3, 4], [1, 2]])
  812. # Test that iterator of unhashable objects can be tested for sameness:
  813. self.assertCountEqual(iter([1, 2, [], 3, 4]),
  814. iter([1, 2, [], 3, 4]))
  815. # hashable types, but not orderable
  816. self.assertRaises(self.failureException, self.assertCountEqual,
  817. [], [divmod, 'x', 1, 5j, 2j, frozenset()])
  818. # comparing dicts
  819. self.assertCountEqual([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
  820. # comparing heterogeneous non-hashable sequences
  821. self.assertCountEqual([1, 'x', divmod, []], [divmod, [], 'x', 1])
  822. self.assertRaises(self.failureException, self.assertCountEqual,
  823. [], [divmod, [], 'x', 1, 5j, 2j, set()])
  824. self.assertRaises(self.failureException, self.assertCountEqual,
  825. [[1]], [[2]])
  826. # Same elements, but not same sequence length
  827. self.assertRaises(self.failureException, self.assertCountEqual,
  828. [1, 1, 2], [2, 1])
  829. self.assertRaises(self.failureException, self.assertCountEqual,
  830. [1, 1, "2", "a", "a"], ["2", "2", True, "a"])
  831. self.assertRaises(self.failureException, self.assertCountEqual,
  832. [1, {'b': 2}, None, True], [{'b': 2}, True, None])
  833. # Same elements which don't reliably compare, in
  834. # different order, see issue 10242
  835. a = [{2,4}, {1,2}]
  836. b = a[::-1]
  837. self.assertCountEqual(a, b)
  838. # test utility functions supporting assertCountEqual()
  839. diffs = set(unittest.util._count_diff_all_purpose('aaabccd', 'abbbcce'))
  840. expected = {(3,1,'a'), (1,3,'b'), (1,0,'d'), (0,1,'e')}
  841. self.assertEqual(diffs, expected)
  842. diffs = unittest.util._count_diff_all_purpose([[]], [])
  843. self.assertEqual(diffs, [(1, 0, [])])
  844. diffs = set(unittest.util._count_diff_hashable('aaabccd', 'abbbcce'))
  845. expected = {(3,1,'a'), (1,3,'b'), (1,0,'d'), (0,1,'e')}
  846. self.assertEqual(diffs, expected)
  847. def testAssertSetEqual(self):
  848. set1 = set()
  849. set2 = set()
  850. self.assertSetEqual(set1, set2)
  851. self.assertRaises(self.failureException, self.assertSetEqual, None, set2)
  852. self.assertRaises(self.failureException, self.assertSetEqual, [], set2)
  853. self.assertRaises(self.failureException, self.assertSetEqual, set1, None)
  854. self.assertRaises(self.failureException, self.assertSetEqual, set1, [])
  855. set1 = set(['a'])
  856. set2 = set()
  857. self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
  858. set1 = set(['a'])
  859. set2 = set(['a'])
  860. self.assertSetEqual(set1, set2)
  861. set1 = set(['a'])
  862. set2 = set(['a', 'b'])
  863. self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
  864. set1 = set(['a'])
  865. set2 = frozenset(['a', 'b'])
  866. self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
  867. set1 = set(['a', 'b'])
  868. set2 = frozenset(['a', 'b'])
  869. self.assertSetEqual(set1, set2)
  870. set1 = set()
  871. set2 = "foo"
  872. self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
  873. self.assertRaises(self.failureException, self.assertSetEqual, set2, set1)
  874. # make sure any string formatting is tuple-safe
  875. set1 = set([(0, 1), (2, 3)])
  876. set2 = set([(4, 5)])
  877. self.assertRaises(self.failureException, self.assertSetEqual, set1, set2)
  878. def testInequality(self):
  879. # Try ints
  880. self.assertGreater(2, 1)
  881. self.assertGreaterEqual(2, 1)
  882. self.assertGreaterEqual(1, 1)
  883. self.assertLess(1, 2)
  884. self.assertLessEqual(1, 2)
  885. self.assertLessEqual(1, 1)
  886. self.assertRaises(self.failureException, self.assertGreater, 1, 2)
  887. self.assertRaises(self.failureException, self.assertGreater, 1, 1)
  888. self.assertRaises(self.failureException, self.assertGreaterEqual, 1, 2)
  889. self.assertRaises(self.failureException, self.assertLess, 2, 1)
  890. self.assertRaises(self.failureException, self.assertLess, 1, 1)
  891. self.assertRaises(self.failureException, self.assertLessEqual, 2, 1)
  892. # Try Floats
  893. self.assertGreater(1.1, 1.0)
  894. self.assertGreaterEqual(1.1, 1.0)
  895. self.assertGreaterEqual(1.0, 1.0)
  896. self.assertLess(1.0, 1.1)
  897. self.assertLessEqual(1.0, 1.1)
  898. self.assertLessEqual(1.0, 1.0)
  899. self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.1)
  900. self.assertRaises(self.failureException, self.assertGreater, 1.0, 1.0)
  901. self.assertRaises(self.failureException, self.assertGreaterEqual, 1.0, 1.1)
  902. self.assertRaises(self.failureException, self.assertLess, 1.1, 1.0)
  903. self.assertRaises(self.failureException, self.assertLess, 1.0, 1.0)
  904. self.assertRaises(self.failureException, self.assertLessEqual, 1.1, 1.0)
  905. # Try Strings
  906. self.assertGreater('bug', 'ant')
  907. self.assertGreaterEqual('bug', 'ant')
  908. self.assertGreaterEqual('ant', 'ant')
  909. self.assertLess('ant', 'bug')
  910. self.assertLessEqual('ant', 'bug')
  911. self.assertLessEqual('ant', 'ant')
  912. self.assertRaises(self.failureException, self.assertGreater, 'ant', 'bug')
  913. self.assertRaises(self.failureException, self.assertGreater, 'ant', 'ant')
  914. self.assertRaises(self.failureException, self.assertGreaterEqual, 'ant', 'bug')
  915. self.assertRaises(self.failureException, self.assertLess, 'bug', 'ant')
  916. self.assertRaises(self.failureException, self.assertLess, 'ant', 'ant')
  917. self.assertRaises(self.failureException, self.assertLessEqual, 'bug', 'ant')
  918. # Try bytes
  919. self.assertGreater(b'bug', b'ant')
  920. self.assertGreaterEqual(b'bug', b'ant')
  921. self.assertGreaterEqual(b'ant', b'ant')
  922. self.assertLess(b'ant', b'bug')
  923. self.assertLessEqual(b'ant', b'bug')
  924. self.assertLessEqual(b'ant', b'ant')
  925. self.assertRaises(self.failureException, self.assertGreater, b'ant', b'bug')
  926. self.assertRaises(self.failureException, self.assertGreater, b'ant', b'ant')
  927. self.assertRaises(self.failureException, self.assertGreaterEqual, b'ant',
  928. b'bug')
  929. self.assertRaises(self.failureException, self.assertLess, b'bug', b'ant')
  930. self.assertRaises(self.failureException, self.assertLess, b'ant', b'ant')
  931. self.assertRaises(self.failureException, self.assertLessEqual, b'bug', b'ant')
  932. def testAssertMultiLineEqual(self):
  933. sample_text = """\
  934. http://www.python.org/doc/2.3/lib/module-unittest.html
  935. test case
  936. A test case is the smallest unit of testing. [...]
  937. """
  938. revised_sample_text = """\
  939. http://www.python.org/doc/2.4.1/lib/module-unittest.html
  940. test case
  941. A test case is the smallest unit of testing. [...] You may provide your
  942. own implementation that does not subclass from TestCase, of course.
  943. """
  944. sample_text_error = """\
  945. - http://www.python.org/doc/2.3/lib/module-unittest.html
  946. ? ^
  947. + http://www.python.org/doc/2.4.1/lib/module-unittest.html
  948. ? ^^^
  949. test case
  950. - A test case is the smallest unit of testing. [...]
  951. + A test case is the smallest unit of testing. [...] You may provide your
  952. ? +++++++++++++++++++++
  953. + own implementation that does not subclass from TestCase, of course.
  954. """
  955. self.maxDiff = None
  956. try:
  957. self.assertMultiLineEqual(sample_text, revised_sample_text)
  958. except self.failureException as e:
  959. # need to remove the first line of the error message
  960. error = str(e).split('\n', 1)[1]
  961. self.assertEqual(sample_text_error, error)
  962. def testAssertEqualSingleLine(self):
  963. sample_text = "laden swallows fly slowly"
  964. revised_sample_text = "unladen swallows fly quickly"
  965. sample_text_error = """\
  966. - laden swallows fly slowly
  967. ? ^^^^
  968. + unladen swallows fly quickly
  969. ? ++ ^^^^^
  970. """
  971. try:
  972. self.assertEqual(sample_text, revised_sample_text)
  973. except self.failureException as e:
  974. # need to remove the first line of the error message
  975. error = str(e).split('\n', 1)[1]
  976. self.assertEqual(sample_text_error, error)
  977. def testEqualityBytesWarning(self):
  978. if sys.flags.bytes_warning:
  979. def bytes_warning():
  980. return self.assertWarnsRegex(BytesWarning,
  981. 'Comparison between bytes and string')
  982. else:
  983. def bytes_warning():
  984. return contextlib.ExitStack()
  985. with bytes_warning(), self.assertRaises(self.failureException):
  986. self.assertEqual('a', b'a')
  987. with bytes_warning():
  988. self.assertNotEqual('a', b'a')
  989. a = [0, 'a']
  990. b = [0, b'a']
  991. with bytes_warning(), self.assertRaises(self.failureException):
  992. self.assertListEqual(a, b)
  993. with bytes_warning(), self.assertRaises(self.failureException):
  994. self.assertTupleEqual(tuple(a), tuple(b))
  995. with bytes_warning(), self.assertRaises(self.failureException):
  996. self.assertSequenceEqual(a, tuple(b))
  997. with bytes_warning(), self.assertRaises(self.failureException):
  998. self.assertSequenceEqual(tuple(a), b)
  999. with bytes_warning(), self.assertRaises(self.failureException):
  1000. self.assertSequenceEqual('a', b'a')
  1001. with bytes_warning(), self.assertRaises(self.failureException):
  1002. self.assertSetEqual(set(a), set(b))
  1003. with self.assertRaises(self.failureException):
  1004. self.assertListEqual(a, tuple(b))
  1005. with self.assertRaises(self.failureException):
  1006. self.assertTupleEqual(tuple(a), b)
  1007. a = [0, b'a']
  1008. b = [0]
  1009. with self.assertRaises(self.failureException):
  1010. self.assertListEqual(a, b)
  1011. with self.assertRaises(self.failureException):
  1012. self.assertTupleEqual(tuple(a), tuple(b))
  1013. with self.assertRaises(self.failureException):
  1014. self.assertSequenceEqual(a, tuple(b))
  1015. with self.assertRaises(self.failureException):
  1016. self.assertSequenceEqual(tuple(a), b)
  1017. with self.assertRaises(self.failureException):
  1018. self.assertSetEqual(set(a), set(b))
  1019. a = [0]
  1020. b = [0, b'a']
  1021. with self.assertRaises(self.failureException):
  1022. self.assertListEqual(a, b)
  1023. with self.assertRaises(self.failureException):
  1024. self.assertTupleEqual(tuple(a), tuple(b))
  1025. with self.assertRaises(self.failureException):
  1026. self.assertSequenceEqual(a, tuple(b))
  1027. with self.assertRaises(self.failureException):
  1028. self.assertSequenceEqual(tuple(a), b)
  1029. with self.assertRaises(self.failureException):
  1030. self.assertSetEqual(set(a), set(b))
  1031. with bytes_warning(), self.assertRaises(self.failureException):
  1032. self.assertDictEqual({'a': 0}, {b'a': 0})
  1033. with self.assertRaises(self.failureException):
  1034. self.assertDictEqual({}, {b'a': 0})
  1035. with self.assertRaises(self.failureException):
  1036. self.assertDictEqual({b'a': 0}, {})
  1037. with self.assertRaises(self.failureException):
  1038. self.assertCountEqual([b'a', b'a'], [b'a', b'a', b'a'])
  1039. with bytes_warning():
  1040. self.assertCountEqual(['a', b'a'], ['a', b'a'])
  1041. with bytes_warning(), self.assertRaises(self.failureException):
  1042. self.assertCountEqual(['a', 'a'], [b'a', b'a'])
  1043. with bytes_warning(), self.assertRaises(self.failureException):
  1044. self.assertCountEqual(['a', 'a', []], [b'a', b'a', []])
  1045. def testAssertIsNone(self):
  1046. self.assertIsNone(None)
  1047. self.assertRaises(self.failureException, self.assertIsNone, False)
  1048. self.assertIsNotNone('DjZoPloGears on Rails')
  1049. self.assertRaises(self.failureException, self.assertIsNotNone, None)
  1050. def testAssertRegex(self):
  1051. self.assertRegex('asdfabasdf', r'ab+')
  1052. self.assertRaises(self.failureException, self.assertRegex,
  1053. 'saaas', r'aaaa')
  1054. def testAssertRaisesCallable(self):
  1055. class ExceptionMock(Exception):
  1056. pass
  1057. def Stub():
  1058. raise ExceptionMock('We expect')
  1059. self.assertRaises(ExceptionMock, Stub)
  1060. # A tuple of exception classes is accepted
  1061. self.assertRaises((ValueError, ExceptionMock), Stub)
  1062. # *args and **kwargs also work
  1063. self.assertRaises(ValueError, int, '19', base=8)
  1064. # Failure when no exception is raised
  1065. with self.assertRaises(self.failureException):
  1066. self.assertRaises(ExceptionMock, lambda: 0)
  1067. # Failure when the function is None
  1068. with self.assertRaises(TypeError):
  1069. self.assertRaises(ExceptionMock, None)
  1070. # Failure when another exception is raised
  1071. with self.assertRaises(ExceptionMock):
  1072. self.assertRaises(ValueError, Stub)
  1073. def testAssertRaisesContext(self):
  1074. class ExceptionMock(Exception):
  1075. pass
  1076. def Stub():
  1077. raise ExceptionMock('We expect')
  1078. with self.assertRaises(ExceptionMock):
  1079. Stub()
  1080. # A tuple of exception classes is accepted
  1081. with self.assertRaises((ValueError, ExceptionMock)) as cm:
  1082. Stub()
  1083. # The context manager exposes caught exception
  1084. self.assertIsInstance(cm.exception, ExceptionMock)
  1085. self.assertEqual(cm.exception.args[0], 'We expect')
  1086. # *args and **kwargs also work
  1087. with self.assertRaises(ValueError):
  1088. int('19', base=8)
  1089. # Failure when no exception is raised
  1090. with self.assertRaises(self.failureException):
  1091. with self.assertRaises(ExceptionMock):
  1092. pass
  1093. # Custom message
  1094. with self.assertRaisesRegex(self.failureException, 'foobar'):
  1095. with self.assertRaises(ExceptionMock, msg='foobar'):
  1096. pass
  1097. # Invalid keyword argument
  1098. with self.assertRaisesRegex(TypeError, 'foobar'):
  1099. with self.assertRaises(ExceptionMock, foobar=42):
  1100. pass
  1101. # Failure when another exception is raised
  1102. with self.assertRaises(ExceptionMock):
  1103. self.assertRaises(ValueError, Stub)
  1104. def testAssertRaisesNoExceptionType(self):
  1105. with self.assertRaises(TypeError):
  1106. self.assertRaises()
  1107. with self.assertRaises(TypeError):
  1108. self.assertRaises(1)
  1109. with self.assertRaises(TypeError):
  1110. self.assertRaises(object)
  1111. with self.assertRaises(TypeError):
  1112. self.assertRaises((ValueError, 1))
  1113. with self.assertRaises(TypeError):
  1114. self.assertRaises((ValueError, object))
  1115. def testAssertRaisesRefcount(self):
  1116. # bpo-23890: assertRaises() must not keep objects alive longer
  1117. # than expected
  1118. def func() :
  1119. try:
  1120. raise ValueError
  1121. except ValueError:
  1122. raise ValueError
  1123. refcount = sys.getrefcount(func)
  1124. self.assertRaises(ValueError, func)
  1125. self.assertEqual(refcount, sys.getrefcount(func))
  1126. def testAssertRaisesRegex(self):
  1127. class ExceptionMock(Exception):
  1128. pass
  1129. def Stub():
  1130. raise ExceptionMock('We expect')
  1131. self.assertRaisesRegex(ExceptionMock, re.compile('expect$'), Stub)
  1132. self.assertRaisesRegex(ExceptionMock, 'expect$', Stub)
  1133. with self.assertRaises(TypeError):
  1134. self.assertRaisesRegex(ExceptionMock, 'expect$', None)
  1135. def testAssertNotRaisesRegex(self):
  1136. self.assertRaisesRegex(
  1137. self.failureException, '^Exception not raised by <lambda>$',
  1138. self.assertRaisesRegex, Exception, re.compile('x'),
  1139. lambda: None)
  1140. self.assertRaisesRegex(
  1141. self.failureException, '^Exception not raised by <lambda>$',
  1142. self.assertRaisesRegex, Exception, 'x',
  1143. lambda: None)
  1144. # Custom message
  1145. with self.assertRaisesRegex(self.failureException, 'foobar'):
  1146. with self.assertRaisesRegex(Exception, 'expect', msg='foobar'):
  1147. pass
  1148. # Invalid keyword argument
  1149. with self.assertRaisesRegex(TypeError, 'foobar'):
  1150. with self.assertRaisesRegex(Exception, 'expect', foobar=42):
  1151. pass
  1152. def testAssertRaisesRegexInvalidRegex(self):
  1153. # Issue 20145.
  1154. class MyExc(Exception):
  1155. pass
  1156. self.assertRaises(TypeError, self.assertRaisesRegex, MyExc, lambda: True)
  1157. def testAssertWarnsRegexInvalidRegex(self):
  1158. # Issue 20145.
  1159. class MyWarn(Warning):
  1160. pass
  1161. self.assertRaises(TypeError, self.assertWarnsRegex, MyWarn, lambda: True)
  1162. def testAssertWarnsModifySysModules(self):
  1163. # bpo-29620: handle modified sys.modules during iteration
  1164. class Foo(types.ModuleType):
  1165. @property
  1166. def __warningregistry__(self):
  1167. sys.modules['@bar@'] = 'bar'
  1168. sys.modules['@foo@'] = Foo('foo')
  1169. try:
  1170. self.assertWarns(UserWarning, warnings.warn, 'expected')
  1171. finally:
  1172. del sys.modules['@foo@']
  1173. del sys.modules['@bar@']
  1174. def testAssertRaisesRegexMismatch(self):
  1175. def Stub():
  1176. raise Exception('Unexpected')
  1177. self.assertRaisesRegex(
  1178. self.failureException,
  1179. r'"\^Expected\$" does not match "Unexpected"',
  1180. self.assertRaisesRegex, Exception, '^Expected$',
  1181. Stub)
  1182. self.assertRaisesRegex(
  1183. self.failureException,
  1184. r'"\^Expected\$" does not match "Unexpected"',
  1185. self.assertRaisesRegex, Exception,
  1186. re.compile('^Expected$'), Stub)
  1187. def testAssertRaisesExcValue(self):
  1188. class ExceptionMock(Exception):
  1189. pass
  1190. def Stub(foo):
  1191. raise ExceptionMock(foo)
  1192. v = "particular value"
  1193. ctx = self.assertRaises(ExceptionMock)
  1194. with ctx:
  1195. Stub(v)
  1196. e = ctx.exception
  1197. self.assertIsInstance(e, ExceptionMock)
  1198. self.assertEqual(e.args[0], v)
  1199. def testAssertRaisesRegexNoExceptionType(self):
  1200. with self.assertRaises(TypeError):
  1201. self.assertRaisesRegex()
  1202. with self.assertRaises(TypeError):
  1203. self.assertRaisesRegex(ValueError)
  1204. with self.assertRaises(TypeError):
  1205. self.assertRaisesRegex(1, 'expect')
  1206. with self.assertRaises(TypeError):
  1207. self.assertRaisesRegex(object, 'expect')
  1208. with self.assertRaises(TypeError):
  1209. self.assertRaisesRegex((ValueError, 1), 'expect')
  1210. with self.assertRaises(TypeError):
  1211. self.assertRaisesRegex((ValueError, object), 'expect')
  1212. def testAssertWarnsCallable(self):
  1213. def _runtime_warn():
  1214. warnings.warn("foo", RuntimeWarning)
  1215. # Success when the right warning is triggered, even several times
  1216. self.assertWarns(RuntimeWarning, _runtime_warn)
  1217. self.assertWarns(RuntimeWarning, _runtime_warn)
  1218. # A tuple of warning classes is accepted
  1219. self.assertWarns((DeprecationWarning, RuntimeWarning), _runtime_warn)
  1220. # *args and **kwargs also work
  1221. self.assertWarns(RuntimeWarning,
  1222. warnings.warn, "foo", category=RuntimeWarning)
  1223. # Failure when no warning is triggered
  1224. with self.assertRaises(self.failureException):
  1225. self.assertWarns(RuntimeWarning, lambda: 0)
  1226. # Failure when the function is None
  1227. with self.assertRaises(TypeError):
  1228. self.assertWarns(RuntimeWarning, None)
  1229. # Failure when another warning is triggered
  1230. with warnings.catch_warnings():
  1231. # Force default filter (in case tests are run with -We)
  1232. warnings.simplefilter("default", RuntimeWarning)
  1233. with self.assertRaises(self.failureException):
  1234. self.assertWarns(DeprecationWarning, _runtime_warn)
  1235. # Filters for other warnings are not modified
  1236. with warnings.catch_warnings():
  1237. warnings.simplefilter("error", RuntimeWarning)
  1238. with self.assertRaises(RuntimeWarning):
  1239. self.assertWarns(DeprecationWarning, _runtime_warn)
  1240. def testAssertWarnsContext(self):
  1241. # Believe it or not, it is preferable to duplicate all tests above,
  1242. # to make sure the __warningregistry__ $@ is circumvented correctly.
  1243. def _runtime_warn():
  1244. warnings.warn("foo", RuntimeWarning)
  1245. _runtime_warn_lineno = inspect.getsourcelines(_runtime_warn)[1]
  1246. with self.assertWarns(RuntimeWarning) as cm:
  1247. _runtime_warn()
  1248. # A tuple of warning classes is accepted
  1249. with self.assertWarns((DeprecationWarning, RuntimeWarning)) as cm:
  1250. _runtime_warn()
  1251. # The context manager exposes various useful attributes
  1252. self.assertIsInstance(cm.warning, RuntimeWarning)
  1253. self.assertEqual(cm.warning.args[0], "foo")
  1254. self.assertIn("test_case.py", cm.filename)
  1255. self.assertEqual(cm.lineno, _runtime_warn_lineno + 1)
  1256. # Same with several warnings
  1257. with self.assertWarns(RuntimeWarning):
  1258. _runtime_warn()
  1259. _runtime_warn()
  1260. with self.assertWarns(RuntimeWarning):
  1261. warnings.warn("foo", category=RuntimeWarning)
  1262. # Failure when no warning is triggered
  1263. with self.assertRaises(self.failureException):
  1264. with self.assertWarns(RuntimeWarning):
  1265. pass
  1266. # Custom message
  1267. with self.assertRaisesRegex(self.failureException, 'foobar'):
  1268. with self.assertWarns(RuntimeWarning, msg='foobar'):
  1269. pass
  1270. # Invalid keyword argument
  1271. with self.assertRaisesRegex(TypeError, 'foobar'):
  1272. with self.assertWarns(RuntimeWarning, foobar=42):
  1273. pass
  1274. # Failure when another warning is triggered
  1275. with warnings.catch_warnings():
  1276. # Force default filter (in case tests are run with -We)
  1277. warnings.simplefilter("default", RuntimeWarning)
  1278. with self.assertRaises(self.failureException):
  1279. with self.assertWarns(DeprecationWarning):
  1280. _runtime_warn()
  1281. # Filters for other warnings are not modified
  1282. with warnings.catch_warnings():
  1283. warnings.simplefilter("error", RuntimeWarning)
  1284. with self.assertRaises(RuntimeWarning):
  1285. with self.assertWarns(DeprecationWarning):
  1286. _runtime_warn()
  1287. def testAssertWarnsNoExceptionType(self):
  1288. with self.assertRaises(TypeError):
  1289. self.assertWarns()
  1290. with self.assertRaises(TypeError):
  1291. self.assertWarns(1)
  1292. with self.assertRaises(TypeError):
  1293. self.assertWarns(object)
  1294. with self.assertRaises(TypeError):
  1295. self.assertWarns((UserWarning, 1))
  1296. with self.assertRaises(TypeError):
  1297. self.assertWarns((UserWarning, object))
  1298. with self.assertRaises(TypeError):
  1299. self.assertWarns((UserWarning, Exception))
  1300. def testAssertWarnsRegexCallable(self):
  1301. def _runtime_warn(msg):
  1302. warnings.warn(msg, RuntimeWarning)
  1303. self.assertWarnsRegex(RuntimeWarning, "o+",
  1304. _runtime_warn, "foox")
  1305. # Failure when no warning is triggered
  1306. with self.assertRaises(self.failureException):
  1307. self.assertWarnsRegex(RuntimeWarning, "o+",
  1308. lambda: 0)
  1309. # Failure when the function is None
  1310. with self.assertRaises(TypeError):
  1311. self.assertWarnsRegex(RuntimeWarning, "o+", None)
  1312. # Failure when another warning is triggered
  1313. with warnings.catch_warnings():
  1314. # Force default filter (in case tests are run with -We)
  1315. warnings.simplefilter("default", RuntimeWarning)
  1316. with self.assertRaises(self.failureException):
  1317. self.assertWarnsRegex(DeprecationWarning, "o+",
  1318. _runtime_warn, "foox")
  1319. # Failure when message doesn't match
  1320. with self.assertRaises(self.failureException):
  1321. self.assertWarnsRegex(RuntimeWarning, "o+",
  1322. _runtime_warn, "barz")
  1323. # A little trickier: we ask RuntimeWarnings to be raised, and then
  1324. # check for some of them. It is implementation-defined whether
  1325. # non-matching RuntimeWarnings are simply re-raised, or produce a
  1326. # failureException.
  1327. with warnings.catch_warnings():
  1328. warnings.simplefilter("error", RuntimeWarning)
  1329. with self.assertRaises((RuntimeWarning, self.failureException)):
  1330. self.assertWarnsRegex(RuntimeWarning, "o+",
  1331. _runtime_warn, "barz")
  1332. def testAssertWarnsRegexContext(self):
  1333. # Same as above, but with assertWarnsRegex as a context manager
  1334. def _runtime_warn(msg):
  1335. warnings.warn(msg, RuntimeWarning)
  1336. _runtime_warn_lineno = inspect.getsourcelines(_runtime_warn)[1]
  1337. with self.assertWarnsRegex(RuntimeWarning, "o+") as cm:
  1338. _runtime_warn("foox")
  1339. self.assertIsInstance(cm.warning, RuntimeWarning)
  1340. self.assertEqual(cm.warning.args[0], "foox")
  1341. self.assertIn("test_case.py", cm.filename)
  1342. self.assertEqual(cm.lineno, _runtime_warn_lineno + 1)
  1343. # Failure when no warning is triggered
  1344. with self.assertRaises(self.failureException):
  1345. with self.assertWarnsRegex(RuntimeWarning, "o+"):
  1346. pass
  1347. # Custom message
  1348. with self.assertRaisesRegex(self.failureException, 'foobar'):
  1349. with self.assertWarnsRegex(RuntimeWarning, 'o+', msg='foobar'):
  1350. pass
  1351. # Invalid keyword argument
  1352. with self.assertRaisesRegex(TypeError, 'foobar'):
  1353. with self.assertWarnsRegex(RuntimeWarning, 'o+', foobar=42):
  1354. pass
  1355. # Failure when another warning is triggered
  1356. with warnings.catch_warnings():
  1357. # Force default filter (in case tests are run with -We)
  1358. warnings.simplefilter("default", RuntimeWarning)
  1359. with self.assertRaises(self.failureException):
  1360. with self.assertWarnsRegex(DeprecationWarning, "o+"):
  1361. _runtime_warn("foox")
  1362. # Failure when message doesn't match
  1363. with self.assertRaises(self.failureException):
  1364. with self.assertWarnsRegex(RuntimeWarning, "o+"):
  1365. _runtime_warn("barz")
  1366. # A little trickier: we ask RuntimeWarnings to be raised, and then
  1367. # check for some of them. It is implementation-defined whether
  1368. # non-matching RuntimeWarnings are simply re-raised, or produce a
  1369. # failureException.
  1370. with warnings.catch_warnings():
  1371. warnings.simplefilter("error", RuntimeWarning)
  1372. with self.assertRaises((RuntimeWarning, self.failureException)):
  1373. with self.assertWarnsRegex(RuntimeWarning, "o+"):
  1374. _runtime_warn("barz")
  1375. def testAssertWarnsRegexNoExceptionType(self):
  1376. with self.assertRaises(TypeError):
  1377. self.assertWarnsRegex()
  1378. with self.assertRaises(TypeError):
  1379. self.assertWarnsRegex(UserWarning)
  1380. with self.assertRaises(TypeError):
  1381. self.assertWarnsRegex(1, 'expect')
  1382. with self.assertRaises(TypeError):
  1383. self.assertWarnsRegex(object, 'expect')
  1384. with self.assertRaises(TypeError):
  1385. self.assertWarnsRegex((UserWarning, 1), 'expect')
  1386. with self.assertRaises(TypeError):
  1387. self.assertWarnsRegex((UserWarning, object), 'expect')
  1388. with self.assertRaises(TypeError):
  1389. self.assertWarnsRegex((UserWarning, Exception), 'expect')
  1390. @contextlib.contextmanager
  1391. def assertNoStderr(self):
  1392. with captured_stderr() as buf:
  1393. yield
  1394. self.assertEqual(buf.getvalue(), "")
  1395. def assertLogRecords(self, records, matches):
  1396. self.assertEqual(len(records), len(matches))
  1397. for rec, match in zip(records, matches):
  1398. self.assertIsInstance(rec, logging.LogRecord)
  1399. for k, v in match.items():
  1400. self.assertEqual(getattr(rec, k), v)
  1401. def testAssertLogsDefaults(self):
  1402. # defaults: root logger, level INFO
  1403. with self.assertNoStderr():
  1404. with self.assertLogs() as cm:
  1405. log_foo.info("1")
  1406. log_foobar.debug("2")
  1407. self.assertEqual(cm.output, ["INFO:foo:1"])
  1408. self.assertLogRecords(cm.records, [{'name': 'foo'}])
  1409. def testAssertLogsTwoMatchingMessages(self):
  1410. # Same, but with two matching log messages
  1411. with self.assertNoStderr():
  1412. with self.assertLogs() as cm:
  1413. log_foo.info("1")
  1414. log_foobar.debug("2")
  1415. log_quux.warning("3")
  1416. self.assertEqual(cm.output, ["INFO:foo:1", "WARNING:quux:3"])
  1417. self.assertLogRecords(cm.records,
  1418. [{'name': 'foo'}, {'name': 'quux'}])
  1419. def checkAssertLogsPerLevel(self, level):
  1420. # Check level filtering
  1421. with self.assertNoStderr():
  1422. with self.assertLogs(level=level) as cm:
  1423. log_foo.warning("1")
  1424. log_foobar.error("2")
  1425. log_quux.critical("3")
  1426. self.assertEqual(cm.output, ["ERROR:foo.bar:2", "CRITICAL:quux:3"])
  1427. self.assertLogRecords(cm.records,
  1428. [{'name': 'foo.bar'}, {'name': 'quux'}])
  1429. def testAssertLogsPerLevel(self):
  1430. self.checkAssertLogsPerLevel(logging.ERROR)
  1431. self.checkAssertLogsPerLevel('ERROR')
  1432. def checkAssertLogsPerLogger(self, logger):
  1433. # Check per-logger filtering
  1434. with self.assertNoStderr():
  1435. with self.assertLogs(level='DEBUG') as outer_cm:
  1436. with self.assertLogs(logger, level='DEBUG') as cm:
  1437. log_foo.info("1")
  1438. log_foobar.debug("2")
  1439. log_quux.warning("3")
  1440. self.assertEqual(cm.output, ["INFO:foo:1", "DEBUG:foo.bar:2"])
  1441. self.assertLogRecords(cm.records,
  1442. [{'name': 'foo'}, {'name': 'foo.bar'}])
  1443. # The outer catchall caught the quux log
  1444. self.assertEqual(outer_cm.output, ["WARNING:quux:3"])
  1445. def testAssertLogsPerLogger(self):
  1446. self.checkAssertLogsPerLogger(logging.getLogger('foo'))
  1447. self.checkAssertLogsPerLogger('foo')
  1448. def testAssertLogsFailureNoLogs(self):
  1449. # Failure due to no logs
  1450. with self.assertNoStderr():
  1451. with self.assertRaises(self.failureException):
  1452. with self.assertLogs():
  1453. pass
  1454. def testAssertLogsFailureLevelTooHigh(self):
  1455. # Failure due to level too high
  1456. with self.assertNoStderr():
  1457. with self.assertRaises(self.failureException):
  1458. with self.assertLogs(level='WARNING'):
  1459. log_foo.info("1")
  1460. def testAssertLogsFailureLevelTooHigh_FilterInRootLogger(self):
  1461. # Failure due to level too high - message propagated to root
  1462. with self.assertNoStderr():
  1463. oldLevel = log_foo.level
  1464. log_foo.setLevel(logging.INFO)
  1465. try:
  1466. with self.assertRaises(self.failureException):
  1467. with self.assertLogs(level='WARNING'):
  1468. log_foo.info("1")
  1469. finally:
  1470. log_foo.setLevel(oldLevel)
  1471. def testAssertLogsFailureMismatchingLogger(self):
  1472. # Failure due to mismatching logger (and the logged message is
  1473. # passed through)
  1474. with self.assertLogs('quux', level='ERROR'):
  1475. with self.assertRaises(self.failureException):
  1476. with self.assertLogs('foo'):
  1477. log_quux.error("1")
  1478. def testAssertLogsUnexpectedException(self):
  1479. # Check unexpected exception will go through.
  1480. with self.assertRaises(ZeroDivisionError):
  1481. with self.assertLogs():
  1482. raise ZeroDivisionError("Unexpected")
  1483. def testAssertNoLogsDefault(self):
  1484. with self.assertRaises(self.failureException) as cm:
  1485. with self.assertNoLogs():
  1486. log_foo.info("1")
  1487. log_foobar.debug("2")
  1488. self.assertEqual(
  1489. str(cm.exception),
  1490. "Unexpected logs found: ['INFO:foo:1']",
  1491. )
  1492. def testAssertNoLogsFailureFoundLogs(self):
  1493. with self.assertRaises(self.failureException) as cm:
  1494. with self.assertNoLogs():
  1495. log_quux.error("1")
  1496. log_foo.error("foo")
  1497. self.assertEqual(
  1498. str(cm.exception),
  1499. "Unexpected logs found: ['ERROR:quux:1', 'ERROR:foo:foo']",
  1500. )
  1501. def testAssertNoLogsPerLogger(self):
  1502. with self.assertNoStderr():
  1503. with self.assertLogs(log_quux):
  1504. with self.assertNoLogs(logger=log_foo):
  1505. log_quux.error("1")
  1506. def testAssertNoLogsFailurePerLogger(self):
  1507. # Failure due to unexpected logs for the given logger or its
  1508. # children.
  1509. with self.assertRaises(self.failureException) as cm:
  1510. with self.assertLogs(log_quux):
  1511. with self.assertNoLogs(logger=log_foo):
  1512. log_quux.error("1")
  1513. log_foobar.info("2")
  1514. self.assertEqual(
  1515. str(cm.exception),
  1516. "Unexpected logs found: ['INFO:foo.bar:2']",
  1517. )
  1518. def testAssertNoLogsPerLevel(self):
  1519. # Check per-level filtering
  1520. with self.assertNoStderr():
  1521. with self.assertNoLogs(level="ERROR"):
  1522. log_foo.info("foo")
  1523. log_quux.debug("1")
  1524. def testAssertNoLogsFailurePerLevel(self):
  1525. # Failure due to unexpected logs at the specified level.
  1526. with self.assertRaises(self.failureException) as cm:
  1527. with self.assertNoLogs(level="DEBUG"):
  1528. log_foo.debug("foo")
  1529. log_quux.debug("1")
  1530. self.assertEqual(
  1531. str(cm.exception),
  1532. "Unexpected logs found: ['DEBUG:foo:foo', 'DEBUG:quux:1']",
  1533. )
  1534. def testAssertNoLogsUnexpectedException(self):
  1535. # Check unexpected exception will go through.
  1536. with self.assertRaises(ZeroDivisionError):
  1537. with self.assertNoLogs():
  1538. raise ZeroDivisionError("Unexpected")
  1539. def testAssertNoLogsYieldsNone(self):
  1540. with self.assertNoLogs() as value:
  1541. pass
  1542. self.assertIsNone(value)
  1543. def testDeprecatedMethodNames(self):
  1544. """
  1545. Test that the deprecated methods raise a DeprecationWarning. See #9424.
  1546. """
  1547. old = (
  1548. (self.failIfEqual, (3, 5)),
  1549. (self.assertNotEquals, (3, 5)),
  1550. (self.failUnlessEqual, (3, 3)),
  1551. (self.assertEquals, (3, 3)),
  1552. (self.failUnlessAlmostEqual, (2.0, 2.0)),
  1553. (self.assertAlmostEquals, (2.0, 2.0)),
  1554. (self.failIfAlmostEqual, (3.0, 5.0)),
  1555. (self.assertNotAlmostEquals, (3.0, 5.0)),
  1556. (self.failUnless, (True,)),
  1557. (self.assert_, (True,)),
  1558. (self.failUnlessRaises, (TypeError, lambda _: 3.14 + 'spam')),
  1559. (self.failIf, (False,)),
  1560. (self.assertDictContainsSubset, (dict(a=1, b=2), dict(a=1, b=2, c=3))),
  1561. (self.assertRaisesRegexp, (KeyError, 'foo', lambda: {}['foo'])),
  1562. (self.assertRegexpMatches, ('bar', 'bar')),
  1563. )
  1564. for meth, args in old:
  1565. with self.assertWarns(DeprecationWarning):
  1566. meth(*args)
  1567. # disable this test for now. When the version where the fail* methods will
  1568. # be removed is decided, re-enable it and update the version
  1569. def _testDeprecatedFailMethods(self):
  1570. """Test that the deprecated fail* methods get removed in 3.x"""
  1571. if sys.version_info[:2] < (3, 3):
  1572. return
  1573. deprecated_names = [
  1574. 'failIfEqual', 'failUnlessEqual', 'failUnlessAlmostEqual',
  1575. 'failIfAlmostEqual', 'failUnless', 'failUnlessRaises', 'failIf',
  1576. 'assertDictContainsSubset',
  1577. ]
  1578. for deprecated_name in deprecated_names:
  1579. with self.assertRaises(AttributeError):
  1580. getattr(self, deprecated_name) # remove these in 3.x
  1581. def testDeepcopy(self):
  1582. # Issue: 5660
  1583. class TestableTest(unittest.TestCase):
  1584. def testNothing(self):
  1585. pass
  1586. test = TestableTest('testNothing')
  1587. # This shouldn't blow up
  1588. deepcopy(test)
  1589. def testPickle(self):
  1590. # Issue 10326
  1591. # Can't use TestCase classes defined in Test class as
  1592. # pickle does not work with inner classes
  1593. test = unittest.TestCase('run')
  1594. for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
  1595. # blew up prior to fix
  1596. pickled_test = pickle.dumps(test, protocol=protocol)
  1597. unpickled_test = pickle.loads(pickled_test)
  1598. self.assertEqual(test, unpickled_test)
  1599. # exercise the TestCase instance in a way that will invoke
  1600. # the type equality lookup mechanism
  1601. unpickled_test.assertEqual(set(), set())
  1602. def testKeyboardInterrupt(self):
  1603. def _raise(self=None):
  1604. raise KeyboardInterrupt
  1605. def nothing(self):
  1606. pass
  1607. class Test1(unittest.TestCase):
  1608. test_something = _raise
  1609. class Test2(unittest.TestCase):
  1610. setUp = _raise
  1611. test_something = nothing
  1612. class Test3(unittest.TestCase):
  1613. test_something = nothing
  1614. tearDown = _raise
  1615. class Test4(unittest.TestCase):
  1616. def test_something(self):
  1617. self.addCleanup(_raise)
  1618. for klass in (Test1, Test2, Test3, Test4):
  1619. with self.assertRaises(KeyboardInterrupt):
  1620. klass('test_something').run()
  1621. def testSkippingEverywhere(self):
  1622. def _skip(self=None):
  1623. raise unittest.SkipTest('some reason')
  1624. def nothing(self):
  1625. pass
  1626. class Test1(unittest.TestCase):
  1627. test_something = _skip
  1628. class Test2(unittest.TestCase):
  1629. setUp = _skip
  1630. test_something = nothing
  1631. class Test3(unittest.TestCase):
  1632. test_something = nothing
  1633. tearDown = _skip
  1634. class Test4(unittest.TestCase):
  1635. def test_something(self):
  1636. self.addCleanup(_skip)
  1637. for klass in (Test1, Test2, Test3, Test4):
  1638. result = unittest.TestResult()
  1639. klass('test_something').run(result)
  1640. self.assertEqual(len(result.skipped), 1)
  1641. self.assertEqual(result.testsRun, 1)
  1642. def testSystemExit(self):
  1643. def _raise(self=None):
  1644. raise SystemExit
  1645. def nothing(self):
  1646. pass
  1647. class Test1(unittest.TestCase):
  1648. test_something = _raise
  1649. class Test2(unittest.TestCase):
  1650. setUp = _raise
  1651. test_something = nothing
  1652. class Test3(unittest.TestCase):
  1653. test_something = nothing
  1654. tearDown = _raise
  1655. class Test4(unittest.TestCase):
  1656. def test_something(self):
  1657. self.addCleanup(_raise)
  1658. for klass in (Test1, Test2, Test3, Test4):
  1659. result = unittest.TestResult()
  1660. klass('test_something').run(result)
  1661. self.assertEqual(len(result.errors), 1)
  1662. self.assertEqual(result.testsRun, 1)
  1663. @support.cpython_only
  1664. def testNoCycles(self):
  1665. case = unittest.TestCase()
  1666. wr = weakref.ref(case)
  1667. with support.disable_gc():
  1668. del case
  1669. self.assertFalse(wr())
  1670. def test_no_exception_leak(self):
  1671. # Issue #19880: TestCase.run() should not keep a reference
  1672. # to the exception
  1673. class MyException(Exception):
  1674. ninstance = 0
  1675. def __init__(self):
  1676. MyException.ninstance += 1
  1677. Exception.__init__(self)
  1678. def __del__(self):
  1679. MyException.ninstance -= 1
  1680. class TestCase(unittest.TestCase):
  1681. def test1(self):
  1682. raise MyException()
  1683. @unittest.expectedFailure
  1684. def test2(self):
  1685. raise MyException()
  1686. for method_name in ('test1', 'test2'):
  1687. testcase = TestCase(method_name)
  1688. testcase.run()
  1689. gc_collect() # For PyPy or other GCs.
  1690. self.assertEqual(MyException.ninstance, 0)
  1691. if __name__ == "__main__":
  1692. unittest.main()