Back to index

python3.2  3.2.2
Public Member Functions | Public Attributes | Static Public Attributes | Private Member Functions | Private Attributes | Static Private Attributes
unittest.case.TestCase Class Reference
Inheritance diagram for unittest.case.TestCase:
Inheritance graph
[legend]
Collaboration diagram for unittest.case.TestCase:
Collaboration graph
[legend]

List of all members.

Public Member Functions

def __init__
def addTypeEqualityFunc
def addCleanup
def setUp
def tearDown
def setUpClass
def tearDownClass
def countTestCases
def defaultTestResult
def shortDescription
def id
def __eq__
def __hash__
def __str__
def __repr__
def run
def doCleanups
def __call__
def debug
def skipTest
def fail
def assertFalse
def assertTrue
def assertRaises
def assertWarns
def assertEqual
def assertNotEqual
def assertAlmostEqual
def assertNotAlmostEqual
def assertSequenceEqual
def assertListEqual
def assertTupleEqual
def assertSetEqual
def assertIn
def assertNotIn
def assertIs
def assertIsNot
def assertDictEqual
def assertDictContainsSubset
def assertSameElements
def assertCountEqual
def assertMultiLineEqual
def assertLess
def assertLessEqual
def assertGreater
def assertGreaterEqual
def assertIsNone
def assertIsNotNone
def assertIsInstance
def assertNotIsInstance
def assertRaisesRegex
def assertWarnsRegex
def assertRegex
def assertNotRegex

Public Attributes

_PyObject_HEAD_EXTRA Py_ssize_t ob_refcnt
struct _typeobjectob_type

Static Public Attributes

 failureException = AssertionError
 longMessage = True
int maxDiff = 80
tuple failUnlessEqual = assertEquals_deprecate(assertEqual)
tuple failIfEqual = assertNotEquals_deprecate(assertNotEqual)
tuple failUnlessAlmostEqual = assertAlmostEquals_deprecate(assertAlmostEqual)
tuple failIfAlmostEqual = assertNotAlmostEquals_deprecate(assertNotAlmostEqual)
tuple failUnless = assert__deprecate(assertTrue)
tuple failUnlessRaises = _deprecate(assertRaises)
tuple failIf = _deprecate(assertFalse)
tuple assertRaisesRegexp = _deprecate(assertRaisesRegex)
tuple assertRegexpMatches = _deprecate(assertRegex)

Private Member Functions

def _addSkip
def _executeTestPart
def _formatMessage
def _getAssertEqualityFunc
def _baseAssertEqual
def _truncateMessage
def _deprecate

Private Attributes

 _testMethodName
 _outcomeForDoCleanups
 _testMethodDoc
 _cleanups
 _type_equality_funcs

Static Private Attributes

int _diffThreshold = 2
 _classSetupFailed = False

Detailed Description

A class whose instances are single test cases.

By default, the test code itself should be placed in a method named
'runTest'.

If the fixture may be used for many test cases, create as
many test methods as are needed. When instantiating such a TestCase
subclass, specify in the constructor arguments the name of the test method
that the instance is to execute.

Test authors should subclass TestCase for their own tests. Construction
and deconstruction of the test's environment ('fixture') can be
implemented by overriding the 'setUp' and 'tearDown' methods respectively.

If it is necessary to override the __init__ method, the base class
__init__ method must always be called. It is important that subclasses
should not change the signature of their __init__ method, since instances
of the classes are instantiated automatically by parts of the framework
in order to be run.

Definition at line 205 of file case.py.


Constructor & Destructor Documentation

def unittest.case.TestCase.__init__ (   self,
  methodName = 'runTest' 
)
Create an instance of the class that will use the named test
   method when executed. Raises a ValueError if the instance does
   not have a method with the specified name.

Definition at line 253 of file case.py.

00253 
00254     def __init__(self, methodName='runTest'):
00255         """Create an instance of the class that will use the named test
00256            method when executed. Raises a ValueError if the instance does
00257            not have a method with the specified name.
00258         """
00259         self._testMethodName = methodName
00260         self._outcomeForDoCleanups = None
00261         self._testMethodDoc = 'No test'
00262         try:
00263             testMethod = getattr(self, methodName)
00264         except AttributeError:
00265             if methodName != 'runTest':
00266                 # we allow instantiation with no explicit method name
00267                 # but not an *incorrect* or missing method name
00268                 raise ValueError("no such test method in %s: %s" %
00269                       (self.__class__, methodName))
00270         else:
00271             self._testMethodDoc = testMethod.__doc__
00272         self._cleanups = []
00273 
00274         # Map types to custom assertEqual functions that will compare
00275         # instances of said type in more detail to generate a more useful
00276         # error message.
00277         self._type_equality_funcs = {}
00278         self.addTypeEqualityFunc(dict, 'assertDictEqual')
00279         self.addTypeEqualityFunc(list, 'assertListEqual')
00280         self.addTypeEqualityFunc(tuple, 'assertTupleEqual')
00281         self.addTypeEqualityFunc(set, 'assertSetEqual')
00282         self.addTypeEqualityFunc(frozenset, 'assertSetEqual')
00283         self.addTypeEqualityFunc(str, 'assertMultiLineEqual')

Here is the caller graph for this function:


Member Function Documentation

def unittest.case.TestCase.__call__ (   self,
  args,
  kwds 
)

Definition at line 476 of file case.py.

00476 
00477     def __call__(self, *args, **kwds):
00478         return self.run(*args, **kwds)

def unittest.case.TestCase.__eq__ (   self,
  other 
)

Reimplemented in unittest.case.FunctionTestCase.

Definition at line 343 of file case.py.

00343 
00344     def __eq__(self, other):
00345         if type(self) is not type(other):
00346             return NotImplemented
00347 
00348         return self._testMethodName == other._testMethodName

Reimplemented in unittest.case.FunctionTestCase.

Definition at line 349 of file case.py.

00349 
00350     def __hash__(self):
00351         return hash((type(self), self._testMethodName))

Reimplemented in unittest.case.FunctionTestCase.

Definition at line 355 of file case.py.

00355 
00356     def __repr__(self):
00357         return "<%s testMethod=%s>" % \
00358                (strclass(self.__class__), self._testMethodName)

Here is the call graph for this function:

Reimplemented in unittest.case.FunctionTestCase.

Definition at line 352 of file case.py.

00352 
00353     def __str__(self):
00354         return "%s (%s)" % (self._testMethodName, strclass(self.__class__))

Here is the call graph for this function:

def unittest.case.TestCase._addSkip (   self,
  result,
  reason 
) [private]

Definition at line 359 of file case.py.

00359 
00360     def _addSkip(self, result, reason):
00361         addSkip = getattr(result, 'addSkip', None)
00362         if addSkip is not None:
00363             addSkip(self, reason)
00364         else:
00365             warnings.warn("TestResult has no addSkip method, skips not reported",
00366                           RuntimeWarning, 2)
00367             result.addSuccess(self)

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.case.TestCase._baseAssertEqual (   self,
  first,
  second,
  msg = None 
) [private]
The default assertEqual implementation, not type specific.

Definition at line 616 of file case.py.

