blob: 0ad78571b2582bd66af4b12bae478461113d063d [file] [log] [blame]
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001"""Test case implementation"""
2
3import sys
4import functools
5import difflib
6import pprint
7import re
8import warnings
Raymond Hettinger6e165b32010-11-27 09:31:37 +00009import collections
Benjamin Petersonbed7d042009-07-19 21:01:52 +000010
Benjamin Peterson847a4112010-03-14 15:04:17 +000011from . import result
12from .util import (strclass, safe_repr, sorted_list_difference,
13 unorderable_list_difference)
Benjamin Petersonbed7d042009-07-19 21:01:52 +000014
Benjamin Petersondccc1fc2010-03-22 00:15:53 +000015__unittest = True
Benjamin Petersonbed7d042009-07-19 21:01:52 +000016
Michael Foord9dad32e2010-06-05 13:49:56 +000017
18DIFF_OMITTED = ('\nDiff is %s characters long. '
19 'Set self.maxDiff to None to see it.')
20
Benjamin Petersonbed7d042009-07-19 21:01:52 +000021class SkipTest(Exception):
22 """
23 Raise this exception in a test to skip it.
24
25 Usually you can use TestResult.skip() or one of the skipping decorators
26 instead of raising this directly.
27 """
28 pass
29
30class _ExpectedFailure(Exception):
31 """
32 Raise this when a test is expected to fail.
33
34 This is an implementation detail.
35 """
36
37 def __init__(self, exc_info):
38 super(_ExpectedFailure, self).__init__()
39 self.exc_info = exc_info
40
41class _UnexpectedSuccess(Exception):
42 """
43 The test was supposed to fail, but it didn't!
44 """
45 pass
46
47def _id(obj):
48 return obj
49
50def skip(reason):
51 """
52 Unconditionally skip a test.
53 """
54 def decorator(test_item):
Benjamin Peterson847a4112010-03-14 15:04:17 +000055 if not (isinstance(test_item, type) and issubclass(test_item, TestCase)):
56 @functools.wraps(test_item)
57 def skip_wrapper(*args, **kwargs):
58 raise SkipTest(reason)
59 test_item = skip_wrapper
60
61 test_item.__unittest_skip__ = True
62 test_item.__unittest_skip_why__ = reason
63 return test_item
Benjamin Petersonbed7d042009-07-19 21:01:52 +000064 return decorator
65
66def skipIf(condition, reason):
67 """
68 Skip a test if the condition is true.
69 """
70 if condition:
71 return skip(reason)
72 return _id
73
74def skipUnless(condition, reason):
75 """
76 Skip a test unless the condition is true.
77 """
78 if not condition:
79 return skip(reason)
80 return _id
81
82
83def expectedFailure(func):
84 @functools.wraps(func)
85 def wrapper(*args, **kwargs):
86 try:
87 func(*args, **kwargs)
88 except Exception:
89 raise _ExpectedFailure(sys.exc_info())
90 raise _UnexpectedSuccess
91 return wrapper
92
93
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +000094class _AssertRaisesBaseContext(object):
Benjamin Petersonbed7d042009-07-19 21:01:52 +000095
96 def __init__(self, expected, test_case, callable_obj=None,
Ezio Melottied3a7d22010-12-01 02:32:32 +000097 expected_regex=None):
Benjamin Petersonbed7d042009-07-19 21:01:52 +000098 self.expected = expected
99 self.failureException = test_case.failureException
100 if callable_obj is not None:
101 try:
102 self.obj_name = callable_obj.__name__
103 except AttributeError:
104 self.obj_name = str(callable_obj)
105 else:
106 self.obj_name = None
Ezio Melottied3a7d22010-12-01 02:32:32 +0000107 if isinstance(expected_regex, (bytes, str)):
108 expected_regex = re.compile(expected_regex)
109 self.expected_regex = expected_regex
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000110
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000111
112class _AssertRaisesContext(_AssertRaisesBaseContext):
113 """A context manager used to implement TestCase.assertRaises* methods."""
114
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000115 def __enter__(self):
Ezio Melotti49008232010-02-08 21:57:48 +0000116 return self
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000117
118 def __exit__(self, exc_type, exc_value, tb):
119 if exc_type is None:
120 try:
121 exc_name = self.expected.__name__
122 except AttributeError:
123 exc_name = str(self.expected)
124 if self.obj_name:
125 raise self.failureException("{0} not raised by {1}"
126 .format(exc_name, self.obj_name))
127 else:
128 raise self.failureException("{0} not raised"
129 .format(exc_name))
130 if not issubclass(exc_type, self.expected):
131 # let unexpected exceptions pass through
132 return False
Ezio Melotti49008232010-02-08 21:57:48 +0000133 # store exception, without traceback, for later retrieval
134 self.exception = exc_value.with_traceback(None)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000135 if self.expected_regex is None:
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000136 return True
137
Ezio Melottied3a7d22010-12-01 02:32:32 +0000138 expected_regex = self.expected_regex
139 if not expected_regex.search(str(exc_value)):
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000140 raise self.failureException('"%s" does not match "%s"' %
Ezio Melottied3a7d22010-12-01 02:32:32 +0000141 (expected_regex.pattern, str(exc_value)))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000142 return True
143
144
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000145class _AssertWarnsContext(_AssertRaisesBaseContext):
146 """A context manager used to implement TestCase.assertWarns* methods."""
147
148 def __enter__(self):
149 # The __warningregistry__'s need to be in a pristine state for tests
150 # to work properly.
151 for v in sys.modules.values():
152 if getattr(v, '__warningregistry__', None):
153 v.__warningregistry__ = {}
154 self.warnings_manager = warnings.catch_warnings(record=True)
155 self.warnings = self.warnings_manager.__enter__()
156 warnings.simplefilter("always", self.expected)
157 return self
158
159 def __exit__(self, exc_type, exc_value, tb):
160 self.warnings_manager.__exit__(exc_type, exc_value, tb)
161 if exc_type is not None:
162 # let unexpected exceptions pass through
163 return
164 try:
165 exc_name = self.expected.__name__
166 except AttributeError:
167 exc_name = str(self.expected)
168 first_matching = None
169 for m in self.warnings:
170 w = m.message
171 if not isinstance(w, self.expected):
172 continue
173 if first_matching is None:
174 first_matching = w
Ezio Melottied3a7d22010-12-01 02:32:32 +0000175 if (self.expected_regex is not None and
176 not self.expected_regex.search(str(w))):
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000177 continue
178 # store warning for later retrieval
179 self.warning = w
180 self.filename = m.filename
181 self.lineno = m.lineno
182 return
183 # Now we simply try to choose a helpful failure message
184 if first_matching is not None:
185 raise self.failureException('"%s" does not match "%s"' %
Ezio Melottied3a7d22010-12-01 02:32:32 +0000186 (self.expected_regex.pattern, str(first_matching)))
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000187 if self.obj_name:
188 raise self.failureException("{0} not triggered by {1}"
189 .format(exc_name, self.obj_name))
190 else:
191 raise self.failureException("{0} not triggered"
192 .format(exc_name))
193
194
Michael Foord8ca6d982010-11-20 15:34:26 +0000195class _TypeEqualityDict(object):
196
197 def __init__(self, testcase):
198 self.testcase = testcase
199 self._store = {}
200
201 def __setitem__(self, key, value):
202 self._store[key] = value
203
204 def __getitem__(self, key):
205 value = self._store[key]
206 if isinstance(value, str):
207 return getattr(self.testcase, value)
208 return value
209
210 def get(self, key, default=None):
211 if key in self._store:
212 return self[key]
213 return default
214
215
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000216class TestCase(object):
217 """A class whose instances are single test cases.
218
219 By default, the test code itself should be placed in a method named
220 'runTest'.
221
222 If the fixture may be used for many test cases, create as
223 many test methods as are needed. When instantiating such a TestCase
224 subclass, specify in the constructor arguments the name of the test method
225 that the instance is to execute.
226
227 Test authors should subclass TestCase for their own tests. Construction
228 and deconstruction of the test's environment ('fixture') can be
229 implemented by overriding the 'setUp' and 'tearDown' methods respectively.
230
231 If it is necessary to override the __init__ method, the base class
232 __init__ method must always be called. It is important that subclasses
233 should not change the signature of their __init__ method, since instances
234 of the classes are instantiated automatically by parts of the framework
235 in order to be run.
236 """
237
238 # This attribute determines which exception will be raised when
239 # the instance's assertion methods fail; test methods raising this
240 # exception will be deemed to have 'failed' rather than 'errored'
241
242 failureException = AssertionError
243
244 # This attribute determines whether long messages (including repr of
245 # objects used in assert methods) will be printed on failure in *addition*
246 # to any explicit message passed.
247
Michael Foord5074df62010-12-03 00:53:09 +0000248 longMessage = True
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000249
Michael Foordc41d1412010-06-10 16:17:07 +0000250 # This attribute sets the maximum length of a diff in failure messages
Michael Foord085dfd32010-06-05 12:17:02 +0000251 # by assert methods using difflib. It is looked up as an instance attribute
252 # so can be configured by individual tests if required.
Michael Foordd50a6b92010-06-05 23:59:34 +0000253
Michael Foord085dfd32010-06-05 12:17:02 +0000254 maxDiff = 80*8
255
Benjamin Peterson847a4112010-03-14 15:04:17 +0000256 # Attribute used by TestSuite for classSetUp
257
258 _classSetupFailed = False
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000259
260 def __init__(self, methodName='runTest'):
261 """Create an instance of the class that will use the named test
262 method when executed. Raises a ValueError if the instance does
263 not have a method with the specified name.
264 """
265 self._testMethodName = methodName
266 self._resultForDoCleanups = None
267 try:
268 testMethod = getattr(self, methodName)
269 except AttributeError:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000270 raise ValueError("no such test method in %s: %s" %
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000271 (self.__class__, methodName))
272 self._testMethodDoc = testMethod.__doc__
273 self._cleanups = []
274
275 # Map types to custom assertEqual functions that will compare
276 # instances of said type in more detail to generate a more useful
277 # error message.
Michael Foord8ca6d982010-11-20 15:34:26 +0000278 self._type_equality_funcs = _TypeEqualityDict(self)
279 self.addTypeEqualityFunc(dict, 'assertDictEqual')
280 self.addTypeEqualityFunc(list, 'assertListEqual')
281 self.addTypeEqualityFunc(tuple, 'assertTupleEqual')
282 self.addTypeEqualityFunc(set, 'assertSetEqual')
283 self.addTypeEqualityFunc(frozenset, 'assertSetEqual')
284 self.addTypeEqualityFunc(str, 'assertMultiLineEqual')
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000285
286 def addTypeEqualityFunc(self, typeobj, function):
287 """Add a type specific assertEqual style function to compare a type.
288
289 This method is for use by TestCase subclasses that need to register
290 their own type equality functions to provide nicer error messages.
291
292 Args:
293 typeobj: The data type to call this function on when both values
294 are of the same type in assertEqual().
295 function: The callable taking two arguments and an optional
296 msg= argument that raises self.failureException with a
297 useful error message when the two arguments are not equal.
298 """
Benjamin Peterson8f326b22009-12-13 02:10:36 +0000299 self._type_equality_funcs[typeobj] = function
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000300
301 def addCleanup(self, function, *args, **kwargs):
302 """Add a function, with arguments, to be called when the test is
303 completed. Functions added are called on a LIFO basis and are
304 called after tearDown on test failure or success.
305
306 Cleanup items are called even if setUp fails (unlike tearDown)."""
307 self._cleanups.append((function, args, kwargs))
308
309 def setUp(self):
310 "Hook method for setting up the test fixture before exercising it."
311 pass
312
313 def tearDown(self):
314 "Hook method for deconstructing the test fixture after testing it."
315 pass
316
Benjamin Peterson847a4112010-03-14 15:04:17 +0000317 @classmethod
318 def setUpClass(cls):
319 "Hook method for setting up class fixture before running tests in the class."
320
321 @classmethod
322 def tearDownClass(cls):
323 "Hook method for deconstructing the class fixture after running all tests in the class."
324
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000325 def countTestCases(self):
326 return 1
327
328 def defaultTestResult(self):
329 return result.TestResult()
330
331 def shortDescription(self):
Michael Foord34c94622010-02-10 15:51:42 +0000332 """Returns a one-line description of the test, or None if no
333 description has been provided.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000334
Michael Foord34c94622010-02-10 15:51:42 +0000335 The default implementation of this method returns the first line of
336 the specified test method's docstring.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000337 """
Michael Foord34c94622010-02-10 15:51:42 +0000338 doc = self._testMethodDoc
339 return doc and doc.split("\n")[0].strip() or None
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000340
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000341
342 def id(self):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000343 return "%s.%s" % (strclass(self.__class__), self._testMethodName)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000344
345 def __eq__(self, other):
346 if type(self) is not type(other):
347 return NotImplemented
348
349 return self._testMethodName == other._testMethodName
350
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000351 def __hash__(self):
352 return hash((type(self), self._testMethodName))
353
354 def __str__(self):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000355 return "%s (%s)" % (self._testMethodName, strclass(self.__class__))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000356
357 def __repr__(self):
358 return "<%s testMethod=%s>" % \
Benjamin Peterson847a4112010-03-14 15:04:17 +0000359 (strclass(self.__class__), self._testMethodName)
360
361 def _addSkip(self, result, reason):
362 addSkip = getattr(result, 'addSkip', None)
363 if addSkip is not None:
364 addSkip(self, reason)
365 else:
366 warnings.warn("TestResult has no addSkip method, skips not reported",
367 RuntimeWarning, 2)
368 result.addSuccess(self)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000369
370 def run(self, result=None):
371 orig_result = result
372 if result is None:
373 result = self.defaultTestResult()
374 startTestRun = getattr(result, 'startTestRun', None)
375 if startTestRun is not None:
376 startTestRun()
377
378 self._resultForDoCleanups = result
379 result.startTest(self)
Benjamin Peterson847a4112010-03-14 15:04:17 +0000380
381 testMethod = getattr(self, self._testMethodName)
382 if (getattr(self.__class__, "__unittest_skip__", False) or
383 getattr(testMethod, "__unittest_skip__", False)):
384 # If the class or method was skipped.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000385 try:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000386 skip_why = (getattr(self.__class__, '__unittest_skip_why__', '')
387 or getattr(testMethod, '__unittest_skip_why__', ''))
388 self._addSkip(result, skip_why)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000389 finally:
390 result.stopTest(self)
391 return
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000392 try:
393 success = False
394 try:
395 self.setUp()
396 except SkipTest as e:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000397 self._addSkip(result, str(e))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000398 except Exception:
399 result.addError(self, sys.exc_info())
400 else:
401 try:
402 testMethod()
403 except self.failureException:
404 result.addFailure(self, sys.exc_info())
405 except _ExpectedFailure as e:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000406 addExpectedFailure = getattr(result, 'addExpectedFailure', None)
407 if addExpectedFailure is not None:
408 addExpectedFailure(self, e.exc_info)
409 else:
410 warnings.warn("TestResult has no addExpectedFailure method, reporting as passes",
411 RuntimeWarning)
412 result.addSuccess(self)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000413 except _UnexpectedSuccess:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000414 addUnexpectedSuccess = getattr(result, 'addUnexpectedSuccess', None)
415 if addUnexpectedSuccess is not None:
416 addUnexpectedSuccess(self)
417 else:
418 warnings.warn("TestResult has no addUnexpectedSuccess method, reporting as failures",
419 RuntimeWarning)
420 result.addFailure(self, sys.exc_info())
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000421 except SkipTest as e:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000422 self._addSkip(result, str(e))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000423 except Exception:
424 result.addError(self, sys.exc_info())
425 else:
426 success = True
427
428 try:
429 self.tearDown()
430 except Exception:
431 result.addError(self, sys.exc_info())
432 success = False
433
434 cleanUpSuccess = self.doCleanups()
435 success = success and cleanUpSuccess
436 if success:
437 result.addSuccess(self)
438 finally:
439 result.stopTest(self)
440 if orig_result is None:
441 stopTestRun = getattr(result, 'stopTestRun', None)
442 if stopTestRun is not None:
443 stopTestRun()
444
445 def doCleanups(self):
446 """Execute all cleanup functions. Normally called for you after
447 tearDown."""
448 result = self._resultForDoCleanups
449 ok = True
450 while self._cleanups:
451 function, args, kwargs = self._cleanups.pop(-1)
452 try:
453 function(*args, **kwargs)
454 except Exception:
455 ok = False
456 result.addError(self, sys.exc_info())
457 return ok
458
459 def __call__(self, *args, **kwds):
460 return self.run(*args, **kwds)
461
462 def debug(self):
463 """Run the test without collecting errors in a TestResult"""
464 self.setUp()
465 getattr(self, self._testMethodName)()
466 self.tearDown()
Michael Foordb8748742010-06-10 16:16:08 +0000467 while self._cleanups:
468 function, args, kwargs = self._cleanups.pop(-1)
469 function(*args, **kwargs)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000470
471 def skipTest(self, reason):
472 """Skip this test."""
473 raise SkipTest(reason)
474
475 def fail(self, msg=None):
476 """Fail immediately, with the given message."""
477 raise self.failureException(msg)
478
479 def assertFalse(self, expr, msg=None):
480 "Fail the test if the expression is true."
481 if expr:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000482 msg = self._formatMessage(msg, "%s is not False" % safe_repr(expr))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000483 raise self.failureException(msg)
484
485 def assertTrue(self, expr, msg=None):
486 """Fail the test unless the expression is true."""
487 if not expr:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000488 msg = self._formatMessage(msg, "%s is not True" % safe_repr(expr))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000489 raise self.failureException(msg)
490
491 def _formatMessage(self, msg, standardMsg):
492 """Honour the longMessage attribute when generating failure messages.
493 If longMessage is False this means:
494 * Use only an explicit message if it is provided
495 * Otherwise use the standard message for the assert
496
497 If longMessage is True:
498 * Use the standard message
499 * If an explicit message is provided, plus ' : ' and the explicit message
500 """
501 if not self.longMessage:
502 return msg or standardMsg
503 if msg is None:
504 return standardMsg
Benjamin Peterson847a4112010-03-14 15:04:17 +0000505 try:
506 # don't switch to '{}' formatting in Python 2.X
507 # it changes the way unicode input is handled
508 return '%s : %s' % (standardMsg, msg)
509 except UnicodeDecodeError:
510 return '%s : %s' % (safe_repr(standardMsg), safe_repr(msg))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000511
512
513 def assertRaises(self, excClass, callableObj=None, *args, **kwargs):
514 """Fail unless an exception of class excClass is thrown
515 by callableObj when invoked with arguments args and keyword
516 arguments kwargs. If a different type of exception is
517 thrown, it will not be caught, and the test case will be
518 deemed to have suffered an error, exactly as for an
519 unexpected exception.
520
521 If called with callableObj omitted or None, will return a
522 context object used like this::
523
Michael Foord1c42b122010-02-05 22:58:21 +0000524 with self.assertRaises(SomeException):
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000525 do_something()
Michael Foord1c42b122010-02-05 22:58:21 +0000526
527 The context manager keeps a reference to the exception as
Ezio Melotti49008232010-02-08 21:57:48 +0000528 the 'exception' attribute. This allows you to inspect the
Michael Foord1c42b122010-02-05 22:58:21 +0000529 exception after the assertion::
530
531 with self.assertRaises(SomeException) as cm:
532 do_something()
Ezio Melotti49008232010-02-08 21:57:48 +0000533 the_exception = cm.exception
Michael Foordb57ac6d2010-02-05 23:26:29 +0000534 self.assertEqual(the_exception.error_code, 3)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000535 """
536 context = _AssertRaisesContext(excClass, self, callableObj)
537 if callableObj is None:
538 return context
539 with context:
540 callableObj(*args, **kwargs)
541
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000542 def assertWarns(self, expected_warning, callable_obj=None, *args, **kwargs):
543 """Fail unless a warning of class warnClass is triggered
544 by callableObj when invoked with arguments args and keyword
545 arguments kwargs. If a different type of warning is
546 triggered, it will not be handled: depending on the other
547 warning filtering rules in effect, it might be silenced, printed
548 out, or raised as an exception.
549
550 If called with callableObj omitted or None, will return a
551 context object used like this::
552
553 with self.assertWarns(SomeWarning):
554 do_something()
555
556 The context manager keeps a reference to the first matching
557 warning as the 'warning' attribute; similarly, the 'filename'
558 and 'lineno' attributes give you information about the line
559 of Python code from which the warning was triggered.
560 This allows you to inspect the warning after the assertion::
561
562 with self.assertWarns(SomeWarning) as cm:
563 do_something()
564 the_warning = cm.warning
565 self.assertEqual(the_warning.some_attribute, 147)
566 """
567 context = _AssertWarnsContext(expected_warning, self, callable_obj)
568 if callable_obj is None:
569 return context
570 with context:
571 callable_obj(*args, **kwargs)
572
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000573 def _getAssertEqualityFunc(self, first, second):
574 """Get a detailed comparison function for the types of the two args.
575
576 Returns: A callable accepting (first, second, msg=None) that will
577 raise a failure exception if first != second with a useful human
578 readable error message for those types.
579 """
580 #
581 # NOTE(gregory.p.smith): I considered isinstance(first, type(second))
582 # and vice versa. I opted for the conservative approach in case
583 # subclasses are not intended to be compared in detail to their super
584 # class instances using a type equality func. This means testing
585 # subtypes won't automagically use the detailed comparison. Callers
586 # should use their type specific assertSpamEqual method to compare
587 # subclasses if the detailed comparison is desired and appropriate.
588 # See the discussion in http://bugs.python.org/issue2578.
589 #
590 if type(first) is type(second):
591 asserter = self._type_equality_funcs.get(type(first))
592 if asserter is not None:
Benjamin Peterson8f326b22009-12-13 02:10:36 +0000593 return asserter
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000594
595 return self._baseAssertEqual
596
597 def _baseAssertEqual(self, first, second, msg=None):
598 """The default assertEqual implementation, not type specific."""
599 if not first == second:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000600 standardMsg = '%s != %s' % (safe_repr(first), safe_repr(second))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000601 msg = self._formatMessage(msg, standardMsg)
602 raise self.failureException(msg)
603
604 def assertEqual(self, first, second, msg=None):
605 """Fail if the two objects are unequal as determined by the '=='
606 operator.
607 """
608 assertion_func = self._getAssertEqualityFunc(first, second)
609 assertion_func(first, second, msg=msg)
610
611 def assertNotEqual(self, first, second, msg=None):
612 """Fail if the two objects are equal as determined by the '=='
613 operator.
614 """
615 if not first != second:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000616 msg = self._formatMessage(msg, '%s == %s' % (safe_repr(first),
617 safe_repr(second)))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000618 raise self.failureException(msg)
619
Michael Foord321d0592010-11-02 13:44:51 +0000620 def assertAlmostEqual(self, first, second, places=None, msg=None,
Benjamin Petersonb48af542010-04-11 20:43:16 +0000621 delta=None):
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000622 """Fail if the two objects are unequal as determined by their
623 difference rounded to the given number of decimal places
Benjamin Petersonb48af542010-04-11 20:43:16 +0000624 (default 7) and comparing to zero, or by comparing that the
625 between the two objects is more than the given delta.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000626
627 Note that decimal places (from zero) are usually not the same
628 as significant digits (measured from the most signficant digit).
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000629
630 If the two objects compare equal then they will automatically
631 compare almost equal.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000632 """
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000633 if first == second:
Benjamin Petersonb48af542010-04-11 20:43:16 +0000634 # shortcut
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000635 return
Benjamin Petersonb48af542010-04-11 20:43:16 +0000636 if delta is not None and places is not None:
637 raise TypeError("specify delta or places not both")
638
639 if delta is not None:
640 if abs(first - second) <= delta:
641 return
642
643 standardMsg = '%s != %s within %s delta' % (safe_repr(first),
644 safe_repr(second),
645 safe_repr(delta))
646 else:
647 if places is None:
648 places = 7
649
650 if round(abs(second-first), places) == 0:
651 return
652
Benjamin Peterson847a4112010-03-14 15:04:17 +0000653 standardMsg = '%s != %s within %r places' % (safe_repr(first),
654 safe_repr(second),
655 places)
Benjamin Petersonb48af542010-04-11 20:43:16 +0000656 msg = self._formatMessage(msg, standardMsg)
657 raise self.failureException(msg)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000658
Michael Foord321d0592010-11-02 13:44:51 +0000659 def assertNotAlmostEqual(self, first, second, places=None, msg=None,
Benjamin Petersonb48af542010-04-11 20:43:16 +0000660 delta=None):
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000661 """Fail if the two objects are equal as determined by their
662 difference rounded to the given number of decimal places
Benjamin Petersonb48af542010-04-11 20:43:16 +0000663 (default 7) and comparing to zero, or by comparing that the
664 between the two objects is less than the given delta.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000665
666 Note that decimal places (from zero) are usually not the same
667 as significant digits (measured from the most signficant digit).
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000668
669 Objects that are equal automatically fail.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000670 """
Benjamin Petersonb48af542010-04-11 20:43:16 +0000671 if delta is not None and places is not None:
672 raise TypeError("specify delta or places not both")
673 if delta is not None:
674 if not (first == second) and abs(first - second) > delta:
675 return
676 standardMsg = '%s == %s within %s delta' % (safe_repr(first),
677 safe_repr(second),
678 safe_repr(delta))
679 else:
680 if places is None:
681 places = 7
682 if not (first == second) and round(abs(second-first), places) != 0:
683 return
Benjamin Peterson847a4112010-03-14 15:04:17 +0000684 standardMsg = '%s == %s within %r places' % (safe_repr(first),
Benjamin Petersonb48af542010-04-11 20:43:16 +0000685 safe_repr(second),
686 places)
687
688 msg = self._formatMessage(msg, standardMsg)
689 raise self.failureException(msg)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000690
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000691
Michael Foord085dfd32010-06-05 12:17:02 +0000692 def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000693 """An equality assertion for ordered sequences (like lists and tuples).
694
R. David Murrayad13f222010-01-29 22:17:58 +0000695 For the purposes of this function, a valid ordered sequence type is one
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000696 which can be indexed, has a length, and has an equality operator.
697
698 Args:
699 seq1: The first sequence to compare.
700 seq2: The second sequence to compare.
701 seq_type: The expected datatype of the sequences, or None if no
702 datatype should be enforced.
703 msg: Optional message to use on failure instead of a list of
704 differences.
705 """
706 if seq_type != None:
707 seq_type_name = seq_type.__name__
708 if not isinstance(seq1, seq_type):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000709 raise self.failureException('First sequence is not a %s: %s'
710 % (seq_type_name, safe_repr(seq1)))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000711 if not isinstance(seq2, seq_type):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000712 raise self.failureException('Second sequence is not a %s: %s'
713 % (seq_type_name, safe_repr(seq2)))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000714 else:
715 seq_type_name = "sequence"
716
717 differing = None
718 try:
719 len1 = len(seq1)
720 except (TypeError, NotImplementedError):
721 differing = 'First %s has no length. Non-sequence?' % (
722 seq_type_name)
723
724 if differing is None:
725 try:
726 len2 = len(seq2)
727 except (TypeError, NotImplementedError):
728 differing = 'Second %s has no length. Non-sequence?' % (
729 seq_type_name)
730
731 if differing is None:
732 if seq1 == seq2:
733 return
734
Benjamin Peterson847a4112010-03-14 15:04:17 +0000735 seq1_repr = safe_repr(seq1)
736 seq2_repr = safe_repr(seq2)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000737 if len(seq1_repr) > 30:
738 seq1_repr = seq1_repr[:30] + '...'
739 if len(seq2_repr) > 30:
740 seq2_repr = seq2_repr[:30] + '...'
741 elements = (seq_type_name.capitalize(), seq1_repr, seq2_repr)
742 differing = '%ss differ: %s != %s\n' % elements
743
744 for i in range(min(len1, len2)):
745 try:
746 item1 = seq1[i]
747 except (TypeError, IndexError, NotImplementedError):
748 differing += ('\nUnable to index element %d of first %s\n' %
749 (i, seq_type_name))
750 break
751
752 try:
753 item2 = seq2[i]
754 except (TypeError, IndexError, NotImplementedError):
755 differing += ('\nUnable to index element %d of second %s\n' %
756 (i, seq_type_name))
757 break
758
759 if item1 != item2:
760 differing += ('\nFirst differing element %d:\n%s\n%s\n' %
761 (i, item1, item2))
762 break
763 else:
764 if (len1 == len2 and seq_type is None and
765 type(seq1) != type(seq2)):
766 # The sequences are the same, but have differing types.
767 return
768
769 if len1 > len2:
770 differing += ('\nFirst %s contains %d additional '
771 'elements.\n' % (seq_type_name, len1 - len2))
772 try:
773 differing += ('First extra element %d:\n%s\n' %
774 (len2, seq1[len2]))
775 except (TypeError, IndexError, NotImplementedError):
776 differing += ('Unable to index element %d '
777 'of first %s\n' % (len2, seq_type_name))
778 elif len1 < len2:
779 differing += ('\nSecond %s contains %d additional '
780 'elements.\n' % (seq_type_name, len2 - len1))
781 try:
782 differing += ('First extra element %d:\n%s\n' %
783 (len1, seq2[len1]))
784 except (TypeError, IndexError, NotImplementedError):
785 differing += ('Unable to index element %d '
786 'of second %s\n' % (len1, seq_type_name))
Michael Foord2034d9a2010-06-05 11:27:52 +0000787 standardMsg = differing
788 diffMsg = '\n' + '\n'.join(
Benjamin Peterson6e8c7572009-10-04 20:19:21 +0000789 difflib.ndiff(pprint.pformat(seq1).splitlines(),
790 pprint.pformat(seq2).splitlines()))
Michael Foord085dfd32010-06-05 12:17:02 +0000791
792 standardMsg = self._truncateMessage(standardMsg, diffMsg)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000793 msg = self._formatMessage(msg, standardMsg)
794 self.fail(msg)
795
Michael Foord085dfd32010-06-05 12:17:02 +0000796 def _truncateMessage(self, message, diff):
797 max_diff = self.maxDiff
798 if max_diff is None or len(diff) <= max_diff:
799 return message + diff
Michael Foord9dad32e2010-06-05 13:49:56 +0000800 return message + (DIFF_OMITTED % len(diff))
Michael Foord085dfd32010-06-05 12:17:02 +0000801
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000802 def assertListEqual(self, list1, list2, msg=None):
803 """A list-specific equality assertion.
804
805 Args:
806 list1: The first list to compare.
807 list2: The second list to compare.
808 msg: Optional message to use on failure instead of a list of
809 differences.
810
811 """
812 self.assertSequenceEqual(list1, list2, msg, seq_type=list)
813
814 def assertTupleEqual(self, tuple1, tuple2, msg=None):
815 """A tuple-specific equality assertion.
816
817 Args:
818 tuple1: The first tuple to compare.
819 tuple2: The second tuple to compare.
820 msg: Optional message to use on failure instead of a list of
821 differences.
822 """
823 self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
824
825 def assertSetEqual(self, set1, set2, msg=None):
826 """A set-specific equality assertion.
827
828 Args:
829 set1: The first set to compare.
830 set2: The second set to compare.
831 msg: Optional message to use on failure instead of a list of
832 differences.
833
Michael Foord91c9da32010-03-20 17:21:27 +0000834 assertSetEqual uses ducktyping to support different types of sets, and
835 is optimized for sets specifically (parameters must support a
836 difference method).
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000837 """
838 try:
839 difference1 = set1.difference(set2)
840 except TypeError as e:
841 self.fail('invalid type when attempting set difference: %s' % e)
842 except AttributeError as e:
843 self.fail('first argument does not support set difference: %s' % e)
844
845 try:
846 difference2 = set2.difference(set1)
847 except TypeError as e:
848 self.fail('invalid type when attempting set difference: %s' % e)
849 except AttributeError as e:
850 self.fail('second argument does not support set difference: %s' % e)
851
852 if not (difference1 or difference2):
853 return
854
855 lines = []
856 if difference1:
857 lines.append('Items in the first set but not the second:')
858 for item in difference1:
859 lines.append(repr(item))
860 if difference2:
861 lines.append('Items in the second set but not the first:')
862 for item in difference2:
863 lines.append(repr(item))
864
865 standardMsg = '\n'.join(lines)
866 self.fail(self._formatMessage(msg, standardMsg))
867
868 def assertIn(self, member, container, msg=None):
869 """Just like self.assertTrue(a in b), but with a nicer default message."""
870 if member not in container:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000871 standardMsg = '%s not found in %s' % (safe_repr(member),
872 safe_repr(container))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000873 self.fail(self._formatMessage(msg, standardMsg))
874
875 def assertNotIn(self, member, container, msg=None):
876 """Just like self.assertTrue(a not in b), but with a nicer default message."""
877 if member in container:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000878 standardMsg = '%s unexpectedly found in %s' % (safe_repr(member),
879 safe_repr(container))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000880 self.fail(self._formatMessage(msg, standardMsg))
881
882 def assertIs(self, expr1, expr2, msg=None):
883 """Just like self.assertTrue(a is b), but with a nicer default message."""
884 if expr1 is not expr2:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000885 standardMsg = '%s is not %s' % (safe_repr(expr1),
886 safe_repr(expr2))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000887 self.fail(self._formatMessage(msg, standardMsg))
888
889 def assertIsNot(self, expr1, expr2, msg=None):
890 """Just like self.assertTrue(a is not b), but with a nicer default message."""
891 if expr1 is expr2:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000892 standardMsg = 'unexpectedly identical: %s' % (safe_repr(expr1),)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000893 self.fail(self._formatMessage(msg, standardMsg))
894
895 def assertDictEqual(self, d1, d2, msg=None):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000896 self.assertIsInstance(d1, dict, 'First argument is not a dictionary')
897 self.assertIsInstance(d2, dict, 'Second argument is not a dictionary')
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000898
899 if d1 != d2:
Michael Foordcb11b252010-06-05 13:14:43 +0000900 standardMsg = '%s != %s' % (safe_repr(d1, True), safe_repr(d2, True))
Michael Foord085dfd32010-06-05 12:17:02 +0000901 diff = ('\n' + '\n'.join(difflib.ndiff(
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000902 pprint.pformat(d1).splitlines(),
903 pprint.pformat(d2).splitlines())))
Michael Foordcb11b252010-06-05 13:14:43 +0000904 standardMsg = self._truncateMessage(standardMsg, diff)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000905 self.fail(self._formatMessage(msg, standardMsg))
906
907 def assertDictContainsSubset(self, expected, actual, msg=None):
908 """Checks whether actual is a superset of expected."""
909 missing = []
910 mismatched = []
911 for key, value in expected.items():
912 if key not in actual:
913 missing.append(key)
914 elif value != actual[key]:
Benjamin Peterson6e8c7572009-10-04 20:19:21 +0000915 mismatched.append('%s, expected: %s, actual: %s' %
Benjamin Peterson847a4112010-03-14 15:04:17 +0000916 (safe_repr(key), safe_repr(value),
917 safe_repr(actual[key])))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000918
919 if not (missing or mismatched):
920 return
921
922 standardMsg = ''
923 if missing:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000924 standardMsg = 'Missing: %s' % ','.join(safe_repr(m) for m in
925 missing)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000926 if mismatched:
927 if standardMsg:
928 standardMsg += '; '
929 standardMsg += 'Mismatched values: %s' % ','.join(mismatched)
930
931 self.fail(self._formatMessage(msg, standardMsg))
932
933 def assertSameElements(self, expected_seq, actual_seq, msg=None):
934 """An unordered sequence specific comparison.
935
936 Raises with an error message listing which elements of expected_seq
937 are missing from actual_seq and vice versa if any.
Michael Foord1c42b122010-02-05 22:58:21 +0000938
939 Duplicate elements are ignored when comparing *expected_seq* and
940 *actual_seq*. It is the equivalent of ``assertEqual(set(expected),
941 set(actual))`` but it works with sequences of unhashable objects as
942 well.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000943 """
Michael Foord91c9da32010-03-20 17:21:27 +0000944 warnings.warn('assertSameElements is deprecated',
945 DeprecationWarning)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000946 try:
947 expected = set(expected_seq)
948 actual = set(actual_seq)
Benjamin Peterson847a4112010-03-14 15:04:17 +0000949 missing = sorted(expected.difference(actual))
950 unexpected = sorted(actual.difference(expected))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000951 except TypeError:
952 # Fall back to slower list-compare if any of the objects are
953 # not hashable.
954 expected = list(expected_seq)
955 actual = list(actual_seq)
956 try:
957 expected.sort()
958 actual.sort()
959 except TypeError:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000960 missing, unexpected = unorderable_list_difference(expected,
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000961 actual)
Benjamin Peterson847a4112010-03-14 15:04:17 +0000962 else:
963 missing, unexpected = sorted_list_difference(expected, actual)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000964 errors = []
965 if missing:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000966 errors.append('Expected, but missing:\n %s' %
967 safe_repr(missing))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000968 if unexpected:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000969 errors.append('Unexpected, but present:\n %s' %
970 safe_repr(unexpected))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000971 if errors:
972 standardMsg = '\n'.join(errors)
973 self.fail(self._formatMessage(msg, standardMsg))
974
Michael Foord8442a602010-03-20 16:58:04 +0000975
Raymond Hettinger6e165b32010-11-27 09:31:37 +0000976 def assertCountEqual(self, expected_seq, actual_seq, msg=None):
977 """An unordered sequence specific comparison. It asserts that
978 expected_seq and actual_seq have the same element counts.
979 Equivalent to::
Michael Foord8442a602010-03-20 16:58:04 +0000980
Raymond Hettinger6e165b32010-11-27 09:31:37 +0000981 self.assertEqual(Counter(iter(expected_seq)),
982 Counter(iter(actual_seq)))
Michael Foord8442a602010-03-20 16:58:04 +0000983
984 Asserts that each element has the same count in both sequences.
985 Example:
986 - [0, 1, 1] and [1, 0, 1] compare equal.
987 - [0, 0, 1] and [0, 1] compare unequal.
988 """
989 try:
Raymond Hettinger6e165b32010-11-27 09:31:37 +0000990 expected = collections.Counter(iter(expected_seq))
991 actual = collections.Counter(iter(actual_seq))
Michael Foord8442a602010-03-20 16:58:04 +0000992 except TypeError:
993 # Unsortable items (example: set(), complex(), ...)
994 expected = list(expected_seq)
995 actual = list(actual_seq)
996 missing, unexpected = unorderable_list_difference(expected, actual)
997 else:
Raymond Hettinger6e165b32010-11-27 09:31:37 +0000998 if expected == actual:
999 return
1000 missing = list(expected - actual)
1001 unexpected = list(actual - expected)
Michael Foord8442a602010-03-20 16:58:04 +00001002
1003 errors = []
1004 if missing:
1005 errors.append('Expected, but missing:\n %s' %
1006 safe_repr(missing))
1007 if unexpected:
1008 errors.append('Unexpected, but present:\n %s' %
1009 safe_repr(unexpected))
1010 if errors:
1011 standardMsg = '\n'.join(errors)
1012 self.fail(self._formatMessage(msg, standardMsg))
1013
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001014 def assertMultiLineEqual(self, first, second, msg=None):
1015 """Assert that two multi-line strings are equal."""
Ezio Melottib3aedd42010-11-20 19:04:17 +00001016 self.assertIsInstance(first, str, 'First argument is not a string')
1017 self.assertIsInstance(second, str, 'Second argument is not a string')
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001018
1019 if first != second:
Michael Foordc653ce32010-07-10 13:52:22 +00001020 firstlines = first.splitlines(True)
1021 secondlines = second.splitlines(True)
1022 if len(firstlines) == 1 and first.strip('\r\n') == first:
1023 firstlines = [first + '\n']
1024 secondlines = [second + '\n']
1025 standardMsg = '%s != %s' % (safe_repr(first, True),
1026 safe_repr(second, True))
1027 diff = '\n' + ''.join(difflib.ndiff(firstlines, secondlines))
Michael Foordcb11b252010-06-05 13:14:43 +00001028 standardMsg = self._truncateMessage(standardMsg, diff)
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001029 self.fail(self._formatMessage(msg, standardMsg))
1030
1031 def assertLess(self, a, b, msg=None):
1032 """Just like self.assertTrue(a < b), but with a nicer default message."""
1033 if not a < b:
Benjamin Peterson847a4112010-03-14 15:04:17 +00001034 standardMsg = '%s not less than %s' % (safe_repr(a), safe_repr(b))
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001035 self.fail(self._formatMessage(msg, standardMsg))
1036
1037 def assertLessEqual(self, a, b, msg=None):
1038 """Just like self.assertTrue(a <= b), but with a nicer default message."""
1039 if not a <= b:
Benjamin Peterson847a4112010-03-14 15:04:17 +00001040 standardMsg = '%s not less than or equal to %s' % (safe_repr(a), safe_repr(b))
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001041 self.fail(self._formatMessage(msg, standardMsg))
1042
1043 def assertGreater(self, a, b, msg=None):
1044 """Just like self.assertTrue(a > b), but with a nicer default message."""
1045 if not a > b:
Benjamin Peterson847a4112010-03-14 15:04:17 +00001046 standardMsg = '%s not greater than %s' % (safe_repr(a), safe_repr(b))
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001047 self.fail(self._formatMessage(msg, standardMsg))
1048
1049 def assertGreaterEqual(self, a, b, msg=None):
1050 """Just like self.assertTrue(a >= b), but with a nicer default message."""
1051 if not a >= b:
Benjamin Peterson847a4112010-03-14 15:04:17 +00001052 standardMsg = '%s not greater than or equal to %s' % (safe_repr(a), safe_repr(b))
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001053 self.fail(self._formatMessage(msg, standardMsg))
1054
1055 def assertIsNone(self, obj, msg=None):
1056 """Same as self.assertTrue(obj is None), with a nicer default message."""
1057 if obj is not None:
Benjamin Peterson847a4112010-03-14 15:04:17 +00001058 standardMsg = '%s is not None' % (safe_repr(obj),)
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001059 self.fail(self._formatMessage(msg, standardMsg))
1060
1061 def assertIsNotNone(self, obj, msg=None):
1062 """Included for symmetry with assertIsNone."""
1063 if obj is None:
1064 standardMsg = 'unexpectedly None'
1065 self.fail(self._formatMessage(msg, standardMsg))
1066
Benjamin Peterson6e8c7572009-10-04 20:19:21 +00001067 def assertIsInstance(self, obj, cls, msg=None):
1068 """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
1069 default message."""
1070 if not isinstance(obj, cls):
Benjamin Peterson847a4112010-03-14 15:04:17 +00001071 standardMsg = '%s is not an instance of %r' % (safe_repr(obj), cls)
Benjamin Peterson6e8c7572009-10-04 20:19:21 +00001072 self.fail(self._formatMessage(msg, standardMsg))
1073
1074 def assertNotIsInstance(self, obj, cls, msg=None):
1075 """Included for symmetry with assertIsInstance."""
1076 if isinstance(obj, cls):
Benjamin Peterson847a4112010-03-14 15:04:17 +00001077 standardMsg = '%s is an instance of %r' % (safe_repr(obj), cls)
Benjamin Peterson6e8c7572009-10-04 20:19:21 +00001078 self.fail(self._formatMessage(msg, standardMsg))
1079
Ezio Melottied3a7d22010-12-01 02:32:32 +00001080 def assertRaisesRegex(self, expected_exception, expected_regex,
1081 callable_obj=None, *args, **kwargs):
1082 """Asserts that the message in a raised exception matches a regex.
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001083
1084 Args:
1085 expected_exception: Exception class expected to be raised.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001086 expected_regex: Regex (re pattern object or string) expected
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001087 to be found in error message.
1088 callable_obj: Function to be called.
1089 args: Extra args.
1090 kwargs: Extra kwargs.
1091 """
1092 context = _AssertRaisesContext(expected_exception, self, callable_obj,
Ezio Melottied3a7d22010-12-01 02:32:32 +00001093 expected_regex)
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001094 if callable_obj is None:
1095 return context
1096 with context:
1097 callable_obj(*args, **kwargs)
1098
Ezio Melottied3a7d22010-12-01 02:32:32 +00001099 def assertWarnsRegex(self, expected_warning, expected_regex,
1100 callable_obj=None, *args, **kwargs):
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001101 """Asserts that the message in a triggered warning matches a regexp.
1102 Basic functioning is similar to assertWarns() with the addition
1103 that only warnings whose messages also match the regular expression
1104 are considered successful matches.
1105
1106 Args:
1107 expected_warning: Warning class expected to be triggered.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001108 expected_regex: Regex (re pattern object or string) expected
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001109 to be found in error message.
1110 callable_obj: Function to be called.
1111 args: Extra args.
1112 kwargs: Extra kwargs.
1113 """
1114 context = _AssertWarnsContext(expected_warning, self, callable_obj,
Ezio Melottied3a7d22010-12-01 02:32:32 +00001115 expected_regex)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001116 if callable_obj is None:
1117 return context
1118 with context:
1119 callable_obj(*args, **kwargs)
1120
Ezio Melottied3a7d22010-12-01 02:32:32 +00001121 def assertRegex(self, text, expected_regex, msg=None):
Michael Foorde3ef5f12010-05-08 16:46:14 +00001122 """Fail the test unless the text matches the regular expression."""
Ezio Melottied3a7d22010-12-01 02:32:32 +00001123 if isinstance(expected_regex, (str, bytes)):
1124 expected_regex = re.compile(expected_regex)
1125 if not expected_regex.search(text):
1126 msg = msg or "Regex didn't match"
1127 msg = '%s: %r not found in %r' % (msg, expected_regex.pattern, text)
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001128 raise self.failureException(msg)
1129
Ezio Melotti8f776302010-12-10 02:32:05 +00001130 def assertNotRegex(self, text, unexpected_regex, msg=None):
Michael Foorde3ef5f12010-05-08 16:46:14 +00001131 """Fail the test if the text matches the regular expression."""
Ezio Melottied3a7d22010-12-01 02:32:32 +00001132 if isinstance(unexpected_regex, (str, bytes)):
1133 unexpected_regex = re.compile(unexpected_regex)
1134 match = unexpected_regex.search(text)
Benjamin Petersonb48af542010-04-11 20:43:16 +00001135 if match:
Ezio Melottied3a7d22010-12-01 02:32:32 +00001136 msg = msg or "Regex matched"
Benjamin Petersonb48af542010-04-11 20:43:16 +00001137 msg = '%s: %r matches %r in %r' % (msg,
1138 text[match.start():match.end()],
Ezio Melottied3a7d22010-12-01 02:32:32 +00001139 unexpected_regex.pattern,
Benjamin Petersonb48af542010-04-11 20:43:16 +00001140 text)
1141 raise self.failureException(msg)
1142
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001143
Ezio Melottied3a7d22010-12-01 02:32:32 +00001144 def _deprecate(original_func):
1145 def deprecated_func(*args, **kwargs):
1146 warnings.warn(
1147 'Please use {0} instead.'.format(original_func.__name__),
1148 DeprecationWarning, 2)
1149 return original_func(*args, **kwargs)
1150 return deprecated_func
1151
1152 # The fail* methods can be removed in 3.3, the 5 assert* methods will
1153 # have to stay around for a few more versions. See #9424.
1154 failUnlessEqual = assertEquals = _deprecate(assertEqual)
1155 failIfEqual = assertNotEquals = _deprecate(assertNotEqual)
1156 failUnlessAlmostEqual = assertAlmostEquals = _deprecate(assertAlmostEqual)
1157 failIfAlmostEqual = assertNotAlmostEquals = _deprecate(assertNotAlmostEqual)
1158 failUnless = assert_ = _deprecate(assertTrue)
1159 failUnlessRaises = _deprecate(assertRaises)
1160 failIf = _deprecate(assertFalse)
1161 assertRaisesRegexp = _deprecate(assertRaisesRegex)
1162 assertRegexpMatches = _deprecate(assertRegex)
1163
1164
1165
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001166class FunctionTestCase(TestCase):
1167 """A test case that wraps a test function.
1168
1169 This is useful for slipping pre-existing test functions into the
1170 unittest framework. Optionally, set-up and tidy-up functions can be
1171 supplied. As with TestCase, the tidy-up ('tearDown') function will
1172 always be called if the set-up ('setUp') function ran successfully.
1173 """
1174
1175 def __init__(self, testFunc, setUp=None, tearDown=None, description=None):
1176 super(FunctionTestCase, self).__init__()
1177 self._setUpFunc = setUp
1178 self._tearDownFunc = tearDown
1179 self._testFunc = testFunc
1180 self._description = description
1181
1182 def setUp(self):
1183 if self._setUpFunc is not None:
1184 self._setUpFunc()
1185
1186 def tearDown(self):
1187 if self._tearDownFunc is not None:
1188 self._tearDownFunc()
1189
1190 def runTest(self):
1191 self._testFunc()
1192
1193 def id(self):
1194 return self._testFunc.__name__
1195
1196 def __eq__(self, other):
1197 if not isinstance(other, self.__class__):
1198 return NotImplemented
1199
1200 return self._setUpFunc == other._setUpFunc and \
1201 self._tearDownFunc == other._tearDownFunc and \
1202 self._testFunc == other._testFunc and \
1203 self._description == other._description
1204
1205 def __ne__(self, other):
1206 return not self == other
1207
1208 def __hash__(self):
1209 return hash((type(self), self._setUpFunc, self._tearDownFunc,
1210 self._testFunc, self._description))
1211
1212 def __str__(self):
Benjamin Peterson847a4112010-03-14 15:04:17 +00001213 return "%s (%s)" % (strclass(self.__class__),
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001214 self._testFunc.__name__)
1215
1216 def __repr__(self):
Benjamin Peterson847a4112010-03-14 15:04:17 +00001217 return "<%s tec=%s>" % (strclass(self.__class__),
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001218 self._testFunc)
1219
1220 def shortDescription(self):
1221 if self._description is not None:
1222 return self._description
1223 doc = self._testFunc.__doc__
1224 return doc and doc.split("\n")[0].strip() or None