test_case.py 72 KB

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