case.py 57 KB

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