1 """Test case implementation"""
12 strclass, safe_repr, sorted_list_difference, unorderable_list_difference
18 DIFF_OMITTED = ('\nDiff is %s characters long. '
19 'Set self.maxDiff to None to see it.')
21 class SkipTest(Exception):
23 Raise this exception in a test to skip it.
25 Usually you can use TestResult.skip() or one of the skipping decorators
26 instead of raising this directly.
30 class _ExpectedFailure(Exception):
32 Raise this when a test is expected to fail.
34 This is an implementation detail.
37 def __init__(self, exc_info):
38 super(_ExpectedFailure, self).__init__()
39 self.exc_info = exc_info
41 class _UnexpectedSuccess(Exception):
43 The test was supposed to fail, but it didn't!
52 Unconditionally skip a test.
54 def decorator(test_item):
55 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
61 test_item.__unittest_skip__ = True
62 test_item.__unittest_skip_why__ = reason
66 def skipIf(condition, reason):
68 Skip a test if the condition is true.
74 def skipUnless(condition, reason):
76 Skip a test unless the condition is true.
83 def expectedFailure(func):
84 @functools.wraps(func)
85 def wrapper(*args, **kwargs):
89 raise _ExpectedFailure(sys.exc_info())
90 raise _UnexpectedSuccess
94 class _AssertRaisesContext(object):
95 """A context manager used to implement TestCase.assertRaises* methods."""
97 def __init__(self, expected, test_case, expected_regexp=None):
98 self.expected = expected
99 self.failureException = test_case.failureException
100 self.expected_regexp = expected_regexp
105 def __exit__(self, exc_type, exc_value, tb):
108 exc_name = self.expected.__name__
109 except AttributeError:
110 exc_name = str(self.expected)
111 raise self.failureException(
112 "{0} not raised".format(exc_name))
113 if not issubclass(exc_type, self.expected):
114 # let unexpected exceptions pass through
116 self.exception = exc_value # store for later retrieval
117 if self.expected_regexp is None:
120 expected_regexp = self.expected_regexp
121 if isinstance(expected_regexp, basestring):
122 expected_regexp = re.compile(expected_regexp)
123 if not expected_regexp.search(str(exc_value)):
124 raise self.failureException('"%s" does not match "%s"' %
125 (expected_regexp.pattern, str(exc_value)))
129 class TestCase(object):
130 """A class whose instances are single test cases.
132 By default, the test code itself should be placed in a method named
135 If the fixture may be used for many test cases, create as
136 many test methods as are needed. When instantiating such a TestCase
137 subclass, specify in the constructor arguments the name of the test method
138 that the instance is to execute.
140 Test authors should subclass TestCase for their own tests. Construction
141 and deconstruction of the test's environment ('fixture') can be
142 implemented by overriding the 'setUp' and 'tearDown' methods respectively.
144 If it is necessary to override the __init__ method, the base class
145 __init__ method must always be called. It is important that subclasses
146 should not change the signature of their __init__ method, since instances
147 of the classes are instantiated automatically by parts of the framework
151 # This attribute determines which exception will be raised when
152 # the instance's assertion methods fail; test methods raising this
153 # exception will be deemed to have 'failed' rather than 'errored'
155 failureException = AssertionError
157 # This attribute determines whether long messages (including repr of
158 # objects used in assert methods) will be printed on failure in *addition*
159 # to any explicit message passed.
163 # This attribute sets the maximum length of a diff in failure messages
164 # by assert methods using difflib. It is looked up as an instance attribute
165 # so can be configured by individual tests if required.
169 # Attribute used by TestSuite for classSetUp
171 _classSetupFailed = False
173 def __init__(self, methodName='runTest'):
174 """Create an instance of the class that will use the named test
175 method when executed. Raises a ValueError if the instance does
176 not have a method with the specified name.
178 self._testMethodName = methodName
179 self._resultForDoCleanups = None
181 testMethod = getattr(self, methodName)
182 except AttributeError:
183 raise ValueError("no such test method in %s: %s" %
184 (self.__class__, methodName))
185 self._testMethodDoc = testMethod.__doc__
188 # Map types to custom assertEqual functions that will compare
189 # instances of said type in more detail to generate a more useful
191 self._type_equality_funcs = {}
192 self.addTypeEqualityFunc(dict, self.assertDictEqual)
193 self.addTypeEqualityFunc(list, self.assertListEqual)
194 self.addTypeEqualityFunc(tuple, self.assertTupleEqual)
195 self.addTypeEqualityFunc(set, self.assertSetEqual)
196 self.addTypeEqualityFunc(frozenset, self.assertSetEqual)
197 self.addTypeEqualityFunc(unicode, self.assertMultiLineEqual)
199 def addTypeEqualityFunc(self, typeobj, function):
200 """Add a type specific assertEqual style function to compare a type.
202 This method is for use by TestCase subclasses that need to register
203 their own type equality functions to provide nicer error messages.
206 typeobj: The data type to call this function on when both values
207 are of the same type in assertEqual().
208 function: The callable taking two arguments and an optional
209 msg= argument that raises self.failureException with a
210 useful error message when the two arguments are not equal.
212 self._type_equality_funcs[typeobj] = function
214 def addCleanup(self, function, *args, **kwargs):
215 """Add a function, with arguments, to be called when the test is
216 completed. Functions added are called on a LIFO basis and are
217 called after tearDown on test failure or success.
219 Cleanup items are called even if setUp fails (unlike tearDown)."""
220 self._cleanups.append((function, args, kwargs))
223 "Hook method for setting up the test fixture before exercising it."
227 "Hook method for deconstructing the test fixture after testing it."
232 "Hook method for setting up class fixture before running tests in the class."
235 def tearDownClass(cls):
236 "Hook method for deconstructing the class fixture after running all tests in the class."
238 def countTestCases(self):
241 def defaultTestResult(self):
242 return result.TestResult()
244 def shortDescription(self):
245 """Returns a one-line description of the test, or None if no
246 description has been provided.
248 The default implementation of this method returns the first line of
249 the specified test method's docstring.
251 doc = self._testMethodDoc
252 return doc and doc.split("\n")[0].strip() or None
256 return "%s.%s" % (strclass(self.__class__), self._testMethodName)
258 def __eq__(self, other):
259 if type(self) is not type(other):
260 return NotImplemented
262 return self._testMethodName == other._testMethodName
264 def __ne__(self, other):
265 return not self == other
268 return hash((type(self), self._testMethodName))
271 return "%s (%s)" % (self._testMethodName, strclass(self.__class__))
274 return "<%s testMethod=%s>" % \
275 (strclass(self.__class__), self._testMethodName)
277 def _addSkip(self, result, reason):
278 addSkip = getattr(result, 'addSkip', None)
279 if addSkip is not None:
280 addSkip(self, reason)
282 warnings.warn("TestResult has no addSkip method, skips not reported",
284 result.addSuccess(self)
286 def run(self, result=None):
289 result = self.defaultTestResult()
290 startTestRun = getattr(result, 'startTestRun', None)
291 if startTestRun is not None:
294 self._resultForDoCleanups = result
295 result.startTest(self)
297 testMethod = getattr(self, self._testMethodName)
298 if (getattr(self.__class__, "__unittest_skip__", False) or
299 getattr(testMethod, "__unittest_skip__", False)):
300 # If the class or method was skipped.
302 skip_why = (getattr(self.__class__, '__unittest_skip_why__', '')
303 or getattr(testMethod, '__unittest_skip_why__', ''))
304 self._addSkip(result, skip_why)
306 result.stopTest(self)
312 except SkipTest as e:
313 self._addSkip(result, str(e))
315 result.addError(self, sys.exc_info())
319 except self.failureException:
320 result.addFailure(self, sys.exc_info())
321 except _ExpectedFailure as e:
322 addExpectedFailure = getattr(result, 'addExpectedFailure', None)
323 if addExpectedFailure is not None:
324 addExpectedFailure(self, e.exc_info)
326 warnings.warn("TestResult has no addExpectedFailure method, reporting as passes",
328 result.addSuccess(self)
329 except _UnexpectedSuccess:
330 addUnexpectedSuccess = getattr(result, 'addUnexpectedSuccess', None)
331 if addUnexpectedSuccess is not None:
332 addUnexpectedSuccess(self)
334 warnings.warn("TestResult has no addUnexpectedSuccess method, reporting as failures",
336 result.addFailure(self, sys.exc_info())
337 except SkipTest as e:
338 self._addSkip(result, str(e))
340 result.addError(self, sys.exc_info())
347 result.addError(self, sys.exc_info())
350 cleanUpSuccess = self.doCleanups()
351 success = success and cleanUpSuccess
353 result.addSuccess(self)
355 result.stopTest(self)
356 if orig_result is None:
357 stopTestRun = getattr(result, 'stopTestRun', None)
358 if stopTestRun is not None:
361 def doCleanups(self):
362 """Execute all cleanup functions. Normally called for you after
364 result = self._resultForDoCleanups
366 while self._cleanups:
367 function, args, kwargs = self._cleanups.pop(-1)
369 function(*args, **kwargs)
372 result.addError(self, sys.exc_info())
375 def __call__(self, *args, **kwds):
376 return self.run(*args, **kwds)
379 """Run the test without collecting errors in a TestResult"""
381 getattr(self, self._testMethodName)()
383 while self._cleanups:
384 function, args, kwargs = self._cleanups.pop(-1)
385 function(*args, **kwargs)
387 def skipTest(self, reason):
388 """Skip this test."""
389 raise SkipTest(reason)
391 def fail(self, msg=None):
392 """Fail immediately, with the given message."""
393 raise self.failureException(msg)
395 def assertFalse(self, expr, msg=None):
396 "Fail the test if the expression is true."
398 msg = self._formatMessage(msg, "%s is not False" % safe_repr(expr))
399 raise self.failureException(msg)
401 def assertTrue(self, expr, msg=None):
402 """Fail the test unless the expression is true."""
404 msg = self._formatMessage(msg, "%s is not True" % safe_repr(expr))
405 raise self.failureException(msg)
407 def _formatMessage(self, msg, standardMsg):
408 """Honour the longMessage attribute when generating failure messages.
409 If longMessage is False this means:
410 * Use only an explicit message if it is provided
411 * Otherwise use the standard message for the assert
413 If longMessage is True:
414 * Use the standard message
415 * If an explicit message is provided, plus ' : ' and the explicit message
417 if not self.longMessage:
418 return msg or standardMsg
422 # don't switch to '{}' formatting in Python 2.X
423 # it changes the way unicode input is handled
424 return '%s : %s' % (standardMsg, msg)
425 except UnicodeDecodeError:
426 return '%s : %s' % (safe_repr(standardMsg), safe_repr(msg))
429 def assertRaises(self, excClass, callableObj=None, *args, **kwargs):
430 """Fail unless an exception of class excClass is thrown
431 by callableObj when invoked with arguments args and keyword
432 arguments kwargs. If a different type of exception is
433 thrown, it will not be caught, and the test case will be
434 deemed to have suffered an error, exactly as for an
435 unexpected exception.
437 If called with callableObj omitted or None, will return a
438 context object used like this::
440 with self.assertRaises(SomeException):
443 The context manager keeps a reference to the exception as
444 the 'exception' attribute. This allows you to inspect the
445 exception after the assertion::
447 with self.assertRaises(SomeException) as cm:
449 the_exception = cm.exception
450 self.assertEqual(the_exception.error_code, 3)
452 context = _AssertRaisesContext(excClass, self)
453 if callableObj is None:
456 callableObj(*args, **kwargs)
458 def _getAssertEqualityFunc(self, first, second):
459 """Get a detailed comparison function for the types of the two args.
461 Returns: A callable accepting (first, second, msg=None) that will
462 raise a failure exception if first != second with a useful human
463 readable error message for those types.
466 # NOTE(gregory.p.smith): I considered isinstance(first, type(second))
467 # and vice versa. I opted for the conservative approach in case
468 # subclasses are not intended to be compared in detail to their super
469 # class instances using a type equality func. This means testing
470 # subtypes won't automagically use the detailed comparison. Callers
471 # should use their type specific assertSpamEqual method to compare
472 # subclasses if the detailed comparison is desired and appropriate.
473 # See the discussion in http://bugs.python.org/issue2578.
475 if type(first) is type(second):
476 asserter = self._type_equality_funcs.get(type(first))
477 if asserter is not None:
480 return self._baseAssertEqual
482 def _baseAssertEqual(self, first, second, msg=None):
483 """The default assertEqual implementation, not type specific."""
484 if not first == second:
485 standardMsg = '%s != %s' % (safe_repr(first), safe_repr(second))
486 msg = self._formatMessage(msg, standardMsg)
487 raise self.failureException(msg)
489 def assertEqual(self, first, second, msg=None):
490 """Fail if the two objects are unequal as determined by the '=='
493 assertion_func = self._getAssertEqualityFunc(first, second)
494 assertion_func(first, second, msg=msg)
496 def assertNotEqual(self, first, second, msg=None):
497 """Fail if the two objects are equal as determined by the '=='
500 if not first != second:
501 msg = self._formatMessage(msg, '%s == %s' % (safe_repr(first),
503 raise self.failureException(msg)
506 def assertAlmostEqual(self, first, second, places=None, msg=None, delta=None):
507 """Fail if the two objects are unequal as determined by their
508 difference rounded to the given number of decimal places
509 (default 7) and comparing to zero, or by comparing that the
510 between the two objects is more than the given delta.
512 Note that decimal places (from zero) are usually not the same
513 as significant digits (measured from the most signficant digit).
515 If the two objects compare equal then they will automatically
516 compare almost equal.
521 if delta is not None and places is not None:
522 raise TypeError("specify delta or places not both")
524 if delta is not None:
525 if abs(first - second) <= delta:
528 standardMsg = '%s != %s within %s delta' % (safe_repr(first),
535 if round(abs(second-first), places) == 0:
538 standardMsg = '%s != %s within %r places' % (safe_repr(first),
541 msg = self._formatMessage(msg, standardMsg)
542 raise self.failureException(msg)
544 def assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None):
545 """Fail if the two objects are equal as determined by their
546 difference rounded to the given number of decimal places
547 (default 7) and comparing to zero, or by comparing that the
548 between the two objects is less than the given delta.
550 Note that decimal places (from zero) are usually not the same
551 as significant digits (measured from the most signficant digit).
553 Objects that are equal automatically fail.
555 if delta is not None and places is not None:
556 raise TypeError("specify delta or places not both")
557 if delta is not None:
558 if not (first == second) and abs(first - second) > delta:
560 standardMsg = '%s == %s within %s delta' % (safe_repr(first),
566 if not (first == second) and round(abs(second-first), places) != 0:
568 standardMsg = '%s == %s within %r places' % (safe_repr(first),
572 msg = self._formatMessage(msg, standardMsg)
573 raise self.failureException(msg)
575 # Synonyms for assertion methods
577 # The plurals are undocumented. Keep them that way to discourage use.
578 # Do not add more. Do not remove.
579 # Going through a deprecation cycle on these would annoy many people.
580 assertEquals = assertEqual
581 assertNotEquals = assertNotEqual
582 assertAlmostEquals = assertAlmostEqual
583 assertNotAlmostEquals = assertNotAlmostEqual
586 # These fail* assertion method names are pending deprecation and will
587 # be a DeprecationWarning in 3.2; http://bugs.python.org/issue2578
588 def _deprecate(original_func):
589 def deprecated_func(*args, **kwargs):
591 'Please use {0} instead.'.format(original_func.__name__),
592 PendingDeprecationWarning, 2)
593 return original_func(*args, **kwargs)
594 return deprecated_func
596 failUnlessEqual = _deprecate(assertEqual)
597 failIfEqual = _deprecate(assertNotEqual)
598 failUnlessAlmostEqual = _deprecate(assertAlmostEqual)
599 failIfAlmostEqual = _deprecate(assertNotAlmostEqual)
600 failUnless = _deprecate(assertTrue)
601 failUnlessRaises = _deprecate(assertRaises)
602 failIf = _deprecate(assertFalse)
604 def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
605 """An equality assertion for ordered sequences (like lists and tuples).
607 For the purposes of this function, a valid ordered sequence type is one
608 which can be indexed, has a length, and has an equality operator.
611 seq1: The first sequence to compare.
612 seq2: The second sequence to compare.
613 seq_type: The expected datatype of the sequences, or None if no
614 datatype should be enforced.
615 msg: Optional message to use on failure instead of a list of
618 if seq_type is not None:
619 seq_type_name = seq_type.__name__
620 if not isinstance(seq1, seq_type):
621 raise self.failureException('First sequence is not a %s: %s'
622 % (seq_type_name, safe_repr(seq1)))
623 if not isinstance(seq2, seq_type):
624 raise self.failureException('Second sequence is not a %s: %s'
625 % (seq_type_name, safe_repr(seq2)))
627 seq_type_name = "sequence"
632 except (TypeError, NotImplementedError):
633 differing = 'First %s has no length. Non-sequence?' % (
636 if differing is None:
639 except (TypeError, NotImplementedError):
640 differing = 'Second %s has no length. Non-sequence?' % (
643 if differing is None:
647 seq1_repr = safe_repr(seq1)
648 seq2_repr = safe_repr(seq2)
649 if len(seq1_repr) > 30:
650 seq1_repr = seq1_repr[:30] + '...'
651 if len(seq2_repr) > 30:
652 seq2_repr = seq2_repr[:30] + '...'
653 elements = (seq_type_name.capitalize(), seq1_repr, seq2_repr)
654 differing = '%ss differ: %s != %s\n' % elements
656 for i in xrange(min(len1, len2)):
659 except (TypeError, IndexError, NotImplementedError):
660 differing += ('\nUnable to index element %d of first %s\n' %
666 except (TypeError, IndexError, NotImplementedError):
667 differing += ('\nUnable to index element %d of second %s\n' %
672 differing += ('\nFirst differing element %d:\n%s\n%s\n' %
676 if (len1 == len2 and seq_type is None and
677 type(seq1) != type(seq2)):
678 # The sequences are the same, but have differing types.
682 differing += ('\nFirst %s contains %d additional '
683 'elements.\n' % (seq_type_name, len1 - len2))
685 differing += ('First extra element %d:\n%s\n' %
687 except (TypeError, IndexError, NotImplementedError):
688 differing += ('Unable to index element %d '
689 'of first %s\n' % (len2, seq_type_name))
691 differing += ('\nSecond %s contains %d additional '
692 'elements.\n' % (seq_type_name, len2 - len1))
694 differing += ('First extra element %d:\n%s\n' %
696 except (TypeError, IndexError, NotImplementedError):
697 differing += ('Unable to index element %d '
698 'of second %s\n' % (len1, seq_type_name))
699 standardMsg = differing
700 diffMsg = '\n' + '\n'.join(
701 difflib.ndiff(pprint.pformat(seq1).splitlines(),
702 pprint.pformat(seq2).splitlines()))
703 standardMsg = self._truncateMessage(standardMsg, diffMsg)
704 msg = self._formatMessage(msg, standardMsg)
707 def _truncateMessage(self, message, diff):
708 max_diff = self.maxDiff
709 if max_diff is None or len(diff) <= max_diff:
710 return message + diff
711 return message + (DIFF_OMITTED % len(diff))
713 def assertListEqual(self, list1, list2, msg=None):
714 """A list-specific equality assertion.
717 list1: The first list to compare.
718 list2: The second list to compare.
719 msg: Optional message to use on failure instead of a list of
723 self.assertSequenceEqual(list1, list2, msg, seq_type=list)
725 def assertTupleEqual(self, tuple1, tuple2, msg=None):
726 """A tuple-specific equality assertion.
729 tuple1: The first tuple to compare.
730 tuple2: The second tuple to compare.
731 msg: Optional message to use on failure instead of a list of
734 self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
736 def assertSetEqual(self, set1, set2, msg=None):
737 """A set-specific equality assertion.
740 set1: The first set to compare.
741 set2: The second set to compare.
742 msg: Optional message to use on failure instead of a list of
745 assertSetEqual uses ducktyping to support different types of sets, and
746 is optimized for sets specifically (parameters must support a
750 difference1 = set1.difference(set2)
752 self.fail('invalid type when attempting set difference: %s' % e)
753 except AttributeError, e:
754 self.fail('first argument does not support set difference: %s' % e)
757 difference2 = set2.difference(set1)
759 self.fail('invalid type when attempting set difference: %s' % e)
760 except AttributeError, e:
761 self.fail('second argument does not support set difference: %s' % e)
763 if not (difference1 or difference2):
768 lines.append('Items in the first set but not the second:')
769 for item in difference1:
770 lines.append(repr(item))
772 lines.append('Items in the second set but not the first:')
773 for item in difference2:
774 lines.append(repr(item))
776 standardMsg = '\n'.join(lines)
777 self.fail(self._formatMessage(msg, standardMsg))
779 def assertIn(self, member, container, msg=None):
780 """Just like self.assertTrue(a in b), but with a nicer default message."""
781 if member not in container:
782 standardMsg = '%s not found in %s' % (safe_repr(member),
783 safe_repr(container))
784 self.fail(self._formatMessage(msg, standardMsg))
786 def assertNotIn(self, member, container, msg=None):
787 """Just like self.assertTrue(a not in b), but with a nicer default message."""
788 if member in container:
789 standardMsg = '%s unexpectedly found in %s' % (safe_repr(member),
790 safe_repr(container))
791 self.fail(self._formatMessage(msg, standardMsg))
793 def assertIs(self, expr1, expr2, msg=None):
794 """Just like self.assertTrue(a is b), but with a nicer default message."""
795 if expr1 is not expr2:
796 standardMsg = '%s is not %s' % (safe_repr(expr1),
798 self.fail(self._formatMessage(msg, standardMsg))
800 def assertIsNot(self, expr1, expr2, msg=None):
801 """Just like self.assertTrue(a is not b), but with a nicer default message."""
803 standardMsg = 'unexpectedly identical: %s' % (safe_repr(expr1),)
804 self.fail(self._formatMessage(msg, standardMsg))
806 def assertDictEqual(self, d1, d2, msg=None):
807 self.assertIsInstance(d1, dict, 'First argument is not a dictionary')
808 self.assertIsInstance(d2, dict, 'Second argument is not a dictionary')
811 standardMsg = '%s != %s' % (safe_repr(d1, True), safe_repr(d2, True))
812 diff = ('\n' + '\n'.join(difflib.ndiff(
813 pprint.pformat(d1).splitlines(),
814 pprint.pformat(d2).splitlines())))
815 standardMsg = self._truncateMessage(standardMsg, diff)
816 self.fail(self._formatMessage(msg, standardMsg))
818 def assertDictContainsSubset(self, expected, actual, msg=None):
819 """Checks whether actual is a superset of expected."""
822 for key, value in expected.iteritems():
823 if key not in actual:
825 elif value != actual[key]:
826 mismatched.append('%s, expected: %s, actual: %s' %
827 (safe_repr(key), safe_repr(value),
828 safe_repr(actual[key])))
830 if not (missing or mismatched):
835 standardMsg = 'Missing: %s' % ','.join(safe_repr(m) for m in
840 standardMsg += 'Mismatched values: %s' % ','.join(mismatched)
842 self.fail(self._formatMessage(msg, standardMsg))
844 def assertItemsEqual(self, expected_seq, actual_seq, msg=None):
845 """An unordered sequence / set specific comparison. It asserts that
846 expected_seq and actual_seq contain the same elements. It is
849 self.assertEqual(sorted(expected_seq), sorted(actual_seq))
851 Raises with an error message listing which elements of expected_seq
852 are missing from actual_seq and vice versa if any.
854 Asserts that each element has the same count in both sequences.
856 - [0, 1, 1] and [1, 0, 1] compare equal.
857 - [0, 0, 1] and [0, 1] compare unequal.
859 with warnings.catch_warnings():
861 # Silence Py3k warning raised during the sorting
862 for _msg in ["(code|dict|type) inequality comparisons",
863 "builtin_function_or_method order comparisons",
864 "comparing unequal types"]:
865 warnings.filterwarnings("ignore", _msg, DeprecationWarning)
867 expected = sorted(expected_seq)
868 actual = sorted(actual_seq)
870 # Unsortable items (example: set(), complex(), ...)
871 expected = list(expected_seq)
872 actual = list(actual_seq)
873 missing, unexpected = unorderable_list_difference(
874 expected, actual, ignore_duplicate=False
877 return self.assertSequenceEqual(expected, actual, msg=msg)
881 errors.append('Expected, but missing:\n %s' %
884 errors.append('Unexpected, but present:\n %s' %
885 safe_repr(unexpected))
887 standardMsg = '\n'.join(errors)
888 self.fail(self._formatMessage(msg, standardMsg))
890 def assertMultiLineEqual(self, first, second, msg=None):
891 """Assert that two multi-line strings are equal."""
892 self.assertIsInstance(first, basestring,
893 'First argument is not a string')
894 self.assertIsInstance(second, basestring,
895 'Second argument is not a string')
898 firstlines = first.splitlines(True)
899 secondlines = second.splitlines(True)
900 if len(firstlines) == 1 and first.strip('\r\n') == first:
901 firstlines = [first + '\n']
902 secondlines = [second + '\n']
903 standardMsg = '%s != %s' % (safe_repr(first, True),
904 safe_repr(second, True))
905 diff = '\n' + ''.join(difflib.ndiff(firstlines, secondlines))
906 standardMsg = self._truncateMessage(standardMsg, diff)
907 self.fail(self._formatMessage(msg, standardMsg))
909 def assertLess(self, a, b, msg=None):
910 """Just like self.assertTrue(a < b), but with a nicer default message."""
912 standardMsg = '%s not less than %s' % (safe_repr(a), safe_repr(b))
913 self.fail(self._formatMessage(msg, standardMsg))
915 def assertLessEqual(self, a, b, msg=None):
916 """Just like self.assertTrue(a <= b), but with a nicer default message."""
918 standardMsg = '%s not less than or equal to %s' % (safe_repr(a), safe_repr(b))
919 self.fail(self._formatMessage(msg, standardMsg))
921 def assertGreater(self, a, b, msg=None):
922 """Just like self.assertTrue(a > b), but with a nicer default message."""
924 standardMsg = '%s not greater than %s' % (safe_repr(a), safe_repr(b))
925 self.fail(self._formatMessage(msg, standardMsg))
927 def assertGreaterEqual(self, a, b, msg=None):
928 """Just like self.assertTrue(a >= b), but with a nicer default message."""
930 standardMsg = '%s not greater than or equal to %s' % (safe_repr(a), safe_repr(b))
931 self.fail(self._formatMessage(msg, standardMsg))
933 def assertIsNone(self, obj, msg=None):
934 """Same as self.assertTrue(obj is None), with a nicer default message."""
936 standardMsg = '%s is not None' % (safe_repr(obj),)
937 self.fail(self._formatMessage(msg, standardMsg))
939 def assertIsNotNone(self, obj, msg=None):
940 """Included for symmetry with assertIsNone."""
942 standardMsg = 'unexpectedly None'
943 self.fail(self._formatMessage(msg, standardMsg))
945 def assertIsInstance(self, obj, cls, msg=None):
946 """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
948 if not isinstance(obj, cls):
949 standardMsg = '%s is not an instance of %r' % (safe_repr(obj), cls)
950 self.fail(self._formatMessage(msg, standardMsg))
952 def assertNotIsInstance(self, obj, cls, msg=None):
953 """Included for symmetry with assertIsInstance."""
954 if isinstance(obj, cls):
955 standardMsg = '%s is an instance of %r' % (safe_repr(obj), cls)
956 self.fail(self._formatMessage(msg, standardMsg))
958 def assertRaisesRegexp(self, expected_exception, expected_regexp,
959 callable_obj=None, *args, **kwargs):
960 """Asserts that the message in a raised exception matches a regexp.
963 expected_exception: Exception class expected to be raised.
964 expected_regexp: Regexp (re pattern object or string) expected
965 to be found in error message.
966 callable_obj: Function to be called.
968 kwargs: Extra kwargs.
970 context = _AssertRaisesContext(expected_exception, self, expected_regexp)
971 if callable_obj is None:
974 callable_obj(*args, **kwargs)
976 def assertRegexpMatches(self, text, expected_regexp, msg=None):
977 """Fail the test unless the text matches the regular expression."""
978 if isinstance(expected_regexp, basestring):
979 expected_regexp = re.compile(expected_regexp)
980 if not expected_regexp.search(text):
981 msg = msg or "Regexp didn't match"
982 msg = '%s: %r not found in %r' % (msg, expected_regexp.pattern, text)
983 raise self.failureException(msg)
985 def assertNotRegexpMatches(self, text, unexpected_regexp, msg=None):
986 """Fail the test if the text matches the regular expression."""
987 if isinstance(unexpected_regexp, basestring):
988 unexpected_regexp = re.compile(unexpected_regexp)
989 match = unexpected_regexp.search(text)
991 msg = msg or "Regexp matched"
992 msg = '%s: %r matches %r in %r' % (msg,
993 text[match.start():match.end()],
994 unexpected_regexp.pattern,
996 raise self.failureException(msg)
999 class FunctionTestCase(TestCase):
1000 """A test case that wraps a test function.
1002 This is useful for slipping pre-existing test functions into the
1003 unittest framework. Optionally, set-up and tidy-up functions can be
1004 supplied. As with TestCase, the tidy-up ('tearDown') function will
1005 always be called if the set-up ('setUp') function ran successfully.
1008 def __init__(self, testFunc, setUp=None, tearDown=None, description=None):
1009 super(FunctionTestCase, self).__init__()
1010 self._setUpFunc = setUp
1011 self._tearDownFunc = tearDown
1012 self._testFunc = testFunc
1013 self._description = description
1016 if self._setUpFunc is not None:
1020 if self._tearDownFunc is not None:
1021 self._tearDownFunc()
1027 return self._testFunc.__name__
1029 def __eq__(self, other):
1030 if not isinstance(other, self.__class__):
1031 return NotImplemented
1033 return self._setUpFunc == other._setUpFunc and \
1034 self._tearDownFunc == other._tearDownFunc and \
1035 self._testFunc == other._testFunc and \
1036 self._description == other._description
1038 def __ne__(self, other):
1039 return not self == other
1042 return hash((type(self), self._setUpFunc, self._tearDownFunc,
1043 self._testFunc, self._description))
1046 return "%s (%s)" % (strclass(self.__class__),
1047 self._testFunc.__name__)
1050 return "<%s tec=%s>" % (strclass(self.__class__),
1053 def shortDescription(self):
1054 if self._description is not None:
1055 return self._description
1056 doc = self._testFunc.__doc__
1057 return doc and doc.split("\n")[0].strip() or None