blob: 644fe5b5c5a8e37fa12f4db54f1145436cfe3bf9 [file] [log] [blame]
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001"""Test case implementation"""
2
Michael Foorde6e0e262010-12-19 15:52:56 +00003import collections
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00004import sys
5import functools
6import difflib
7import pprint
8import re
Antoine Pitrou38153162012-04-25 17:31:12 +02009import types
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +000010import warnings
11
Michael Foord225a0992010-02-18 20:30:09 +000012from . import result
Michael Foord98e7b762010-03-20 03:00:34 +000013from .util import (
Michael Foord4c9e91a2011-03-16 20:34:53 -040014 strclass, safe_repr, unorderable_list_difference,
15 _count_diff_all_purpose, _count_diff_hashable
Michael Foord98e7b762010-03-20 03:00:34 +000016)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +000017
Michael Foord4c9e91a2011-03-16 20:34:53 -040018
Michael Foordb1aa30f2010-03-22 00:06:30 +000019__unittest = True
Michael Foordb1aa30f2010-03-22 00:06:30 +000020
Michael Foord5fe21ff2010-06-05 13:38:16 +000021
22DIFF_OMITTED = ('\nDiff is %s characters long. '
23 'Set self.maxDiff to None to see it.')
24
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +000025class SkipTest(Exception):
26 """
27 Raise this exception in a test to skip it.
28
Ezio Melotti352def02013-03-27 20:11:55 +020029 Usually you can use TestCase.skipTest() or one of the skipping decorators
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +000030 instead of raising this directly.
31 """
32 pass
33
34class _ExpectedFailure(Exception):
35 """
36 Raise this when a test is expected to fail.
37
38 This is an implementation detail.
39 """
40
41 def __init__(self, exc_info):
42 super(_ExpectedFailure, self).__init__()
43 self.exc_info = exc_info
44
45class _UnexpectedSuccess(Exception):
46 """
47 The test was supposed to fail, but it didn't!
48 """
49 pass
50
51def _id(obj):
52 return obj
53
54def skip(reason):
55 """
56 Unconditionally skip a test.
57 """
58 def decorator(test_item):
Antoine Pitrou38153162012-04-25 17:31:12 +020059 if not isinstance(test_item, (type, types.ClassType)):
Michael Foord53e8eea2010-03-07 20:22:12 +000060 @functools.wraps(test_item)
61 def skip_wrapper(*args, **kwargs):
62 raise SkipTest(reason)
63 test_item = skip_wrapper
64
65 test_item.__unittest_skip__ = True
66 test_item.__unittest_skip_why__ = reason
67 return test_item
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +000068 return decorator
69
70def skipIf(condition, reason):
71 """
72 Skip a test if the condition is true.
73 """
74 if condition:
75 return skip(reason)
76 return _id
77
78def skipUnless(condition, reason):
79 """
80 Skip a test unless the condition is true.
81 """
82 if not condition:
83 return skip(reason)
84 return _id
85
86
87def expectedFailure(func):
88 @functools.wraps(func)
89 def wrapper(*args, **kwargs):
90 try:
91 func(*args, **kwargs)
92 except Exception:
93 raise _ExpectedFailure(sys.exc_info())
94 raise _UnexpectedSuccess
95 return wrapper
96
97
98class _AssertRaisesContext(object):
99 """A context manager used to implement TestCase.assertRaises* methods."""
100
101 def __init__(self, expected, test_case, expected_regexp=None):
102 self.expected = expected
103 self.failureException = test_case.failureException
Georg Brandlb0eb4d32010-02-07 11:34:15 +0000104 self.expected_regexp = expected_regexp
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000105
106 def __enter__(self):
Michael Foord2bd52dc2010-02-07 18:44:12 +0000107 return self
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000108
109 def __exit__(self, exc_type, exc_value, tb):
110 if exc_type is None:
111 try:
112 exc_name = self.expected.__name__
113 except AttributeError:
114 exc_name = str(self.expected)
115 raise self.failureException(
116 "{0} not raised".format(exc_name))
117 if not issubclass(exc_type, self.expected):
118 # let unexpected exceptions pass through
119 return False
Georg Brandldc3694b2010-02-07 17:02:22 +0000120 self.exception = exc_value # store for later retrieval
Georg Brandlb0eb4d32010-02-07 11:34:15 +0000121 if self.expected_regexp is None:
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000122 return True
123
Georg Brandlb0eb4d32010-02-07 11:34:15 +0000124 expected_regexp = self.expected_regexp
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000125 if not expected_regexp.search(str(exc_value)):
126 raise self.failureException('"%s" does not match "%s"' %
127 (expected_regexp.pattern, str(exc_value)))
128 return True
129
130
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000131class TestCase(object):
132 """A class whose instances are single test cases.
133
134 By default, the test code itself should be placed in a method named
135 'runTest'.
136
137 If the fixture may be used for many test cases, create as
138 many test methods as are needed. When instantiating such a TestCase
139 subclass, specify in the constructor arguments the name of the test method
140 that the instance is to execute.
141
142 Test authors should subclass TestCase for their own tests. Construction
143 and deconstruction of the test's environment ('fixture') can be
144 implemented by overriding the 'setUp' and 'tearDown' methods respectively.
145
146 If it is necessary to override the __init__ method, the base class
147 __init__ method must always be called. It is important that subclasses
148 should not change the signature of their __init__ method, since instances
149 of the classes are instantiated automatically by parts of the framework
150 in order to be run.
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000151
Ezio Melotti035ecbe2013-03-29 03:42:29 +0200152 When subclassing TestCase, you can set these attributes:
153 * failureException: determines which exception will be raised when
154 the instance's assertion methods fail; test methods raising this
155 exception will be deemed to have 'failed' rather than 'errored'.
156 * longMessage: determines whether long messages (including repr of
157 objects used in assert methods) will be printed on failure in *addition*
158 to any explicit message passed.
159 * maxDiff: sets the maximum length of a diff in failure messages
160 by assert methods using difflib. It is looked up as an instance
161 attribute so can be configured by individual tests if required.
162 """
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000163
164 failureException = AssertionError
165
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000166 longMessage = False
167
Michael Foorde37d75f2010-06-05 12:10:52 +0000168 maxDiff = 80*8
169
Ezio Melotti34b32d62011-04-27 09:45:46 +0300170 # If a string is longer than _diffThreshold, use normal comparison instead
171 # of difflib. See #11763.
172 _diffThreshold = 2**16
173
Michael Foord5ffa3252010-03-07 22:04:55 +0000174 # Attribute used by TestSuite for classSetUp
175
176 _classSetupFailed = False
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000177
178 def __init__(self, methodName='runTest'):
179 """Create an instance of the class that will use the named test
180 method when executed. Raises a ValueError if the instance does
181 not have a method with the specified name.
182 """
183 self._testMethodName = methodName
184 self._resultForDoCleanups = None
185 try:
186 testMethod = getattr(self, methodName)
187 except AttributeError:
Michael Foordc2294dd2010-02-18 21:37:07 +0000188 raise ValueError("no such test method in %s: %s" %
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000189 (self.__class__, methodName))
190 self._testMethodDoc = testMethod.__doc__
191 self._cleanups = []
192
193 # Map types to custom assertEqual functions that will compare
194 # instances of said type in more detail to generate a more useful
195 # error message.
Benjamin Peterson83c14fe2011-07-12 19:21:42 -0500196 self._type_equality_funcs = {}
Raymond Hettinger67a3e832011-06-25 12:16:25 +0200197 self.addTypeEqualityFunc(dict, 'assertDictEqual')
198 self.addTypeEqualityFunc(list, 'assertListEqual')
199 self.addTypeEqualityFunc(tuple, 'assertTupleEqual')
200 self.addTypeEqualityFunc(set, 'assertSetEqual')
201 self.addTypeEqualityFunc(frozenset, 'assertSetEqual')
Martin v. Löwised11a5d2012-05-20 10:42:17 +0200202 try:
203 self.addTypeEqualityFunc(unicode, 'assertMultiLineEqual')
204 except NameError:
205 # No unicode support in this build
206 pass
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000207
208 def addTypeEqualityFunc(self, typeobj, function):
209 """Add a type specific assertEqual style function to compare a type.
210
211 This method is for use by TestCase subclasses that need to register
212 their own type equality functions to provide nicer error messages.
213
214 Args:
215 typeobj: The data type to call this function on when both values
216 are of the same type in assertEqual().
217 function: The callable taking two arguments and an optional
218 msg= argument that raises self.failureException with a
219 useful error message when the two arguments are not equal.
220 """
Benjamin Petersond46430b2009-11-29 22:26:26 +0000221 self._type_equality_funcs[typeobj] = function
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000222
223 def addCleanup(self, function, *args, **kwargs):
224 """Add a function, with arguments, to be called when the test is
225 completed. Functions added are called on a LIFO basis and are
226 called after tearDown on test failure or success.
227
228 Cleanup items are called even if setUp fails (unlike tearDown)."""
229 self._cleanups.append((function, args, kwargs))
230
231 def setUp(self):
232 "Hook method for setting up the test fixture before exercising it."
233 pass
234
235 def tearDown(self):
236 "Hook method for deconstructing the test fixture after testing it."
237 pass
238
Michael Foord5ffa3252010-03-07 22:04:55 +0000239 @classmethod
240 def setUpClass(cls):
241 "Hook method for setting up class fixture before running tests in the class."
242
243 @classmethod
244 def tearDownClass(cls):
245 "Hook method for deconstructing the class fixture after running all tests in the class."
246
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000247 def countTestCases(self):
248 return 1
249
250 def defaultTestResult(self):
251 return result.TestResult()
252
253 def shortDescription(self):
Michael Foorddb43b5a2010-02-10 14:25:12 +0000254 """Returns a one-line description of the test, or None if no
255 description has been provided.
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000256
Michael Foorddb43b5a2010-02-10 14:25:12 +0000257 The default implementation of this method returns the first line of
258 the specified test method's docstring.
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000259 """
Michael Foorddb43b5a2010-02-10 14:25:12 +0000260 doc = self._testMethodDoc
261 return doc and doc.split("\n")[0].strip() or None
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000262
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000263
264 def id(self):
Michael Foord225a0992010-02-18 20:30:09 +0000265 return "%s.%s" % (strclass(self.__class__), self._testMethodName)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000266
267 def __eq__(self, other):
268 if type(self) is not type(other):
269 return NotImplemented
270
271 return self._testMethodName == other._testMethodName
272
273 def __ne__(self, other):
274 return not self == other
275
276 def __hash__(self):
277 return hash((type(self), self._testMethodName))
278
279 def __str__(self):
Michael Foord225a0992010-02-18 20:30:09 +0000280 return "%s (%s)" % (self._testMethodName, strclass(self.__class__))
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000281
282 def __repr__(self):
283 return "<%s testMethod=%s>" % \
Michael Foord225a0992010-02-18 20:30:09 +0000284 (strclass(self.__class__), self._testMethodName)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000285
Michael Foordae3db0a2010-02-22 23:28:32 +0000286 def _addSkip(self, result, reason):
287 addSkip = getattr(result, 'addSkip', None)
288 if addSkip is not None:
289 addSkip(self, reason)
290 else:
291 warnings.warn("TestResult has no addSkip method, skips not reported",
292 RuntimeWarning, 2)
293 result.addSuccess(self)
294
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000295 def run(self, result=None):
296 orig_result = result
297 if result is None:
298 result = self.defaultTestResult()
299 startTestRun = getattr(result, 'startTestRun', None)
300 if startTestRun is not None:
301 startTestRun()
302
303 self._resultForDoCleanups = result
304 result.startTest(self)
Michael Foord53e8eea2010-03-07 20:22:12 +0000305
306 testMethod = getattr(self, self._testMethodName)
307 if (getattr(self.__class__, "__unittest_skip__", False) or
308 getattr(testMethod, "__unittest_skip__", False)):
309 # If the class or method was skipped.
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000310 try:
Michael Foord53e8eea2010-03-07 20:22:12 +0000311 skip_why = (getattr(self.__class__, '__unittest_skip_why__', '')
312 or getattr(testMethod, '__unittest_skip_why__', ''))
313 self._addSkip(result, skip_why)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000314 finally:
315 result.stopTest(self)
316 return
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000317 try:
318 success = False
319 try:
320 self.setUp()
321 except SkipTest as e:
Michael Foordae3db0a2010-02-22 23:28:32 +0000322 self._addSkip(result, str(e))
Michael Foorda17f0762010-12-19 14:53:19 +0000323 except KeyboardInterrupt:
324 raise
325 except:
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000326 result.addError(self, sys.exc_info())
327 else:
328 try:
329 testMethod()
Michael Foorda17f0762010-12-19 14:53:19 +0000330 except KeyboardInterrupt:
331 raise
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000332 except self.failureException:
333 result.addFailure(self, sys.exc_info())
334 except _ExpectedFailure as e:
Michael Foordae3db0a2010-02-22 23:28:32 +0000335 addExpectedFailure = getattr(result, 'addExpectedFailure', None)
336 if addExpectedFailure is not None:
337 addExpectedFailure(self, e.exc_info)
338 else:
339 warnings.warn("TestResult has no addExpectedFailure method, reporting as passes",
340 RuntimeWarning)
341 result.addSuccess(self)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000342 except _UnexpectedSuccess:
Michael Foordae3db0a2010-02-22 23:28:32 +0000343 addUnexpectedSuccess = getattr(result, 'addUnexpectedSuccess', None)
344 if addUnexpectedSuccess is not None:
345 addUnexpectedSuccess(self)
346 else:
347 warnings.warn("TestResult has no addUnexpectedSuccess method, reporting as failures",
348 RuntimeWarning)
349 result.addFailure(self, sys.exc_info())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000350 except SkipTest as e:
Michael Foordae3db0a2010-02-22 23:28:32 +0000351 self._addSkip(result, str(e))
Michael Foorda17f0762010-12-19 14:53:19 +0000352 except:
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000353 result.addError(self, sys.exc_info())
354 else:
355 success = True
356
357 try:
358 self.tearDown()
Michael Foorda17f0762010-12-19 14:53:19 +0000359 except KeyboardInterrupt:
360 raise
361 except:
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000362 result.addError(self, sys.exc_info())
363 success = False
364
365 cleanUpSuccess = self.doCleanups()
366 success = success and cleanUpSuccess
367 if success:
368 result.addSuccess(self)
369 finally:
370 result.stopTest(self)
371 if orig_result is None:
372 stopTestRun = getattr(result, 'stopTestRun', None)
373 if stopTestRun is not None:
374 stopTestRun()
375
376 def doCleanups(self):
377 """Execute all cleanup functions. Normally called for you after
378 tearDown."""
379 result = self._resultForDoCleanups
380 ok = True
381 while self._cleanups:
382 function, args, kwargs = self._cleanups.pop(-1)
383 try:
384 function(*args, **kwargs)
Michael Foorda17f0762010-12-19 14:53:19 +0000385 except KeyboardInterrupt:
386 raise
387 except:
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000388 ok = False
389 result.addError(self, sys.exc_info())
390 return ok
391
392 def __call__(self, *args, **kwds):
393 return self.run(*args, **kwds)
394
395 def debug(self):
396 """Run the test without collecting errors in a TestResult"""
397 self.setUp()
398 getattr(self, self._testMethodName)()
399 self.tearDown()
Michael Foord0fedb282010-06-08 22:44:52 +0000400 while self._cleanups:
401 function, args, kwargs = self._cleanups.pop(-1)
402 function(*args, **kwargs)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000403
404 def skipTest(self, reason):
405 """Skip this test."""
406 raise SkipTest(reason)
407
408 def fail(self, msg=None):
409 """Fail immediately, with the given message."""
410 raise self.failureException(msg)
411
412 def assertFalse(self, expr, msg=None):
Ezio Melottic139a562010-12-18 17:58:29 +0000413 """Check that the expression is false."""
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000414 if expr:
Ezio Melottic139a562010-12-18 17:58:29 +0000415 msg = self._formatMessage(msg, "%s is not false" % safe_repr(expr))
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000416 raise self.failureException(msg)
417
418 def assertTrue(self, expr, msg=None):
Ezio Melottic139a562010-12-18 17:58:29 +0000419 """Check that the expression is true."""
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000420 if not expr:
Ezio Melottic139a562010-12-18 17:58:29 +0000421 msg = self._formatMessage(msg, "%s is not true" % safe_repr(expr))
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000422 raise self.failureException(msg)
423
424 def _formatMessage(self, msg, standardMsg):
425 """Honour the longMessage attribute when generating failure messages.
426 If longMessage is False this means:
427 * Use only an explicit message if it is provided
428 * Otherwise use the standard message for the assert
429
430 If longMessage is True:
431 * Use the standard message
432 * If an explicit message is provided, plus ' : ' and the explicit message
433 """
434 if not self.longMessage:
435 return msg or standardMsg
436 if msg is None:
437 return standardMsg
Michael Foord53e8eea2010-03-07 20:22:12 +0000438 try:
439 # don't switch to '{}' formatting in Python 2.X
440 # it changes the way unicode input is handled
441 return '%s : %s' % (standardMsg, msg)
442 except UnicodeDecodeError:
443 return '%s : %s' % (safe_repr(standardMsg), safe_repr(msg))
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000444
445
446 def assertRaises(self, excClass, callableObj=None, *args, **kwargs):
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200447 """Fail unless an exception of class excClass is raised
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000448 by callableObj when invoked with arguments args and keyword
449 arguments kwargs. If a different type of exception is
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200450 raised, it will not be caught, and the test case will be
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000451 deemed to have suffered an error, exactly as for an
452 unexpected exception.
453
454 If called with callableObj omitted or None, will return a
455 context object used like this::
456
Michael Foordd0edec32010-02-05 22:55:09 +0000457 with self.assertRaises(SomeException):
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000458 do_something()
Michael Foordd0edec32010-02-05 22:55:09 +0000459
460 The context manager keeps a reference to the exception as
Ezio Melotticd4f6572010-02-08 21:52:08 +0000461 the 'exception' attribute. This allows you to inspect the
Michael Foordd0edec32010-02-05 22:55:09 +0000462 exception after the assertion::
463
464 with self.assertRaises(SomeException) as cm:
465 do_something()
Georg Brandldc3694b2010-02-07 17:02:22 +0000466 the_exception = cm.exception
Michael Foord757cc4d2010-02-05 23:22:37 +0000467 self.assertEqual(the_exception.error_code, 3)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000468 """
469 context = _AssertRaisesContext(excClass, self)
470 if callableObj is None:
471 return context
472 with context:
473 callableObj(*args, **kwargs)
474
475 def _getAssertEqualityFunc(self, first, second):
476 """Get a detailed comparison function for the types of the two args.
477
478 Returns: A callable accepting (first, second, msg=None) that will
479 raise a failure exception if first != second with a useful human
480 readable error message for those types.
481 """
482 #
483 # NOTE(gregory.p.smith): I considered isinstance(first, type(second))
484 # and vice versa. I opted for the conservative approach in case
485 # subclasses are not intended to be compared in detail to their super
486 # class instances using a type equality func. This means testing
487 # subtypes won't automagically use the detailed comparison. Callers
488 # should use their type specific assertSpamEqual method to compare
489 # subclasses if the detailed comparison is desired and appropriate.
490 # See the discussion in http://bugs.python.org/issue2578.
491 #
492 if type(first) is type(second):
493 asserter = self._type_equality_funcs.get(type(first))
494 if asserter is not None:
Benjamin Peterson83c14fe2011-07-12 19:21:42 -0500495 if isinstance(asserter, basestring):
496 asserter = getattr(self, asserter)
Benjamin Petersond46430b2009-11-29 22:26:26 +0000497 return asserter
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000498
499 return self._baseAssertEqual
500
501 def _baseAssertEqual(self, first, second, msg=None):
502 """The default assertEqual implementation, not type specific."""
503 if not first == second:
Michael Foord225a0992010-02-18 20:30:09 +0000504 standardMsg = '%s != %s' % (safe_repr(first), safe_repr(second))
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000505 msg = self._formatMessage(msg, standardMsg)
506 raise self.failureException(msg)
507
508 def assertEqual(self, first, second, msg=None):
509 """Fail if the two objects are unequal as determined by the '=='
510 operator.
511 """
512 assertion_func = self._getAssertEqualityFunc(first, second)
513 assertion_func(first, second, msg=msg)
514
515 def assertNotEqual(self, first, second, msg=None):
Ezio Melotti9b19c4b2012-11-08 11:08:39 +0200516 """Fail if the two objects are equal as determined by the '!='
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000517 operator.
518 """
519 if not first != second:
Michael Foord225a0992010-02-18 20:30:09 +0000520 msg = self._formatMessage(msg, '%s == %s' % (safe_repr(first),
521 safe_repr(second)))
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000522 raise self.failureException(msg)
523
Michael Foorda7e08fe2010-03-27 19:10:11 +0000524
525 def assertAlmostEqual(self, first, second, places=None, msg=None, delta=None):
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000526 """Fail if the two objects are unequal as determined by their
527 difference rounded to the given number of decimal places
Michael Foorda7e08fe2010-03-27 19:10:11 +0000528 (default 7) and comparing to zero, or by comparing that the
529 between the two objects is more than the given delta.
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000530
531 Note that decimal places (from zero) are usually not the same
532 as significant digits (measured from the most signficant digit).
Michael Foordc3f79372009-09-13 16:40:02 +0000533
534 If the two objects compare equal then they will automatically
535 compare almost equal.
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000536 """
Michael Foordc3f79372009-09-13 16:40:02 +0000537 if first == second:
Michael Foorda7e08fe2010-03-27 19:10:11 +0000538 # shortcut
Michael Foordc3f79372009-09-13 16:40:02 +0000539 return
Michael Foorda7e08fe2010-03-27 19:10:11 +0000540 if delta is not None and places is not None:
541 raise TypeError("specify delta or places not both")
542
543 if delta is not None:
544 if abs(first - second) <= delta:
545 return
546
547 standardMsg = '%s != %s within %s delta' % (safe_repr(first),
548 safe_repr(second),
549 safe_repr(delta))
550 else:
551 if places is None:
552 places = 7
553
554 if round(abs(second-first), places) == 0:
555 return
556
Michael Foord225a0992010-02-18 20:30:09 +0000557 standardMsg = '%s != %s within %r places' % (safe_repr(first),
558 safe_repr(second),
559 places)
Michael Foorda7e08fe2010-03-27 19:10:11 +0000560 msg = self._formatMessage(msg, standardMsg)
561 raise self.failureException(msg)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000562
Michael Foorda7e08fe2010-03-27 19:10:11 +0000563 def assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None):
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000564 """Fail if the two objects are equal as determined by their
565 difference rounded to the given number of decimal places
Michael Foorda7e08fe2010-03-27 19:10:11 +0000566 (default 7) and comparing to zero, or by comparing that the
567 between the two objects is less than the given delta.
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000568
569 Note that decimal places (from zero) are usually not the same
570 as significant digits (measured from the most signficant digit).
Michael Foordc3f79372009-09-13 16:40:02 +0000571
572 Objects that are equal automatically fail.
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000573 """
Michael Foorda7e08fe2010-03-27 19:10:11 +0000574 if delta is not None and places is not None:
575 raise TypeError("specify delta or places not both")
576 if delta is not None:
577 if not (first == second) and abs(first - second) > delta:
578 return
579 standardMsg = '%s == %s within %s delta' % (safe_repr(first),
580 safe_repr(second),
581 safe_repr(delta))
582 else:
583 if places is None:
584 places = 7
585 if not (first == second) and round(abs(second-first), places) != 0:
586 return
Michael Foord225a0992010-02-18 20:30:09 +0000587 standardMsg = '%s == %s within %r places' % (safe_repr(first),
Michael Foorda7e08fe2010-03-27 19:10:11 +0000588 safe_repr(second),
589 places)
590
591 msg = self._formatMessage(msg, standardMsg)
592 raise self.failureException(msg)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000593
594 # Synonyms for assertion methods
595
596 # The plurals are undocumented. Keep them that way to discourage use.
597 # Do not add more. Do not remove.
598 # Going through a deprecation cycle on these would annoy many people.
599 assertEquals = assertEqual
600 assertNotEquals = assertNotEqual
601 assertAlmostEquals = assertAlmostEqual
602 assertNotAlmostEquals = assertNotAlmostEqual
Michael Foord67dfc772010-02-10 14:31:30 +0000603 assert_ = assertTrue
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000604
605 # These fail* assertion method names are pending deprecation and will
606 # be a DeprecationWarning in 3.2; http://bugs.python.org/issue2578
607 def _deprecate(original_func):
608 def deprecated_func(*args, **kwargs):
609 warnings.warn(
610 'Please use {0} instead.'.format(original_func.__name__),
611 PendingDeprecationWarning, 2)
612 return original_func(*args, **kwargs)
613 return deprecated_func
614
615 failUnlessEqual = _deprecate(assertEqual)
616 failIfEqual = _deprecate(assertNotEqual)
617 failUnlessAlmostEqual = _deprecate(assertAlmostEqual)
618 failIfAlmostEqual = _deprecate(assertNotAlmostEqual)
619 failUnless = _deprecate(assertTrue)
620 failUnlessRaises = _deprecate(assertRaises)
621 failIf = _deprecate(assertFalse)
622
Michael Foorde37d75f2010-06-05 12:10:52 +0000623 def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000624 """An equality assertion for ordered sequences (like lists and tuples).
625
R. David Murray05b41712010-01-29 19:35:39 +0000626 For the purposes of this function, a valid ordered sequence type is one
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000627 which can be indexed, has a length, and has an equality operator.
628
629 Args:
630 seq1: The first sequence to compare.
631 seq2: The second sequence to compare.
632 seq_type: The expected datatype of the sequences, or None if no
633 datatype should be enforced.
634 msg: Optional message to use on failure instead of a list of
635 differences.
636 """
Florent Xicluna4a0f8b82010-03-21 10:50:44 +0000637 if seq_type is not None:
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000638 seq_type_name = seq_type.__name__
639 if not isinstance(seq1, seq_type):
Michael Foord225a0992010-02-18 20:30:09 +0000640 raise self.failureException('First sequence is not a %s: %s'
641 % (seq_type_name, safe_repr(seq1)))
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000642 if not isinstance(seq2, seq_type):
Michael Foord225a0992010-02-18 20:30:09 +0000643 raise self.failureException('Second sequence is not a %s: %s'
644 % (seq_type_name, safe_repr(seq2)))
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000645 else:
646 seq_type_name = "sequence"
647
648 differing = None
649 try:
650 len1 = len(seq1)
651 except (TypeError, NotImplementedError):
652 differing = 'First %s has no length. Non-sequence?' % (
653 seq_type_name)
654
655 if differing is None:
656 try:
657 len2 = len(seq2)
658 except (TypeError, NotImplementedError):
659 differing = 'Second %s has no length. Non-sequence?' % (
660 seq_type_name)
661
662 if differing is None:
663 if seq1 == seq2:
664 return
665
Michael Foord225a0992010-02-18 20:30:09 +0000666 seq1_repr = safe_repr(seq1)
667 seq2_repr = safe_repr(seq2)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000668 if len(seq1_repr) > 30:
669 seq1_repr = seq1_repr[:30] + '...'
670 if len(seq2_repr) > 30:
671 seq2_repr = seq2_repr[:30] + '...'
672 elements = (seq_type_name.capitalize(), seq1_repr, seq2_repr)
673 differing = '%ss differ: %s != %s\n' % elements
674
675 for i in xrange(min(len1, len2)):
676 try:
677 item1 = seq1[i]
678 except (TypeError, IndexError, NotImplementedError):
679 differing += ('\nUnable to index element %d of first %s\n' %
680 (i, seq_type_name))
681 break
682
683 try:
684 item2 = seq2[i]
685 except (TypeError, IndexError, NotImplementedError):
686 differing += ('\nUnable to index element %d of second %s\n' %
687 (i, seq_type_name))
688 break
689
690 if item1 != item2:
691 differing += ('\nFirst differing element %d:\n%s\n%s\n' %
692 (i, item1, item2))
693 break
694 else:
695 if (len1 == len2 and seq_type is None and
696 type(seq1) != type(seq2)):
697 # The sequences are the same, but have differing types.
698 return
699
700 if len1 > len2:
701 differing += ('\nFirst %s contains %d additional '
702 'elements.\n' % (seq_type_name, len1 - len2))
703 try:
704 differing += ('First extra element %d:\n%s\n' %
705 (len2, seq1[len2]))
706 except (TypeError, IndexError, NotImplementedError):
707 differing += ('Unable to index element %d '
708 'of first %s\n' % (len2, seq_type_name))
709 elif len1 < len2:
710 differing += ('\nSecond %s contains %d additional '
711 'elements.\n' % (seq_type_name, len2 - len1))
712 try:
713 differing += ('First extra element %d:\n%s\n' %
714 (len1, seq2[len1]))
715 except (TypeError, IndexError, NotImplementedError):
716 differing += ('Unable to index element %d '
717 'of second %s\n' % (len1, seq_type_name))
Michael Foord01007022010-06-05 11:23:51 +0000718 standardMsg = differing
719 diffMsg = '\n' + '\n'.join(
Georg Brandl46cc46a2009-10-01 20:11:14 +0000720 difflib.ndiff(pprint.pformat(seq1).splitlines(),
721 pprint.pformat(seq2).splitlines()))
Michael Foorde37d75f2010-06-05 12:10:52 +0000722 standardMsg = self._truncateMessage(standardMsg, diffMsg)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000723 msg = self._formatMessage(msg, standardMsg)
724 self.fail(msg)
725
Michael Foorde37d75f2010-06-05 12:10:52 +0000726 def _truncateMessage(self, message, diff):
727 max_diff = self.maxDiff
Michael Foorda4412872010-06-05 11:46:59 +0000728 if max_diff is None or len(diff) <= max_diff:
729 return message + diff
Michael Foord5fe21ff2010-06-05 13:38:16 +0000730 return message + (DIFF_OMITTED % len(diff))
Michael Foorda4412872010-06-05 11:46:59 +0000731
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000732 def assertListEqual(self, list1, list2, msg=None):
733 """A list-specific equality assertion.
734
735 Args:
736 list1: The first list to compare.
737 list2: The second list to compare.
738 msg: Optional message to use on failure instead of a list of
739 differences.
740
741 """
742 self.assertSequenceEqual(list1, list2, msg, seq_type=list)
743
744 def assertTupleEqual(self, tuple1, tuple2, msg=None):
745 """A tuple-specific equality assertion.
746
747 Args:
748 tuple1: The first tuple to compare.
749 tuple2: The second tuple to compare.
750 msg: Optional message to use on failure instead of a list of
751 differences.
752 """
753 self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
754
755 def assertSetEqual(self, set1, set2, msg=None):
756 """A set-specific equality assertion.
757
758 Args:
759 set1: The first set to compare.
760 set2: The second set to compare.
761 msg: Optional message to use on failure instead of a list of
762 differences.
763
Michael Foord98e7b762010-03-20 03:00:34 +0000764 assertSetEqual uses ducktyping to support different types of sets, and
765 is optimized for sets specifically (parameters must support a
766 difference method).
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000767 """
768 try:
769 difference1 = set1.difference(set2)
770 except TypeError, e:
771 self.fail('invalid type when attempting set difference: %s' % e)
772 except AttributeError, e:
773 self.fail('first argument does not support set difference: %s' % e)
774
775 try:
776 difference2 = set2.difference(set1)
777 except TypeError, e:
778 self.fail('invalid type when attempting set difference: %s' % e)
779 except AttributeError, e:
780 self.fail('second argument does not support set difference: %s' % e)
781
782 if not (difference1 or difference2):
783 return
784
785 lines = []
786 if difference1:
787 lines.append('Items in the first set but not the second:')
788 for item in difference1:
789 lines.append(repr(item))
790 if difference2:
791 lines.append('Items in the second set but not the first:')
792 for item in difference2:
793 lines.append(repr(item))
794
795 standardMsg = '\n'.join(lines)
796 self.fail(self._formatMessage(msg, standardMsg))
797
798 def assertIn(self, member, container, msg=None):
799 """Just like self.assertTrue(a in b), but with a nicer default message."""
800 if member not in container:
Michael Foord225a0992010-02-18 20:30:09 +0000801 standardMsg = '%s not found in %s' % (safe_repr(member),
802 safe_repr(container))
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000803 self.fail(self._formatMessage(msg, standardMsg))
804
805 def assertNotIn(self, member, container, msg=None):
806 """Just like self.assertTrue(a not in b), but with a nicer default message."""
807 if member in container:
Michael Foord225a0992010-02-18 20:30:09 +0000808 standardMsg = '%s unexpectedly found in %s' % (safe_repr(member),
809 safe_repr(container))
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000810 self.fail(self._formatMessage(msg, standardMsg))
811
812 def assertIs(self, expr1, expr2, msg=None):
813 """Just like self.assertTrue(a is b), but with a nicer default message."""
814 if expr1 is not expr2:
Michael Foord225a0992010-02-18 20:30:09 +0000815 standardMsg = '%s is not %s' % (safe_repr(expr1),
Michael Foordc2294dd2010-02-18 21:37:07 +0000816 safe_repr(expr2))
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000817 self.fail(self._formatMessage(msg, standardMsg))
818
819 def assertIsNot(self, expr1, expr2, msg=None):
820 """Just like self.assertTrue(a is not b), but with a nicer default message."""
821 if expr1 is expr2:
Michael Foord225a0992010-02-18 20:30:09 +0000822 standardMsg = 'unexpectedly identical: %s' % (safe_repr(expr1),)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000823 self.fail(self._formatMessage(msg, standardMsg))
824
825 def assertDictEqual(self, d1, d2, msg=None):
Ezio Melotti2623a372010-11-21 13:34:58 +0000826 self.assertIsInstance(d1, dict, 'First argument is not a dictionary')
827 self.assertIsInstance(d2, dict, 'Second argument is not a dictionary')
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000828
829 if d1 != d2:
Michael Foord674648e2010-06-05 12:58:39 +0000830 standardMsg = '%s != %s' % (safe_repr(d1, True), safe_repr(d2, True))
Michael Foorde37d75f2010-06-05 12:10:52 +0000831 diff = ('\n' + '\n'.join(difflib.ndiff(
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000832 pprint.pformat(d1).splitlines(),
833 pprint.pformat(d2).splitlines())))
Michael Foord674648e2010-06-05 12:58:39 +0000834 standardMsg = self._truncateMessage(standardMsg, diff)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000835 self.fail(self._formatMessage(msg, standardMsg))
836
837 def assertDictContainsSubset(self, expected, actual, msg=None):
838 """Checks whether actual is a superset of expected."""
839 missing = []
840 mismatched = []
841 for key, value in expected.iteritems():
842 if key not in actual:
843 missing.append(key)
844 elif value != actual[key]:
Georg Brandl46cc46a2009-10-01 20:11:14 +0000845 mismatched.append('%s, expected: %s, actual: %s' %
Michael Foordc2294dd2010-02-18 21:37:07 +0000846 (safe_repr(key), safe_repr(value),
847 safe_repr(actual[key])))
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000848
849 if not (missing or mismatched):
850 return
851
852 standardMsg = ''
853 if missing:
Michael Foord225a0992010-02-18 20:30:09 +0000854 standardMsg = 'Missing: %s' % ','.join(safe_repr(m) for m in
855 missing)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000856 if mismatched:
857 if standardMsg:
858 standardMsg += '; '
859 standardMsg += 'Mismatched values: %s' % ','.join(mismatched)
860
861 self.fail(self._formatMessage(msg, standardMsg))
862
Michael Foord98e7b762010-03-20 03:00:34 +0000863 def assertItemsEqual(self, expected_seq, actual_seq, msg=None):
Michael Foorde6e0e262010-12-19 15:52:56 +0000864 """An unordered sequence specific comparison. It asserts that
865 actual_seq and expected_seq have the same element counts.
866 Equivalent to::
Michael Foord98e7b762010-03-20 03:00:34 +0000867
Michael Foorde6e0e262010-12-19 15:52:56 +0000868 self.assertEqual(Counter(iter(actual_seq)),
869 Counter(iter(expected_seq)))
Michael Foordd0edec32010-02-05 22:55:09 +0000870
Michael Foord98e7b762010-03-20 03:00:34 +0000871 Asserts that each element has the same count in both sequences.
872 Example:
873 - [0, 1, 1] and [1, 0, 1] compare equal.
874 - [0, 0, 1] and [0, 1] compare unequal.
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000875 """
R David Murray69493922012-05-16 14:01:03 -0400876 first_seq, second_seq = list(expected_seq), list(actual_seq)
Florent Xicluna1f3b4e12010-03-07 12:14:25 +0000877 with warnings.catch_warnings():
878 if sys.py3kwarning:
879 # Silence Py3k warning raised during the sorting
Florent Xicluna4a0f8b82010-03-21 10:50:44 +0000880 for _msg in ["(code|dict|type) inequality comparisons",
Michael Foord98e7b762010-03-20 03:00:34 +0000881 "builtin_function_or_method order comparisons",
882 "comparing unequal types"]:
Michael Foorda7152552010-03-07 23:10:36 +0000883 warnings.filterwarnings("ignore", _msg, DeprecationWarning)
Florent Xicluna1f3b4e12010-03-07 12:14:25 +0000884 try:
Michael Foord4c9e91a2011-03-16 20:34:53 -0400885 first = collections.Counter(first_seq)
886 second = collections.Counter(second_seq)
Michael Foord98e7b762010-03-20 03:00:34 +0000887 except TypeError:
Michael Foord4c9e91a2011-03-16 20:34:53 -0400888 # Handle case with unhashable elements
889 differences = _count_diff_all_purpose(first_seq, second_seq)
Michael Foord98e7b762010-03-20 03:00:34 +0000890 else:
Michael Foord4c9e91a2011-03-16 20:34:53 -0400891 if first == second:
Michael Foorde6e0e262010-12-19 15:52:56 +0000892 return
Michael Foord4c9e91a2011-03-16 20:34:53 -0400893 differences = _count_diff_hashable(first_seq, second_seq)
Michael Foord98e7b762010-03-20 03:00:34 +0000894
Michael Foord4c9e91a2011-03-16 20:34:53 -0400895 if differences:
896 standardMsg = 'Element counts were not equal:\n'
897 lines = ['First has %d, Second has %d: %r' % diff for diff in differences]
898 diffMsg = '\n'.join(lines)
899 standardMsg = self._truncateMessage(standardMsg, diffMsg)
900 msg = self._formatMessage(msg, standardMsg)
901 self.fail(msg)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000902
903 def assertMultiLineEqual(self, first, second, msg=None):
904 """Assert that two multi-line strings are equal."""
Ezio Melotti2623a372010-11-21 13:34:58 +0000905 self.assertIsInstance(first, basestring,
906 'First argument is not a string')
907 self.assertIsInstance(second, basestring,
908 'Second argument is not a string')
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000909
910 if first != second:
Ezio Melotti34b32d62011-04-27 09:45:46 +0300911 # don't use difflib if the strings are too long
912 if (len(first) > self._diffThreshold or
913 len(second) > self._diffThreshold):
914 self._baseAssertEqual(first, second, msg)
Michael Foord94f071c2010-07-10 13:51:42 +0000915 firstlines = first.splitlines(True)
916 secondlines = second.splitlines(True)
917 if len(firstlines) == 1 and first.strip('\r\n') == first:
918 firstlines = [first + '\n']
919 secondlines = [second + '\n']
920 standardMsg = '%s != %s' % (safe_repr(first, True),
921 safe_repr(second, True))
922 diff = '\n' + ''.join(difflib.ndiff(firstlines, secondlines))
Michael Foord674648e2010-06-05 12:58:39 +0000923 standardMsg = self._truncateMessage(standardMsg, diff)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000924 self.fail(self._formatMessage(msg, standardMsg))
925
926 def assertLess(self, a, b, msg=None):
927 """Just like self.assertTrue(a < b), but with a nicer default message."""
928 if not a < b:
Michael Foord225a0992010-02-18 20:30:09 +0000929 standardMsg = '%s not less than %s' % (safe_repr(a), safe_repr(b))
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000930 self.fail(self._formatMessage(msg, standardMsg))
931
932 def assertLessEqual(self, a, b, msg=None):
933 """Just like self.assertTrue(a <= b), but with a nicer default message."""
934 if not a <= b:
Michael Foord225a0992010-02-18 20:30:09 +0000935 standardMsg = '%s not less than or equal to %s' % (safe_repr(a), safe_repr(b))
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000936 self.fail(self._formatMessage(msg, standardMsg))
937
938 def assertGreater(self, a, b, msg=None):
939 """Just like self.assertTrue(a > b), but with a nicer default message."""
940 if not a > b:
Michael Foord225a0992010-02-18 20:30:09 +0000941 standardMsg = '%s not greater than %s' % (safe_repr(a), safe_repr(b))
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000942 self.fail(self._formatMessage(msg, standardMsg))
943
944 def assertGreaterEqual(self, a, b, msg=None):
945 """Just like self.assertTrue(a >= b), but with a nicer default message."""
946 if not a >= b:
Michael Foord225a0992010-02-18 20:30:09 +0000947 standardMsg = '%s not greater than or equal to %s' % (safe_repr(a), safe_repr(b))
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000948 self.fail(self._formatMessage(msg, standardMsg))
949
950 def assertIsNone(self, obj, msg=None):
951 """Same as self.assertTrue(obj is None), with a nicer default message."""
952 if obj is not None:
Michael Foord225a0992010-02-18 20:30:09 +0000953 standardMsg = '%s is not None' % (safe_repr(obj),)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000954 self.fail(self._formatMessage(msg, standardMsg))
955
956 def assertIsNotNone(self, obj, msg=None):
957 """Included for symmetry with assertIsNone."""
958 if obj is None:
959 standardMsg = 'unexpectedly None'
960 self.fail(self._formatMessage(msg, standardMsg))
961
Georg Brandlf895cf52009-10-01 20:59:31 +0000962 def assertIsInstance(self, obj, cls, msg=None):
963 """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
964 default message."""
965 if not isinstance(obj, cls):
Michael Foord225a0992010-02-18 20:30:09 +0000966 standardMsg = '%s is not an instance of %r' % (safe_repr(obj), cls)
Georg Brandlf895cf52009-10-01 20:59:31 +0000967 self.fail(self._formatMessage(msg, standardMsg))
968
969 def assertNotIsInstance(self, obj, cls, msg=None):
970 """Included for symmetry with assertIsInstance."""
971 if isinstance(obj, cls):
Michael Foord225a0992010-02-18 20:30:09 +0000972 standardMsg = '%s is an instance of %r' % (safe_repr(obj), cls)
Georg Brandlf895cf52009-10-01 20:59:31 +0000973 self.fail(self._formatMessage(msg, standardMsg))
974
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000975 def assertRaisesRegexp(self, expected_exception, expected_regexp,
976 callable_obj=None, *args, **kwargs):
977 """Asserts that the message in a raised exception matches a regexp.
978
979 Args:
980 expected_exception: Exception class expected to be raised.
981 expected_regexp: Regexp (re pattern object or string) expected
982 to be found in error message.
983 callable_obj: Function to be called.
984 args: Extra args.
985 kwargs: Extra kwargs.
986 """
R David Murray6d911762014-03-25 15:29:42 -0400987 if expected_regexp is not None:
988 expected_regexp = re.compile(expected_regexp)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000989 context = _AssertRaisesContext(expected_exception, self, expected_regexp)
990 if callable_obj is None:
991 return context
992 with context:
993 callable_obj(*args, **kwargs)
994
Georg Brandlb0eb4d32010-02-07 11:34:15 +0000995 def assertRegexpMatches(self, text, expected_regexp, msg=None):
Michael Foord959c16d2010-05-08 16:40:52 +0000996 """Fail the test unless the text matches the regular expression."""
Georg Brandlb0eb4d32010-02-07 11:34:15 +0000997 if isinstance(expected_regexp, basestring):
998 expected_regexp = re.compile(expected_regexp)
999 if not expected_regexp.search(text):
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001000 msg = msg or "Regexp didn't match"
Georg Brandlb0eb4d32010-02-07 11:34:15 +00001001 msg = '%s: %r not found in %r' % (msg, expected_regexp.pattern, text)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001002 raise self.failureException(msg)
1003
Michael Foorda04c7a02010-04-02 22:55:59 +00001004 def assertNotRegexpMatches(self, text, unexpected_regexp, msg=None):
Michael Foord959c16d2010-05-08 16:40:52 +00001005 """Fail the test if the text matches the regular expression."""
Michael Foorda04c7a02010-04-02 22:55:59 +00001006 if isinstance(unexpected_regexp, basestring):
1007 unexpected_regexp = re.compile(unexpected_regexp)
1008 match = unexpected_regexp.search(text)
1009 if match:
1010 msg = msg or "Regexp matched"
1011 msg = '%s: %r matches %r in %r' % (msg,
1012 text[match.start():match.end()],
1013 unexpected_regexp.pattern,
1014 text)
1015 raise self.failureException(msg)
1016
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001017
1018class FunctionTestCase(TestCase):
1019 """A test case that wraps a test function.
1020
1021 This is useful for slipping pre-existing test functions into the
1022 unittest framework. Optionally, set-up and tidy-up functions can be
1023 supplied. As with TestCase, the tidy-up ('tearDown') function will
1024 always be called if the set-up ('setUp') function ran successfully.
1025 """
1026
1027 def __init__(self, testFunc, setUp=None, tearDown=None, description=None):
1028 super(FunctionTestCase, self).__init__()
1029 self._setUpFunc = setUp
1030 self._tearDownFunc = tearDown
1031 self._testFunc = testFunc
1032 self._description = description
1033
1034 def setUp(self):
1035 if self._setUpFunc is not None:
1036 self._setUpFunc()
1037
1038 def tearDown(self):
1039 if self._tearDownFunc is not None:
1040 self._tearDownFunc()
1041
1042 def runTest(self):
1043 self._testFunc()
1044
1045 def id(self):
1046 return self._testFunc.__name__
1047
1048 def __eq__(self, other):
1049 if not isinstance(other, self.__class__):
1050 return NotImplemented
1051
1052 return self._setUpFunc == other._setUpFunc and \
1053 self._tearDownFunc == other._tearDownFunc and \
1054 self._testFunc == other._testFunc and \
1055 self._description == other._description
1056
1057 def __ne__(self, other):
1058 return not self == other
1059
1060 def __hash__(self):
1061 return hash((type(self), self._setUpFunc, self._tearDownFunc,
1062 self._testFunc, self._description))
1063
1064 def __str__(self):
Michael Foord225a0992010-02-18 20:30:09 +00001065 return "%s (%s)" % (strclass(self.__class__),
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001066 self._testFunc.__name__)
1067
1068 def __repr__(self):
Michael Foord225a0992010-02-18 20:30:09 +00001069 return "<%s tec=%s>" % (strclass(self.__class__),
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001070 self._testFunc)
1071
1072 def shortDescription(self):
1073 if self._description is not None:
1074 return self._description
1075 doc = self._testFunc.__doc__
1076 return doc and doc.split("\n")[0].strip() or None