00616 
00617     def _baseAssertEqual(self, first, second, msg=None):
00618         """The default assertEqual implementation, not type specific."""
00619         if not first == second:
00620             standardMsg = '%s != %s' % (safe_repr(first), safe_repr(second))
00621             msg = self._formatMessage(msg, standardMsg)
00622             raise self.failureException(msg)

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.case.TestCase._deprecate (   original_func) [private]

Definition at line 1165 of file case.py.

01165 
01166     def _deprecate(original_func):
01167         def deprecated_func(*args, **kwargs):
01168             warnings.warn(
01169                 'Please use {0} instead.'.format(original_func.__name__),
01170                 DeprecationWarning, 2)
01171             return original_func(*args, **kwargs)
01172         return deprecated_func

Here is the call graph for this function:

def unittest.case.TestCase._executeTestPart (   self,
  function,
  outcome,
  isTest = False 
) [private]

Definition at line 368 of file case.py.

00368 
00369     def _executeTestPart(self, function, outcome, isTest=False):
00370         try:
00371             function()
00372         except KeyboardInterrupt:
00373             raise
00374         except SkipTest as e:
00375             outcome.success = False
00376             outcome.skipped = str(e)
00377         except _UnexpectedSuccess:
00378             exc_info = sys.exc_info()
00379             outcome.success = False
00380             if isTest:
00381                 outcome.unexpectedSuccess = exc_info
00382             else:
00383                 outcome.errors.append(exc_info)
00384         except _ExpectedFailure:
00385             outcome.success = False
00386             exc_info = sys.exc_info()
00387             if isTest:
00388                 outcome.expectedFailure = exc_info
00389             else:
00390                 outcome.errors.append(exc_info)
00391         except self.failureException:
00392             outcome.success = False
00393             outcome.failures.append(sys.exc_info())
00394             exc_info = sys.exc_info()
00395         except:
00396             outcome.success = False
00397             outcome.errors.append(sys.exc_info())

Here is the caller graph for this function:

def unittest.case.TestCase._formatMessage (   self,
  msg,
  standardMsg 
) [private]
Honour the longMessage attribute when generating failure messages.
If longMessage is False this means:
* Use only an explicit message if it is provided
* Otherwise use the standard message for the assert

If longMessage is True:
* Use the standard message
* If an explicit message is provided, plus ' : ' and the explicit message

Definition at line 508 of file case.py.

00508 
00509     def _formatMessage(self, msg, standardMsg):
00510         """Honour the longMessage attribute when generating failure messages.
00511         If longMessage is False this means:
00512         * Use only an explicit message if it is provided
00513         * Otherwise use the standard message for the assert
00514 
00515         If longMessage is True:
00516         * Use the standard message
00517         * If an explicit message is provided, plus ' : ' and the explicit message
00518         """
00519         if not self.longMessage:
00520             return msg or standardMsg
00521         if msg is None:
00522             return standardMsg
00523         try:
00524             # don't switch to '{}' formatting in Python 2.X
00525             # it changes the way unicode input is handled
00526             return '%s : %s' % (standardMsg, msg)
00527         except UnicodeDecodeError:
00528             return  '%s : %s' % (safe_repr(standardMsg), safe_repr(msg))
00529 

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.case.TestCase._getAssertEqualityFunc (   self,
  first,
  second 
) [private]
Get a detailed comparison function for the types of the two args.

Returns: A callable accepting (first, second, msg=None) that will
raise a failure exception if first != second with a useful human
readable error message for those types.

Definition at line 590 of file case.py.

00590 
00591     def _getAssertEqualityFunc(self, first, second):
00592         """Get a detailed comparison function for the types of the two args.
00593 
00594         Returns: A callable accepting (first, second, msg=None) that will
00595         raise a failure exception if first != second with a useful human
00596         readable error message for those types.
00597         """
00598         #
00599         # NOTE(gregory.p.smith): I considered isinstance(first, type(second))
00600         # and vice versa.  I opted for the conservative approach in case
00601         # subclasses are not intended to be compared in detail to their super
00602         # class instances using a type equality func.  This means testing
00603         # subtypes won't automagically use the detailed comparison.  Callers
00604         # should use their type specific assertSpamEqual method to compare
00605         # subclasses if the detailed comparison is desired and appropriate.
00606         # See the discussion in http://bugs.python.org/issue2578.
00607         #
00608         if type(first) is type(second):
00609             asserter = self._type_equality_funcs.get(type(first))
00610             if asserter is not None:
00611                 if isinstance(asserter, str):
00612                     asserter = getattr(self, asserter)
00613                 return asserter
00614 
00615         return self._baseAssertEqual

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.case.TestCase._truncateMessage (   self,
  message,
  diff 
) [private]

Definition at line 815 of file case.py.

00815 
00816     def _truncateMessage(self, message, diff):
00817         max_diff = self.maxDiff
00818         if max_diff is None or len(diff) <= max_diff:
00819             return message + diff
00820         return message + (DIFF_OMITTED % len(diff))

Here is the caller graph for this function:

def unittest.case.TestCase.addCleanup (   self,
  function,
  args,
  kwargs 
)
Add a function, with arguments, to be called when the test is
completed. Functions added are called on a LIFO basis and are
called after tearDown on test failure or success.

Cleanup items are called even if setUp fails (unlike tearDown).

Definition at line 299 of file case.py.

00299 
00300     def addCleanup(self, function, *args, **kwargs):
00301         """Add a function, with arguments, to be called when the test is
00302         completed. Functions added are called on a LIFO basis and are
00303         called after tearDown on test failure or success.
00304 
00305         Cleanup items are called even if setUp fails (unlike tearDown)."""
00306         self._cleanups.append((function, args, kwargs))

def unittest.case.TestCase.addTypeEqualityFunc (   self,
  typeobj,
  function 
)
Add a type specific assertEqual style function to compare a type.

This method is for use by TestCase subclasses that need to register
their own type equality functions to provide nicer error messages.

Args:
    typeobj: The data type to call this function on when both values
    are of the same type in assertEqual().
    function: The callable taking two arguments and an optional
    msg= argument that raises self.failureException with a
    useful error message when the two arguments are not equal.

Definition at line 284 of file case.py.

00284 
00285     def addTypeEqualityFunc(self, typeobj, function):
00286         """Add a type specific assertEqual style function to compare a type.
00287 
00288         This method is for use by TestCase subclasses that need to register
00289         their own type equality functions to provide nicer error messages.
00290 
00291         Args:
00292             typeobj: The data type to call this function on when both values
00293                     are of the same type in assertEqual().
00294             function: The callable taking two arguments and an optional
00295                     msg= argument that raises self.failureException with a
00296                     useful error message when the two arguments are not equal.
00297         """
00298         self._type_equality_funcs[typeobj] = function

def unittest.case.TestCase.assertAlmostEqual (   self,
  first,
  second,
  places = None,
  msg = None,
  delta = None 
)
Fail if the two objects are unequal as determined by their
   difference rounded to the given number of decimal places
   (default 7) and comparing to zero, or by comparing that the
   between the two objects is more than the given delta.

   Note that decimal places (from zero) are usually not the same
   as significant digits (measured from the most signficant digit).

   If the two objects compare equal then they will automatically
   compare almost equal.

