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