PageRenderTime 48ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/unittest/case.py

https://bitbucket.org/bwesterb/pypy
Python | 1072 lines | 1000 code | 10 blank | 62 comment | 7 complexity | 19a2c7d1108c2293aec8d4214dff7ec0 MD5 | raw file
  1. """Test case implementation"""
  2. import collections
  3. import sys
  4. import functools
  5. import difflib
  6. import pprint
  7. import re
  8. import warnings
  9. from . import result
  10. from .util import (
  11. strclass, safe_repr, unorderable_list_difference,
  12. _count_diff_all_purpose, _count_diff_hashable
  13. )
  14. __unittest = True
  15. DIFF_OMITTED = ('\nDiff is %s characters long. '
  16. 'Set self.maxDiff to None to see it.')
  17. class SkipTest(Exception):
  18. """
  19. Raise this exception in a test to skip it.
  20. Usually you can use TestResult.skip() or one of the skipping decorators
  21. instead of raising this directly.
  22. """
  23. pass
  24. class _ExpectedFailure(Exception):
  25. """
  26. Raise this when a test is expected to fail.
  27. This is an implementation detail.
  28. """
  29. def __init__(self, exc_info):
  30. super(_ExpectedFailure, self).__init__()
  31. self.exc_info = exc_info
  32. class _UnexpectedSuccess(Exception):
  33. """
  34. The test was supposed to fail, but it didn't!
  35. """
  36. pass
  37. def _id(obj):
  38. return obj
  39. def skip(reason):
  40. """
  41. Unconditionally skip a test.
  42. """
  43. def decorator(test_item):
  44. if not (isinstance(test_item, type) and issubclass(test_item, TestCase)):
  45. @functools.wraps(test_item)
  46. def skip_wrapper(*args, **kwargs):
  47. raise SkipTest(reason)
  48. test_item = skip_wrapper
  49. test_item.__unittest_skip__ = True
  50. test_item.__unittest_skip_why__ = reason
  51. return test_item
  52. return decorator
  53. def skipIf(condition, reason):
  54. """
  55. Skip a test if the condition is true.
  56. """
  57. if condition:
  58. return skip(reason)
  59. return _id
  60. def skipUnless(condition, reason):
  61. """
  62. Skip a test unless the condition is true.
  63. """
  64. if not condition:
  65. return skip(reason)
  66. return _id
  67. def expectedFailure(func):
  68. @functools.wraps(func)
  69. def wrapper(*args, **kwargs):
  70. try:
  71. func(*args, **kwargs)
  72. except Exception:
  73. raise _ExpectedFailure(sys.exc_info())
  74. raise _UnexpectedSuccess
  75. return wrapper
  76. class _AssertRaisesContext(object):
  77. """A context manager used to implement TestCase.assertRaises* methods."""
  78. def __init__(self, expected, test_case, expected_regexp=None):
  79. self.expected = expected
  80. self.failureException = test_case.failureException
  81. self.expected_regexp = expected_regexp
  82. def __enter__(self):
  83. return self
  84. def __exit__(self, exc_type, exc_value, tb):
  85. if exc_type is None:
  86. try:
  87. exc_name = self.expected.__name__
  88. except AttributeError:
  89. exc_name = str(self.expected)
  90. raise self.failureException(
  91. "{0} not raised".format(exc_name))
  92. if not issubclass(exc_type, self.expected):
  93. # let unexpected exceptions pass through
  94. return False
  95. self.exception = exc_value # store for later retrieval
  96. if self.expected_regexp is None:
  97. return True
  98. expected_regexp = self.expected_regexp
  99. if isinstance(expected_regexp, basestring):
  100. expected_regexp = re.compile(expected_regexp)
  101. if not expected_regexp.search(str(exc_value)):
  102. raise self.failureException('"%s" does not match "%s"' %
  103. (expected_regexp.pattern, str(exc_value)))
  104. return True
  105. class TestCase(object):
  106. """A class whose instances are single test cases.
  107. By default, the test code itself should be placed in a method named
  108. 'runTest'.
  109. If the fixture may be used for many test cases, create as
  110. many test methods as are needed. When instantiating such a TestCase
  111. subclass, specify in the constructor arguments the name of the test method
  112. that the instance is to execute.
  113. Test authors should subclass TestCase for their own tests. Construction
  114. and deconstruction of the test's environment ('fixture') can be
  115. implemented by overriding the 'setUp' and 'tearDown' methods respectively.
  116. If it is necessary to override the __init__ method, the base class
  117. __init__ method must always be called. It is important that subclasses
  118. should not change the signature of their __init__ method, since instances
  119. of the classes are instantiated automatically by parts of the framework
  120. in order to be run.
  121. """
  122. # This attribute determines which exception will be raised when
  123. # the instance's assertion methods fail; test methods raising this
  124. # exception will be deemed to have 'failed' rather than 'errored'
  125. failureException = AssertionError
  126. # This attribute determines whether long messages (including repr of
  127. # objects used in assert methods) will be printed on failure in *addition*
  128. # to any explicit message passed.
  129. longMessage = False
  130. # This attribute sets the maximum length of a diff in failure messages
  131. # by assert methods using difflib. It is looked up as an instance attribute
  132. # so can be configured by individual tests if required.
  133. maxDiff = 80*8
  134. # If a string is longer than _diffThreshold, use normal comparison instead
  135. # of difflib. See #11763.
  136. _diffThreshold = 2**16
  137. # Attribute used by TestSuite for classSetUp
  138. _classSetupFailed = False
  139. def __init__(self, methodName='runTest'):
  140. """Create an instance of the class that will use the named test
  141. method when executed. Raises a ValueError if the instance does
  142. not have a method with the specified name.
  143. """
  144. self._testMethodName = methodName
  145. self._resultForDoCleanups = None
  146. try:
  147. testMethod = getattr(self, methodName)
  148. except AttributeError:
  149. raise ValueError("no such test method in %s: %s" %
  150. (self.__class__, methodName))
  151. self._testMethodDoc = testMethod.__doc__
  152. self._cleanups = []
  153. # Map types to custom assertEqual functions that will compare
  154. # instances of said type in more detail to generate a more useful
  155. # error message.
  156. self._type_equality_funcs = {}
  157. self.addTypeEqualityFunc(dict, 'assertDictEqual')
  158. self.addTypeEqualityFunc(list, 'assertListEqual')
  159. self.addTypeEqualityFunc(tuple, 'assertTupleEqual')
  160. self.addTypeEqualityFunc(set, 'assertSetEqual')
  161. self.addTypeEqualityFunc(frozenset, 'assertSetEqual')
  162. self.addTypeEqualityFunc(unicode, 'assertMultiLineEqual')
  163. def addTypeEqualityFunc(self, typeobj, function):
  164. """Add a type specific assertEqual style function to compare a type.
  165. This method is for use by TestCase subclasses that need to register
  166. their own type equality functions to provide nicer error messages.
  167. Args:
  168. typeobj: The data type to call this function on when both values
  169. are of the same type in assertEqual().
  170. function: The callable taking two arguments and an optional
  171. msg= argument that raises self.failureException with a
  172. useful error message when the two arguments are not equal.
  173. """
  174. self._type_equality_funcs[typeobj] = function
  175. def addCleanup(self, function, *args, **kwargs):
  176. """Add a function, with arguments, to be called when the test is
  177. completed. Functions added are called on a LIFO basis and are
  178. called after tearDown on test failure or success.
  179. Cleanup items are called even if setUp fails (unlike tearDown)."""
  180. self._cleanups.append((function, args, kwargs))
  181. def setUp(self):
  182. "Hook method for setting up the test fixture before exercising it."
  183. pass
  184. def tearDown(self):
  185. "Hook method for deconstructing the test fixture after testing it."
  186. pass
  187. @classmethod
  188. def setUpClass(cls):
  189. "Hook method for setting up class fixture before running tests in the class."
  190. @classmethod
  191. def tearDownClass(cls):
  192. "Hook method for deconstructing the class fixture after running all tests in the class."
  193. def countTestCases(self):
  194. return 1
  195. def defaultTestResult(self):
  196. return result.TestResult()
  197. def shortDescription(self):
  198. """Returns a one-line description of the test, or None if no
  199. description has been provided.
  200. The default implementation of this method returns the first line of
  201. the specified test method's docstring.
  202. """
  203. doc = self._testMethodDoc
  204. return doc and doc.split("\n")[0].strip() or None
  205. def id(self):
  206. return "%s.%s" % (strclass(self.__class__), self._testMethodName)
  207. def __eq__(self, other):
  208. if type(self) is not type(other):
  209. return NotImplemented
  210. return self._testMethodName == other._testMethodName
  211. def __ne__(self, other):
  212. return not self == other
  213. def __hash__(self):
  214. return hash((type(self), self._testMethodName))
  215. def __str__(self):
  216. return "%s (%s)" % (self._testMethodName, strclass(self.__class__))
  217. def __repr__(self):
  218. return "<%s testMethod=%s>" % \
  219. (strclass(self.__class__), self._testMethodName)
  220. def _addSkip(self, result, reason):
  221. addSkip = getattr(result, 'addSkip', None)
  222. if addSkip is not None:
  223. addSkip(self, reason)
  224. else:
  225. warnings.warn("TestResult has no addSkip method, skips not reported",
  226. RuntimeWarning, 2)
  227. result.addSuccess(self)
  228. def run(self, result=None):
  229. orig_result = result
  230. if result is None:
  231. result = self.defaultTestResult()
  232. startTestRun = getattr(result, 'startTestRun', None)
  233. if startTestRun is not None:
  234. startTestRun()
  235. self._resultForDoCleanups = result
  236. result.startTest(self)
  237. testMethod = getattr(self, self._testMethodName)
  238. if (getattr(self.__class__, "__unittest_skip__", False) or
  239. getattr(testMethod, "__unittest_skip__", False)):
  240. # If the class or method was skipped.
  241. try:
  242. skip_why = (getattr(self.__class__, '__unittest_skip_why__', '')
  243. or getattr(testMethod, '__unittest_skip_why__', ''))
  244. self._addSkip(result, skip_why)
  245. finally:
  246. result.stopTest(self)
  247. return
  248. try:
  249. success = False
  250. try:
  251. self.setUp()
  252. except SkipTest as e:
  253. self._addSkip(result, str(e))
  254. except KeyboardInterrupt:
  255. raise
  256. except:
  257. result.addError(self, sys.exc_info())
  258. else:
  259. try:
  260. testMethod()
  261. except KeyboardInterrupt:
  262. raise
  263. except self.failureException:
  264. result.addFailure(self, sys.exc_info())
  265. except _ExpectedFailure as e:
  266. addExpectedFailure = getattr(result, 'addExpectedFailure', None)
  267. if addExpectedFailure is not None:
  268. addExpectedFailure(self, e.exc_info)
  269. else:
  270. warnings.warn("TestResult has no addExpectedFailure method, reporting as passes",
  271. RuntimeWarning)
  272. result.addSuccess(self)
  273. except _UnexpectedSuccess:
  274. addUnexpectedSuccess = getattr(result, 'addUnexpectedSuccess', None)
  275. if addUnexpectedSuccess is not None:
  276. addUnexpectedSuccess(self)
  277. else:
  278. warnings.warn("TestResult has no addUnexpectedSuccess method, reporting as failures",
  279. RuntimeWarning)
  280. result.addFailure(self, sys.exc_info())
  281. except SkipTest as e:
  282. self._addSkip(result, str(e))
  283. except:
  284. result.addError(self, sys.exc_info())
  285. else:
  286. success = True
  287. try:
  288. self.tearDown()
  289. except KeyboardInterrupt:
  290. raise
  291. except:
  292. result.addError(self, sys.exc_info())
  293. success = False
  294. cleanUpSuccess = self.doCleanups()
  295. success = success and cleanUpSuccess
  296. if success:
  297. result.addSuccess(self)
  298. finally:
  299. result.stopTest(self)
  300. if orig_result is None:
  301. stopTestRun = getattr(result, 'stopTestRun', None)
  302. if stopTestRun is not None:
  303. stopTestRun()
  304. def doCleanups(self):
  305. """Execute all cleanup functions. Normally called for you after
  306. tearDown."""
  307. result = self._resultForDoCleanups
  308. ok = True
  309. while self._cleanups:
  310. function, args, kwargs = self._cleanups.pop(-1)
  311. try:
  312. function(*args, **kwargs)
  313. except KeyboardInterrupt:
  314. raise
  315. except:
  316. ok = False
  317. result.addError(self, sys.exc_info())
  318. return ok
  319. def __call__(self, *args, **kwds):
  320. return self.run(*args, **kwds)
  321. def debug(self):
  322. """Run the test without collecting errors in a TestResult"""
  323. self.setUp()
  324. getattr(self, self._testMethodName)()
  325. self.tearDown()
  326. while self._cleanups:
  327. function, args, kwargs = self._cleanups.pop(-1)
  328. function(*args, **kwargs)
  329. def skipTest(self, reason):
  330. """Skip this test."""
  331. raise SkipTest(reason)
  332. def fail(self, msg=None):
  333. """Fail immediately, with the given message."""
  334. raise self.failureException(msg)
  335. def assertFalse(self, expr, msg=None):
  336. """Check that the expression is false."""
  337. if expr:
  338. msg = self._formatMessage(msg, "%s is not false" % safe_repr(expr))
  339. raise self.failureException(msg)
  340. def assertTrue(self, expr, msg=None):
  341. """Check that the expression is true."""
  342. if not expr:
  343. msg = self._formatMessage(msg, "%s is not true" % safe_repr(expr))
  344. raise self.failureException(msg)
  345. def _formatMessage(self, msg, standardMsg):
  346. """Honour the longMessage attribute when generating failure messages.
  347. If longMessage is False this means:
  348. * Use only an explicit message if it is provided
  349. * Otherwise use the standard message for the assert
  350. If longMessage is True:
  351. * Use the standard message
  352. * If an explicit message is provided, plus ' : ' and the explicit message
  353. """
  354. if not self.longMessage:
  355. return msg or standardMsg
  356. if msg is None:
  357. return standardMsg
  358. try:
  359. # don't switch to '{}' formatting in Python 2.X
  360. # it changes the way unicode input is handled
  361. return '%s : %s' % (standardMsg, msg)
  362. except UnicodeDecodeError:
  363. return '%s : %s' % (safe_repr(standardMsg), safe_repr(msg))
  364. def assertRaises(self, excClass, callableObj=None, *args, **kwargs):
  365. """Fail unless an exception of class excClass is thrown
  366. by callableObj when invoked with arguments args and keyword
  367. arguments kwargs. If a different type of exception is
  368. thrown, it will not be caught, and the test case will be
  369. deemed to have suffered an error, exactly as for an
  370. unexpected exception.
  371. If called with callableObj omitted or None, will return a
  372. context object used like this::
  373. with self.assertRaises(SomeException):
  374. do_something()
  375. The context manager keeps a reference to the exception as
  376. the 'exception' attribute. This allows you to inspect the
  377. exception after the assertion::
  378. with self.assertRaises(SomeException) as cm:
  379. do_something()
  380. the_exception = cm.exception
  381. self.assertEqual(the_exception.error_code, 3)
  382. """
  383. context = _AssertRaisesContext(excClass, self)
  384. if callableObj is None:
  385. return context
  386. with context:
  387. callableObj(*args, **kwargs)
  388. def _getAssertEqualityFunc(self, first, second):
  389. """Get a detailed comparison function for the types of the two args.
  390. Returns: A callable accepting (first, second, msg=None) that will
  391. raise a failure exception if first != second with a useful human
  392. readable error message for those types.
  393. """
  394. #
  395. # NOTE(gregory.p.smith): I considered isinstance(first, type(second))
  396. # and vice versa. I opted for the conservative approach in case
  397. # subclasses are not intended to be compared in detail to their super
  398. # class instances using a type equality func. This means testing
  399. # subtypes won't automagically use the detailed comparison. Callers
  400. # should use their type specific assertSpamEqual method to compare
  401. # subclasses if the detailed comparison is desired and appropriate.
  402. # See the discussion in http://bugs.python.org/issue2578.
  403. #
  404. if type(first) is type(second):
  405. asserter = self._type_equality_funcs.get(type(first))
  406. if asserter is not None:
  407. if isinstance(asserter, basestring):
  408. asserter = getattr(self, asserter)
  409. return asserter
  410. return self._baseAssertEqual
  411. def _baseAssertEqual(self, first, second, msg=None):
  412. """The default assertEqual implementation, not type specific."""
  413. if not first == second:
  414. standardMsg = '%s != %s' % (safe_repr(first), safe_repr(second))
  415. msg = self._formatMessage(msg, standardMsg)
  416. raise self.failureException(msg)
  417. def assertEqual(self, first, second, msg=None):
  418. """Fail if the two objects are unequal as determined by the '=='
  419. operator.
  420. """
  421. assertion_func = self._getAssertEqualityFunc(first, second)
  422. assertion_func(first, second, msg=msg)
  423. def assertNotEqual(self, first, second, msg=None):
  424. """Fail if the two objects are equal as determined by the '=='
  425. operator.
  426. """
  427. if not first != second:
  428. msg = self._formatMessage(msg, '%s == %s' % (safe_repr(first),
  429. safe_repr(second)))
  430. raise self.failureException(msg)
  431. def assertAlmostEqual(self, first, second, places=None, msg=None, delta=None):
  432. """Fail if the two objects are unequal as determined by their
  433. difference rounded to the given number of decimal places
  434. (default 7) and comparing to zero, or by comparing that the
  435. between the two objects is more than the given delta.
  436. Note that decimal places (from zero) are usually not the same
  437. as significant digits (measured from the most signficant digit).
  438. If the two objects compare equal then they will automatically
  439. compare almost equal.
  440. """
  441. if first == second:
  442. # shortcut
  443. return
  444. if delta is not None and places is not None:
  445. raise TypeError("specify delta or places not both")
  446. if delta is not None:
  447. if abs(first - second) <= delta:
  448. return
  449. standardMsg = '%s != %s within %s delta' % (safe_repr(first),
  450. safe_repr(second),
  451. safe_repr(delta))
  452. else:
  453. if places is None:
  454. places = 7
  455. if round(abs(second-first), places) == 0:
  456. return
  457. standardMsg = '%s != %s within %r places' % (safe_repr(first),
  458. safe_repr(second),
  459. places)
  460. msg = self._formatMessage(msg, standardMsg)
  461. raise self.failureException(msg)
  462. def assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None):
  463. """Fail if the two objects are equal as determined by their
  464. difference rounded to the given number of decimal places
  465. (default 7) and comparing to zero, or by comparing that the
  466. between the two objects is less than the given delta.
  467. Note that decimal places (from zero) are usually not the same
  468. as significant digits (measured from the most signficant digit).
  469. Objects that are equal automatically fail.
  470. """
  471. if delta is not None and places is not None:
  472. raise TypeError("specify delta or places not both")
  473. if delta is not None:
  474. if not (first == second) and abs(first - second) > delta:
  475. return
  476. standardMsg = '%s == %s within %s delta' % (safe_repr(first),
  477. safe_repr(second),
  478. safe_repr(delta))
  479. else:
  480. if places is None:
  481. places = 7
  482. if not (first == second) and round(abs(second-first), places) != 0:
  483. return
  484. standardMsg = '%s == %s within %r places' % (safe_repr(first),
  485. safe_repr(second),
  486. places)
  487. msg = self._formatMessage(msg, standardMsg)
  488. raise self.failureException(msg)
  489. # Synonyms for assertion methods
  490. # The plurals are undocumented. Keep them that way to discourage use.
  491. # Do not add more. Do not remove.
  492. # Going through a deprecation cycle on these would annoy many people.
  493. assertEquals = assertEqual
  494. assertNotEquals = assertNotEqual
  495. assertAlmostEquals = assertAlmostEqual
  496. assertNotAlmostEquals = assertNotAlmostEqual
  497. assert_ = assertTrue
  498. # These fail* assertion method names are pending deprecation and will
  499. # be a DeprecationWarning in 3.2; http://bugs.python.org/issue2578
  500. def _deprecate(original_func):
  501. def deprecated_func(*args, **kwargs):
  502. warnings.warn(
  503. 'Please use {0} instead.'.format(original_func.__name__),
  504. PendingDeprecationWarning, 2)
  505. return original_func(*args, **kwargs)
  506. return deprecated_func
  507. failUnlessEqual = _deprecate(assertEqual)
  508. failIfEqual = _deprecate(assertNotEqual)
  509. failUnlessAlmostEqual = _deprecate(assertAlmostEqual)
  510. failIfAlmostEqual = _deprecate(assertNotAlmostEqual)
  511. failUnless = _deprecate(assertTrue)
  512. failUnlessRaises = _deprecate(assertRaises)
  513. failIf = _deprecate(assertFalse)
  514. def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
  515. """An equality assertion for ordered sequences (like lists and tuples).
  516. For the purposes of this function, a valid ordered sequence type is one
  517. which can be indexed, has a length, and has an equality operator.
  518. Args:
  519. seq1: The first sequence to compare.
  520. seq2: The second sequence to compare.
  521. seq_type: The expected datatype of the sequences, or None if no
  522. datatype should be enforced.
  523. msg: Optional message to use on failure instead of a list of
  524. differences.
  525. """
  526. if seq_type is not None:
  527. seq_type_name = seq_type.__name__
  528. if not isinstance(seq1, seq_type):
  529. raise self.failureException('First sequence is not a %s: %s'
  530. % (seq_type_name, safe_repr(seq1)))
  531. if not isinstance(seq2, seq_type):
  532. raise self.failureException('Second sequence is not a %s: %s'
  533. % (seq_type_name, safe_repr(seq2)))
  534. else:
  535. seq_type_name = "sequence"
  536. differing = None
  537. try:
  538. len1 = len(seq1)
  539. except (TypeError, NotImplementedError):
  540. differing = 'First %s has no length. Non-sequence?' % (
  541. seq_type_name)
  542. if differing is None:
  543. try:
  544. len2 = len(seq2)
  545. except (TypeError, NotImplementedError):
  546. differing = 'Second %s has no length. Non-sequence?' % (
  547. seq_type_name)
  548. if differing is None:
  549. if seq1 == seq2:
  550. return
  551. seq1_repr = safe_repr(seq1)
  552. seq2_repr = safe_repr(seq2)
  553. if len(seq1_repr) > 30:
  554. seq1_repr = seq1_repr[:30] + '...'
  555. if len(seq2_repr) > 30:
  556. seq2_repr = seq2_repr[:30] + '...'
  557. elements = (seq_type_name.capitalize(), seq1_repr, seq2_repr)
  558. differing = '%ss differ: %s != %s\n' % elements
  559. for i in xrange(min(len1, len2)):
  560. try:
  561. item1 = seq1[i]
  562. except (TypeError, IndexError, NotImplementedError):
  563. differing += ('\nUnable to index element %d of first %s\n' %
  564. (i, seq_type_name))
  565. break
  566. try:
  567. item2 = seq2[i]
  568. except (TypeError, IndexError, NotImplementedError):
  569. differing += ('\nUnable to index element %d of second %s\n' %
  570. (i, seq_type_name))
  571. break
  572. if item1 != item2:
  573. differing += ('\nFirst differing element %d:\n%s\n%s\n' %
  574. (i, item1, item2))
  575. break
  576. else:
  577. if (len1 == len2 and seq_type is None and
  578. type(seq1) != type(seq2)):
  579. # The sequences are the same, but have differing types.
  580. return
  581. if len1 > len2:
  582. differing += ('\nFirst %s contains %d additional '
  583. 'elements.\n' % (seq_type_name, len1 - len2))
  584. try:
  585. differing += ('First extra element %d:\n%s\n' %
  586. (len2, seq1[len2]))
  587. except (TypeError, IndexError, NotImplementedError):
  588. differing += ('Unable to index element %d '
  589. 'of first %s\n' % (len2, seq_type_name))
  590. elif len1 < len2:
  591. differing += ('\nSecond %s contains %d additional '
  592. 'elements.\n' % (seq_type_name, len2 - len1))
  593. try:
  594. differing += ('First extra element %d:\n%s\n' %
  595. (len1, seq2[len1]))
  596. except (TypeError, IndexError, NotImplementedError):
  597. differing += ('Unable to index element %d '
  598. 'of second %s\n' % (len1, seq_type_name))
  599. standardMsg = differing
  600. diffMsg = '\n' + '\n'.join(
  601. difflib.ndiff(pprint.pformat(seq1).splitlines(),
  602. pprint.pformat(seq2).splitlines()))
  603. standardMsg = self._truncateMessage(standardMsg, diffMsg)
  604. msg = self._formatMessage(msg, standardMsg)
  605. self.fail(msg)
  606. def _truncateMessage(self, message, diff):
  607. max_diff = self.maxDiff
  608. if max_diff is None or len(diff) <= max_diff:
  609. return message + diff
  610. return message + (DIFF_OMITTED % len(diff))
  611. def assertListEqual(self, list1, list2, msg=None):
  612. """A list-specific equality assertion.
  613. Args:
  614. list1: The first list to compare.
  615. list2: The second list to compare.
  616. msg: Optional message to use on failure instead of a list of
  617. differences.
  618. """
  619. self.assertSequenceEqual(list1, list2, msg, seq_type=list)
  620. def assertTupleEqual(self, tuple1, tuple2, msg=None):
  621. """A tuple-specific equality assertion.
  622. Args:
  623. tuple1: The first tuple to compare.
  624. tuple2: The second tuple to compare.
  625. msg: Optional message to use on failure instead of a list of
  626. differences.
  627. """
  628. self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
  629. def assertSetEqual(self, set1, set2, msg=None):
  630. """A set-specific equality assertion.
  631. Args:
  632. set1: The first set to compare.
  633. set2: The second set to compare.
  634. msg: Optional message to use on failure instead of a list of
  635. differences.
  636. assertSetEqual uses ducktyping to support different types of sets, and
  637. is optimized for sets specifically (parameters must support a
  638. difference method).
  639. """
  640. try:
  641. difference1 = set1.difference(set2)
  642. except TypeError, e:
  643. self.fail('invalid type when attempting set difference: %s' % e)
  644. except AttributeError, e:
  645. self.fail('first argument does not support set difference: %s' % e)
  646. try:
  647. difference2 = set2.difference(set1)
  648. except TypeError, e:
  649. self.fail('invalid type when attempting set difference: %s' % e)
  650. except AttributeError, e:
  651. self.fail('second argument does not support set difference: %s' % e)
  652. if not (difference1 or difference2):
  653. return
  654. lines = []
  655. if difference1:
  656. lines.append('Items in the first set but not the second:')
  657. for item in difference1:
  658. lines.append(repr(item))
  659. if difference2:
  660. lines.append('Items in the second set but not the first:')
  661. for item in difference2:
  662. lines.append(repr(item))
  663. standardMsg = '\n'.join(lines)
  664. self.fail(self._formatMessage(msg, standardMsg))
  665. def assertIn(self, member, container, msg=None):
  666. """Just like self.assertTrue(a in b), but with a nicer default message."""
  667. if member not in container:
  668. standardMsg = '%s not found in %s' % (safe_repr(member),
  669. safe_repr(container))
  670. self.fail(self._formatMessage(msg, standardMsg))
  671. def assertNotIn(self, member, container, msg=None):
  672. """Just like self.assertTrue(a not in b), but with a nicer default message."""
  673. if member in container:
  674. standardMsg = '%s unexpectedly found in %s' % (safe_repr(member),
  675. safe_repr(container))
  676. self.fail(self._formatMessage(msg, standardMsg))
  677. def assertIs(self, expr1, expr2, msg=None):
  678. """Just like self.assertTrue(a is b), but with a nicer default message."""
  679. if expr1 is not expr2:
  680. standardMsg = '%s is not %s' % (safe_repr(expr1),
  681. safe_repr(expr2))
  682. self.fail(self._formatMessage(msg, standardMsg))
  683. def assertIsNot(self, expr1, expr2, msg=None):
  684. """Just like self.assertTrue(a is not b), but with a nicer default message."""
  685. if expr1 is expr2:
  686. standardMsg = 'unexpectedly identical: %s' % (safe_repr(expr1),)
  687. self.fail(self._formatMessage(msg, standardMsg))
  688. def assertDictEqual(self, d1, d2, msg=None):
  689. self.assertIsInstance(d1, dict, 'First argument is not a dictionary')
  690. self.assertIsInstance(d2, dict, 'Second argument is not a dictionary')
  691. if d1 != d2:
  692. standardMsg = '%s != %s' % (safe_repr(d1, True), safe_repr(d2, True))
  693. diff = ('\n' + '\n'.join(difflib.ndiff(
  694. pprint.pformat(d1).splitlines(),
  695. pprint.pformat(d2).splitlines())))
  696. standardMsg = self._truncateMessage(standardMsg, diff)
  697. self.fail(self._formatMessage(msg, standardMsg))
  698. def assertDictContainsSubset(self, expected, actual, msg=None):
  699. """Checks whether actual is a superset of expected."""
  700. missing = []
  701. mismatched = []
  702. for key, value in expected.iteritems():
  703. if key not in actual:
  704. missing.append(key)
  705. elif value != actual[key]:
  706. mismatched.append('%s, expected: %s, actual: %s' %
  707. (safe_repr(key), safe_repr(value),
  708. safe_repr(actual[key])))
  709. if not (missing or mismatched):
  710. return
  711. standardMsg = ''
  712. if missing:
  713. standardMsg = 'Missing: %s' % ','.join(safe_repr(m) for m in
  714. missing)
  715. if mismatched:
  716. if standardMsg:
  717. standardMsg += '; '
  718. standardMsg += 'Mismatched values: %s' % ','.join(mismatched)
  719. self.fail(self._formatMessage(msg, standardMsg))
  720. def assertItemsEqual(self, expected_seq, actual_seq, msg=None):
  721. """An unordered sequence specific comparison. It asserts that
  722. actual_seq and expected_seq have the same element counts.
  723. Equivalent to::
  724. self.assertEqual(Counter(iter(actual_seq)),
  725. Counter(iter(expected_seq)))
  726. Asserts that each element has the same count in both sequences.
  727. Example:
  728. - [0, 1, 1] and [1, 0, 1] compare equal.
  729. - [0, 0, 1] and [0, 1] compare unequal.
  730. """
  731. first_seq, second_seq = list(actual_seq), list(expected_seq)
  732. with warnings.catch_warnings():
  733. if sys.py3kwarning:
  734. # Silence Py3k warning raised during the sorting
  735. for _msg in ["(code|dict|type) inequality comparisons",
  736. "builtin_function_or_method order comparisons",
  737. "comparing unequal types"]:
  738. warnings.filterwarnings("ignore", _msg, DeprecationWarning)
  739. try:
  740. first = collections.Counter(first_seq)
  741. second = collections.Counter(second_seq)
  742. except TypeError:
  743. # Handle case with unhashable elements
  744. differences = _count_diff_all_purpose(first_seq, second_seq)
  745. else:
  746. if first == second:
  747. return
  748. differences = _count_diff_hashable(first_seq, second_seq)
  749. if differences:
  750. standardMsg = 'Element counts were not equal:\n'
  751. lines = ['First has %d, Second has %d: %r' % diff for diff in differences]
  752. diffMsg = '\n'.join(lines)
  753. standardMsg = self._truncateMessage(standardMsg, diffMsg)
  754. msg = self._formatMessage(msg, standardMsg)
  755. self.fail(msg)
  756. def assertMultiLineEqual(self, first, second, msg=None):
  757. """Assert that two multi-line strings are equal."""
  758. self.assertIsInstance(first, basestring,
  759. 'First argument is not a string')
  760. self.assertIsInstance(second, basestring,
  761. 'Second argument is not a string')
  762. if first != second:
  763. # don't use difflib if the strings are too long
  764. if (len(first) > self._diffThreshold or
  765. len(second) > self._diffThreshold):
  766. self._baseAssertEqual(first, second, msg)
  767. firstlines = first.splitlines(True)
  768. secondlines = second.splitlines(True)
  769. if len(firstlines) == 1 and first.strip('\r\n') == first:
  770. firstlines = [first + '\n']
  771. secondlines = [second + '\n']
  772. standardMsg = '%s != %s' % (safe_repr(first, True),
  773. safe_repr(second, True))
  774. diff = '\n' + ''.join(difflib.ndiff(firstlines, secondlines))
  775. standardMsg = self._truncateMessage(standardMsg, diff)
  776. self.fail(self._formatMessage(msg, standardMsg))
  777. def assertLess(self, a, b, msg=None):
  778. """Just like self.assertTrue(a < b), but with a nicer default message."""
  779. if not a < b:
  780. standardMsg = '%s not less than %s' % (safe_repr(a), safe_repr(b))
  781. self.fail(self._formatMessage(msg, standardMsg))
  782. def assertLessEqual(self, a, b, msg=None):
  783. """Just like self.assertTrue(a <= b), but with a nicer default message."""
  784. if not a <= b:
  785. standardMsg = '%s not less than or equal to %s' % (safe_repr(a), safe_repr(b))
  786. self.fail(self._formatMessage(msg, standardMsg))
  787. def assertGreater(self, a, b, msg=None):
  788. """Just like self.assertTrue(a > b), but with a nicer default message."""
  789. if not a > b:
  790. standardMsg = '%s not greater than %s' % (safe_repr(a), safe_repr(b))
  791. self.fail(self._formatMessage(msg, standardMsg))
  792. def assertGreaterEqual(self, a, b, msg=None):
  793. """Just like self.assertTrue(a >= b), but with a nicer default message."""
  794. if not a >= b:
  795. standardMsg = '%s not greater than or equal to %s' % (safe_repr(a), safe_repr(b))
  796. self.fail(self._formatMessage(msg, standardMsg))
  797. def assertIsNone(self, obj, msg=None):
  798. """Same as self.assertTrue(obj is None), with a nicer default message."""
  799. if obj is not None:
  800. standardMsg = '%s is not None' % (safe_repr(obj),)
  801. self.fail(self._formatMessage(msg, standardMsg))
  802. def assertIsNotNone(self, obj, msg=None):
  803. """Included for symmetry with assertIsNone."""
  804. if obj is None:
  805. standardMsg = 'unexpectedly None'
  806. self.fail(self._formatMessage(msg, standardMsg))
  807. def assertIsInstance(self, obj, cls, msg=None):
  808. """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
  809. default message."""
  810. if not isinstance(obj, cls):
  811. standardMsg = '%s is not an instance of %r' % (safe_repr(obj), cls)
  812. self.fail(self._formatMessage(msg, standardMsg))
  813. def assertNotIsInstance(self, obj, cls, msg=None):
  814. """Included for symmetry with assertIsInstance."""
  815. if isinstance(obj, cls):
  816. standardMsg = '%s is an instance of %r' % (safe_repr(obj), cls)
  817. self.fail(self._formatMessage(msg, standardMsg))
  818. def assertRaisesRegexp(self, expected_exception, expected_regexp,
  819. callable_obj=None, *args, **kwargs):
  820. """Asserts that the message in a raised exception matches a regexp.
  821. Args:
  822. expected_exception: Exception class expected to be raised.
  823. expected_regexp: Regexp (re pattern object or string) expected
  824. to be found in error message.
  825. callable_obj: Function to be called.
  826. args: Extra args.
  827. kwargs: Extra kwargs.
  828. """
  829. context = _AssertRaisesContext(expected_exception, self, expected_regexp)
  830. if callable_obj is None:
  831. return context
  832. with context:
  833. callable_obj(*args, **kwargs)
  834. def assertRegexpMatches(self, text, expected_regexp, msg=None):
  835. """Fail the test unless the text matches the regular expression."""
  836. if isinstance(expected_regexp, basestring):
  837. expected_regexp = re.compile(expected_regexp)
  838. if not expected_regexp.search(text):
  839. msg = msg or "Regexp didn't match"
  840. msg = '%s: %r not found in %r' % (msg, expected_regexp.pattern, text)
  841. raise self.failureException(msg)
  842. def assertNotRegexpMatches(self, text, unexpected_regexp, msg=None):
  843. """Fail the test if the text matches the regular expression."""
  844. if isinstance(unexpected_regexp, basestring):
  845. unexpected_regexp = re.compile(unexpected_regexp)
  846. match = unexpected_regexp.search(text)
  847. if match:
  848. msg = msg or "Regexp matched"
  849. msg = '%s: %r matches %r in %r' % (msg,
  850. text[match.start():match.end()],
  851. unexpected_regexp.pattern,
  852. text)
  853. raise self.failureException(msg)
  854. class FunctionTestCase(TestCase):
  855. """A test case that wraps a test function.
  856. This is useful for slipping pre-existing test functions into the
  857. unittest framework. Optionally, set-up and tidy-up functions can be
  858. supplied. As with TestCase, the tidy-up ('tearDown') function will
  859. always be called if the set-up ('setUp') function ran successfully.
  860. """
  861. def __init__(self, testFunc, setUp=None, tearDown=None, description=None):
  862. super(FunctionTestCase, self).__init__()
  863. self._setUpFunc = setUp
  864. self._tearDownFunc = tearDown
  865. self._testFunc = testFunc
  866. self._description = description
  867. def setUp(self):
  868. if self._setUpFunc is not None:
  869. self._setUpFunc()
  870. def tearDown(self):
  871. if self._tearDownFunc is not None:
  872. self._tearDownFunc()
  873. def runTest(self):
  874. self._testFunc()
  875. def id(self):
  876. return self._testFunc.__name__
  877. def __eq__(self, other):
  878. if not isinstance(other, self.__class__):
  879. return NotImplemented
  880. return self._setUpFunc == other._setUpFunc and \
  881. self._tearDownFunc == other._tearDownFunc and \
  882. self._testFunc == other._testFunc and \
  883. self._description == other._description
  884. def __ne__(self, other):
  885. return not self == other
  886. def __hash__(self):
  887. return hash((type(self), self._setUpFunc, self._tearDownFunc,
  888. self._testFunc, self._description))
  889. def __str__(self):
  890. return "%s (%s)" % (strclass(self.__class__),
  891. self._testFunc.__name__)
  892. def __repr__(self):
  893. return "<%s tec=%s>" % (strclass(self.__class__),
  894. self._testFunc)
  895. def shortDescription(self):
  896. if self._description is not None:
  897. return self._description
  898. doc = self._testFunc.__doc__
  899. return doc and doc.split("\n")[0].strip() or None