test_case.py 72 KB

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