PageRenderTime 25ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/python/lib/Lib/site-packages/django/utils/unittest/case.py

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