blob: 6bbc55fbc6edacceb694220bc6b6aaa66cc48b71 [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
Serhiy Storchaka7f71e042015-05-06 19:10:40 +0300130def _sentinel(*args, **kwargs):
Serhiy Storchaka2e2dcf62015-05-06 19:21:00 +0300131 raise AssertionError('Should never be called')
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000132
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000133class TestCase(object):
134 """A class whose instances are single test cases.
135
136 By default, the test code itself should be placed in a method named
137 'runTest'.
138
139 If the fixture may be used for many test cases, create as
140 many test methods as are needed. When instantiating such a TestCase
141 subclass, specify in the constructor arguments the name of the test method
142 that the instance is to execute.
143
144 Test authors should subclass TestCase for their own tests. Construction
145 and deconstruction of the test's environment ('fixture') can be
146 implemented by overriding the 'setUp' and 'tearDown' methods respectively.
147
148 If it is necessary to override the __init__ method, the base class
149 __init__ method must always be called. It is important that subclasses
150 should not change the signature of their __init__ method, since instances
151 of the classes are instantiated automatically by parts of the framework
152 in order to be run.
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000153
Ezio Melotti035ecbe2013-03-29 03:42:29 +0200154 When subclassing TestCase, you can set these attributes:
155 * failureException: determines which exception will be raised when
156 the instance's assertion methods fail; test methods raising this
157 exception will be deemed to have 'failed' rather than 'errored'.
158 * longMessage: determines whether long messages (including repr of
159 objects used in assert methods) will be printed on failure in *addition*
160 to any explicit message passed.
161 * maxDiff: sets the maximum length of a diff in failure messages
162 by assert methods using difflib. It is looked up as an instance
163 attribute so can be configured by individual tests if required.
164 """
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000165
166 failureException = AssertionError
167
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000168 longMessage = False
169
Michael Foorde37d75f2010-06-05 12:10:52 +0000170 maxDiff = 80*8
171
Ezio Melotti34b32d62011-04-27 09:45:46 +0300172 # If a string is longer than _diffThreshold, use normal comparison instead
173 # of difflib. See #11763.
174 _diffThreshold = 2**16
175
Michael Foord5ffa3252010-03-07 22:04:55 +0000176 # Attribute used by TestSuite for classSetUp
177
178 _classSetupFailed = False
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000179
180 def __init__(self, methodName='runTest'):
181 """Create an instance of the class that will use the named test
182 method when executed. Raises a ValueError if the instance does
183 not have a method with the specified name.
184 """
185 self._testMethodName = methodName
186 self._resultForDoCleanups = None
187 try:
188 testMethod = getattr(self, methodName)
189 except AttributeError:
Michael Foordc2294dd2010-02-18 21:37:07 +0000190 raise ValueError("no such test method in %s: %s" %
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000191 (self.__class__, methodName))
192 self._testMethodDoc = testMethod.__doc__
193 self._cleanups = []
194
195 # Map types to custom assertEqual functions that will compare
196 # instances of said type in more detail to generate a more useful
197 # error message.
Benjamin Peterson83c14fe2011-07-12 19:21:42 -0500198 self._type_equality_funcs = {}
Raymond Hettinger67a3e832011-06-25 12:16:25 +0200199 self.addTypeEqualityFunc(dict, 'assertDictEqual')
200 self.addTypeEqualityFunc(list, 'assertListEqual')
201 self.addTypeEqualityFunc(tuple, 'assertTupleEqual')
202 self.addTypeEqualityFunc(set, 'assertSetEqual')
203 self.addTypeEqualityFunc(frozenset, 'assertSetEqual')
Martin v. Löwised11a5d2012-05-20 10:42:17 +0200204 try:
205 self.addTypeEqualityFunc(unicode, 'assertMultiLineEqual')
206 except NameError:
207 # No unicode support in this build
208 pass
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000209
210 def addTypeEqualityFunc(self, typeobj, function):
211 """Add a type specific assertEqual style function to compare a type.
212
213 This method is for use by TestCase subclasses that need to register
214 their own type equality functions to provide nicer error messages.
215
216 Args:
217 typeobj: The data type to call this function on when both values
218 are of the same type in assertEqual().
219 function: The callable taking two arguments and an optional
220 msg= argument that raises self.failureException with a
221 useful error message when the two arguments are not equal.
222 """
Benjamin Petersond46430b2009-11-29 22:26:26 +0000223 self._type_equality_funcs[typeobj] = function
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000224
225 def addCleanup(self, function, *args, **kwargs):
226 """Add a function, with arguments, to be called when the test is
227 completed. Functions added are called on a LIFO basis and are
228 called after tearDown on test failure or success.
229
230 Cleanup items are called even if setUp fails (unlike tearDown)."""
231 self._cleanups.append((function, args, kwargs))
232
233 def setUp(self):
234 "Hook method for setting up the test fixture before exercising it."
235 pass
236
237 def tearDown(self):
238 "Hook method for deconstructing the test fixture after testing it."
239 pass
240
Michael Foord5ffa3252010-03-07 22:04:55 +0000241 @classmethod
242 def setUpClass(cls):
243 "Hook method for setting up class fixture before running tests in the class."
244
245 @classmethod
246 def tearDownClass(cls):
247 "Hook method for deconstructing the class fixture after running all tests in the class."
248
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000249 def countTestCases(self):
250 return 1
251
252 def defaultTestResult(self):
253 return result.TestResult()
254
255 def shortDescription(self):
Michael Foorddb43b5a2010-02-10 14:25:12 +0000256 """Returns a one-line description of the test, or None if no
257 description has been provided.
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000258
Michael Foorddb43b5a2010-02-10 14:25:12 +0000259 The default implementation of this method returns the first line of
260 the specified test method's docstring.
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000261 """
Michael Foorddb43b5a2010-02-10 14:25:12 +0000262 doc = self._testMethodDoc
263 return doc and doc.split("\n")[0].strip() or None
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000264
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000265
266 def id(self):
Michael Foord225a0992010-02-18 20:30:09 +0000267 return "%s.%s" % (strclass(self.__class__), self._testMethodName)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000268
269 def __eq__(self, other):
270 if type(self) is not type(other):
271 return NotImplemented
272
273 return self._testMethodName == other._testMethodName
274
275 def __ne__(self, other):
276 return not self == other
277
278 def __hash__(self):
279 return hash((type(self), self._testMethodName))
280
281 def __str__(self):
Michael Foord225a0992010-02-18 20:30:09 +0000282 return "%s (%s)" % (self._testMethodName, strclass(self.__class__))
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000283
284 def __repr__(self):
285 return "<%s testMethod=%s>" % \
Michael Foord225a0992010-02-18 20:30:09 +0000286 (strclass(self.__class__), self._testMethodName)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000287
Michael Foordae3db0a2010-02-22 23:28:32 +0000288 def _addSkip(self, result, reason):
289 addSkip = getattr(result, 'addSkip', None)
290 if addSkip is not None:
291 addSkip(self, reason)
292 else:
293 warnings.warn("TestResult has no addSkip method, skips not reported",
294 RuntimeWarning, 2)
295 result.addSuccess(self)
296
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000297 def run(self, result=None):
298 orig_result = result
299 if result is None:
300 result = self.defaultTestResult()
301 startTestRun = getattr(result, 'startTestRun', None)
302 if startTestRun is not None:
303 startTestRun()
304
305 self._resultForDoCleanups = result
306 result.startTest(self)
Michael Foord53e8eea2010-03-07 20:22:12 +0000307
308 testMethod = getattr(self, self._testMethodName)
309 if (getattr(self.__class__, "__unittest_skip__", False) or
310 getattr(testMethod, "__unittest_skip__", False)):
311 # If the class or method was skipped.
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000312 try:
Michael Foord53e8eea2010-03-07 20:22:12 +0000313 skip_why = (getattr(self.__class__, '__unittest_skip_why__', '')
314 or getattr(testMethod, '__unittest_skip_why__', ''))
315 self._addSkip(result, skip_why)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000316 finally:
317 result.stopTest(self)
318 return
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000319 try:
320 success = False
321 try:
322 self.setUp()
323 except SkipTest as e:
Michael Foordae3db0a2010-02-22 23:28:32 +0000324 self._addSkip(result, str(e))
Michael Foorda17f0762010-12-19 14:53:19 +0000325 except KeyboardInterrupt:
326 raise
327 except:
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000328 result.addError(self, sys.exc_info())
329 else:
330 try:
331 testMethod()
Michael Foorda17f0762010-12-19 14:53:19 +0000332 except KeyboardInterrupt:
333 raise
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000334 except self.failureException:
335 result.addFailure(self, sys.exc_info())
336 except _ExpectedFailure as e:
Michael Foordae3db0a2010-02-22 23:28:32 +0000337 addExpectedFailure = getattr(result, 'addExpectedFailure', None)
338 if addExpectedFailure is not None:
339 addExpectedFailure(self, e.exc_info)
340 else:
341 warnings.warn("TestResult has no addExpectedFailure method, reporting as passes",
342 RuntimeWarning)
343 result.addSuccess(self)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000344 except _UnexpectedSuccess:
Michael Foordae3db0a2010-02-22 23:28:32 +0000345 addUnexpectedSuccess = getattr(result, 'addUnexpectedSuccess', None)
346 if addUnexpectedSuccess is not None:
347 addUnexpectedSuccess(self)
348 else:
349 warnings.warn("TestResult has no addUnexpectedSuccess method, reporting as failures",
350 RuntimeWarning)
351 result.addFailure(self, sys.exc_info())
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000352 except SkipTest as e:
Michael Foordae3db0a2010-02-22 23:28:32 +0000353 self._addSkip(result, str(e))
Michael Foorda17f0762010-12-19 14:53:19 +0000354 except:
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000355 result.addError(self, sys.exc_info())
356 else:
357 success = True
358
359 try:
360 self.tearDown()
Michael Foorda17f0762010-12-19 14:53:19 +0000361 except KeyboardInterrupt:
362 raise
363 except:
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000364 result.addError(self, sys.exc_info())
365 success = False
366
367 cleanUpSuccess = self.doCleanups()
368 success = success and cleanUpSuccess
369 if success:
370 result.addSuccess(self)
371 finally:
372 result.stopTest(self)
373 if orig_result is None:
374 stopTestRun = getattr(result, 'stopTestRun', None)
375 if stopTestRun is not None:
376 stopTestRun()
377
378 def doCleanups(self):
379 """Execute all cleanup functions. Normally called for you after
380 tearDown."""
381 result = self._resultForDoCleanups
382 ok = True
383 while self._cleanups:
384 function, args, kwargs = self._cleanups.pop(-1)
385 try:
386 function(*args, **kwargs)
Michael Foorda17f0762010-12-19 14:53:19 +0000387 except KeyboardInterrupt:
388 raise
389 except:
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000390 ok = False
391 result.addError(self, sys.exc_info())
392 return ok
393
394 def __call__(self, *args, **kwds):
395 return self.run(*args, **kwds)
396
397 def debug(self):
398 """Run the test without collecting errors in a TestResult"""
399 self.setUp()
400 getattr(self, self._testMethodName)()
401 self.tearDown()
Michael Foord0fedb282010-06-08 22:44:52 +0000402 while self._cleanups:
403 function, args, kwargs = self._cleanups.pop(-1)
404 function(*args, **kwargs)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000405
406 def skipTest(self, reason):
407 """Skip this test."""
408 raise SkipTest(reason)
409
410 def fail(self, msg=None):
411 """Fail immediately, with the given message."""
412 raise self.failureException(msg)
413
414 def assertFalse(self, expr, msg=None):
Ezio Melottic139a562010-12-18 17:58:29 +0000415 """Check that the expression is false."""
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000416 if expr:
Ezio Melottic139a562010-12-18 17:58:29 +0000417 msg = self._formatMessage(msg, "%s is not false" % safe_repr(expr))
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000418 raise self.failureException(msg)
419
420 def assertTrue(self, expr, msg=None):
Ezio Melottic139a562010-12-18 17:58:29 +0000421 """Check that the expression is true."""
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000422 if not expr:
Ezio Melottic139a562010-12-18 17:58:29 +0000423 msg = self._formatMessage(msg, "%s is not true" % safe_repr(expr))
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000424 raise self.failureException(msg)
425
426 def _formatMessage(self, msg, standardMsg):
427 """Honour the longMessage attribute when generating failure messages.
428 If longMessage is False this means:
429 * Use only an explicit message if it is provided
430 * Otherwise use the standard message for the assert
431
432 If longMessage is True:
433 * Use the standard message
434 * If an explicit message is provided, plus ' : ' and the explicit message
435 """
436 if not self.longMessage:
437 return msg or standardMsg
438 if msg is None:
439 return standardMsg
Michael Foord53e8eea2010-03-07 20:22:12 +0000440 try:
441 # don't switch to '{}' formatting in Python 2.X
442 # it changes the way unicode input is handled
443 return '%s : %s' % (standardMsg, msg)
444 except UnicodeDecodeError:
445 return '%s : %s' % (safe_repr(standardMsg), safe_repr(msg))
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000446
447
Serhiy Storchaka7f71e042015-05-06 19:10:40 +0300448 def assertRaises(self, excClass, callableObj=_sentinel, *args, **kwargs):
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200449 """Fail unless an exception of class excClass is raised
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000450 by callableObj when invoked with arguments args and keyword
451 arguments kwargs. If a different type of exception is
Andrew Svetlov4bb142b2012-12-18 21:27:37 +0200452 raised, it will not be caught, and the test case will be
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000453 deemed to have suffered an error, exactly as for an
454 unexpected exception.
455
Serhiy Storchaka7f71e042015-05-06 19:10:40 +0300456 If called with callableObj omitted, will return a
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000457 context object used like this::
458
Michael Foordd0edec32010-02-05 22:55:09 +0000459 with self.assertRaises(SomeException):
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000460 do_something()
Michael Foordd0edec32010-02-05 22:55:09 +0000461
462 The context manager keeps a reference to the exception as
Ezio Melotticd4f6572010-02-08 21:52:08 +0000463 the 'exception' attribute. This allows you to inspect the
Michael Foordd0edec32010-02-05 22:55:09 +0000464 exception after the assertion::
465
466 with self.assertRaises(SomeException) as cm:
467 do_something()
Georg Brandldc3694b2010-02-07 17:02:22 +0000468 the_exception = cm.exception
Michael Foord757cc4d2010-02-05 23:22:37 +0000469 self.assertEqual(the_exception.error_code, 3)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000470 """
471 context = _AssertRaisesContext(excClass, self)
Serhiy Storchaka7f71e042015-05-06 19:10:40 +0300472 if callableObj is _sentinel:
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000473 return context
474 with context:
475 callableObj(*args, **kwargs)
476
477 def _getAssertEqualityFunc(self, first, second):
478 """Get a detailed comparison function for the types of the two args.
479
480 Returns: A callable accepting (first, second, msg=None) that will
481 raise a failure exception if first != second with a useful human
482 readable error message for those types.
483 """
484 #
485 # NOTE(gregory.p.smith): I considered isinstance(first, type(second))
486 # and vice versa. I opted for the conservative approach in case
487 # subclasses are not intended to be compared in detail to their super
488 # class instances using a type equality func. This means testing
489 # subtypes won't automagically use the detailed comparison. Callers
490 # should use their type specific assertSpamEqual method to compare
491 # subclasses if the detailed comparison is desired and appropriate.
492 # See the discussion in http://bugs.python.org/issue2578.
493 #
494 if type(first) is type(second):
495 asserter = self._type_equality_funcs.get(type(first))
496 if asserter is not None:
Benjamin Peterson83c14fe2011-07-12 19:21:42 -0500497 if isinstance(asserter, basestring):
498 asserter = getattr(self, asserter)
Benjamin Petersond46430b2009-11-29 22:26:26 +0000499 return asserter
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000500
501 return self._baseAssertEqual
502
503 def _baseAssertEqual(self, first, second, msg=None):
504 """The default assertEqual implementation, not type specific."""
505 if not first == second:
Michael Foord225a0992010-02-18 20:30:09 +0000506 standardMsg = '%s != %s' % (safe_repr(first), safe_repr(second))
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000507 msg = self._formatMessage(msg, standardMsg)
508 raise self.failureException(msg)
509
510 def assertEqual(self, first, second, msg=None):
511 """Fail if the two objects are unequal as determined by the '=='
512 operator.
513 """
514 assertion_func = self._getAssertEqualityFunc(first, second)
515 assertion_func(first, second, msg=msg)
516
517 def assertNotEqual(self, first, second, msg=None):
Ezio Melotti9b19c4b2012-11-08 11:08:39 +0200518 """Fail if the two objects are equal as determined by the '!='
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000519 operator.
520 """
521 if not first != second:
Michael Foord225a0992010-02-18 20:30:09 +0000522 msg = self._formatMessage(msg, '%s == %s' % (safe_repr(first),
523 safe_repr(second)))
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000524 raise self.failureException(msg)
525
Michael Foorda7e08fe2010-03-27 19:10:11 +0000526
527 def assertAlmostEqual(self, first, second, places=None, msg=None, delta=None):
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000528 """Fail if the two objects are unequal as determined by their
529 difference rounded to the given number of decimal places
Michael Foorda7e08fe2010-03-27 19:10:11 +0000530 (default 7) and comparing to zero, or by comparing that the
531 between the two objects is more than the given delta.
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000532
533 Note that decimal places (from zero) are usually not the same
534 as significant digits (measured from the most signficant digit).
Michael Foordc3f79372009-09-13 16:40:02 +0000535
536 If the two objects compare equal then they will automatically
537 compare almost equal.
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000538 """
Michael Foordc3f79372009-09-13 16:40:02 +0000539 if first == second:
Michael Foorda7e08fe2010-03-27 19:10:11 +0000540 # shortcut
Michael Foordc3f79372009-09-13 16:40:02 +0000541 return
Michael Foorda7e08fe2010-03-27 19:10:11 +0000542 if delta is not None and places is not None:
543 raise TypeError("specify delta or places not both")
544
545 if delta is not None:
546 if abs(first - second) <= delta:
547 return
548
549 standardMsg = '%s != %s within %s delta' % (safe_repr(first),
550 safe_repr(second),
551 safe_repr(delta))
552 else:
553 if places is None:
554 places = 7
555
556 if round(abs(second-first), places) == 0:
557 return
558
Michael Foord225a0992010-02-18 20:30:09 +0000559 standardMsg = '%s != %s within %r places' % (safe_repr(first),
560 safe_repr(second),
561 places)
Michael Foorda7e08fe2010-03-27 19:10:11 +0000562 msg = self._formatMessage(msg, standardMsg)
563 raise self.failureException(msg)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000564
Michael Foorda7e08fe2010-03-27 19:10:11 +0000565 def assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None):
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000566 """Fail if the two objects are equal as determined by their
567 difference rounded to the given number of decimal places
Michael Foorda7e08fe2010-03-27 19:10:11 +0000568 (default 7) and comparing to zero, or by comparing that the
569 between the two objects is less than the given delta.
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000570
571 Note that decimal places (from zero) are usually not the same
572 as significant digits (measured from the most signficant digit).
Michael Foordc3f79372009-09-13 16:40:02 +0000573
574 Objects that are equal automatically fail.
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000575 """
Michael Foorda7e08fe2010-03-27 19:10:11 +0000576 if delta is not None and places is not None:
577 raise TypeError("specify delta or places not both")
578 if delta is not None:
579 if not (first == second) and abs(first - second) > delta:
580 return
581 standardMsg = '%s == %s within %s delta' % (safe_repr(first),
582 safe_repr(second),
583 safe_repr(delta))
584 else:
585 if places is None:
586 places = 7
587 if not (first == second) and round(abs(second-first), places) != 0:
588 return
Michael Foord225a0992010-02-18 20:30:09 +0000589 standardMsg = '%s == %s within %r places' % (safe_repr(first),
Michael Foorda7e08fe2010-03-27 19:10:11 +0000590 safe_repr(second),
591 places)
592
593 msg = self._formatMessage(msg, standardMsg)
594 raise self.failureException(msg)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000595
596 # Synonyms for assertion methods
597
598 # The plurals are undocumented. Keep them that way to discourage use.
599 # Do not add more. Do not remove.
600 # Going through a deprecation cycle on these would annoy many people.
601 assertEquals = assertEqual
602 assertNotEquals = assertNotEqual
603 assertAlmostEquals = assertAlmostEqual
604 assertNotAlmostEquals = assertNotAlmostEqual
Michael Foord67dfc772010-02-10 14:31:30 +0000605 assert_ = assertTrue
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000606
607 # These fail* assertion method names are pending deprecation and will
608 # be a DeprecationWarning in 3.2; http://bugs.python.org/issue2578
609 def _deprecate(original_func):
610 def deprecated_func(*args, **kwargs):
611 warnings.warn(
612 'Please use {0} instead.'.format(original_func.__name__),
613 PendingDeprecationWarning, 2)
614 return original_func(*args, **kwargs)
615 return deprecated_func
616
617 failUnlessEqual = _deprecate(assertEqual)
618 failIfEqual = _deprecate(assertNotEqual)
619 failUnlessAlmostEqual = _deprecate(assertAlmostEqual)
620 failIfAlmostEqual = _deprecate(assertNotAlmostEqual)
621 failUnless = _deprecate(assertTrue)
622 failUnlessRaises = _deprecate(assertRaises)
623 failIf = _deprecate(assertFalse)
624
Michael Foorde37d75f2010-06-05 12:10:52 +0000625 def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000626 """An equality assertion for ordered sequences (like lists and tuples).
627
R. David Murray05b41712010-01-29 19:35:39 +0000628 For the purposes of this function, a valid ordered sequence type is one
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000629 which can be indexed, has a length, and has an equality operator.
630
631 Args:
632 seq1: The first sequence to compare.
633 seq2: The second sequence to compare.
634 seq_type: The expected datatype of the sequences, or None if no
635 datatype should be enforced.
636 msg: Optional message to use on failure instead of a list of
637 differences.
638 """
Florent Xicluna4a0f8b82010-03-21 10:50:44 +0000639 if seq_type is not None:
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000640 seq_type_name = seq_type.__name__
641 if not isinstance(seq1, seq_type):
Michael Foord225a0992010-02-18 20:30:09 +0000642 raise self.failureException('First sequence is not a %s: %s'
643 % (seq_type_name, safe_repr(seq1)))
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000644 if not isinstance(seq2, seq_type):
Michael Foord225a0992010-02-18 20:30:09 +0000645 raise self.failureException('Second sequence is not a %s: %s'
646 % (seq_type_name, safe_repr(seq2)))
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000647 else:
648 seq_type_name = "sequence"
649
650 differing = None
651 try:
652 len1 = len(seq1)
653 except (TypeError, NotImplementedError):
654 differing = 'First %s has no length. Non-sequence?' % (
655 seq_type_name)
656
657 if differing is None:
658 try:
659 len2 = len(seq2)
660 except (TypeError, NotImplementedError):
661 differing = 'Second %s has no length. Non-sequence?' % (
662 seq_type_name)
663
664 if differing is None:
665 if seq1 == seq2:
666 return
667
Michael Foord225a0992010-02-18 20:30:09 +0000668 seq1_repr = safe_repr(seq1)
669 seq2_repr = safe_repr(seq2)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000670 if len(seq1_repr) > 30:
671 seq1_repr = seq1_repr[:30] + '...'
672 if len(seq2_repr) > 30:
673 seq2_repr = seq2_repr[:30] + '...'
674 elements = (seq_type_name.capitalize(), seq1_repr, seq2_repr)
675 differing = '%ss differ: %s != %s\n' % elements
676
677 for i in xrange(min(len1, len2)):
678 try:
679 item1 = seq1[i]
680 except (TypeError, IndexError, NotImplementedError):
681 differing += ('\nUnable to index element %d of first %s\n' %
682 (i, seq_type_name))
683 break
684
685 try:
686 item2 = seq2[i]
687 except (TypeError, IndexError, NotImplementedError):
688 differing += ('\nUnable to index element %d of second %s\n' %
689 (i, seq_type_name))
690 break
691
692 if item1 != item2:
693 differing += ('\nFirst differing element %d:\n%s\n%s\n' %
694 (i, item1, item2))
695 break
696 else:
697 if (len1 == len2 and seq_type is None and
698 type(seq1) != type(seq2)):
699 # The sequences are the same, but have differing types.
700 return
701
702 if len1 > len2:
703 differing += ('\nFirst %s contains %d additional '
704 'elements.\n' % (seq_type_name, len1 - len2))
705 try:
706 differing += ('First extra element %d:\n%s\n' %
707 (len2, seq1[len2]))
708 except (TypeError, IndexError, NotImplementedError):
709 differing += ('Unable to index element %d '
710 'of first %s\n' % (len2, seq_type_name))
711 elif len1 < len2:
712 differing += ('\nSecond %s contains %d additional '
713 'elements.\n' % (seq_type_name, len2 - len1))
714 try:
715 differing += ('First extra element %d:\n%s\n' %
716 (len1, seq2[len1]))
717 except (TypeError, IndexError, NotImplementedError):
718 differing += ('Unable to index element %d '
719 'of second %s\n' % (len1, seq_type_name))
Michael Foord01007022010-06-05 11:23:51 +0000720 standardMsg = differing
721 diffMsg = '\n' + '\n'.join(
Georg Brandl46cc46a2009-10-01 20:11:14 +0000722 difflib.ndiff(pprint.pformat(seq1).splitlines(),
723 pprint.pformat(seq2).splitlines()))
Michael Foorde37d75f2010-06-05 12:10:52 +0000724 standardMsg = self._truncateMessage(standardMsg, diffMsg)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000725 msg = self._formatMessage(msg, standardMsg)
726 self.fail(msg)
727
Michael Foorde37d75f2010-06-05 12:10:52 +0000728 def _truncateMessage(self, message, diff):
729 max_diff = self.maxDiff
Michael Foorda4412872010-06-05 11:46:59 +0000730 if max_diff is None or len(diff) <= max_diff:
731 return message + diff
Michael Foord5fe21ff2010-06-05 13:38:16 +0000732 return message + (DIFF_OMITTED % len(diff))
Michael Foorda4412872010-06-05 11:46:59 +0000733
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000734 def assertListEqual(self, list1, list2, msg=None):
735 """A list-specific equality assertion.
736
737 Args:
738 list1: The first list to compare.
739 list2: The second list to compare.
740 msg: Optional message to use on failure instead of a list of
741 differences.
742
743 """
744 self.assertSequenceEqual(list1, list2, msg, seq_type=list)
745
746 def assertTupleEqual(self, tuple1, tuple2, msg=None):
747 """A tuple-specific equality assertion.
748
749 Args:
750 tuple1: The first tuple to compare.
751 tuple2: The second tuple to compare.
752 msg: Optional message to use on failure instead of a list of
753 differences.
754 """
755 self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
756
757 def assertSetEqual(self, set1, set2, msg=None):
758 """A set-specific equality assertion.
759
760 Args:
761 set1: The first set to compare.
762 set2: The second set to compare.
763 msg: Optional message to use on failure instead of a list of
764 differences.
765
Michael Foord98e7b762010-03-20 03:00:34 +0000766 assertSetEqual uses ducktyping to support different types of sets, and
767 is optimized for sets specifically (parameters must support a
768 difference method).
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000769 """
770 try:
771 difference1 = set1.difference(set2)
772 except TypeError, e:
773 self.fail('invalid type when attempting set difference: %s' % e)
774 except AttributeError, e:
775 self.fail('first argument does not support set difference: %s' % e)
776
777 try:
778 difference2 = set2.difference(set1)
779 except TypeError, e:
780 self.fail('invalid type when attempting set difference: %s' % e)
781 except AttributeError, e:
782 self.fail('second argument does not support set difference: %s' % e)
783
784 if not (difference1 or difference2):
785 return
786
787 lines = []
788 if difference1:
789 lines.append('Items in the first set but not the second:')
790 for item in difference1:
791 lines.append(repr(item))
792 if difference2:
793 lines.append('Items in the second set but not the first:')
794 for item in difference2:
795 lines.append(repr(item))
796
797 standardMsg = '\n'.join(lines)
798 self.fail(self._formatMessage(msg, standardMsg))
799
800 def assertIn(self, member, container, msg=None):
801 """Just like self.assertTrue(a in b), but with a nicer default message."""
802 if member not in container:
Michael Foord225a0992010-02-18 20:30:09 +0000803 standardMsg = '%s not found in %s' % (safe_repr(member),
804 safe_repr(container))
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000805 self.fail(self._formatMessage(msg, standardMsg))
806
807 def assertNotIn(self, member, container, msg=None):
808 """Just like self.assertTrue(a not in b), but with a nicer default message."""
809 if member in container:
Michael Foord225a0992010-02-18 20:30:09 +0000810 standardMsg = '%s unexpectedly found in %s' % (safe_repr(member),
811 safe_repr(container))
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000812 self.fail(self._formatMessage(msg, standardMsg))
813
814 def assertIs(self, expr1, expr2, msg=None):
815 """Just like self.assertTrue(a is b), but with a nicer default message."""
816 if expr1 is not expr2:
Michael Foord225a0992010-02-18 20:30:09 +0000817 standardMsg = '%s is not %s' % (safe_repr(expr1),
Michael Foordc2294dd2010-02-18 21:37:07 +0000818 safe_repr(expr2))
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000819 self.fail(self._formatMessage(msg, standardMsg))
820
821 def assertIsNot(self, expr1, expr2, msg=None):
822 """Just like self.assertTrue(a is not b), but with a nicer default message."""
823 if expr1 is expr2:
Michael Foord225a0992010-02-18 20:30:09 +0000824 standardMsg = 'unexpectedly identical: %s' % (safe_repr(expr1),)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000825 self.fail(self._formatMessage(msg, standardMsg))
826
827 def assertDictEqual(self, d1, d2, msg=None):
Ezio Melotti2623a372010-11-21 13:34:58 +0000828 self.assertIsInstance(d1, dict, 'First argument is not a dictionary')
829 self.assertIsInstance(d2, dict, 'Second argument is not a dictionary')
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000830
831 if d1 != d2:
Michael Foord674648e2010-06-05 12:58:39 +0000832 standardMsg = '%s != %s' % (safe_repr(d1, True), safe_repr(d2, True))
Michael Foorde37d75f2010-06-05 12:10:52 +0000833 diff = ('\n' + '\n'.join(difflib.ndiff(
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000834 pprint.pformat(d1).splitlines(),
835 pprint.pformat(d2).splitlines())))
Michael Foord674648e2010-06-05 12:58:39 +0000836 standardMsg = self._truncateMessage(standardMsg, diff)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000837 self.fail(self._formatMessage(msg, standardMsg))
838
839 def assertDictContainsSubset(self, expected, actual, msg=None):
840 """Checks whether actual is a superset of expected."""
841 missing = []
842 mismatched = []
843 for key, value in expected.iteritems():
844 if key not in actual:
845 missing.append(key)
846 elif value != actual[key]:
Georg Brandl46cc46a2009-10-01 20:11:14 +0000847 mismatched.append('%s, expected: %s, actual: %s' %
Michael Foordc2294dd2010-02-18 21:37:07 +0000848 (safe_repr(key), safe_repr(value),
849 safe_repr(actual[key])))
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000850
851 if not (missing or mismatched):
852 return
853
854 standardMsg = ''
855 if missing:
Michael Foord225a0992010-02-18 20:30:09 +0000856 standardMsg = 'Missing: %s' % ','.join(safe_repr(m) for m in
857 missing)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000858 if mismatched:
859 if standardMsg:
860 standardMsg += '; '
861 standardMsg += 'Mismatched values: %s' % ','.join(mismatched)
862
863 self.fail(self._formatMessage(msg, standardMsg))
864
Michael Foord98e7b762010-03-20 03:00:34 +0000865 def assertItemsEqual(self, expected_seq, actual_seq, msg=None):
Michael Foorde6e0e262010-12-19 15:52:56 +0000866 """An unordered sequence specific comparison. It asserts that
867 actual_seq and expected_seq have the same element counts.
868 Equivalent to::
Michael Foord98e7b762010-03-20 03:00:34 +0000869
Michael Foorde6e0e262010-12-19 15:52:56 +0000870 self.assertEqual(Counter(iter(actual_seq)),
871 Counter(iter(expected_seq)))
Michael Foordd0edec32010-02-05 22:55:09 +0000872
Michael Foord98e7b762010-03-20 03:00:34 +0000873 Asserts that each element has the same count in both sequences.
874 Example:
875 - [0, 1, 1] and [1, 0, 1] compare equal.
876 - [0, 0, 1] and [0, 1] compare unequal.
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000877 """
R David Murray69493922012-05-16 14:01:03 -0400878 first_seq, second_seq = list(expected_seq), list(actual_seq)
Florent Xicluna1f3b4e12010-03-07 12:14:25 +0000879 with warnings.catch_warnings():
880 if sys.py3kwarning:
881 # Silence Py3k warning raised during the sorting
Florent Xicluna4a0f8b82010-03-21 10:50:44 +0000882 for _msg in ["(code|dict|type) inequality comparisons",
Michael Foord98e7b762010-03-20 03:00:34 +0000883 "builtin_function_or_method order comparisons",
884 "comparing unequal types"]:
Michael Foorda7152552010-03-07 23:10:36 +0000885 warnings.filterwarnings("ignore", _msg, DeprecationWarning)
Florent Xicluna1f3b4e12010-03-07 12:14:25 +0000886 try:
Michael Foord4c9e91a2011-03-16 20:34:53 -0400887 first = collections.Counter(first_seq)
888 second = collections.Counter(second_seq)
Michael Foord98e7b762010-03-20 03:00:34 +0000889 except TypeError:
Michael Foord4c9e91a2011-03-16 20:34:53 -0400890 # Handle case with unhashable elements
891 differences = _count_diff_all_purpose(first_seq, second_seq)
Michael Foord98e7b762010-03-20 03:00:34 +0000892 else:
Michael Foord4c9e91a2011-03-16 20:34:53 -0400893 if first == second:
Michael Foorde6e0e262010-12-19 15:52:56 +0000894 return
Michael Foord4c9e91a2011-03-16 20:34:53 -0400895 differences = _count_diff_hashable(first_seq, second_seq)
Michael Foord98e7b762010-03-20 03:00:34 +0000896
Michael Foord4c9e91a2011-03-16 20:34:53 -0400897 if differences:
898 standardMsg = 'Element counts were not equal:\n'
899 lines = ['First has %d, Second has %d: %r' % diff for diff in differences]
900 diffMsg = '\n'.join(lines)
901 standardMsg = self._truncateMessage(standardMsg, diffMsg)
902 msg = self._formatMessage(msg, standardMsg)
903 self.fail(msg)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000904
905 def assertMultiLineEqual(self, first, second, msg=None):
906 """Assert that two multi-line strings are equal."""
Ezio Melotti2623a372010-11-21 13:34:58 +0000907 self.assertIsInstance(first, basestring,
908 'First argument is not a string')
909 self.assertIsInstance(second, basestring,
910 'Second argument is not a string')
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000911
912 if first != second:
Ezio Melotti34b32d62011-04-27 09:45:46 +0300913 # don't use difflib if the strings are too long
914 if (len(first) > self._diffThreshold or
915 len(second) > self._diffThreshold):
916 self._baseAssertEqual(first, second, msg)
Michael Foord94f071c2010-07-10 13:51:42 +0000917 firstlines = first.splitlines(True)
918 secondlines = second.splitlines(True)
919 if len(firstlines) == 1 and first.strip('\r\n') == first:
920 firstlines = [first + '\n']
921 secondlines = [second + '\n']
922 standardMsg = '%s != %s' % (safe_repr(first, True),
923 safe_repr(second, True))
924 diff = '\n' + ''.join(difflib.ndiff(firstlines, secondlines))
Michael Foord674648e2010-06-05 12:58:39 +0000925 standardMsg = self._truncateMessage(standardMsg, diff)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000926 self.fail(self._formatMessage(msg, standardMsg))
927
928 def assertLess(self, a, b, msg=None):
929 """Just like self.assertTrue(a < b), but with a nicer default message."""
930 if not a < b:
Michael Foord225a0992010-02-18 20:30:09 +0000931 standardMsg = '%s not less than %s' % (safe_repr(a), safe_repr(b))
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000932 self.fail(self._formatMessage(msg, standardMsg))
933
934 def assertLessEqual(self, a, b, msg=None):
935 """Just like self.assertTrue(a <= b), but with a nicer default message."""
936 if not a <= b:
Michael Foord225a0992010-02-18 20:30:09 +0000937 standardMsg = '%s not less than or equal to %s' % (safe_repr(a), safe_repr(b))
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000938 self.fail(self._formatMessage(msg, standardMsg))
939
940 def assertGreater(self, a, b, msg=None):
941 """Just like self.assertTrue(a > b), but with a nicer default message."""
942 if not a > b:
Michael Foord225a0992010-02-18 20:30:09 +0000943 standardMsg = '%s not greater than %s' % (safe_repr(a), safe_repr(b))
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000944 self.fail(self._formatMessage(msg, standardMsg))
945
946 def assertGreaterEqual(self, a, b, msg=None):
947 """Just like self.assertTrue(a >= b), but with a nicer default message."""
948 if not a >= b:
Michael Foord225a0992010-02-18 20:30:09 +0000949 standardMsg = '%s not greater than or equal to %s' % (safe_repr(a), safe_repr(b))
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000950 self.fail(self._formatMessage(msg, standardMsg))
951
952 def assertIsNone(self, obj, msg=None):
953 """Same as self.assertTrue(obj is None), with a nicer default message."""
954 if obj is not None:
Michael Foord225a0992010-02-18 20:30:09 +0000955 standardMsg = '%s is not None' % (safe_repr(obj),)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000956 self.fail(self._formatMessage(msg, standardMsg))
957
958 def assertIsNotNone(self, obj, msg=None):
959 """Included for symmetry with assertIsNone."""
960 if obj is None:
961 standardMsg = 'unexpectedly None'
962 self.fail(self._formatMessage(msg, standardMsg))
963
Georg Brandlf895cf52009-10-01 20:59:31 +0000964 def assertIsInstance(self, obj, cls, msg=None):
965 """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
966 default message."""
967 if not isinstance(obj, cls):
Michael Foord225a0992010-02-18 20:30:09 +0000968 standardMsg = '%s is not an instance of %r' % (safe_repr(obj), cls)
Georg Brandlf895cf52009-10-01 20:59:31 +0000969 self.fail(self._formatMessage(msg, standardMsg))
970
971 def assertNotIsInstance(self, obj, cls, msg=None):
972 """Included for symmetry with assertIsInstance."""
973 if isinstance(obj, cls):
Michael Foord225a0992010-02-18 20:30:09 +0000974 standardMsg = '%s is an instance of %r' % (safe_repr(obj), cls)
Georg Brandlf895cf52009-10-01 20:59:31 +0000975 self.fail(self._formatMessage(msg, standardMsg))
976
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000977 def assertRaisesRegexp(self, expected_exception, expected_regexp,
Serhiy Storchaka7f71e042015-05-06 19:10:40 +0300978 callable_obj=_sentinel, *args, **kwargs):
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000979 """Asserts that the message in a raised exception matches a regexp.
980
981 Args:
982 expected_exception: Exception class expected to be raised.
983 expected_regexp: Regexp (re pattern object or string) expected
984 to be found in error message.
985 callable_obj: Function to be called.
986 args: Extra args.
987 kwargs: Extra kwargs.
988 """
R David Murray6d911762014-03-25 15:29:42 -0400989 if expected_regexp is not None:
990 expected_regexp = re.compile(expected_regexp)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000991 context = _AssertRaisesContext(expected_exception, self, expected_regexp)
Serhiy Storchaka7f71e042015-05-06 19:10:40 +0300992 if callable_obj is _sentinel:
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +0000993 return context
994 with context:
995 callable_obj(*args, **kwargs)
996
Georg Brandlb0eb4d32010-02-07 11:34:15 +0000997 def assertRegexpMatches(self, text, expected_regexp, msg=None):
Michael Foord959c16d2010-05-08 16:40:52 +0000998 """Fail the test unless the text matches the regular expression."""
Georg Brandlb0eb4d32010-02-07 11:34:15 +0000999 if isinstance(expected_regexp, basestring):
1000 expected_regexp = re.compile(expected_regexp)
1001 if not expected_regexp.search(text):
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001002 msg = msg or "Regexp didn't match"
Georg Brandlb0eb4d32010-02-07 11:34:15 +00001003 msg = '%s: %r not found in %r' % (msg, expected_regexp.pattern, text)
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001004 raise self.failureException(msg)
1005
Michael Foorda04c7a02010-04-02 22:55:59 +00001006 def assertNotRegexpMatches(self, text, unexpected_regexp, msg=None):
Michael Foord959c16d2010-05-08 16:40:52 +00001007 """Fail the test if the text matches the regular expression."""
Michael Foorda04c7a02010-04-02 22:55:59 +00001008 if isinstance(unexpected_regexp, basestring):
1009 unexpected_regexp = re.compile(unexpected_regexp)
1010 match = unexpected_regexp.search(text)
1011 if match:
1012 msg = msg or "Regexp matched"
1013 msg = '%s: %r matches %r in %r' % (msg,
1014 text[match.start():match.end()],
1015 unexpected_regexp.pattern,
1016 text)
1017 raise self.failureException(msg)
1018
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001019
1020class FunctionTestCase(TestCase):
1021 """A test case that wraps a test function.
1022
1023 This is useful for slipping pre-existing test functions into the
1024 unittest framework. Optionally, set-up and tidy-up functions can be
1025 supplied. As with TestCase, the tidy-up ('tearDown') function will
1026 always be called if the set-up ('setUp') function ran successfully.
1027 """
1028
1029 def __init__(self, testFunc, setUp=None, tearDown=None, description=None):
1030 super(FunctionTestCase, self).__init__()
1031 self._setUpFunc = setUp
1032 self._tearDownFunc = tearDown
1033 self._testFunc = testFunc
1034 self._description = description
1035
1036 def setUp(self):
1037 if self._setUpFunc is not None:
1038 self._setUpFunc()
1039
1040 def tearDown(self):
1041 if self._tearDownFunc is not None:
1042 self._tearDownFunc()
1043
1044 def runTest(self):
1045 self._testFunc()
1046
1047 def id(self):
1048 return self._testFunc.__name__
1049
1050 def __eq__(self, other):
1051 if not isinstance(other, self.__class__):
1052 return NotImplemented
1053
1054 return self._setUpFunc == other._setUpFunc and \
1055 self._tearDownFunc == other._tearDownFunc and \
1056 self._testFunc == other._testFunc and \
1057 self._description == other._description
1058
1059 def __ne__(self, other):
1060 return not self == other
1061
1062 def __hash__(self):
1063 return hash((type(self), self._setUpFunc, self._tearDownFunc,
1064 self._testFunc, self._description))
1065
1066 def __str__(self):
Michael Foord225a0992010-02-18 20:30:09 +00001067 return "%s (%s)" % (strclass(self.__class__),
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001068 self._testFunc.__name__)
1069
1070 def __repr__(self):
Michael Foord225a0992010-02-18 20:30:09 +00001071 return "<%s tec=%s>" % (strclass(self.__class__),
Benjamin Petersond7b0eeb2009-07-19 20:18:21 +00001072 self._testFunc)
1073
1074 def shortDescription(self):
1075 if self._description is not None:
1076 return self._description
1077 doc = self._testFunc.__doc__
1078 return doc and doc.split("\n")[0].strip() or None