test_case.py 70 KB

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