Definition at line 640 of file case.py.

00640 
00641                           delta=None):
00642         """Fail if the two objects are unequal as determined by their
00643            difference rounded to the given number of decimal places
00644            (default 7) and comparing to zero, or by comparing that the
00645            between the two objects is more than the given delta.
00646 
00647            Note that decimal places (from zero) are usually not the same
00648            as significant digits (measured from the most signficant digit).
00649 
00650            If the two objects compare equal then they will automatically
00651            compare almost equal.
00652         """
00653         if first == second:
00654             # shortcut
00655             return
00656         if delta is not None and places is not None:
00657             raise TypeError("specify delta or places not both")
00658 
00659         if delta is not None:
00660             if abs(first - second) <= delta:
00661                 return
00662 
00663             standardMsg = '%s != %s within %s delta' % (safe_repr(first),
00664                                                         safe_repr(second),
00665                                                         safe_repr(delta))
00666         else:
00667             if places is None:
00668                 places = 7
00669 
00670             if round(abs(second-first), places) == 0:
00671                 return
00672 
00673             standardMsg = '%s != %s within %r places' % (safe_repr(first),
00674                                                           safe_repr(second),
00675                                                           places)
00676         msg = self._formatMessage(msg, standardMsg)
00677         raise self.failureException(msg)

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.case.TestCase.assertCountEqual (   self,
  first,
  second,
  msg = None 
)
An unordered sequence comparison asserting that the same elements,
regardless of order.  If the same element occurs more than once,
it verifies that the elements occur the same number of times.

    self.assertEqual(Counter(list(first)),
             Counter(list(second)))

 Example:
    - [0, 1, 1] and [1, 0, 1] compare equal.
    - [0, 0, 1] and [0, 1] compare unequal.

Definition at line 997 of file case.py.

00997 
00998     def assertCountEqual(self, first, second, msg=None):
00999         """An unordered sequence comparison asserting that the same elements,
01000         regardless of order.  If the same element occurs more than once,
01001         it verifies that the elements occur the same number of times.
01002 
01003             self.assertEqual(Counter(list(first)),
01004                              Counter(list(second)))
01005 
01006          Example:
01007             - [0, 1, 1] and [1, 0, 1] compare equal.
01008             - [0, 0, 1] and [0, 1] compare unequal.
01009 
01010         """
01011         first_seq, second_seq = list(first), list(second)
01012         try:
01013             first = collections.Counter(first_seq)
01014             second = collections.Counter(second_seq)
01015         except TypeError:
01016             # Handle case with unhashable elements
01017             differences = _count_diff_all_purpose(first_seq, second_seq)
01018         else:
01019             if first == second:
01020                 return
01021             differences = _count_diff_hashable(first_seq, second_seq)
01022 
01023         if differences:
01024             standardMsg = 'Element counts were not equal:\n'
01025             lines = ['First has %d, Second has %d:  %r' % diff for diff in differences]
01026             diffMsg = '\n'.join(lines)
01027             standardMsg = self._truncateMessage(standardMsg, diffMsg)
01028             msg = self._formatMessage(msg, standardMsg)
01029             self.fail(msg)

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.case.TestCase.assertDictContainsSubset (   self,
  subset,
  dictionary,
  msg = None 
)
Checks whether dictionary is a superset of subset.

Definition at line 926 of file case.py.

00926 
00927     def assertDictContainsSubset(self, subset, dictionary, msg=None):
00928         """Checks whether dictionary is a superset of subset."""
00929         warnings.warn('assertDictContainsSubset is deprecated',
00930                       DeprecationWarning)
00931         missing = []
00932         mismatched = []
00933         for key, value in subset.items():
00934             if key not in dictionary:
00935                 missing.append(key)
00936             elif value != dictionary[key]:
00937                 mismatched.append('%s, expected: %s, actual: %s' %
00938                                   (safe_repr(key), safe_repr(value),
00939                                    safe_repr(dictionary[key])))
00940 
00941         if not (missing or mismatched):
00942             return
00943 
00944         standardMsg = ''
00945         if missing:
00946             standardMsg = 'Missing: %s' % ','.join(safe_repr(m) for m in
00947                                                     missing)
00948         if mismatched:
00949             if standardMsg:
00950                 standardMsg += '; '
00951             standardMsg += 'Mismatched values: %s' % ','.join(mismatched)
00952 
00953         self.fail(self._formatMessage(msg, standardMsg))

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.case.TestCase.assertDictEqual (   self,
  d1,
  d2,
  msg = None 
)

Definition at line 914 of file case.py.

00914 
00915     def assertDictEqual(self, d1, d2, msg=None):
00916         self.assertIsInstance(d1, dict, 'First argument is not a dictionary')
00917         self.assertIsInstance(d2, dict, 'Second argument is not a dictionary')
00918 
00919         if d1 != d2:
00920             standardMsg = '%s != %s' % (safe_repr(d1, True), safe_repr(d2, True))
00921             diff = ('\n' + '\n'.join(difflib.ndiff(
00922                            pprint.pformat(d1).splitlines(),
00923                            pprint.pformat(d2).splitlines())))
00924             standardMsg = self._truncateMessage(standardMsg, diff)
00925             self.fail(self._formatMessage(msg, standardMsg))

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.case.TestCase.assertEqual (   self,
  first,
  second,
  msg = None 
)
Fail if the two objects are unequal as determined by the '=='
   operator.

Definition at line 623 of file case.py.

00623 
00624     def assertEqual(self, first, second, msg=None):
00625         """Fail if the two objects are unequal as determined by the '=='
00626            operator.
00627         """
00628         assertion_func = self._getAssertEqualityFunc(first, second)
00629         assertion_func(first, second, msg=msg)

Here is the call graph for this function:

def unittest.case.TestCase.assertFalse (   self,
  expr,
  msg = None 
)
Check that the expression is false.

Definition at line 496 of file case.py.

00496 
00497     def assertFalse(self, expr, msg=None):
00498         """Check that the expression is false."""
00499         if expr:
00500             msg = self._formatMessage(msg, "%s is not false" % safe_repr(expr))
00501             raise self.failureException(msg)

Here is the call graph for this function:

def unittest.case.TestCase.assertGreater (   self,
  a,
  b,
  msg = None 
)
Just like self.assertTrue(a > b), but with a nicer default message.

Definition at line 1063 of file case.py.

01063 
01064     def assertGreater(self, a, b, msg=None):
01065         """Just like self.assertTrue(a > b), but with a nicer default message."""
01066         if not a > b:
01067             standardMsg = '%s not greater than %s' % (safe_repr(a), safe_repr(b))
01068             self.fail(self._formatMessage(msg, standardMsg))

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.case.TestCase.assertGreaterEqual (   self,
  a,
  b,
  msg = None 
)
Just like self.assertTrue(a >= b), but with a nicer default message.

Definition at line 1069 of file case.py.

