case.py 56 KB

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