case.py 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443
  1. """Test case implementation"""
  2. import sys
  3. import functools
  4. import difflib
  5. import pprint
  6. import re
  7. import warnings
  8. import collections
  9. import contextlib
  10. import traceback
  11. import types
  12. from . import result
  13. from .util import (strclass, safe_repr, _count_diff_all_purpose,
  14. _count_diff_hashable, _common_shorten_repr)
  15. __unittest = True
  16. _subtest_msg_sentinel = object()
  17. DIFF_OMITTED = ('\nDiff is %s characters long. '
  18. 'Set self.maxDiff to None to see it.')
  19. class SkipTest(Exception):
  20. """
  21. Raise this exception in a test to skip it.
  22. Usually you can use TestCase.skipTest() or one of the skipping decorators
  23. instead of raising this directly.
  24. """
  25. class _ShouldStop(Exception):
  26. """
  27. The test should stop.
  28. """
  29. class _UnexpectedSuccess(Exception):
  30. """
  31. The test was supposed to fail, but it didn't!
  32. """
  33. class _Outcome(object):
  34. def __init__(self, result=None):
  35. self.expecting_failure = False
  36. self.result = result
  37. self.result_supports_subtests = hasattr(result, "addSubTest")
  38. self.success = True
  39. self.skipped = []
  40. self.expectedFailure = None
  41. self.errors = []
  42. @contextlib.contextmanager
  43. def testPartExecutor(self, test_case, isTest=False):
  44. old_success = self.success
  45. self.success = True
  46. try:
  47. yield
  48. except KeyboardInterrupt:
  49. raise
  50. except SkipTest as e:
  51. self.success = False
  52. self.skipped.append((test_case, str(e)))
  53. except _ShouldStop:
  54. pass
  55. except:
  56. exc_info = sys.exc_info()
  57. if self.expecting_failure:
  58. self.expectedFailure = exc_info
  59. else:
  60. self.success = False
  61. self.errors.append((test_case, exc_info))
  62. # explicitly break a reference cycle:
  63. # exc_info -> frame -> exc_info
  64. exc_info = None
  65. else:
  66. if self.result_supports_subtests and self.success:
  67. self.errors.append((test_case, None))
  68. finally:
  69. self.success = self.success and old_success
  70. def _id(obj):
  71. return obj
  72. _module_cleanups = []
  73. def addModuleCleanup(function, /, *args, **kwargs):
  74. """Same as addCleanup, except the cleanup items are called even if
  75. setUpModule fails (unlike tearDownModule)."""
  76. _module_cleanups.append((function, args, kwargs))
  77. def doModuleCleanups():
  78. """Execute all module cleanup functions. Normally called for you after
  79. tearDownModule."""
  80. exceptions = []
  81. while _module_cleanups:
  82. function, args, kwargs = _module_cleanups.pop()
  83. try:
  84. function(*args, **kwargs)
  85. except Exception as exc:
  86. exceptions.append(exc)
  87. if exceptions:
  88. # Swallows all but first exception. If a multi-exception handler
  89. # gets written we should use that here instead.
  90. raise exceptions[0]
  91. def skip(reason):
  92. """
  93. Unconditionally skip a test.
  94. """
  95. def decorator(test_item):
  96. if not isinstance(test_item, type):
  97. @functools.wraps(test_item)
  98. def skip_wrapper(*args, **kwargs):
  99. raise SkipTest(reason)
  100. test_item = skip_wrapper
  101. test_item.__unittest_skip__ = True
  102. test_item.__unittest_skip_why__ = reason
  103. return test_item
  104. if isinstance(reason, types.FunctionType):
  105. test_item = reason
  106. reason = ''
  107. return decorator(test_item)
  108. return decorator
  109. def skipIf(condition, reason):
  110. """
  111. Skip a test if the condition is true.
  112. """
  113. if condition:
  114. return skip(reason)
  115. return _id
  116. def skipUnless(condition, reason):
  117. """
  118. Skip a test unless the condition is true.
  119. """
  120. if not condition:
  121. return skip(reason)
  122. return _id
  123. def expectedFailure(test_item):
  124. test_item.__unittest_expecting_failure__ = True
  125. return test_item
  126. def _is_subtype(expected, basetype):
  127. if isinstance(expected, tuple):
  128. return all(_is_subtype(e, basetype) for e in expected)
  129. return isinstance(expected, type) and issubclass(expected, basetype)
  130. class _BaseTestCaseContext:
  131. def __init__(self, test_case):
  132. self.test_case = test_case
  133. def _raiseFailure(self, standardMsg):
  134. msg = self.test_case._formatMessage(self.msg, standardMsg)
  135. raise self.test_case.failureException(msg)
  136. class _AssertRaisesBaseContext(_BaseTestCaseContext):
  137. def __init__(self, expected, test_case, expected_regex=None):
  138. _BaseTestCaseContext.__init__(self, test_case)
  139. self.expected = expected
  140. self.test_case = test_case
  141. if expected_regex is not None:
  142. expected_regex = re.compile(expected_regex)
  143. self.expected_regex = expected_regex
  144. self.obj_name = None
  145. self.msg = None
  146. def handle(self, name, args, kwargs):
  147. """
  148. If args is empty, assertRaises/Warns is being used as a
  149. context manager, so check for a 'msg' kwarg and return self.
  150. If args is not empty, call a callable passing positional and keyword
  151. arguments.
  152. """
  153. try:
  154. if not _is_subtype(self.expected, self._base_type):
  155. raise TypeError('%s() arg 1 must be %s' %
  156. (name, self._base_type_str))
  157. if not args:
  158. self.msg = kwargs.pop('msg', None)
  159. if kwargs:
  160. raise TypeError('%r is an invalid keyword argument for '
  161. 'this function' % (next(iter(kwargs)),))
  162. return self
  163. callable_obj, *args = args
  164. try:
  165. self.obj_name = callable_obj.__name__
  166. except AttributeError:
  167. self.obj_name = str(callable_obj)
  168. with self:
  169. callable_obj(*args, **kwargs)
  170. finally:
  171. # bpo-23890: manually break a reference cycle
  172. self = None
  173. class _AssertRaisesContext(_AssertRaisesBaseContext):
  174. """A context manager used to implement TestCase.assertRaises* methods."""
  175. _base_type = BaseException
  176. _base_type_str = 'an exception type or tuple of exception types'
  177. def __enter__(self):
  178. return self
  179. def __exit__(self, exc_type, exc_value, tb):
  180. if exc_type is None:
  181. try:
  182. exc_name = self.expected.__name__
  183. except AttributeError:
  184. exc_name = str(self.expected)
  185. if self.obj_name:
  186. self._raiseFailure("{} not raised by {}".format(exc_name,
  187. self.obj_name))
  188. else:
  189. self._raiseFailure("{} not raised".format(exc_name))
  190. else:
  191. traceback.clear_frames(tb)
  192. if not issubclass(exc_type, self.expected):
  193. # let unexpected exceptions pass through
  194. return False
  195. # store exception, without traceback, for later retrieval
  196. self.exception = exc_value.with_traceback(None)
  197. if self.expected_regex is None:
  198. return True
  199. expected_regex = self.expected_regex
  200. if not expected_regex.search(str(exc_value)):
  201. self._raiseFailure('"{}" does not match "{}"'.format(
  202. expected_regex.pattern, str(exc_value)))
  203. return True
  204. __class_getitem__ = classmethod(types.GenericAlias)
  205. class _AssertWarnsContext(_AssertRaisesBaseContext):
  206. """A context manager used to implement TestCase.assertWarns* methods."""
  207. _base_type = Warning
  208. _base_type_str = 'a warning type or tuple of warning types'
  209. def __enter__(self):
  210. # The __warningregistry__'s need to be in a pristine state for tests
  211. # to work properly.
  212. for v in list(sys.modules.values()):
  213. if getattr(v, '__warningregistry__', None):
  214. v.__warningregistry__ = {}
  215. self.warnings_manager = warnings.catch_warnings(record=True)
  216. self.warnings = self.warnings_manager.__enter__()
  217. warnings.simplefilter("always", self.expected)
  218. return self
  219. def __exit__(self, exc_type, exc_value, tb):
  220. self.warnings_manager.__exit__(exc_type, exc_value, tb)
  221. if exc_type is not None:
  222. # let unexpected exceptions pass through
  223. return
  224. try:
  225. exc_name = self.expected.__name__
  226. except AttributeError:
  227. exc_name = str(self.expected)
  228. first_matching = None
  229. for m in self.warnings:
  230. w = m.message
  231. if not isinstance(w, self.expected):
  232. continue
  233. if first_matching is None:
  234. first_matching = w
  235. if (self.expected_regex is not None and
  236. not self.expected_regex.search(str(w))):
  237. continue
  238. # store warning for later retrieval
  239. self.warning = w
  240. self.filename = m.filename
  241. self.lineno = m.lineno
  242. return
  243. # Now we simply try to choose a helpful failure message
  244. if first_matching is not None:
  245. self._raiseFailure('"{}" does not match "{}"'.format(
  246. self.expected_regex.pattern, str(first_matching)))
  247. if self.obj_name:
  248. self._raiseFailure("{} not triggered by {}".format(exc_name,
  249. self.obj_name))
  250. else:
  251. self._raiseFailure("{} not triggered".format(exc_name))
  252. class _OrderedChainMap(collections.ChainMap):
  253. def __iter__(self):
  254. seen = set()
  255. for mapping in self.maps:
  256. for k in mapping:
  257. if k not in seen:
  258. seen.add(k)
  259. yield k
  260. class TestCase(object):
  261. """A class whose instances are single test cases.
  262. By default, the test code itself should be placed in a method named
  263. 'runTest'.
  264. If the fixture may be used for many test cases, create as
  265. many test methods as are needed. When instantiating such a TestCase
  266. subclass, specify in the constructor arguments the name of the test method
  267. that the instance is to execute.
  268. Test authors should subclass TestCase for their own tests. Construction
  269. and deconstruction of the test's environment ('fixture') can be
  270. implemented by overriding the 'setUp' and 'tearDown' methods respectively.
  271. If it is necessary to override the __init__ method, the base class
  272. __init__ method must always be called. It is important that subclasses
  273. should not change the signature of their __init__ method, since instances
  274. of the classes are instantiated automatically by parts of the framework
  275. in order to be run.
  276. When subclassing TestCase, you can set these attributes:
  277. * failureException: determines which exception will be raised when
  278. the instance's assertion methods fail; test methods raising this
  279. exception will be deemed to have 'failed' rather than 'errored'.
  280. * longMessage: determines whether long messages (including repr of
  281. objects used in assert methods) will be printed on failure in *addition*
  282. to any explicit message passed.
  283. * maxDiff: sets the maximum length of a diff in failure messages
  284. by assert methods using difflib. It is looked up as an instance
  285. attribute so can be configured by individual tests if required.
  286. """
  287. failureException = AssertionError
  288. longMessage = True
  289. maxDiff = 80*8
  290. # If a string is longer than _diffThreshold, use normal comparison instead
  291. # of difflib. See #11763.
  292. _diffThreshold = 2**16
  293. # Attribute used by TestSuite for classSetUp
  294. _classSetupFailed = False
  295. _class_cleanups = []
  296. def __init__(self, methodName='runTest'):
  297. """Create an instance of the class that will use the named test
  298. method when executed. Raises a ValueError if the instance does
  299. not have a method with the specified name.
  300. """
  301. self._testMethodName = methodName
  302. self._outcome = None
  303. self._testMethodDoc = 'No test'
  304. try:
  305. testMethod = getattr(self, methodName)
  306. except AttributeError:
  307. if methodName != 'runTest':
  308. # we allow instantiation with no explicit method name
  309. # but not an *incorrect* or missing method name
  310. raise ValueError("no such test method in %s: %s" %
  311. (self.__class__, methodName))
  312. else:
  313. self._testMethodDoc = testMethod.__doc__
  314. self._cleanups = []
  315. self._subtest = None
  316. # Map types to custom assertEqual functions that will compare
  317. # instances of said type in more detail to generate a more useful
  318. # error message.
  319. self._type_equality_funcs = {}
  320. self.addTypeEqualityFunc(dict, 'assertDictEqual')
  321. self.addTypeEqualityFunc(list, 'assertListEqual')
  322. self.addTypeEqualityFunc(tuple, 'assertTupleEqual')
  323. self.addTypeEqualityFunc(set, 'assertSetEqual')
  324. self.addTypeEqualityFunc(frozenset, 'assertSetEqual')
  325. self.addTypeEqualityFunc(str, 'assertMultiLineEqual')
  326. def addTypeEqualityFunc(self, typeobj, function):
  327. """Add a type specific assertEqual style function to compare a type.
  328. This method is for use by TestCase subclasses that need to register
  329. their own type equality functions to provide nicer error messages.
  330. Args:
  331. typeobj: The data type to call this function on when both values
  332. are of the same type in assertEqual().
  333. function: The callable taking two arguments and an optional
  334. msg= argument that raises self.failureException with a
  335. useful error message when the two arguments are not equal.
  336. """
  337. self._type_equality_funcs[typeobj] = function
  338. def addCleanup(self, function, /, *args, **kwargs):
  339. """Add a function, with arguments, to be called when the test is
  340. completed. Functions added are called on a LIFO basis and are
  341. called after tearDown on test failure or success.
  342. Cleanup items are called even if setUp fails (unlike tearDown)."""
  343. self._cleanups.append((function, args, kwargs))
  344. @classmethod
  345. def addClassCleanup(cls, function, /, *args, **kwargs):
  346. """Same as addCleanup, except the cleanup items are called even if
  347. setUpClass fails (unlike tearDownClass)."""
  348. cls._class_cleanups.append((function, args, kwargs))
  349. def setUp(self):
  350. "Hook method for setting up the test fixture before exercising it."
  351. pass
  352. def tearDown(self):
  353. "Hook method for deconstructing the test fixture after testing it."
  354. pass
  355. @classmethod
  356. def setUpClass(cls):
  357. "Hook method for setting up class fixture before running tests in the class."
  358. @classmethod
  359. def tearDownClass(cls):
  360. "Hook method for deconstructing the class fixture after running all tests in the class."
  361. def countTestCases(self):
  362. return 1
  363. def defaultTestResult(self):
  364. return result.TestResult()
  365. def shortDescription(self):
  366. """Returns a one-line description of the test, or None if no
  367. description has been provided.
  368. The default implementation of this method returns the first line of
  369. the specified test method's docstring.
  370. """
  371. doc = self._testMethodDoc
  372. return doc.strip().split("\n")[0].strip() if doc else None
  373. def id(self):
  374. return "%s.%s" % (strclass(self.__class__), self._testMethodName)
  375. def __eq__(self, other):
  376. if type(self) is not type(other):
  377. return NotImplemented
  378. return self._testMethodName == other._testMethodName
  379. def __hash__(self):
  380. return hash((type(self), self._testMethodName))
  381. def __str__(self):
  382. return "%s (%s)" % (self._testMethodName, strclass(self.__class__))
  383. def __repr__(self):
  384. return "<%s testMethod=%s>" % \
  385. (strclass(self.__class__), self._testMethodName)
  386. def _addSkip(self, result, test_case, reason):
  387. addSkip = getattr(result, 'addSkip', None)
  388. if addSkip is not None:
  389. addSkip(test_case, reason)
  390. else:
  391. warnings.warn("TestResult has no addSkip method, skips not reported",
  392. RuntimeWarning, 2)
  393. result.addSuccess(test_case)
  394. @contextlib.contextmanager
  395. def subTest(self, msg=_subtest_msg_sentinel, **params):
  396. """Return a context manager that will return the enclosed block
  397. of code in a subtest identified by the optional message and
  398. keyword parameters. A failure in the subtest marks the test
  399. case as failed but resumes execution at the end of the enclosed
  400. block, allowing further test code to be executed.
  401. """
  402. if self._outcome is None or not self._outcome.result_supports_subtests:
  403. yield
  404. return
  405. parent = self._subtest
  406. if parent is None:
  407. params_map = _OrderedChainMap(params)
  408. else:
  409. params_map = parent.params.new_child(params)
  410. self._subtest = _SubTest(self, msg, params_map)
  411. try:
  412. with self._outcome.testPartExecutor(self._subtest, isTest=True):
  413. yield
  414. if not self._outcome.success:
  415. result = self._outcome.result
  416. if result is not None and result.failfast:
  417. raise _ShouldStop
  418. elif self._outcome.expectedFailure:
  419. # If the test is expecting a failure, we really want to
  420. # stop now and register the expected failure.
  421. raise _ShouldStop
  422. finally:
  423. self._subtest = parent
  424. def _feedErrorsToResult(self, result, errors):
  425. for test, exc_info in errors:
  426. if isinstance(test, _SubTest):
  427. result.addSubTest(test.test_case, test, exc_info)
  428. elif exc_info is not None:
  429. if issubclass(exc_info[0], self.failureException):
  430. result.addFailure(test, exc_info)
  431. else:
  432. result.addError(test, exc_info)
  433. def _addExpectedFailure(self, result, exc_info):
  434. try:
  435. addExpectedFailure = result.addExpectedFailure
  436. except AttributeError:
  437. warnings.warn("TestResult has no addExpectedFailure method, reporting as passes",
  438. RuntimeWarning)
  439. result.addSuccess(self)
  440. else:
  441. addExpectedFailure(self, exc_info)
  442. def _addUnexpectedSuccess(self, result):
  443. try:
  444. addUnexpectedSuccess = result.addUnexpectedSuccess
  445. except AttributeError:
  446. warnings.warn("TestResult has no addUnexpectedSuccess method, reporting as failure",
  447. RuntimeWarning)
  448. # We need to pass an actual exception and traceback to addFailure,
  449. # otherwise the legacy result can choke.
  450. try:
  451. raise _UnexpectedSuccess from None
  452. except _UnexpectedSuccess:
  453. result.addFailure(self, sys.exc_info())
  454. else:
  455. addUnexpectedSuccess(self)
  456. def _callSetUp(self):
  457. self.setUp()
  458. def _callTestMethod(self, method):
  459. method()
  460. def _callTearDown(self):
  461. self.tearDown()
  462. def _callCleanup(self, function, /, *args, **kwargs):
  463. function(*args, **kwargs)
  464. def run(self, result=None):
  465. if result is None:
  466. result = self.defaultTestResult()
  467. startTestRun = getattr(result, 'startTestRun', None)
  468. stopTestRun = getattr(result, 'stopTestRun', None)
  469. if startTestRun is not None:
  470. startTestRun()
  471. else:
  472. stopTestRun = None
  473. result.startTest(self)
  474. try:
  475. testMethod = getattr(self, self._testMethodName)
  476. if (getattr(self.__class__, "__unittest_skip__", False) or
  477. getattr(testMethod, "__unittest_skip__", False)):
  478. # If the class or method was skipped.
  479. skip_why = (getattr(self.__class__, '__unittest_skip_why__', '')
  480. or getattr(testMethod, '__unittest_skip_why__', ''))
  481. self._addSkip(result, self, skip_why)
  482. return result
  483. expecting_failure = (
  484. getattr(self, "__unittest_expecting_failure__", False) or
  485. getattr(testMethod, "__unittest_expecting_failure__", False)
  486. )
  487. outcome = _Outcome(result)
  488. try:
  489. self._outcome = outcome
  490. with outcome.testPartExecutor(self):
  491. self._callSetUp()
  492. if outcome.success:
  493. outcome.expecting_failure = expecting_failure
  494. with outcome.testPartExecutor(self, isTest=True):
  495. self._callTestMethod(testMethod)
  496. outcome.expecting_failure = False
  497. with outcome.testPartExecutor(self):
  498. self._callTearDown()
  499. self.doCleanups()
  500. for test, reason in outcome.skipped:
  501. self._addSkip(result, test, reason)
  502. self._feedErrorsToResult(result, outcome.errors)
  503. if outcome.success:
  504. if expecting_failure:
  505. if outcome.expectedFailure:
  506. self._addExpectedFailure(result, outcome.expectedFailure)
  507. else:
  508. self._addUnexpectedSuccess(result)
  509. else:
  510. result.addSuccess(self)
  511. return result
  512. finally:
  513. # explicitly break reference cycles:
  514. # outcome.errors -> frame -> outcome -> outcome.errors
  515. # outcome.expectedFailure -> frame -> outcome -> outcome.expectedFailure
  516. outcome.errors.clear()
  517. outcome.expectedFailure = None
  518. # clear the outcome, no more needed
  519. self._outcome = None
  520. finally:
  521. result.stopTest(self)
  522. if stopTestRun is not None:
  523. stopTestRun()
  524. def doCleanups(self):
  525. """Execute all cleanup functions. Normally called for you after
  526. tearDown."""
  527. outcome = self._outcome or _Outcome()
  528. while self._cleanups:
  529. function, args, kwargs = self._cleanups.pop()
  530. with outcome.testPartExecutor(self):
  531. self._callCleanup(function, *args, **kwargs)
  532. # return this for backwards compatibility
  533. # even though we no longer use it internally
  534. return outcome.success
  535. @classmethod
  536. def doClassCleanups(cls):
  537. """Execute all class cleanup functions. Normally called for you after
  538. tearDownClass."""
  539. cls.tearDown_exceptions = []
  540. while cls._class_cleanups:
  541. function, args, kwargs = cls._class_cleanups.pop()
  542. try:
  543. function(*args, **kwargs)
  544. except Exception:
  545. cls.tearDown_exceptions.append(sys.exc_info())
  546. def __call__(self, *args, **kwds):
  547. return self.run(*args, **kwds)
  548. def debug(self):
  549. """Run the test without collecting errors in a TestResult"""
  550. testMethod = getattr(self, self._testMethodName)
  551. if (getattr(self.__class__, "__unittest_skip__", False) or
  552. getattr(testMethod, "__unittest_skip__", False)):
  553. # If the class or method was skipped.
  554. skip_why = (getattr(self.__class__, '__unittest_skip_why__', '')
  555. or getattr(testMethod, '__unittest_skip_why__', ''))
  556. raise SkipTest(skip_why)
  557. self._callSetUp()
  558. self._callTestMethod(testMethod)
  559. self._callTearDown()
  560. while self._cleanups:
  561. function, args, kwargs = self._cleanups.pop()
  562. self._callCleanup(function, *args, **kwargs)
  563. def skipTest(self, reason):
  564. """Skip this test."""
  565. raise SkipTest(reason)
  566. def fail(self, msg=None):
  567. """Fail immediately, with the given message."""
  568. raise self.failureException(msg)
  569. def assertFalse(self, expr, msg=None):
  570. """Check that the expression is false."""
  571. if expr:
  572. msg = self._formatMessage(msg, "%s is not false" % safe_repr(expr))
  573. raise self.failureException(msg)
  574. def assertTrue(self, expr, msg=None):
  575. """Check that the expression is true."""
  576. if not expr:
  577. msg = self._formatMessage(msg, "%s is not true" % safe_repr(expr))
  578. raise self.failureException(msg)
  579. def _formatMessage(self, msg, standardMsg):
  580. """Honour the longMessage attribute when generating failure messages.
  581. If longMessage is False this means:
  582. * Use only an explicit message if it is provided
  583. * Otherwise use the standard message for the assert
  584. If longMessage is True:
  585. * Use the standard message
  586. * If an explicit message is provided, plus ' : ' and the explicit message
  587. """
  588. if not self.longMessage:
  589. return msg or standardMsg
  590. if msg is None:
  591. return standardMsg
  592. try:
  593. # don't switch to '{}' formatting in Python 2.X
  594. # it changes the way unicode input is handled
  595. return '%s : %s' % (standardMsg, msg)
  596. except UnicodeDecodeError:
  597. return '%s : %s' % (safe_repr(standardMsg), safe_repr(msg))
  598. def assertRaises(self, expected_exception, *args, **kwargs):
  599. """Fail unless an exception of class expected_exception is raised
  600. by the callable when invoked with specified positional and
  601. keyword arguments. If a different type of exception is
  602. raised, it will not be caught, and the test case will be
  603. deemed to have suffered an error, exactly as for an
  604. unexpected exception.
  605. If called with the callable and arguments omitted, will return a
  606. context object used like this::
  607. with self.assertRaises(SomeException):
  608. do_something()
  609. An optional keyword argument 'msg' can be provided when assertRaises
  610. is used as a context object.
  611. The context manager keeps a reference to the exception as
  612. the 'exception' attribute. This allows you to inspect the
  613. exception after the assertion::
  614. with self.assertRaises(SomeException) as cm:
  615. do_something()
  616. the_exception = cm.exception
  617. self.assertEqual(the_exception.error_code, 3)
  618. """
  619. context = _AssertRaisesContext(expected_exception, self)
  620. try:
  621. return context.handle('assertRaises', args, kwargs)
  622. finally:
  623. # bpo-23890: manually break a reference cycle
  624. context = None
  625. def assertWarns(self, expected_warning, *args, **kwargs):
  626. """Fail unless a warning of class warnClass is triggered
  627. by the callable when invoked with specified positional and
  628. keyword arguments. If a different type of warning is
  629. triggered, it will not be handled: depending on the other
  630. warning filtering rules in effect, it might be silenced, printed
  631. out, or raised as an exception.
  632. If called with the callable and arguments omitted, will return a
  633. context object used like this::
  634. with self.assertWarns(SomeWarning):
  635. do_something()
  636. An optional keyword argument 'msg' can be provided when assertWarns
  637. is used as a context object.
  638. The context manager keeps a reference to the first matching
  639. warning as the 'warning' attribute; similarly, the 'filename'
  640. and 'lineno' attributes give you information about the line
  641. of Python code from which the warning was triggered.
  642. This allows you to inspect the warning after the assertion::
  643. with self.assertWarns(SomeWarning) as cm:
  644. do_something()
  645. the_warning = cm.warning
  646. self.assertEqual(the_warning.some_attribute, 147)
  647. """
  648. context = _AssertWarnsContext(expected_warning, self)
  649. return context.handle('assertWarns', args, kwargs)
  650. def assertLogs(self, logger=None, level=None):
  651. """Fail unless a log message of level *level* or higher is emitted
  652. on *logger_name* or its children. If omitted, *level* defaults to
  653. INFO and *logger* defaults to the root logger.
  654. This method must be used as a context manager, and will yield
  655. a recording object with two attributes: `output` and `records`.
  656. At the end of the context manager, the `output` attribute will
  657. be a list of the matching formatted log messages and the
  658. `records` attribute will be a list of the corresponding LogRecord
  659. objects.
  660. Example::
  661. with self.assertLogs('foo', level='INFO') as cm:
  662. logging.getLogger('foo').info('first message')
  663. logging.getLogger('foo.bar').error('second message')
  664. self.assertEqual(cm.output, ['INFO:foo:first message',
  665. 'ERROR:foo.bar:second message'])
  666. """
  667. # Lazy import to avoid importing logging if it is not needed.
  668. from ._log import _AssertLogsContext
  669. return _AssertLogsContext(self, logger, level)
  670. def _getAssertEqualityFunc(self, first, second):
  671. """Get a detailed comparison function for the types of the two args.
  672. Returns: A callable accepting (first, second, msg=None) that will
  673. raise a failure exception if first != second with a useful human
  674. readable error message for those types.
  675. """
  676. #
  677. # NOTE(gregory.p.smith): I considered isinstance(first, type(second))
  678. # and vice versa. I opted for the conservative approach in case
  679. # subclasses are not intended to be compared in detail to their super
  680. # class instances using a type equality func. This means testing
  681. # subtypes won't automagically use the detailed comparison. Callers
  682. # should use their type specific assertSpamEqual method to compare
  683. # subclasses if the detailed comparison is desired and appropriate.
  684. # See the discussion in http://bugs.python.org/issue2578.
  685. #
  686. if type(first) is type(second):
  687. asserter = self._type_equality_funcs.get(type(first))
  688. if asserter is not None:
  689. if isinstance(asserter, str):
  690. asserter = getattr(self, asserter)
  691. return asserter
  692. return self._baseAssertEqual
  693. def _baseAssertEqual(self, first, second, msg=None):
  694. """The default assertEqual implementation, not type specific."""
  695. if not first == second:
  696. standardMsg = '%s != %s' % _common_shorten_repr(first, second)
  697. msg = self._formatMessage(msg, standardMsg)
  698. raise self.failureException(msg)
  699. def assertEqual(self, first, second, msg=None):
  700. """Fail if the two objects are unequal as determined by the '=='
  701. operator.
  702. """
  703. assertion_func = self._getAssertEqualityFunc(first, second)
  704. assertion_func(first, second, msg=msg)
  705. def assertNotEqual(self, first, second, msg=None):
  706. """Fail if the two objects are equal as determined by the '!='
  707. operator.
  708. """
  709. if not first != second:
  710. msg = self._formatMessage(msg, '%s == %s' % (safe_repr(first),
  711. safe_repr(second)))
  712. raise self.failureException(msg)
  713. def assertAlmostEqual(self, first, second, places=None, msg=None,
  714. delta=None):
  715. """Fail if the two objects are unequal as determined by their
  716. difference rounded to the given number of decimal places
  717. (default 7) and comparing to zero, or by comparing that the
  718. difference between the two objects is more than the given
  719. delta.
  720. Note that decimal places (from zero) are usually not the same
  721. as significant digits (measured from the most significant digit).
  722. If the two objects compare equal then they will automatically
  723. compare almost equal.
  724. """
  725. if first == second:
  726. # shortcut
  727. return
  728. if delta is not None and places is not None:
  729. raise TypeError("specify delta or places not both")
  730. diff = abs(first - second)
  731. if delta is not None:
  732. if diff <= delta:
  733. return
  734. standardMsg = '%s != %s within %s delta (%s difference)' % (
  735. safe_repr(first),
  736. safe_repr(second),
  737. safe_repr(delta),
  738. safe_repr(diff))
  739. else:
  740. if places is None:
  741. places = 7
  742. if round(diff, places) == 0:
  743. return
  744. standardMsg = '%s != %s within %r places (%s difference)' % (
  745. safe_repr(first),
  746. safe_repr(second),
  747. places,
  748. safe_repr(diff))
  749. msg = self._formatMessage(msg, standardMsg)
  750. raise self.failureException(msg)
  751. def assertNotAlmostEqual(self, first, second, places=None, msg=None,
  752. delta=None):
  753. """Fail if the two objects are equal as determined by their
  754. difference rounded to the given number of decimal places
  755. (default 7) and comparing to zero, or by comparing that the
  756. difference between the two objects is less than the given delta.
  757. Note that decimal places (from zero) are usually not the same
  758. as significant digits (measured from the most significant digit).
  759. Objects that are equal automatically fail.
  760. """
  761. if delta is not None and places is not None:
  762. raise TypeError("specify delta or places not both")
  763. diff = abs(first - second)
  764. if delta is not None:
  765. if not (first == second) and diff > delta:
  766. return
  767. standardMsg = '%s == %s within %s delta (%s difference)' % (
  768. safe_repr(first),
  769. safe_repr(second),
  770. safe_repr(delta),
  771. safe_repr(diff))
  772. else:
  773. if places is None:
  774. places = 7
  775. if not (first == second) and round(diff, places) != 0:
  776. return
  777. standardMsg = '%s == %s within %r places' % (safe_repr(first),
  778. safe_repr(second),
  779. places)
  780. msg = self._formatMessage(msg, standardMsg)
  781. raise self.failureException(msg)
  782. def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
  783. """An equality assertion for ordered sequences (like lists and tuples).
  784. For the purposes of this function, a valid ordered sequence type is one
  785. which can be indexed, has a length, and has an equality operator.
  786. Args:
  787. seq1: The first sequence to compare.
  788. seq2: The second sequence to compare.
  789. seq_type: The expected datatype of the sequences, or None if no
  790. datatype should be enforced.
  791. msg: Optional message to use on failure instead of a list of
  792. differences.
  793. """
  794. if seq_type is not None:
  795. seq_type_name = seq_type.__name__
  796. if not isinstance(seq1, seq_type):
  797. raise self.failureException('First sequence is not a %s: %s'
  798. % (seq_type_name, safe_repr(seq1)))
  799. if not isinstance(seq2, seq_type):
  800. raise self.failureException('Second sequence is not a %s: %s'
  801. % (seq_type_name, safe_repr(seq2)))
  802. else:
  803. seq_type_name = "sequence"
  804. differing = None
  805. try:
  806. len1 = len(seq1)
  807. except (TypeError, NotImplementedError):
  808. differing = 'First %s has no length. Non-sequence?' % (
  809. seq_type_name)
  810. if differing is None:
  811. try:
  812. len2 = len(seq2)
  813. except (TypeError, NotImplementedError):
  814. differing = 'Second %s has no length. Non-sequence?' % (
  815. seq_type_name)
  816. if differing is None:
  817. if seq1 == seq2:
  818. return
  819. differing = '%ss differ: %s != %s\n' % (
  820. (seq_type_name.capitalize(),) +
  821. _common_shorten_repr(seq1, seq2))
  822. for i in range(min(len1, len2)):
  823. try:
  824. item1 = seq1[i]
  825. except (TypeError, IndexError, NotImplementedError):
  826. differing += ('\nUnable to index element %d of first %s\n' %
  827. (i, seq_type_name))
  828. break
  829. try:
  830. item2 = seq2[i]
  831. except (TypeError, IndexError, NotImplementedError):
  832. differing += ('\nUnable to index element %d of second %s\n' %
  833. (i, seq_type_name))
  834. break
  835. if item1 != item2:
  836. differing += ('\nFirst differing element %d:\n%s\n%s\n' %
  837. ((i,) + _common_shorten_repr(item1, item2)))
  838. break
  839. else:
  840. if (len1 == len2 and seq_type is None and
  841. type(seq1) != type(seq2)):
  842. # The sequences are the same, but have differing types.
  843. return
  844. if len1 > len2:
  845. differing += ('\nFirst %s contains %d additional '
  846. 'elements.\n' % (seq_type_name, len1 - len2))
  847. try:
  848. differing += ('First extra element %d:\n%s\n' %
  849. (len2, safe_repr(seq1[len2])))
  850. except (TypeError, IndexError, NotImplementedError):
  851. differing += ('Unable to index element %d '
  852. 'of first %s\n' % (len2, seq_type_name))
  853. elif len1 < len2:
  854. differing += ('\nSecond %s contains %d additional '
  855. 'elements.\n' % (seq_type_name, len2 - len1))
  856. try:
  857. differing += ('First extra element %d:\n%s\n' %
  858. (len1, safe_repr(seq2[len1])))
  859. except (TypeError, IndexError, NotImplementedError):
  860. differing += ('Unable to index element %d '
  861. 'of second %s\n' % (len1, seq_type_name))
  862. standardMsg = differing
  863. diffMsg = '\n' + '\n'.join(
  864. difflib.ndiff(pprint.pformat(seq1).splitlines(),
  865. pprint.pformat(seq2).splitlines()))
  866. standardMsg = self._truncateMessage(standardMsg, diffMsg)
  867. msg = self._formatMessage(msg, standardMsg)
  868. self.fail(msg)
  869. def _truncateMessage(self, message, diff):
  870. max_diff = self.maxDiff
  871. if max_diff is None or len(diff) <= max_diff:
  872. return message + diff
  873. return message + (DIFF_OMITTED % len(diff))
  874. def assertListEqual(self, list1, list2, msg=None):
  875. """A list-specific equality assertion.
  876. Args:
  877. list1: The first list to compare.
  878. list2: The second list to compare.
  879. msg: Optional message to use on failure instead of a list of
  880. differences.
  881. """
  882. self.assertSequenceEqual(list1, list2, msg, seq_type=list)
  883. def assertTupleEqual(self, tuple1, tuple2, msg=None):
  884. """A tuple-specific equality assertion.
  885. Args:
  886. tuple1: The first tuple to compare.
  887. tuple2: The second tuple to compare.
  888. msg: Optional message to use on failure instead of a list of
  889. differences.
  890. """
  891. self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
  892. def assertSetEqual(self, set1, set2, msg=None):
  893. """A set-specific equality assertion.
  894. Args:
  895. set1: The first set to compare.
  896. set2: The second set to compare.
  897. msg: Optional message to use on failure instead of a list of
  898. differences.
  899. assertSetEqual uses ducktyping to support different types of sets, and
  900. is optimized for sets specifically (parameters must support a
  901. difference method).
  902. """
  903. try:
  904. difference1 = set1.difference(set2)
  905. except TypeError as e:
  906. self.fail('invalid type when attempting set difference: %s' % e)
  907. except AttributeError as e:
  908. self.fail('first argument does not support set difference: %s' % e)
  909. try:
  910. difference2 = set2.difference(set1)
  911. except TypeError as e:
  912. self.fail('invalid type when attempting set difference: %s' % e)
  913. except AttributeError as e:
  914. self.fail('second argument does not support set difference: %s' % e)
  915. if not (difference1 or difference2):
  916. return
  917. lines = []
  918. if difference1:
  919. lines.append('Items in the first set but not the second:')
  920. for item in difference1:
  921. lines.append(repr(item))
  922. if difference2:
  923. lines.append('Items in the second set but not the first:')
  924. for item in difference2:
  925. lines.append(repr(item))
  926. standardMsg = '\n'.join(lines)
  927. self.fail(self._formatMessage(msg, standardMsg))
  928. def assertIn(self, member, container, msg=None):
  929. """Just like self.assertTrue(a in b), but with a nicer default message."""
  930. if member not in container:
  931. standardMsg = '%s not found in %s' % (safe_repr(member),
  932. safe_repr(container))
  933. self.fail(self._formatMessage(msg, standardMsg))
  934. def assertNotIn(self, member, container, msg=None):
  935. """Just like self.assertTrue(a not in b), but with a nicer default message."""
  936. if member in container:
  937. standardMsg = '%s unexpectedly found in %s' % (safe_repr(member),
  938. safe_repr(container))
  939. self.fail(self._formatMessage(msg, standardMsg))
  940. def assertIs(self, expr1, expr2, msg=None):
  941. """Just like self.assertTrue(a is b), but with a nicer default message."""
  942. if expr1 is not expr2:
  943. standardMsg = '%s is not %s' % (safe_repr(expr1),
  944. safe_repr(expr2))
  945. self.fail(self._formatMessage(msg, standardMsg))
  946. def assertIsNot(self, expr1, expr2, msg=None):
  947. """Just like self.assertTrue(a is not b), but with a nicer default message."""
  948. if expr1 is expr2:
  949. standardMsg = 'unexpectedly identical: %s' % (safe_repr(expr1),)
  950. self.fail(self._formatMessage(msg, standardMsg))
  951. def assertDictEqual(self, d1, d2, msg=None):
  952. self.assertIsInstance(d1, dict, 'First argument is not a dictionary')
  953. self.assertIsInstance(d2, dict, 'Second argument is not a dictionary')
  954. if d1 != d2:
  955. standardMsg = '%s != %s' % _common_shorten_repr(d1, d2)
  956. diff = ('\n' + '\n'.join(difflib.ndiff(
  957. pprint.pformat(d1).splitlines(),
  958. pprint.pformat(d2).splitlines())))
  959. standardMsg = self._truncateMessage(standardMsg, diff)
  960. self.fail(self._formatMessage(msg, standardMsg))
  961. def assertDictContainsSubset(self, subset, dictionary, msg=None):
  962. """Checks whether dictionary is a superset of subset."""
  963. warnings.warn('assertDictContainsSubset is deprecated',
  964. DeprecationWarning)
  965. missing = []
  966. mismatched = []
  967. for key, value in subset.items():
  968. if key not in dictionary:
  969. missing.append(key)
  970. elif value != dictionary[key]:
  971. mismatched.append('%s, expected: %s, actual: %s' %
  972. (safe_repr(key), safe_repr(value),
  973. safe_repr(dictionary[key])))
  974. if not (missing or mismatched):
  975. return
  976. standardMsg = ''
  977. if missing:
  978. standardMsg = 'Missing: %s' % ','.join(safe_repr(m) for m in
  979. missing)
  980. if mismatched:
  981. if standardMsg:
  982. standardMsg += '; '
  983. standardMsg += 'Mismatched values: %s' % ','.join(mismatched)
  984. self.fail(self._formatMessage(msg, standardMsg))
  985. def assertCountEqual(self, first, second, msg=None):
  986. """Asserts that two iterables have the same elements, the same number of
  987. times, without regard to order.
  988. self.assertEqual(Counter(list(first)),
  989. Counter(list(second)))
  990. Example:
  991. - [0, 1, 1] and [1, 0, 1] compare equal.
  992. - [0, 0, 1] and [0, 1] compare unequal.
  993. """
  994. first_seq, second_seq = list(first), list(second)
  995. try:
  996. first = collections.Counter(first_seq)
  997. second = collections.Counter(second_seq)
  998. except TypeError:
  999. # Handle case with unhashable elements
  1000. differences = _count_diff_all_purpose(first_seq, second_seq)
  1001. else:
  1002. if first == second:
  1003. return
  1004. differences = _count_diff_hashable(first_seq, second_seq)
  1005. if differences:
  1006. standardMsg = 'Element counts were not equal:\n'
  1007. lines = ['First has %d, Second has %d: %r' % diff for diff in differences]
  1008. diffMsg = '\n'.join(lines)
  1009. standardMsg = self._truncateMessage(standardMsg, diffMsg)
  1010. msg = self._formatMessage(msg, standardMsg)
  1011. self.fail(msg)
  1012. def assertMultiLineEqual(self, first, second, msg=None):
  1013. """Assert that two multi-line strings are equal."""
  1014. self.assertIsInstance(first, str, 'First argument is not a string')
  1015. self.assertIsInstance(second, str, 'Second argument is not a string')
  1016. if first != second:
  1017. # don't use difflib if the strings are too long
  1018. if (len(first) > self._diffThreshold or
  1019. len(second) > self._diffThreshold):
  1020. self._baseAssertEqual(first, second, msg)
  1021. firstlines = first.splitlines(keepends=True)
  1022. secondlines = second.splitlines(keepends=True)
  1023. if len(firstlines) == 1 and first.strip('\r\n') == first:
  1024. firstlines = [first + '\n']
  1025. secondlines = [second + '\n']
  1026. standardMsg = '%s != %s' % _common_shorten_repr(first, second)
  1027. diff = '\n' + ''.join(difflib.ndiff(firstlines, secondlines))
  1028. standardMsg = self._truncateMessage(standardMsg, diff)
  1029. self.fail(self._formatMessage(msg, standardMsg))
  1030. def assertLess(self, a, b, msg=None):
  1031. """Just like self.assertTrue(a < b), but with a nicer default message."""
  1032. if not a < b:
  1033. standardMsg = '%s not less than %s' % (safe_repr(a), safe_repr(b))
  1034. self.fail(self._formatMessage(msg, standardMsg))
  1035. def assertLessEqual(self, a, b, msg=None):
  1036. """Just like self.assertTrue(a <= b), but with a nicer default message."""
  1037. if not a <= b:
  1038. standardMsg = '%s not less than or equal to %s' % (safe_repr(a), safe_repr(b))
  1039. self.fail(self._formatMessage(msg, standardMsg))
  1040. def assertGreater(self, a, b, msg=None):
  1041. """Just like self.assertTrue(a > b), but with a nicer default message."""
  1042. if not a > b:
  1043. standardMsg = '%s not greater than %s' % (safe_repr(a), safe_repr(b))
  1044. self.fail(self._formatMessage(msg, standardMsg))
  1045. def assertGreaterEqual(self, a, b, msg=None):
  1046. """Just like self.assertTrue(a >= b), but with a nicer default message."""
  1047. if not a >= b:
  1048. standardMsg = '%s not greater than or equal to %s' % (safe_repr(a), safe_repr(b))
  1049. self.fail(self._formatMessage(msg, standardMsg))
  1050. def assertIsNone(self, obj, msg=None):
  1051. """Same as self.assertTrue(obj is None), with a nicer default message."""
  1052. if obj is not None:
  1053. standardMsg = '%s is not None' % (safe_repr(obj),)
  1054. self.fail(self._formatMessage(msg, standardMsg))
  1055. def assertIsNotNone(self, obj, msg=None):
  1056. """Included for symmetry with assertIsNone."""
  1057. if obj is None:
  1058. standardMsg = 'unexpectedly None'
  1059. self.fail(self._formatMessage(msg, standardMsg))
  1060. def assertIsInstance(self, obj, cls, msg=None):
  1061. """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
  1062. default message."""
  1063. if not isinstance(obj, cls):
  1064. standardMsg = '%s is not an instance of %r' % (safe_repr(obj), cls)
  1065. self.fail(self._formatMessage(msg, standardMsg))
  1066. def assertNotIsInstance(self, obj, cls, msg=None):
  1067. """Included for symmetry with assertIsInstance."""
  1068. if isinstance(obj, cls):
  1069. standardMsg = '%s is an instance of %r' % (safe_repr(obj), cls)
  1070. self.fail(self._formatMessage(msg, standardMsg))
  1071. def assertRaisesRegex(self, expected_exception, expected_regex,
  1072. *args, **kwargs):
  1073. """Asserts that the message in a raised exception matches a regex.
  1074. Args:
  1075. expected_exception: Exception class expected to be raised.
  1076. expected_regex: Regex (re.Pattern object or string) expected
  1077. to be found in error message.
  1078. args: Function to be called and extra positional args.
  1079. kwargs: Extra kwargs.
  1080. msg: Optional message used in case of failure. Can only be used
  1081. when assertRaisesRegex is used as a context manager.
  1082. """
  1083. context = _AssertRaisesContext(expected_exception, self, expected_regex)
  1084. return context.handle('assertRaisesRegex', args, kwargs)
  1085. def assertWarnsRegex(self, expected_warning, expected_regex,
  1086. *args, **kwargs):
  1087. """Asserts that the message in a triggered warning matches a regexp.
  1088. Basic functioning is similar to assertWarns() with the addition
  1089. that only warnings whose messages also match the regular expression
  1090. are considered successful matches.
  1091. Args:
  1092. expected_warning: Warning class expected to be triggered.
  1093. expected_regex: Regex (re.Pattern object or string) expected
  1094. to be found in error message.
  1095. args: Function to be called and extra positional args.
  1096. kwargs: Extra kwargs.
  1097. msg: Optional message used in case of failure. Can only be used
  1098. when assertWarnsRegex is used as a context manager.
  1099. """
  1100. context = _AssertWarnsContext(expected_warning, self, expected_regex)
  1101. return context.handle('assertWarnsRegex', args, kwargs)
  1102. def assertRegex(self, text, expected_regex, msg=None):
  1103. """Fail the test unless the text matches the regular expression."""
  1104. if isinstance(expected_regex, (str, bytes)):
  1105. assert expected_regex, "expected_regex must not be empty."
  1106. expected_regex = re.compile(expected_regex)
  1107. if not expected_regex.search(text):
  1108. standardMsg = "Regex didn't match: %r not found in %r" % (
  1109. expected_regex.pattern, text)
  1110. # _formatMessage ensures the longMessage option is respected
  1111. msg = self._formatMessage(msg, standardMsg)
  1112. raise self.failureException(msg)
  1113. def assertNotRegex(self, text, unexpected_regex, msg=None):
  1114. """Fail the test if the text matches the regular expression."""
  1115. if isinstance(unexpected_regex, (str, bytes)):
  1116. unexpected_regex = re.compile(unexpected_regex)
  1117. match = unexpected_regex.search(text)
  1118. if match:
  1119. standardMsg = 'Regex matched: %r matches %r in %r' % (
  1120. text[match.start() : match.end()],
  1121. unexpected_regex.pattern,
  1122. text)
  1123. # _formatMessage ensures the longMessage option is respected
  1124. msg = self._formatMessage(msg, standardMsg)
  1125. raise self.failureException(msg)
  1126. def _deprecate(original_func):
  1127. def deprecated_func(*args, **kwargs):
  1128. warnings.warn(
  1129. 'Please use {0} instead.'.format(original_func.__name__),
  1130. DeprecationWarning, 2)
  1131. return original_func(*args, **kwargs)
  1132. return deprecated_func
  1133. # see #9424
  1134. failUnlessEqual = assertEquals = _deprecate(assertEqual)
  1135. failIfEqual = assertNotEquals = _deprecate(assertNotEqual)
  1136. failUnlessAlmostEqual = assertAlmostEquals = _deprecate(assertAlmostEqual)
  1137. failIfAlmostEqual = assertNotAlmostEquals = _deprecate(assertNotAlmostEqual)
  1138. failUnless = assert_ = _deprecate(assertTrue)
  1139. failUnlessRaises = _deprecate(assertRaises)
  1140. failIf = _deprecate(assertFalse)
  1141. assertRaisesRegexp = _deprecate(assertRaisesRegex)
  1142. assertRegexpMatches = _deprecate(assertRegex)
  1143. assertNotRegexpMatches = _deprecate(assertNotRegex)
  1144. class FunctionTestCase(TestCase):
  1145. """A test case that wraps a test function.
  1146. This is useful for slipping pre-existing test functions into the
  1147. unittest framework. Optionally, set-up and tidy-up functions can be
  1148. supplied. As with TestCase, the tidy-up ('tearDown') function will
  1149. always be called if the set-up ('setUp') function ran successfully.
  1150. """
  1151. def __init__(self, testFunc, setUp=None, tearDown=None, description=None):
  1152. super(FunctionTestCase, self).__init__()
  1153. self._setUpFunc = setUp
  1154. self._tearDownFunc = tearDown
  1155. self._testFunc = testFunc
  1156. self._description = description
  1157. def setUp(self):
  1158. if self._setUpFunc is not None:
  1159. self._setUpFunc()
  1160. def tearDown(self):
  1161. if self._tearDownFunc is not None:
  1162. self._tearDownFunc()
  1163. def runTest(self):
  1164. self._testFunc()
  1165. def id(self):
  1166. return self._testFunc.__name__
  1167. def __eq__(self, other):
  1168. if not isinstance(other, self.__class__):
  1169. return NotImplemented
  1170. return self._setUpFunc == other._setUpFunc and \
  1171. self._tearDownFunc == other._tearDownFunc and \
  1172. self._testFunc == other._testFunc and \
  1173. self._description == other._description
  1174. def __hash__(self):
  1175. return hash((type(self), self._setUpFunc, self._tearDownFunc,
  1176. self._testFunc, self._description))
  1177. def __str__(self):
  1178. return "%s (%s)" % (strclass(self.__class__),
  1179. self._testFunc.__name__)
  1180. def __repr__(self):
  1181. return "<%s tec=%s>" % (strclass(self.__class__),
  1182. self._testFunc)
  1183. def shortDescription(self):
  1184. if self._description is not None:
  1185. return self._description
  1186. doc = self._testFunc.__doc__
  1187. return doc and doc.split("\n")[0].strip() or None
  1188. class _SubTest(TestCase):
  1189. def __init__(self, test_case, message, params):
  1190. super().__init__()
  1191. self._message = message
  1192. self.test_case = test_case
  1193. self.params = params
  1194. self.failureException = test_case.failureException
  1195. def runTest(self):
  1196. raise NotImplementedError("subtests cannot be run directly")
  1197. def _subDescription(self):
  1198. parts = []
  1199. if self._message is not _subtest_msg_sentinel:
  1200. parts.append("[{}]".format(self._message))
  1201. if self.params:
  1202. params_desc = ', '.join(
  1203. "{}={!r}".format(k, v)
  1204. for (k, v) in self.params.items())
  1205. parts.append("({})".format(params_desc))
  1206. return " ".join(parts) or '(<subtest>)'
  1207. def id(self):
  1208. return "{} {}".format(self.test_case.id(), self._subDescription())
  1209. def shortDescription(self):
  1210. """Returns a one-line description of the subtest, or None if no
  1211. description has been provided.
  1212. """
  1213. return self.test_case.shortDescription()
  1214. def __str__(self):
  1215. return "{} {}".format(self.test_case, self._subDescription())