01069 
01070     def assertGreaterEqual(self, a, b, msg=None):
01071         """Just like self.assertTrue(a >= b), but with a nicer default message."""
01072         if not a >= b:
01073             standardMsg = '%s not greater than or equal to %s' % (safe_repr(a), safe_repr(b))
01074             self.fail(self._formatMessage(msg, standardMsg))

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.case.TestCase.assertIn (   self,
  member,
  container,
  msg = None 
)
Just like self.assertTrue(a in b), but with a nicer default message.

Definition at line 887 of file case.py.

00887 
00888     def assertIn(self, member, container, msg=None):
00889         """Just like self.assertTrue(a in b), but with a nicer default message."""
00890         if member not in container:
00891             standardMsg = '%s not found in %s' % (safe_repr(member),
00892                                                   safe_repr(container))
00893             self.fail(self._formatMessage(msg, standardMsg))

Here is the call graph for this function:

def unittest.case.TestCase.assertIs (   self,
  expr1,
  expr2,
  msg = None 
)
Just like self.assertTrue(a is b), but with a nicer default message.

Definition at line 901 of file case.py.

00901 
00902     def assertIs(self, expr1, expr2, msg=None):
00903         """Just like self.assertTrue(a is b), but with a nicer default message."""
00904         if expr1 is not expr2:
00905             standardMsg = '%s is not %s' % (safe_repr(expr1),
00906                                              safe_repr(expr2))
00907             self.fail(self._formatMessage(msg, standardMsg))

Here is the call graph for this function:

def unittest.case.TestCase.assertIsInstance (   self,
  obj,
  cls,
  msg = None 
)
Same as self.assertTrue(isinstance(obj, cls)), with a nicer
default message.

Definition at line 1087 of file case.py.

01087 
01088     def assertIsInstance(self, obj, cls, msg=None):
01089         """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
01090         default message."""
01091         if not isinstance(obj, cls):
01092             standardMsg = '%s is not an instance of %r' % (safe_repr(obj), cls)
01093             self.fail(self._formatMessage(msg, standardMsg))

Here is the call graph for this function:

def unittest.case.TestCase.assertIsNone (   self,
  obj,
  msg = None 
)
Same as self.assertTrue(obj is None), with a nicer default message.

Definition at line 1075 of file case.py.

01075 
01076     def assertIsNone(self, obj, msg=None):
01077         """Same as self.assertTrue(obj is None), with a nicer default message."""
01078         if obj is not None:
01079             standardMsg = '%s is not None' % (safe_repr(obj),)
01080             self.fail(self._formatMessage(msg, standardMsg))

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.case.TestCase.assertIsNot (   self,
  expr1,
  expr2,
  msg = None 
)
Just like self.assertTrue(a is not b), but with a nicer default message.

Definition at line 908 of file case.py.

00908 
00909     def assertIsNot(self, expr1, expr2, msg=None):
00910         """Just like self.assertTrue(a is not b), but with a nicer default message."""
00911         if expr1 is expr2:
00912             standardMsg = 'unexpectedly identical: %s' % (safe_repr(expr1),)
00913             self.fail(self._formatMessage(msg, standardMsg))

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.case.TestCase.assertIsNotNone (   self,
  obj,
  msg = None 
)
Included for symmetry with assertIsNone.

Definition at line 1081 of file case.py.

01081 
01082     def assertIsNotNone(self, obj, msg=None):
01083         """Included for symmetry with assertIsNone."""
01084         if obj is None:
01085             standardMsg = 'unexpectedly None'
01086             self.fail(self._formatMessage(msg, standardMsg))

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.case.TestCase.assertLess (   self,
  a,
  b,
  msg = None 
)
Just like self.assertTrue(a < b), but with a nicer default message.

Definition at line 1051 of file case.py.

01051 
01052     def assertLess(self, a, b, msg=None):
01053         """Just like self.assertTrue(a < b), but with a nicer default message."""
01054         if not a < b:
01055             standardMsg = '%s not less than %s' % (safe_repr(a), safe_repr(b))
01056             self.fail(self._formatMessage(msg, standardMsg))

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.case.TestCase.assertLessEqual (   self,
  a,
  b,
  msg = None 
)
Just like self.assertTrue(a <= b), but with a nicer default message.

Definition at line 1057 of file case.py.

01057 
01058     def assertLessEqual(self, a, b, msg=None):
01059         """Just like self.assertTrue(a <= b), but with a nicer default message."""
01060         if not a <= b:
01061             standardMsg = '%s not less than or equal to %s' % (safe_repr(a), safe_repr(b))
01062             self.fail(self._formatMessage(msg, standardMsg))

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.case.TestCase.assertListEqual (   self,
  list1,
  list2,
  msg = None 
)
A list-specific equality assertion.

Args:
    list1: The first list to compare.
    list2: The second list to compare.
    msg: Optional message to use on failure instead of a list of
    differences.

Definition at line 821 of file case.py.

00821 
00822     def assertListEqual(self, list1, list2, msg=None):
00823         """A list-specific equality assertion.
00824 
00825         Args:
00826             list1: The first list to compare.
00827             list2: The second list to compare.
00828             msg: Optional message to use on failure instead of a list of
00829                     differences.
00830 
00831         """
00832         self.assertSequenceEqual(list1, list2, msg, seq_type=list)

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.case.TestCase.assertMultiLineEqual (   self,
  first,
  second,
  msg = None 
)
Assert that two multi-line strings are equal.

Definition at line 1030 of file case.py.

01030 
01031     def assertMultiLineEqual(self, first, second, msg=None):
01032         """Assert that two multi-line strings are equal."""
01033         self.assertIsInstance(first, str, 'First argument is not a string')
01034         self.assertIsInstance(second, str, 'Second argument is not a string')
01035 
01036         if first != second:
01037             # don't use difflib if the strings are too long
01038             if (len(first) > self._diffThreshold or
01039                 len(second) > self._diffThreshold):
01040                 self._baseAssertEqual(first, second, msg)
01041             firstlines = first.splitlines(True)
01042             secondlines = second.splitlines(True)
01043             if len(firstlines) == 1 and first.strip('\r\n') == first:
01044                 firstlines = [first + '\n']
01045                 secondlines = [second + '\n']
01046             standardMsg = '%s != %s' % (safe_repr(first, True),
01047                                         safe_repr(second, True))
01048             diff = '\n' + ''.join(difflib.ndiff(firstlines, secondlines))
01049             standardMsg = self._truncateMessage(standardMsg, diff)
01050             self.fail(self._formatMessage(msg, standardMsg))

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.case.TestCase.assertNotAlmostEqual (   self,
  first,
  second,
  places = None,
  msg = None,
  delta = None 
)
Fail if the two objects are equal as determined by their
   difference rounded to the given number of decimal places
   (default 7) and comparing to zero, or by comparing that the
   between the two objects is less than the given delta.

   Note that decimal places (from zero) are usually not the same
   as significant digits (measured from the most signficant digit).

   Objects that are equal automatically fail.

Definition at line 679 of file case.py.

