case.py 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  1. """Test case implementation"""
  2. import collections
  3. import sys
  4. import functools
  5. import difflib
  6. import pprint
  7. import re
  8. import types
  9. import warnings
  10. from . import result
  11. from .util import (
  12. strclass, safe_repr, unorderable_list_difference,
  13. _count_diff_all_purpose, _count_diff_hashable
  14. )
  15. __unittest = True
  16. DIFF_OMITTED = ('\nDiff is %s characters long. '
  17. 'Set self.maxDiff to None to see it.')
  18. class SkipTest(Exception):
  19. """
  20. Raise this exception in a test to skip it.
  21. Usually you can use TestCase.skipTest() or one of the skipping decorators
  22. instead of raising this directly.
  23. """
  24. pass
  25. class _ExpectedFailure(Exception):
  26. """
  27. Raise this when a test is expected to fail.
  28. This is an implementation detail.
  29. """
  30. def __init__(self, exc_info):
  31. super(_ExpectedFailure, self).__init__()
  32. self.exc_info = exc_info
  33. class _UnexpectedSuccess(Exception):
  34. """
  35. The test was supposed to fail, but it didn't!
  36. """
  37. pass
  38. def _id(obj):
  39. return obj
  40. def skip(reason):
  41. """
  42. Unconditionally skip a test.
  43. """
  44. def decorator(test_item):
  45. if not isinstance(test_item, (type, types.ClassType)):
  46. @functools.wraps(test_item)
  47. def skip_wrapper(*args, **kwargs):
  48. raise SkipTest(reason)
  49. test_item = skip_wrapper
  50. test_item.__unittest_skip__ = True
  51. test_item.__unittest_skip_why__ = reason
  52. return test_item
  53. return decorator
  54. def skipIf(condition, reason):
  55. """
  56. Skip a test if the condition is true.
  57. """
  58. if condition:
  59. return skip(reason)
  60. return _id
  61. def skipUnless(condition, reason):
  62. """
  63. Skip a test unless the condition is true.
  64. """
  65. if not condition:
  66. return skip(reason)
  67. return _id
  68. def expectedFailure(func):
  69. @functools.wraps(func)
  70. def wrapper(*args, **kwargs):
  71. try:
  72. func(*args, **kwargs)
  73. except Exception:
  74. raise _ExpectedFailure(sys.exc_info())
  75. raise _UnexpectedSuccess
  76. return wrapper
  77. class _AssertRaisesContext(object):
  78. """A context manager used to implement TestCase.assertRaises* methods."""
  79. def __init__(self, expected, test_case, expected_regexp=None):
  80. self.expected = expected
  81. self.failureException = test_case.failureException
  82. self.expected_regexp = expected_regexp
  83. def __enter__(self):
  84. return self
  85. def __exit__(self, exc_type, exc_value, tb):
  86. if exc_type is None:
  87. try:
  88. exc_name = self.expected.__name__
  89. except AttributeError:
  90. exc_name = str(self.expected)
  91. raise self.failureException(
  92. "{0} not raised".format(exc_name))
  93. if not issubclass(exc_type, self.expected):
  94. # let unexpected exceptions pass through
  95. return False
  96. self.exception = exc_value # store for later retrieval
  97. if self.expected_regexp is None:
  98. return True
  99. expected_regexp = self.expected_regexp
  100. if not expected_regexp.search(str(exc_value)):
  101. raise self.failureException('"%s" does not match "%s"' %
  102. (expected_regexp.pattern, str(exc_value)))
  103. return True
  104. class TestCase(object):
  105. """A class whose instances are single test cases.
  106. By default, the test code itself should be placed in a method named
  107. 'runTest'.
  108. If the fixture may be used for many test cases, create as
  109. many test methods as are needed. When instantiating such a TestCase
  110. subclass, specify in the constructor arguments the name of the test method
  111. that the instance is to execute.
  112. Test authors should subclass TestCase for their own tests. Construction
  113. and deconstruction of the test's environment ('fixture') can be
  114. implemented by overriding the 'setUp' and 'tearDown' methods respectively.
  115. If it is necessary to override the __init__ method, the base class
  116. __init__ method must always be called. It is important that subclasses
  117. should not change the signature of their __init__ method, since instances
  118. of the classes are instantiated automatically by parts of the framework
  119. in order to be run.
  120. When subclassing TestCase, you can set these attributes:
  121. * failureException: determines which exception will be raised when
  122. the instance's assertion methods fail; test methods raising this
  123. exception will be deemed to have 'failed' rather than 'errored'.
  124. * longMessage: determines whether long messages (including repr of
  125. objects used in assert methods) will be printed on failure in *addition*
  126. to any explicit message passed.
  127. * maxDiff: sets the maximum length of a diff in failure messages
  128. by assert methods using difflib. It is looked up as an instance
  129. attribute so can be configured by individual tests if required.
  130. """
  131. failureException = AssertionError
  132. longMessage = False
  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. try:
  163. self.addTypeEqualityFunc(unicode, 'assertMultiLineEqual')
  164. except NameError:
  165. # No unicode support in this build
  166. pass
  167. def addTypeEqualityFunc(self, typeobj, function):
  168. """Add a type specific assertEqual style function to compare a type.
  169. This method is for use by TestCase subclasses that need to register
  170. their own type equality functions to provide nicer error messages.
  171. Args:
  172. typeobj: The data type to call this function on when both values
  173. are of the same type in assertEqual().
  174. function: The callable taking two arguments and an optional
  175. msg= argument that raises self.failureException with a
  176. useful error message when the two arguments are not equal.
  177. """
  178. self._type_equality_funcs[typeobj] = function
  179. def addCleanup(self, function, *args, **kwargs):
  180. """Add a function, with arguments, to be called when the test is
  181. completed. Functions added are called on a LIFO basis and are
  182. called after tearDown on test failure or success.
  183. Cleanup items are called even if setUp fails (unlike tearDown)."""
  184. self._cleanups.append((function, args, kwargs))
  185. def setUp(self):
  186. "Hook method for setting up the test fixture before exercising it."
  187. pass
  188. def tearDown(self):
  189. "Hook method for deconstructing the test fixture after testing it."
  190. pass
  191. @classmethod
  192. def setUpClass(cls):
  193. "Hook method for setting up class fixture before running tests in the class."
  194. @classmethod
  195. def tearDownClass(cls):
  196. "Hook method for deconstructing the class fixture after running all tests in the class."
  197. def countTestCases(self):
  198. return 1
  199. def defaultTestResult(self):
  200. return result.TestResult()
  201. def shortDescription(self):
  202. """Returns a one-line description of the test, or None if no
  203. description has been provided.
  204. The default implementation of this method returns the first line of
  205. the specified test method's docstring.
  206. """
  207. doc = self._testMethodDoc
  208. return doc and doc.split("\n")[0].strip() or None
  209. def id(self):
  210. return "%s.%s" % (strclass(self.__class__), self._testMethodName)
  211. def __eq__(self, other):
  212. if type(self) is not type(other):
  213. return NotImplemented
  214. return self._testMethodName == other._testMethodName
  215. def __ne__(self, other):
  216. return not self == other
  217. def __hash__(self):
  218. return hash((type(self), self._testMethodName))
  219. def __str__(self):
  220. return "%s (%s)" % (self._testMethodName, strclass(self.__class__))
  221. def __repr__(self):
  222. return "<%s testMethod=%s>" % \
  223. (strclass(self.__class__), self._testMethodName)
  224. def _addSkip(self, result, reason):
  225. addSkip = getattr(result, 'addSkip', None)
  226. if addSkip is not None:
  227. addSkip(self, reason)
  228. else:
  229. warnings.warn("TestResult has no addSkip method, skips not reported",
  230. RuntimeWarning, 2)
  231. result.addSuccess(self)
  232. def run(self, result=None):
  233. orig_result = result
  234. if result is None:
  235. result = self.defaultTestResult()
  236. startTestRun = getattr(result, 'startTestRun', None)
  237. if startTestRun is not None:
  238. startTestRun()
  239. self._resultForDoCleanups = result
  240. result.startTest(self)
  241. testMethod = getattr(self, self._testMethodName)
  242. if (getattr(self.__class__, "__unittest_skip__", False) or
  243. getattr(testMethod, "__unittest_skip__", False)):
  244. # If the class or method was skipped.
  245. try:
  246. skip_why = (getattr(self.__class__, '__unittest_skip_why__', '')
  247. or getattr(testMethod, '__unittest_skip_why__', ''))
  248. self._addSkip(result, skip_why)
  249. finally:
  250. result.stopTest(self)
  251. return
  252. try:
  253. success = False
  254. try:
  255. self.setUp()
  256. except SkipTest as e:
  257. self._addSkip(result, str(e))
  258. except KeyboardInterrupt:
  259. raise
  260. except:
  261. result.addError(self, sys.exc_info())
  262. else:
  263. try:
  264. testMethod()
  265. except KeyboardInterrupt:
  266. raise
  267. except self.failureException:
  268. result.addFailure(self, sys.exc_info())
  269. except _ExpectedFailure as e:
  270. addExpectedFailure = getattr(result, 'addExpectedFailure', None)
  271. if addExpectedFailure is not None:
  272. addExpectedFailure(self, e.exc_info)
  273. else:
  274. warnings.warn("TestResult has no addExpectedFailure method, reporting as passes",
  275. RuntimeWarning)
  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("TestResult has no addUnexpectedSuccess method, reporting as failures",
  283. RuntimeWarning)
  284. result.addFailure(self, sys.exc_info())
  285. except SkipTest as e:
  286. self._addSkip(result, str(e))
  287. except:
  288. result.addError(self, sys.exc_info())
  289. else:
  290. success = True
  291. try:
  292. self.tearDown()
  293. except KeyboardInterrupt:
  294. raise
  295. except:
  296. result.addError(self, sys.exc_info())
  297. success = False
  298. cleanUpSuccess = self.doCleanups()
  299. success = success and cleanUpSuccess
  300. if success:
  301. result.addSuccess(self)
  302. finally:
  303. result.stopTest(self)
  304. if orig_result is None:
  305. stopTestRun = getattr(result, 'stopTestRun', None)
  306. if stopTestRun is not None:
  307. stopTestRun()
  308. def doCleanups(self):
  309. """Execute all cleanup functions. Normally called for you after
  310. tearDown."""
  311. result = self._resultForDoCleanups
  312. ok = True
  313. while self._cleanups:
  314. function, args, kwargs = self._cleanups.pop(-1)
  315. try:
  316. function(*args, **kwargs)
  317. except KeyboardInterrupt:
  318. raise
  319. except:
  320. ok = False
  321. result.addError(self, sys.exc_info())
  322. return ok
  323. def __call__(self, *args, **kwds):
  324. return self.run(*args, **kwds)
  325. def debug(self):
  326. """Run the test without collecting errors in a TestResult"""
  327. self.setUp()
  328. getattr(self, self._testMethodName)()
  329. self.tearDown()
  330. while self._cleanups:
  331. function, args, kwargs = self._cleanups.pop(-1)
  332. function(*args, **kwargs)
  333. def skipTest(self, reason):
  334. """Skip this test."""
  335. raise SkipTest(reason)
  336. def fail(self, msg=None):
  337. """Fail immediately, with the given message."""
  338. raise self.failureException(msg)
  339. def assertFalse(self, expr, msg=None):
  340. """Check that the expression is false."""
  341. if expr:
  342. msg = self._formatMessage(msg, "%s is not false" % safe_repr(expr))
  343. raise self.failureException(msg)
  344. def assertTrue(self, expr, msg=None):
  345. """Check that the expression is true."""
  346. if not expr:
  347. msg = self._formatMessage(msg, "%s is not true" % safe_repr(expr))
  348. raise self.failureException(msg)
  349. def _formatMessage(self, msg, standardMsg):
  350. """Honour the longMessage attribute when generating failure messages.
  351. If longMessage is False this means:
  352. * Use only an explicit message if it is provided
  353. * Otherwise use the standard message for the assert
  354. If longMessage is True:
  355. * Use the standard message
  356. * If an explicit message is provided, plus ' : ' and the explicit message
  357. """
  358. if not self.longMessage:
  359. return msg or standardMsg
  360. if msg is None:
  361. return standardMsg
  362. try:
  363. # don't switch to '{}' formatting in Python 2.X
  364. # it changes the way unicode input is handled
  365. return '%s : %s' % (standardMsg, msg)
  366. except UnicodeDecodeError:
  367. return '%s : %s' % (safe_repr(standardMsg), safe_repr(msg))
  368. def assertRaises(self, excClass, callableObj=None, *args, **kwargs):
  369. """Fail unless an exception of class excClass is raised
  370. by callableObj when invoked with arguments args and keyword
  371. arguments kwargs. If a different type of exception is
  372. raised, it will not be caught, and the test case will be
  373. deemed to have suffered an error, exactly as for an
  374. unexpected exception.
  375. If called with callableObj omitted or None, will return a
  376. context object used like this::
  377. with self.assertRaises(SomeException):
  378. do_something()
  379. The context manager keeps a reference to the exception as
  380. the 'exception' attribute. This allows you to inspect the
  381. exception after the assertion::
  382. with self.assertRaises(SomeException) as cm:
  383. do_something()
  384. the_exception = cm.exception
  385. self.assertEqual(the_exception.error_code, 3)
  386. """
  387. context = _AssertRaisesContext(excClass, self)
  388. if callableObj is None:
  389. return context
  390. with context:
  391. callableObj(*args, **kwargs)
  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. if isinstance(asserter, basestring):
  412. asserter = getattr(self, asserter)
  413. return asserter
  414. return self._baseAssertEqual
  415. def _baseAssertEqual(self, first, second, msg=None):
  416. """The default assertEqual implementation, not type specific."""
  417. if not first == second:
  418. standardMsg = '%s != %s' % (safe_repr(first), safe_repr(second))
  419. msg = self._formatMessage(msg, standardMsg)
  420. raise self.failureException(msg)
  421. def assertEqual(self, first, second, msg=None):
  422. """Fail if the two objects are unequal as determined by the '=='
  423. operator.
  424. """
  425. assertion_func = self._getAssertEqualityFunc(first, second)
  426. assertion_func(first, second, msg=msg)
  427. def assertNotEqual(self, first, second, msg=None):
  428. """Fail if the two objects are equal as determined by the '!='
  429. operator.
  430. """
  431. if not first != second:
  432. msg = self._formatMessage(msg, '%s == %s' % (safe_repr(first),
  433. safe_repr(second)))
  434. raise self.failureException(msg)
  435. def assertAlmostEqual(self, first, second, places=None, msg=None, delta=None):
  436. """Fail if the two objects are unequal as determined by their
  437. difference rounded to the given number of decimal places
  438. (default 7) and comparing to zero, or by comparing that the
  439. between the two objects is more than the given delta.
  440. Note that decimal places (from zero) are usually not the same
  441. as significant digits (measured from the most signficant digit).
  442. If the two objects compare equal then they will automatically
  443. compare almost equal.
  444. """
  445. if first == second:
  446. # shortcut
  447. return
  448. if delta is not None and places is not None:
  449. raise TypeError("specify delta or places not both")
  450. if delta is not None:
  451. if abs(first - second) <= delta:
  452. return
  453. standardMsg = '%s != %s within %s delta' % (safe_repr(first),
  454. safe_repr(second),
  455. safe_repr(delta))
  456. else:
  457. if places is None:
  458. places = 7
  459. if round(abs(second-first), places) == 0:
  460. return
  461. standardMsg = '%s != %s within %r places' % (safe_repr(first),
  462. safe_repr(second),
  463. places)
  464. msg = self._formatMessage(msg, standardMsg)
  465. raise self.failureException(msg)
  466. def assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None):
  467. """Fail if the two objects are equal as determined by their
  468. difference rounded to the given number of decimal places
  469. (default 7) and comparing to zero, or by comparing that the
  470. between the two objects is less than the given delta.
  471. Note that decimal places (from zero) are usually not the same
  472. as significant digits (measured from the most signficant digit).
  473. Objects that are equal automatically fail.
  474. """
  475. if delta is not None and places is not None:
  476. raise TypeError("specify delta or places not both")
  477. if delta is not None:
  478. if not (first == second) and abs(first - second) > delta:
  479. return
  480. standardMsg = '%s == %s within %s delta' % (safe_repr(first),
  481. safe_repr(second),
  482. safe_repr(delta))
  483. else:
  484. if places is None:
  485. places = 7
  486. if not (first == second) and round(abs(second-first), places) != 0:
  487. return
  488. standardMsg = '%s == %s within %r places' % (safe_repr(first),
  489. safe_repr(second),
  490. places)
  491. msg = self._formatMessage(msg, standardMsg)
  492. raise self.failureException(msg)
  493. # Synonyms for assertion methods
  494. # The plurals are undocumented. Keep them that way to discourage use.
  495. # Do not add more. Do not remove.
  496. # Going through a deprecation cycle on these would annoy many people.
  497. assertEquals = assertEqual
  498. assertNotEquals = assertNotEqual
  499. assertAlmostEquals = assertAlmostEqual
  500. assertNotAlmostEquals = assertNotAlmostEqual
  501. assert_ = assertTrue
  502. # These fail* assertion method names are pending deprecation and will
  503. # be a DeprecationWarning in 3.2; http://bugs.python.org/issue2578
  504. def _deprecate(original_func):
  505. def deprecated_func(*args, **kwargs):
  506. warnings.warn(
  507. 'Please use {0} instead.'.format(original_func.__name__),
  508. PendingDeprecationWarning, 2)
  509. return original_func(*args, **kwargs)
  510. return deprecated_func
  511. failUnlessEqual = _deprecate(assertEqual)
  512. failIfEqual = _deprecate(assertNotEqual)
  513. failUnlessAlmostEqual = _deprecate(assertAlmostEqual)
  514. failIfAlmostEqual = _deprecate(assertNotAlmostEqual)
  515. failUnless = _deprecate(assertTrue)
  516. failUnlessRaises = _deprecate(assertRaises)
  517. failIf = _deprecate(assertFalse)
  518. def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
  519. """An equality assertion for ordered sequences (like lists and tuples).
  520. For the purposes of this function, a valid ordered sequence type is one
  521. which can be indexed, has a length, and has an equality operator.
  522. Args:
  523. seq1: The first sequence to compare.
  524. seq2: The second sequence to compare.
  525. seq_type: The expected datatype of the sequences, or None if no
  526. datatype should be enforced.
  527. msg: Optional message to use on failure instead of a list of
  528. differences.
  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 = safe_repr(seq1)
  556. seq2_repr = safe_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, safe_repr(item1), safe_repr(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, safe_repr(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, safe_repr(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 different types of sets, and
  641. is optimized for sets specifically (parameters must support a
  642. 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),
  685. safe_repr(expr2))
  686. self.fail(self._formatMessage(msg, standardMsg))
  687. def assertIsNot(self, expr1, expr2, msg=None):
  688. """Just like self.assertTrue(a is not b), but with a nicer default message."""
  689. if expr1 is expr2:
  690. standardMsg = 'unexpectedly identical: %s' % (safe_repr(expr1),)
  691. self.fail(self._formatMessage(msg, standardMsg))
  692. def assertDictEqual(self, d1, d2, msg=None):
  693. self.assertIsInstance(d1, dict, 'First argument is not a dictionary')
  694. self.assertIsInstance(d2, dict, 'Second argument is not a dictionary')
  695. if d1 != d2:
  696. standardMsg = '%s != %s' % (safe_repr(d1, True), safe_repr(d2, True))
  697. diff = ('\n' + '\n'.join(difflib.ndiff(
  698. pprint.pformat(d1).splitlines(),
  699. pprint.pformat(d2).splitlines())))
  700. standardMsg = self._truncateMessage(standardMsg, diff)
  701. self.fail(self._formatMessage(msg, standardMsg))
  702. def assertDictContainsSubset(self, expected, actual, msg=None):
  703. """Checks whether actual is a superset of expected."""
  704. missing = []
  705. mismatched = []
  706. for key, value in expected.iteritems():
  707. if key not in actual:
  708. missing.append(key)
  709. elif value != actual[key]:
  710. mismatched.append('%s, expected: %s, actual: %s' %
  711. (safe_repr(key), safe_repr(value),
  712. safe_repr(actual[key])))
  713. if not (missing or mismatched):
  714. return
  715. standardMsg = ''
  716. if missing:
  717. standardMsg = 'Missing: %s' % ','.join(safe_repr(m) for m in
  718. missing)
  719. if mismatched:
  720. if standardMsg:
  721. standardMsg += '; '
  722. standardMsg += 'Mismatched values: %s' % ','.join(mismatched)
  723. self.fail(self._formatMessage(msg, standardMsg))
  724. def assertItemsEqual(self, expected_seq, actual_seq, msg=None):
  725. """An unordered sequence specific comparison. It asserts that
  726. actual_seq and expected_seq have the same element counts.
  727. Equivalent to::
  728. self.assertEqual(Counter(iter(actual_seq)),
  729. Counter(iter(expected_seq)))
  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. first_seq, second_seq = list(expected_seq), list(actual_seq)
  736. with warnings.catch_warnings():
  737. if sys.py3kwarning:
  738. # Silence Py3k warning raised during the sorting
  739. for _msg in ["(code|dict|type) inequality comparisons",
  740. "builtin_function_or_method order comparisons",
  741. "comparing unequal types"]:
  742. warnings.filterwarnings("ignore", _msg, DeprecationWarning)
  743. try:
  744. first = collections.Counter(first_seq)
  745. second = collections.Counter(second_seq)
  746. except TypeError:
  747. # Handle case with unhashable elements
  748. differences = _count_diff_all_purpose(first_seq, second_seq)
  749. else:
  750. if first == second:
  751. return
  752. differences = _count_diff_hashable(first_seq, second_seq)
  753. if differences:
  754. standardMsg = 'Element counts were not equal:\n'
  755. lines = ['First has %d, Second has %d: %r' % diff for diff in differences]
  756. diffMsg = '\n'.join(lines)
  757. standardMsg = self._truncateMessage(standardMsg, diffMsg)
  758. msg = self._formatMessage(msg, standardMsg)
  759. self.fail(msg)
  760. def assertMultiLineEqual(self, first, second, msg=None):
  761. """Assert that two multi-line strings are equal."""
  762. self.assertIsInstance(first, basestring,
  763. 'First argument is not a string')
  764. self.assertIsInstance(second, basestring,
  765. 'Second argument is not a string')
  766. if first != second:
  767. # don't use difflib if the strings are too long
  768. if (len(first) > self._diffThreshold or
  769. len(second) > self._diffThreshold):
  770. self._baseAssertEqual(first, second, msg)
  771. firstlines = first.splitlines(True)
  772. secondlines = second.splitlines(True)
  773. if len(firstlines) == 1 and first.strip('\r\n') == first:
  774. firstlines = [first + '\n']
  775. secondlines = [second + '\n']
  776. standardMsg = '%s != %s' % (safe_repr(first, True),
  777. safe_repr(second, True))
  778. diff = '\n' + ''.join(difflib.ndiff(firstlines, secondlines))
  779. standardMsg = self._truncateMessage(standardMsg, diff)
  780. self.fail(self._formatMessage(msg, standardMsg))
  781. def assertLess(self, a, b, msg=None):
  782. """Just like self.assertTrue(a < b), but with a nicer default message."""
  783. if not a < b:
  784. standardMsg = '%s not less than %s' % (safe_repr(a), safe_repr(b))
  785. self.fail(self._formatMessage(msg, standardMsg))
  786. def assertLessEqual(self, a, b, msg=None):
  787. """Just like self.assertTrue(a <= b), but with a nicer default message."""
  788. if not a <= b:
  789. standardMsg = '%s not less than or equal to %s' % (safe_repr(a), safe_repr(b))
  790. self.fail(self._formatMessage(msg, standardMsg))
  791. def assertGreater(self, a, b, msg=None):
  792. """Just like self.assertTrue(a > b), but with a nicer default message."""
  793. if not a > b:
  794. standardMsg = '%s not greater than %s' % (safe_repr(a), safe_repr(b))
  795. self.fail(self._formatMessage(msg, standardMsg))
  796. def assertGreaterEqual(self, a, b, msg=None):
  797. """Just like self.assertTrue(a >= b), but with a nicer default message."""
  798. if not a >= b:
  799. standardMsg = '%s not greater than or equal to %s' % (safe_repr(a), safe_repr(b))
  800. self.fail(self._formatMessage(msg, standardMsg))
  801. def assertIsNone(self, obj, msg=None):
  802. """Same as self.assertTrue(obj is None), with a nicer default message."""
  803. if obj is not None:
  804. standardMsg = '%s is not None' % (safe_repr(obj),)
  805. self.fail(self._formatMessage(msg, standardMsg))
  806. def assertIsNotNone(self, obj, msg=None):
  807. """Included for symmetry with assertIsNone."""
  808. if obj is None:
  809. standardMsg = 'unexpectedly None'
  810. self.fail(self._formatMessage(msg, standardMsg))
  811. def assertIsInstance(self, obj, cls, msg=None):
  812. """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
  813. default message."""
  814. if not isinstance(obj, cls):
  815. standardMsg = '%s is not an instance of %r' % (safe_repr(obj), cls)
  816. self.fail(self._formatMessage(msg, standardMsg))
  817. def assertNotIsInstance(self, obj, cls, msg=None):
  818. """Included for symmetry with assertIsInstance."""
  819. if isinstance(obj, cls):
  820. standardMsg = '%s is an instance of %r' % (safe_repr(obj), cls)
  821. self.fail(self._formatMessage(msg, standardMsg))
  822. def assertRaisesRegexp(self, expected_exception, expected_regexp,
  823. callable_obj=None, *args, **kwargs):
  824. """Asserts that the message in a raised exception matches a regexp.
  825. Args:
  826. expected_exception: Exception class expected to be raised.
  827. expected_regexp: Regexp (re pattern object or string) expected
  828. to be found in error message.
  829. callable_obj: Function to be called.
  830. args: Extra args.
  831. kwargs: Extra kwargs.
  832. """
  833. if expected_regexp is not None:
  834. expected_regexp = re.compile(expected_regexp)
  835. context = _AssertRaisesContext(expected_exception, self, expected_regexp)
  836. if callable_obj is None:
  837. return context
  838. with context:
  839. callable_obj(*args, **kwargs)
  840. def assertRegexpMatches(self, text, expected_regexp, msg=None):
  841. """Fail the test unless the text matches the regular expression."""
  842. if isinstance(expected_regexp, basestring):
  843. expected_regexp = re.compile(expected_regexp)
  844. if not expected_regexp.search(text):
  845. msg = msg or "Regexp didn't match"
  846. msg = '%s: %r not found in %r' % (msg, expected_regexp.pattern, text)
  847. raise self.failureException(msg)
  848. def assertNotRegexpMatches(self, text, unexpected_regexp, msg=None):
  849. """Fail the test if the text matches the regular expression."""
  850. if isinstance(unexpected_regexp, basestring):
  851. unexpected_regexp = re.compile(unexpected_regexp)
  852. match = unexpected_regexp.search(text)
  853. if match:
  854. msg = msg or "Regexp matched"
  855. msg = '%s: %r matches %r in %r' % (msg,
  856. text[match.start():match.end()],
  857. unexpected_regexp.pattern,
  858. text)
  859. raise self.failureException(msg)
  860. class FunctionTestCase(TestCase):
  861. """A test case that wraps a test function.
  862. This is useful for slipping pre-existing test functions into the
  863. unittest framework. Optionally, set-up and tidy-up functions can be
  864. supplied. As with TestCase, the tidy-up ('tearDown') function will
  865. always be called if the set-up ('setUp') function ran successfully.
  866. """
  867. def __init__(self, testFunc, setUp=None, tearDown=None, description=None):
  868. super(FunctionTestCase, self).__init__()
  869. self._setUpFunc = setUp
  870. self._tearDownFunc = tearDown
  871. self._testFunc = testFunc
  872. self._description = description
  873. def setUp(self):
  874. if self._setUpFunc is not None:
  875. self._setUpFunc()
  876. def tearDown(self):
  877. if self._tearDownFunc is not None:
  878. self._tearDownFunc()
  879. def runTest(self):
  880. self._testFunc()
  881. def id(self):
  882. return self._testFunc.__name__
  883. def __eq__(self, other):
  884. if not isinstance(other, self.__class__):
  885. return NotImplemented
  886. return self._setUpFunc == other._setUpFunc and \
  887. self._tearDownFunc == other._tearDownFunc and \
  888. self._testFunc == other._testFunc and \
  889. self._description == other._description
  890. def __ne__(self, other):
  891. return not self == other
  892. def __hash__(self):
  893. return hash((type(self), self._setUpFunc, self._tearDownFunc,
  894. self._testFunc, self._description))
  895. def __str__(self):
  896. return "%s (%s)" % (strclass(self.__class__),
  897. self._testFunc.__name__)
  898. def __repr__(self):
  899. return "<%s tec=%s>" % (strclass(self.__class__),
  900. self._testFunc)
  901. def shortDescription(self):
  902. if self._description is not None:
  903. return self._description
  904. doc = self._testFunc.__doc__
  905. return doc and doc.split("\n")[0].strip() or None