00679 
00680                              delta=None):
00681         """Fail if the two objects are equal as determined by their
00682            difference rounded to the given number of decimal places
00683            (default 7) and comparing to zero, or by comparing that the
00684            between the two objects is less than the given delta.
00685 
00686            Note that decimal places (from zero) are usually not the same
00687            as significant digits (measured from the most signficant digit).
00688 
00689            Objects that are equal automatically fail.
00690         """
00691         if delta is not None and places is not None:
00692             raise TypeError("specify delta or places not both")
00693         if delta is not None:
00694             if not (first == second) and abs(first - second) > delta:
00695                 return
00696             standardMsg = '%s == %s within %s delta' % (safe_repr(first),
00697                                                         safe_repr(second),
00698                                                         safe_repr(delta))
00699         else:
00700             if places is None:
00701                 places = 7
00702             if not (first == second) and round(abs(second-first), places) != 0:
00703                 return
00704             standardMsg = '%s == %s within %r places' % (safe_repr(first),
00705                                                          safe_repr(second),
00706                                                          places)
00707 
00708         msg = self._formatMessage(msg, standardMsg)
00709         raise self.failureException(msg)
00710 

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.case.TestCase.assertNotEqual (   self,
  first,
  second,
  msg = None 
)
Fail if the two objects are equal as determined by the '=='
   operator.

Definition at line 630 of file case.py.

00630 
00631     def assertNotEqual(self, first, second, msg=None):
00632         """Fail if the two objects are equal as determined by the '=='
00633            operator.
00634         """
00635         if not first != second:
00636             msg = self._formatMessage(msg, '%s == %s' % (safe_repr(first),
00637                                                           safe_repr(second)))
00638             raise self.failureException(msg)

Here is the call graph for this function:

def unittest.case.TestCase.assertNotIn (   self,
  member,
  container,
  msg = None 
)
Just like self.assertTrue(a not in b), but with a nicer default message.

Definition at line 894 of file case.py.

00894 
00895     def assertNotIn(self, member, container, msg=None):
00896         """Just like self.assertTrue(a not in b), but with a nicer default message."""
00897         if member in container:
00898             standardMsg = '%s unexpectedly found in %s' % (safe_repr(member),
00899                                                         safe_repr(container))
00900             self.fail(self._formatMessage(msg, standardMsg))

Here is the call graph for this function:

def unittest.case.TestCase.assertNotIsInstance (   self,
  obj,
  cls,
  msg = None 
)
Included for symmetry with assertIsInstance.

Definition at line 1094 of file case.py.

01094 
01095     def assertNotIsInstance(self, obj, cls, msg=None):
01096         """Included for symmetry with assertIsInstance."""
01097         if isinstance(obj, cls):
01098             standardMsg = '%s is an instance of %r' % (safe_repr(obj), cls)
01099             self.fail(self._formatMessage(msg, standardMsg))

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.case.TestCase.assertNotRegex (   self,
  text,
  unexpected_regex,
  msg = None 
)
Fail the test if the text matches the regular expression.

Definition at line 1151 of file case.py.

01151 
01152     def assertNotRegex(self, text, unexpected_regex, msg=None):
01153         """Fail the test if the text matches the regular expression."""
01154         if isinstance(unexpected_regex, (str, bytes)):
01155             unexpected_regex = re.compile(unexpected_regex)
01156         match = unexpected_regex.search(text)
01157         if match:
01158             msg = msg or "Regex matched"
01159             msg = '%s: %r matches %r in %r' % (msg,
01160                                                text[match.start():match.end()],
01161                                                unexpected_regex.pattern,
01162                                                text)
01163             raise self.failureException(msg)
01164 

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.case.TestCase.assertRaises (   self,
  excClass,
  callableObj = None,
  args,
  kwargs 
)
Fail unless an exception of class excClass is thrown
   by callableObj when invoked with arguments args and keyword
   arguments kwargs. If a different type of exception is
   thrown, it will not be caught, and the test case will be
   deemed to have suffered an error, exactly as for an
   unexpected exception.

   If called with callableObj omitted or None, will return a
   context object used like this::

with self.assertRaises(SomeException):
    do_something()

   The context manager keeps a reference to the exception as
   the 'exception' attribute. This allows you to inspect the
   exception after the assertion::

       with self.assertRaises(SomeException) as cm:
   do_something()
       the_exception = cm.exception
       self.assertEqual(the_exception.error_code, 3)

Definition at line 530 of file case.py.

00530 
00531     def assertRaises(self, excClass, callableObj=None, *args, **kwargs):
00532         """Fail unless an exception of class excClass is thrown
00533            by callableObj when invoked with arguments args and keyword
00534            arguments kwargs. If a different type of exception is
00535            thrown, it will not be caught, and the test case will be
00536            deemed to have suffered an error, exactly as for an
00537            unexpected exception.
00538 
00539            If called with callableObj omitted or None, will return a
00540            context object used like this::
00541 
00542                 with self.assertRaises(SomeException):
00543                     do_something()
00544 
00545            The context manager keeps a reference to the exception as
00546            the 'exception' attribute. This allows you to inspect the
00547            exception after the assertion::
00548 
00549                with self.assertRaises(SomeException) as cm:
00550                    do_something()
00551                the_exception = cm.exception
00552                self.assertEqual(the_exception.error_code, 3)
00553         """
00554         context = _AssertRaisesContext(excClass, self, callableObj)
00555         if callableObj is None:
00556             return context
00557         with context:
00558             callableObj(*args, **kwargs)

def unittest.case.TestCase.assertRaisesRegex (   self,
  expected_exception,
  expected_regex,
  callable_obj = None,
  args,
  kwargs 
)
Asserts that the message in a raised exception matches a regex.

Args:
    expected_exception: Exception class expected to be raised.
    expected_regex: Regex (re pattern object or string) expected
    to be found in error message.
    callable_obj: Function to be called.
    args: Extra args.
    kwargs: Extra kwargs.

Definition at line 1101 of file case.py.

01101 
01102                           callable_obj=None, *args, **kwargs):
01103         """Asserts that the message in a raised exception matches a regex.
01104 
01105         Args:
01106             expected_exception: Exception class expected to be raised.
01107             expected_regex: Regex (re pattern object or string) expected
01108                     to be found in error message.
01109             callable_obj: Function to be called.
01110             args: Extra args.
01111             kwargs: Extra kwargs.
01112         """
01113         context = _AssertRaisesContext(expected_exception, self, callable_obj,
01114                                        expected_regex)
01115         if callable_obj is None:
01116             return context
01117         with context:
01118             callable_obj(*args, **kwargs)

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.case.TestCase.assertRegex (   self,
  text,
  expected_regex,
  msg = None 
)
Fail the test unless the text matches the regular expression.

Definition at line 1141 of file case.py.

01141 
01142     def assertRegex(self, text, expected_regex, msg=None):
01143         """Fail the test unless the text matches the regular expression."""
01144         if isinstance(expected_regex, (str, bytes)):
01145             assert expected_regex, "expected_regex must not be empty."
01146             expected_regex = re.compile(expected_regex)
01147         if not expected_regex.search(text):
01148             msg = msg or "Regex didn't match"
01149             msg = '%s: %r not found in %r' % (msg, expected_regex.pattern, text)
01150             raise self.failureException(msg)

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.case.TestCase.assertSameElements (   self,
  expected_seq,
  actual_seq,
  msg = None 
)
An unordered sequence specific comparison.

Raises with an error message listing which elements of expected_seq
are missing from actual_seq and vice versa if any.

Duplicate elements are ignored when comparing *expected_seq* and
*actual_seq*. It is the equivalent of ``assertEqual(set(expected),
set(actual))`` but it works with sequences of unhashable objects as
well.

Definition at line 954 of file case.py.

00954 
00955     def assertSameElements(self, expected_seq, actual_seq, msg=None):
00956         """An unordered sequence specific comparison.
00957 
00958         Raises with an error message listing which elements of expected_seq
00959         are missing from actual_seq and vice versa if any.
00960 
00961         Duplicate elements are ignored when comparing *expected_seq* and
00962         *actual_seq*. It is the equivalent of ``assertEqual(set(expected),
00963         set(actual))`` but it works with sequences of unhashable objects as
00964         well.
00965         """
00966         warnings.warn('assertSameElements is deprecated',
00967                       DeprecationWarning)
00968         try:
00969             expected = set(expected_seq)
00970             actual = set(actual_seq)
00971             missing = sorted(expected.difference(actual))
00972             unexpected = sorted(actual.difference(expected))
00973         except TypeError:
00974             # Fall back to slower list-compare if any of the objects are
00975             # not hashable.
00976             expected = list(expected_seq)
00977             actual = list(actual_seq)
00978             try:
00979                 expected.sort()
00980                 actual.sort()
00981             except TypeError:
00982                 missing, unexpected = unorderable_list_difference(expected,
00983                                                                   actual)
00984             else:
00985                 missing, unexpected = sorted_list_difference(expected, actual)
00986         errors = []
00987         if missing:
00988             errors.append('Expected, but missing:\n    %s' %
00989                           safe_repr(missing))
00990         if unexpected:
00991             errors.append('Unexpected, but present:\n    %s' %
00992                           safe_repr(unexpected))
00993         if errors:
00994             standardMsg = '\n'.join(errors)
00995             self.fail(self._formatMessage(msg, standardMsg))
00996 

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.case.TestCase.assertSequenceEqual (   self,
  seq1,
  seq2,
  msg = None,
  seq_type = None 
)
An equality assertion for ordered sequences (like lists and tuples).

For the purposes of this function, a valid ordered sequence type is one
which can be indexed, has a length, and has an equality operator.

Args:
    seq1: The first sequence to compare.
    seq2: The second sequence to compare.
    seq_type: The expected datatype of the sequences, or None if no
    datatype should be enforced.
    msg: Optional message to use on failure instead of a list of
    differences.

Definition at line 711 of file case.py.

00711 
00712     def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
00713         """An equality assertion for ordered sequences (like lists and tuples).
00714 
00715         For the purposes of this function, a valid ordered sequence type is one
00716         which can be indexed, has a length, and has an equality operator.
00717 
00718         Args:
00719             seq1: The first sequence to compare.
00720             seq2: The second sequence to compare.
00721             seq_type: The expected datatype of the sequences, or None if no
00722                     datatype should be enforced.
00723             msg: Optional message to use on failure instead of a list of
00724                     differences.
00725         """
00726         if seq_type != None:
00727             seq_type_name = seq_type.__name__
00728             if not isinstance(seq1, seq_type):
00729                 raise self.failureException('First sequence is not a %s: %s'
00730                                         % (seq_type_name, safe_repr(seq1)))
00731             if not isinstance(seq2, seq_type):
00732                 raise self.failureException('Second sequence is not a %s: %s'
00733                                         % (seq_type_name, safe_repr(seq2)))
00734         else:
00735             seq_type_name = "sequence"
00736 
00737         differing = None
00738         try:
00739             len1 = len(seq1)
00740         except (TypeError, NotImplementedError):
00741             differing = 'First %s has no length.    Non-sequence?' % (
00742                     seq_type_name)
00743 
00744         if differing is None:
00745             try:
00746                 len2 = len(seq2)
00747             except (TypeError, NotImplementedError):
00748                 differing = 'Second %s has no length.    Non-sequence?' % (
00749                         seq_type_name)
00750 
00751         if differing is None:
00752             if seq1 == seq2:
00753                 return
00754 
00755             seq1_repr = safe_repr(seq1)
00756             seq2_repr = safe_repr(seq2)
00757             if len(seq1_repr) > 30:
00758                 seq1_repr = seq1_repr[:30] + '...'
00759             if len(seq2_repr) > 30:
00760                 seq2_repr = seq2_repr[:30] + '...'
00761             elements = (seq_type_name.capitalize(), seq1_repr, seq2_repr)
00762             differing = '%ss differ: %s != %s\n' % elements
00763 
00764             for i in range(min(len1, len2)):
00765                 try:
00766                     item1 = seq1[i]
00767                 except (TypeError, IndexError, NotImplementedError):
00768                     differing += ('\nUnable to index element %d of first %s\n' %
00769                                  (i, seq_type_name))
00770                     break
00771 
00772                 try:
00773                     item2 = seq2[i]
00774                 except (TypeError, IndexError, NotImplementedError):
00775                     differing += ('\nUnable to index element %d of second %s\n' %
00776                                  (i, seq_type_name))
00777                     break
00778 
00779                 if item1 != item2:
00780                     differing += ('\nFirst differing element %d:\n%s\n%s\n' %
00781                                  (i, item1, item2))
00782                     break
00783             else:
00784                 if (len1 == len2 and seq_type is None and
00785                     type(seq1) != type(seq2)):
00786                     # The sequences are the same, but have differing types.
00787                     return
00788 
00789             if len1 > len2:
00790                 differing += ('\nFirst %s contains %d additional '
00791                              'elements.\n' % (seq_type_name, len1 - len2))
00792                 try:
00793                     differing += ('First extra element %d:\n%s\n' %
00794                                   (len2, seq1[len2]))
00795                 except (TypeError, IndexError, NotImplementedError):
00796                     differing += ('Unable to index element %d '
00797                                   'of first %s\n' % (len2, seq_type_name))
00798             elif len1 < len2:
00799                 differing += ('\nSecond %s contains %d additional '
00800                              'elements.\n' % (seq_type_name, len2 - len1))
00801                 try:
00802                     differing += ('First extra element %d:\n%s\n' %
00803                                   (len1, seq2[len1]))
00804                 except (TypeError, IndexError, NotImplementedError):
00805                     differing += ('Unable to index element %d '
00806                                   'of second %s\n' % (len1, seq_type_name))
00807         standardMsg = differing
00808         diffMsg = '\n' + '\n'.join(
00809             difflib.ndiff(pprint.pformat(seq1).splitlines(),
00810                           pprint.pformat(seq2).splitlines()))
00811 
00812         standardMsg = self._truncateMessage(standardMsg, diffMsg)
00813         msg = self._formatMessage(msg, standardMsg)
00814         self.fail(msg)

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.case.TestCase.assertSetEqual (   self,
  set1,
  set2,
  msg = None 
)
A set-specific equality assertion.

Args:
    set1: The first set to compare.
    set2: The second set to compare.
    msg: Optional message to use on failure instead of a list of
    differences.

assertSetEqual uses ducktyping to support different types of sets, and
is optimized for sets specifically (parameters must support a
difference method).

Definition at line 844 of file case.py.

00844 
00845     def assertSetEqual(self, set1, set2, msg=None):
00846         """A set-specific equality assertion.
00847 
00848         Args:
00849             set1: The first set to compare.
00850             set2: The second set to compare.
00851             msg: Optional message to use on failure instead of a list of
00852                     differences.
00853 
00854         assertSetEqual uses ducktyping to support different types of sets, and
00855         is optimized for sets specifically (parameters must support a
00856         difference method).
00857         """
00858         try:
00859             difference1 = set1.difference(set2)
00860         except TypeError as e:
00861             self.fail('invalid type when attempting set difference: %s' % e)
00862         except AttributeError as e:
00863             self.fail('first argument does not support set difference: %s' % e)
00864 
00865         try:
00866             difference2 = set2.difference(set1)
00867         except TypeError as e:
00868             self.fail('invalid type when attempting set difference: %s' % e)
00869         except AttributeError as e:
00870             self.fail('second argument does not support set difference: %s' % e)
00871 
00872         if not (difference1 or difference2):
00873             return
00874 
00875         lines = []
00876         if difference1:
00877             lines.append('Items in the first set but not the second:')
00878             for item in difference1:
00879                 lines.append(repr(item))
00880         if difference2:
00881             lines.append('Items in the second set but not the first:')
00882             for item in difference2:
00883                 lines.append(repr(item))
00884 
00885         standardMsg = '\n'.join(lines)
00886         self.fail(self._formatMessage(msg, standardMsg))

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.case.TestCase.assertTrue (   self,
  expr,
  msg = None 
)
Check that the expression is true.

Definition at line 502 of file case.py.

00502 
00503     def assertTrue(self, expr, msg=None):
00504         """Check that the expression is true."""
00505         if not expr:
00506             msg = self._formatMessage(msg, "%s is not true" % safe_repr(expr))
00507             raise self.failureException(msg)

Here is the call graph for this function:

def unittest.case.TestCase.assertTupleEqual (   self,
  tuple1,
  tuple2,
  msg = None 
)
A tuple-specific equality assertion.

Args:
    tuple1: The first tuple to compare.
    tuple2: The second tuple to compare.
    msg: Optional message to use on failure instead of a list of
    differences.

Definition at line 833 of file case.py.

00833 
00834     def assertTupleEqual(self, tuple1, tuple2, msg=None):
00835         """A tuple-specific equality assertion.
00836 
00837         Args:
00838             tuple1: The first tuple to compare.
00839             tuple2: The second tuple to compare.
00840             msg: Optional message to use on failure instead of a list of
00841                     differences.
00842         """
00843         self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.case.TestCase.assertWarns (   self,
  expected_warning,
  callable_obj = None,
  args,
  kwargs 
)
Fail unless a warning of class warnClass is triggered
   by callableObj when invoked with arguments args and keyword
   arguments kwargs.  If a different type of warning is
   triggered, it will not be handled: depending on the other
   warning filtering rules in effect, it might be silenced, printed
   out, or raised as an exception.

   If called with callableObj omitted or None, will return a
   context object used like this::

with self.assertWarns(SomeWarning):
    do_something()

   The context manager keeps a reference to the first matching
   warning as the 'warning' attribute; similarly, the 'filename'
   and 'lineno' attributes give you information about the line
   of Python code from which the warning was triggered.
   This allows you to inspect the warning after the assertion::

       with self.assertWarns(SomeWarning) as cm:
   do_something()
       the_warning = cm.warning
       self.assertEqual(the_warning.some_attribute, 147)

Definition at line 559 of file case.py.

00559 
00560     def assertWarns(self, expected_warning, callable_obj=None, *args, **kwargs):
00561         """Fail unless a warning of class warnClass is triggered
00562            by callableObj when invoked with arguments args and keyword
00563            arguments kwargs.  If a different type of warning is
00564            triggered, it will not be handled: depending on the other
00565            warning filtering rules in effect, it might be silenced, printed
00566            out, or raised as an exception.
00567 
00568            If called with callableObj omitted or None, will return a
00569            context object used like this::
00570 
00571                 with self.assertWarns(SomeWarning):
00572                     do_something()
00573 
00574            The context manager keeps a reference to the first matching
00575            warning as the 'warning' attribute; similarly, the 'filename'
00576            and 'lineno' attributes give you information about the line
00577            of Python code from which the warning was triggered.
00578            This allows you to inspect the warning after the assertion::
00579 
00580                with self.assertWarns(SomeWarning) as cm:
00581                    do_something()
00582                the_warning = cm.warning
00583                self.assertEqual(the_warning.some_attribute, 147)
00584         """
00585         context = _AssertWarnsContext(expected_warning, self, callable_obj)
00586         if callable_obj is None:
00587             return context
00588         with context:
00589             callable_obj(*args, **kwargs)

Here is the caller graph for this function:

def unittest.case.TestCase.assertWarnsRegex (   self,
  expected_warning,
  expected_regex,
  callable_obj = None,
  args,
  kwargs 
)
Asserts that the message in a triggered warning matches a regexp.
Basic functioning is similar to assertWarns() with the addition
that only warnings whose messages also match the regular expression
are considered successful matches.

Args:
    expected_warning: Warning class expected to be triggered.
    expected_regex: Regex (re pattern object or string) expected
    to be found in error message.
    callable_obj: Function to be called.
    args: Extra args.
    kwargs: Extra kwargs.

Definition at line 1120 of file case.py.

01120 
01121                          callable_obj=None, *args, **kwargs):
01122         """Asserts that the message in a triggered warning matches a regexp.
01123         Basic functioning is similar to assertWarns() with the addition
01124         that only warnings whose messages also match the regular expression
01125         are considered successful matches.
01126 
01127         Args:
01128             expected_warning: Warning class expected to be triggered.
01129             expected_regex: Regex (re pattern object or string) expected
01130                     to be found in error message.
01131             callable_obj: Function to be called.
01132             args: Extra args.
01133             kwargs: Extra kwargs.
01134         """
01135         context = _AssertWarnsContext(expected_warning, self, callable_obj,
01136                                       expected_regex)
01137         if callable_obj is None:
01138             return context
01139         with context:
01140             callable_obj(*args, **kwargs)

Here is the caller graph for this function:

Definition at line 323 of file case.py.

00323 
00324     def countTestCases(self):
00325         return 1

Run the test without collecting errors in a TestResult

Definition at line 479 of file case.py.

00479 
00480     def debug(self):
00481         """Run the test without collecting errors in a TestResult"""
00482         self.setUp()
00483         getattr(self, self._testMethodName)()
00484         self.tearDown()
00485         while self._cleanups:
00486             function, args, kwargs = self._cleanups.pop(-1)
00487             function(*args, **kwargs)

Definition at line 326 of file case.py.

00326 
00327     def defaultTestResult(self):
00328         return result.TestResult()

Here is the caller graph for this function:

Execute all cleanup functions. Normally called for you after
tearDown.

Definition at line 463 of file case.py.

00463 
00464     def doCleanups(self):
00465         """Execute all cleanup functions. Normally called for you after
00466         tearDown."""
00467         outcome = self._outcomeForDoCleanups or _Outcome()
00468         while self._cleanups:
00469             function, args, kwargs = self._cleanups.pop()
00470             part = lambda: function(*args, **kwargs)
00471             self._executeTestPart(part, outcome)
00472 
00473         # return this for backwards compatibility
00474         # even though we no longer us it internally
00475         return outcome.success

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.case.TestCase.fail (   self,
  msg = None 
)
Fail immediately, with the given message.

Definition at line 492 of file case.py.

00492 
00493     def fail(self, msg=None):
00494         """Fail immediately, with the given message."""
00495         raise self.failureException(msg)

def unittest.case.TestCase.id (   self)

Reimplemented in unittest.case.FunctionTestCase.

Definition at line 340 of file case.py.

00340 
00341     def id(self):
00342         return "%s.%s" % (strclass(self.__class__), self._testMethodName)

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.case.TestCase.run (   self,
  result = None 
)

Definition at line 398 of file case.py.

00398 
00399     def run(self, result=None):
00400         orig_result = result
00401         if result is None:
00402             result = self.defaultTestResult()
00403             startTestRun = getattr(result, 'startTestRun', None)
00404             if startTestRun is not None:
00405                 startTestRun()
00406 
00407         result.startTest(self)
00408 
00409         testMethod = getattr(self, self._testMethodName)
00410         if (getattr(self.__class__, "__unittest_skip__", False) or
00411             getattr(testMethod, "__unittest_skip__", False)):
00412             # If the class or method was skipped.
00413             try:
00414                 skip_why = (getattr(self.__class__, '__unittest_skip_why__', '')
00415                             or getattr(testMethod, '__unittest_skip_why__', ''))
00416                 self._addSkip(result, skip_why)
00417             finally:
00418                 result.stopTest(self)
00419             return
00420         try:
00421             outcome = _Outcome()
00422             self._outcomeForDoCleanups = outcome
00423 
00424             self._executeTestPart(self.setUp, outcome)
00425             if outcome.success:
00426                 self._executeTestPart(testMethod, outcome, isTest=True)
00427                 self._executeTestPart(self.tearDown, outcome)
00428 
00429             self.doCleanups()
00430             if outcome.success:
00431                 result.addSuccess(self)
00432             else:
00433                 if outcome.skipped is not None:
00434                     self._addSkip(result, outcome.skipped)
00435                 for exc_info in outcome.errors:
00436                     result.addError(self, exc_info)
00437                 for exc_info in outcome.failures:
00438                     result.addFailure(self, exc_info)
00439                 if outcome.unexpectedSuccess is not None:
00440                     addUnexpectedSuccess = getattr(result, 'addUnexpectedSuccess', None)
00441                     if addUnexpectedSuccess is not None:
00442                         addUnexpectedSuccess(self)
00443                     else:
00444                         warnings.warn("TestResult has no addUnexpectedSuccess method, reporting as failures",
00445                                       RuntimeWarning)
00446                         result.addFailure(self, outcome.unexpectedSuccess)
00447 
00448                 if outcome.expectedFailure is not None:
00449                     addExpectedFailure = getattr(result, 'addExpectedFailure', None)
00450                     if addExpectedFailure is not None:
00451                         addExpectedFailure(self, outcome.expectedFailure)
00452                     else:
00453                         warnings.warn("TestResult has no addExpectedFailure method, reporting as passes",
00454                                       RuntimeWarning)
00455                         result.addSuccess(self)
00456 
00457         finally:
00458             result.stopTest(self)
00459             if orig_result is None:
00460                 stopTestRun = getattr(result, 'stopTestRun', None)
00461                 if stopTestRun is not None:
00462                     stopTestRun()

Here is the caller graph for this function:

Reimplemented in unittest.case.FunctionTestCase.

Definition at line 307 of file case.py.

00307 
00308     def setUp(self):
00309         "Hook method for setting up the test fixture before exercising it."
00310         pass

Here is the caller graph for this function:

Definition at line 316 of file case.py.

00316 
00317     def setUpClass(cls):
00318         "Hook method for setting up class fixture before running tests in the class."

Returns a one-line description of the test, or None if no
description has been provided.

The default implementation of this method returns the first line of
the specified test method's docstring.

Reimplemented in unittest.case.FunctionTestCase.

Definition at line 329 of file case.py.

00329 
00330     def shortDescription(self):
00331         """Returns a one-line description of the test, or None if no
00332         description has been provided.
00333 
00334         The default implementation of this method returns the first line of
00335         the specified test method's docstring.
00336         """
00337         doc = self._testMethodDoc
00338         return doc and doc.split("\n")[0].strip() or None
00339 

Here is the caller graph for this function:

def unittest.case.TestCase.skipTest (   self,
  reason 
)
Skip this test.

Definition at line 488 of file case.py.

00488 
00489     def skipTest(self, reason):
00490         """Skip this test."""
00491         raise SkipTest(reason)

Reimplemented in unittest.case.FunctionTestCase.

Definition at line 311 of file case.py.

00311 
00312     def tearDown(self):
00313         "Hook method for deconstructing the test fixture after testing it."
00314         pass

Here is the caller graph for this function:

Definition at line 320 of file case.py.

00320 
00321     def tearDownClass(cls):
00322         "Hook method for deconstructing the class fixture after running all tests in the class."


Member Data Documentation

unittest.case.TestCase._classSetupFailed = False [static, private]

Definition at line 251 of file case.py.

Definition at line 271 of file case.py.

Definition at line 247 of file case.py.

Definition at line 259 of file case.py.

Definition at line 260 of file case.py.

Definition at line 258 of file case.py.

Definition at line 276 of file case.py.

Definition at line 1181 of file case.py.

Definition at line 1182 of file case.py.

Definition at line 1180 of file case.py.

tuple unittest.case.TestCase.failIfAlmostEqual = assertNotAlmostEquals_deprecate(assertNotAlmostEqual) [static]

Definition at line 1177 of file case.py.

tuple unittest.case.TestCase.failIfEqual = assertNotEquals_deprecate(assertNotEqual) [static]

Definition at line 1175 of file case.py.

tuple unittest.case.TestCase.failUnless = assert__deprecate(assertTrue) [static]

Definition at line 1178 of file case.py.

tuple unittest.case.TestCase.failUnlessAlmostEqual = assertAlmostEquals_deprecate(assertAlmostEqual) [static]

Definition at line 1176 of file case.py.

tuple unittest.case.TestCase.failUnlessEqual = assertEquals_deprecate(assertEqual) [static]

Definition at line 1174 of file case.py.

Definition at line 1179 of file case.py.

unittest.case.TestCase.failureException = AssertionError [static]

Definition at line 231 of file case.py.

Definition at line 237 of file case.py.

Definition at line 243 of file case.py.

Definition at line 107 of file object.h.

struct _typeobject* _object::ob_type [inherited]

Definition at line 108 of file object.h.


The documentation for this class was generated from the following file: