blob: dbf7aa2e40edcf685712f6bca4fcef9d83708356 [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
9
Benjamin Peterson847a4112010-03-14 15:04:17 +000010from . import result
11from .util import (strclass, safe_repr, sorted_list_difference,
12 unorderable_list_difference)
Benjamin Petersonbed7d042009-07-19 21:01:52 +000013
Benjamin Petersondccc1fc2010-03-22 00:15:53 +000014__unittest = True
Benjamin Petersonbed7d042009-07-19 21:01:52 +000015
Michael Foord9dad32e2010-06-05 13:49:56 +000016
17DIFF_OMITTED = ('\nDiff is %s characters long. '
18 'Set self.maxDiff to None to see it.')
19
Benjamin Petersonbed7d042009-07-19 21:01:52 +000020class SkipTest(Exception):
21 """
22 Raise this exception in a test to skip it.
23
24 Usually you can use TestResult.skip() or one of the skipping decorators
25 instead of raising this directly.
26 """
27 pass
28
29class _ExpectedFailure(Exception):
30 """
31 Raise this when a test is expected to fail.
32
33 This is an implementation detail.
34 """
35
36 def __init__(self, exc_info):
37 super(_ExpectedFailure, self).__init__()
38 self.exc_info = exc_info
39
40class _UnexpectedSuccess(Exception):
41 """
42 The test was supposed to fail, but it didn't!
43 """
44 pass
45
46def _id(obj):
47 return obj
48
49def skip(reason):
50 """
51 Unconditionally skip a test.
52 """
53 def decorator(test_item):
Benjamin Peterson847a4112010-03-14 15:04:17 +000054 if not (isinstance(test_item, type) and issubclass(test_item, TestCase)):
55 @functools.wraps(test_item)
56 def skip_wrapper(*args, **kwargs):
57 raise SkipTest(reason)
58 test_item = skip_wrapper
59
60 test_item.__unittest_skip__ = True
61 test_item.__unittest_skip_why__ = reason
62 return test_item
Benjamin Petersonbed7d042009-07-19 21:01:52 +000063 return decorator
64
65def skipIf(condition, reason):
66 """
67 Skip a test if the condition is true.
68 """
69 if condition:
70 return skip(reason)
71 return _id
72
73def skipUnless(condition, reason):
74 """
75 Skip a test unless the condition is true.
76 """
77 if not condition:
78 return skip(reason)
79 return _id
80
81
82def expectedFailure(func):
83 @functools.wraps(func)
84 def wrapper(*args, **kwargs):
85 try:
86 func(*args, **kwargs)
87 except Exception:
88 raise _ExpectedFailure(sys.exc_info())
89 raise _UnexpectedSuccess
90 return wrapper
91
92
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +000093class _AssertRaisesBaseContext(object):
Benjamin Petersonbed7d042009-07-19 21:01:52 +000094
95 def __init__(self, expected, test_case, callable_obj=None,
96 expected_regexp=None):
97 self.expected = expected
98 self.failureException = test_case.failureException
99 if callable_obj is not None:
100 try:
101 self.obj_name = callable_obj.__name__
102 except AttributeError:
103 self.obj_name = str(callable_obj)
104 else:
105 self.obj_name = None
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000106 if isinstance(expected_regexp, (bytes, str)):
107 expected_regexp = re.compile(expected_regexp)
Georg Brandl89fad142010-03-14 10:23:39 +0000108 self.expected_regexp = expected_regexp
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000109
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000110
111class _AssertRaisesContext(_AssertRaisesBaseContext):
112 """A context manager used to implement TestCase.assertRaises* methods."""
113
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000114 def __enter__(self):
Ezio Melotti49008232010-02-08 21:57:48 +0000115 return self
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000116
117 def __exit__(self, exc_type, exc_value, tb):
118 if exc_type is None:
119 try:
120 exc_name = self.expected.__name__
121 except AttributeError:
122 exc_name = str(self.expected)
123 if self.obj_name:
124 raise self.failureException("{0} not raised by {1}"
125 .format(exc_name, self.obj_name))
126 else:
127 raise self.failureException("{0} not raised"
128 .format(exc_name))
129 if not issubclass(exc_type, self.expected):
130 # let unexpected exceptions pass through
131 return False
Ezio Melotti49008232010-02-08 21:57:48 +0000132 # store exception, without traceback, for later retrieval
133 self.exception = exc_value.with_traceback(None)
Georg Brandl89fad142010-03-14 10:23:39 +0000134 if self.expected_regexp is None:
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000135 return True
136
Georg Brandl89fad142010-03-14 10:23:39 +0000137 expected_regexp = self.expected_regexp
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000138 if not expected_regexp.search(str(exc_value)):
139 raise self.failureException('"%s" does not match "%s"' %
140 (expected_regexp.pattern, str(exc_value)))
141 return True
142
143
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000144class _AssertWarnsContext(_AssertRaisesBaseContext):
145 """A context manager used to implement TestCase.assertWarns* methods."""
146
147 def __enter__(self):
148 # The __warningregistry__'s need to be in a pristine state for tests
149 # to work properly.
150 for v in sys.modules.values():
151 if getattr(v, '__warningregistry__', None):
152 v.__warningregistry__ = {}
153 self.warnings_manager = warnings.catch_warnings(record=True)
154 self.warnings = self.warnings_manager.__enter__()
155 warnings.simplefilter("always", self.expected)
156 return self
157
158 def __exit__(self, exc_type, exc_value, tb):
159 self.warnings_manager.__exit__(exc_type, exc_value, tb)
160 if exc_type is not None:
161 # let unexpected exceptions pass through
162 return
163 try:
164 exc_name = self.expected.__name__
165 except AttributeError:
166 exc_name = str(self.expected)
167 first_matching = None
168 for m in self.warnings:
169 w = m.message
170 if not isinstance(w, self.expected):
171 continue
172 if first_matching is None:
173 first_matching = w
174 if (self.expected_regexp is not None and
175 not self.expected_regexp.search(str(w))):
176 continue
177 # store warning for later retrieval
178 self.warning = w
179 self.filename = m.filename
180 self.lineno = m.lineno
181 return
182 # Now we simply try to choose a helpful failure message
183 if first_matching is not None:
184 raise self.failureException('"%s" does not match "%s"' %
185 (self.expected_regexp.pattern, str(first_matching)))
186 if self.obj_name:
187 raise self.failureException("{0} not triggered by {1}"
188 .format(exc_name, self.obj_name))
189 else:
190 raise self.failureException("{0} not triggered"
191 .format(exc_name))
192
193
Michael Foord8ca6d982010-11-20 15:34:26 +0000194class _TypeEqualityDict(object):
195
196 def __init__(self, testcase):
197 self.testcase = testcase
198 self._store = {}
199
200 def __setitem__(self, key, value):
201 self._store[key] = value
202
203 def __getitem__(self, key):
204 value = self._store[key]
205 if isinstance(value, str):
206 return getattr(self.testcase, value)
207 return value
208
209 def get(self, key, default=None):
210 if key in self._store:
211 return self[key]
212 return default
213
214
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000215class TestCase(object):
216 """A class whose instances are single test cases.
217
218 By default, the test code itself should be placed in a method named
219 'runTest'.
220
221 If the fixture may be used for many test cases, create as
222 many test methods as are needed. When instantiating such a TestCase
223 subclass, specify in the constructor arguments the name of the test method
224 that the instance is to execute.
225
226 Test authors should subclass TestCase for their own tests. Construction
227 and deconstruction of the test's environment ('fixture') can be
228 implemented by overriding the 'setUp' and 'tearDown' methods respectively.
229
230 If it is necessary to override the __init__ method, the base class
231 __init__ method must always be called. It is important that subclasses
232 should not change the signature of their __init__ method, since instances
233 of the classes are instantiated automatically by parts of the framework
234 in order to be run.
235 """
236
237 # This attribute determines which exception will be raised when
238 # the instance's assertion methods fail; test methods raising this
239 # exception will be deemed to have 'failed' rather than 'errored'
240
241 failureException = AssertionError
242
243 # This attribute determines whether long messages (including repr of
244 # objects used in assert methods) will be printed on failure in *addition*
245 # to any explicit message passed.
246
247 longMessage = False
248
Michael Foordc41d1412010-06-10 16:17:07 +0000249 # This attribute sets the maximum length of a diff in failure messages
Michael Foord085dfd32010-06-05 12:17:02 +0000250 # by assert methods using difflib. It is looked up as an instance attribute
251 # so can be configured by individual tests if required.
Michael Foordd50a6b92010-06-05 23:59:34 +0000252
Michael Foord085dfd32010-06-05 12:17:02 +0000253 maxDiff = 80*8
254
Benjamin Peterson847a4112010-03-14 15:04:17 +0000255 # Attribute used by TestSuite for classSetUp
256
257 _classSetupFailed = False
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000258
259 def __init__(self, methodName='runTest'):
260 """Create an instance of the class that will use the named test
261 method when executed. Raises a ValueError if the instance does
262 not have a method with the specified name.
263 """
264 self._testMethodName = methodName
265 self._resultForDoCleanups = None
266 try:
267 testMethod = getattr(self, methodName)
268 except AttributeError:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000269 raise ValueError("no such test method in %s: %s" %
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000270 (self.__class__, methodName))
271 self._testMethodDoc = testMethod.__doc__
272 self._cleanups = []
273
274 # Map types to custom assertEqual functions that will compare
275 # instances of said type in more detail to generate a more useful
276 # error message.
Michael Foord8ca6d982010-11-20 15:34:26 +0000277 self._type_equality_funcs = _TypeEqualityDict(self)
278 self.addTypeEqualityFunc(dict, 'assertDictEqual')
279 self.addTypeEqualityFunc(list, 'assertListEqual')
280 self.addTypeEqualityFunc(tuple, 'assertTupleEqual')
281 self.addTypeEqualityFunc(set, 'assertSetEqual')
282 self.addTypeEqualityFunc(frozenset, 'assertSetEqual')
283 self.addTypeEqualityFunc(str, 'assertMultiLineEqual')
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000284
285 def addTypeEqualityFunc(self, typeobj, function):
286 """Add a type specific assertEqual style function to compare a type.
287
288 This method is for use by TestCase subclasses that need to register
289 their own type equality functions to provide nicer error messages.
290
291 Args:
292 typeobj: The data type to call this function on when both values
293 are of the same type in assertEqual().
294 function: The callable taking two arguments and an optional
295 msg= argument that raises self.failureException with a
296 useful error message when the two arguments are not equal.
297 """
Benjamin Peterson8f326b22009-12-13 02:10:36 +0000298 self._type_equality_funcs[typeobj] = function
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000299
300 def addCleanup(self, function, *args, **kwargs):
301 """Add a function, with arguments, to be called when the test is
302 completed. Functions added are called on a LIFO basis and are
303 called after tearDown on test failure or success.
304
305 Cleanup items are called even if setUp fails (unlike tearDown)."""
306 self._cleanups.append((function, args, kwargs))
307
308 def setUp(self):
309 "Hook method for setting up the test fixture before exercising it."
310 pass
311
312 def tearDown(self):
313 "Hook method for deconstructing the test fixture after testing it."
314 pass
315
Benjamin Peterson847a4112010-03-14 15:04:17 +0000316 @classmethod
317 def setUpClass(cls):
318 "Hook method for setting up class fixture before running tests in the class."
319
320 @classmethod
321 def tearDownClass(cls):
322 "Hook method for deconstructing the class fixture after running all tests in the class."
323
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000324 def countTestCases(self):
325 return 1
326
327 def defaultTestResult(self):
328 return result.TestResult()
329
330 def shortDescription(self):
Michael Foord34c94622010-02-10 15:51:42 +0000331 """Returns a one-line description of the test, or None if no
332 description has been provided.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000333
Michael Foord34c94622010-02-10 15:51:42 +0000334 The default implementation of this method returns the first line of
335 the specified test method's docstring.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000336 """
Michael Foord34c94622010-02-10 15:51:42 +0000337 doc = self._testMethodDoc
338 return doc and doc.split("\n")[0].strip() or None
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000339
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000340
341 def id(self):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000342 return "%s.%s" % (strclass(self.__class__), self._testMethodName)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000343
344 def __eq__(self, other):
345 if type(self) is not type(other):
346 return NotImplemented
347
348 return self._testMethodName == other._testMethodName
349
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000350 def __hash__(self):
351 return hash((type(self), self._testMethodName))
352
353 def __str__(self):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000354 return "%s (%s)" % (self._testMethodName, strclass(self.__class__))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000355
356 def __repr__(self):
357 return "<%s testMethod=%s>" % \
Benjamin Peterson847a4112010-03-14 15:04:17 +0000358 (strclass(self.__class__), self._testMethodName)
359
360 def _addSkip(self, result, reason):
361 addSkip = getattr(result, 'addSkip', None)
362 if addSkip is not None:
363 addSkip(self, reason)
364 else:
365 warnings.warn("TestResult has no addSkip method, skips not reported",
366 RuntimeWarning, 2)
367 result.addSuccess(self)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000368
369 def run(self, result=None):
370 orig_result = result
371 if result is None:
372 result = self.defaultTestResult()
373 startTestRun = getattr(result, 'startTestRun', None)
374 if startTestRun is not None:
375 startTestRun()
376
377 self._resultForDoCleanups = result
378 result.startTest(self)
Benjamin Peterson847a4112010-03-14 15:04:17 +0000379
380 testMethod = getattr(self, self._testMethodName)
381 if (getattr(self.__class__, "__unittest_skip__", False) or
382 getattr(testMethod, "__unittest_skip__", False)):
383 # If the class or method was skipped.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000384 try:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000385 skip_why = (getattr(self.__class__, '__unittest_skip_why__', '')
386 or getattr(testMethod, '__unittest_skip_why__', ''))
387 self._addSkip(result, skip_why)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000388 finally:
389 result.stopTest(self)
390 return
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000391 try:
392 success = False
393 try:
394 self.setUp()
395 except SkipTest as e:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000396 self._addSkip(result, str(e))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000397 except Exception:
398 result.addError(self, sys.exc_info())
399 else:
400 try:
401 testMethod()
402 except self.failureException:
403 result.addFailure(self, sys.exc_info())
404 except _ExpectedFailure as e:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000405 addExpectedFailure = getattr(result, 'addExpectedFailure', None)
406 if addExpectedFailure is not None:
407 addExpectedFailure(self, e.exc_info)
408 else:
409 warnings.warn("TestResult has no addExpectedFailure method, reporting as passes",
410 RuntimeWarning)
411 result.addSuccess(self)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000412 except _UnexpectedSuccess:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000413 addUnexpectedSuccess = getattr(result, 'addUnexpectedSuccess', None)
414 if addUnexpectedSuccess is not None:
415 addUnexpectedSuccess(self)
416 else:
417 warnings.warn("TestResult has no addUnexpectedSuccess method, reporting as failures",
418 RuntimeWarning)
419 result.addFailure(self, sys.exc_info())
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000420 except SkipTest as e:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000421 self._addSkip(result, str(e))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000422 except Exception:
423 result.addError(self, sys.exc_info())
424 else:
425 success = True
426
427 try:
428 self.tearDown()
429 except Exception:
430 result.addError(self, sys.exc_info())
431 success = False
432
433 cleanUpSuccess = self.doCleanups()
434 success = success and cleanUpSuccess
435 if success:
436 result.addSuccess(self)
437 finally:
438 result.stopTest(self)
439 if orig_result is None:
440 stopTestRun = getattr(result, 'stopTestRun', None)
441 if stopTestRun is not None:
442 stopTestRun()
443
444 def doCleanups(self):
445 """Execute all cleanup functions. Normally called for you after
446 tearDown."""
447 result = self._resultForDoCleanups
448 ok = True
449 while self._cleanups:
450 function, args, kwargs = self._cleanups.pop(-1)
451 try:
452 function(*args, **kwargs)
453 except Exception:
454 ok = False
455 result.addError(self, sys.exc_info())
456 return ok
457
458 def __call__(self, *args, **kwds):
459 return self.run(*args, **kwds)
460
461 def debug(self):
462 """Run the test without collecting errors in a TestResult"""
463 self.setUp()
464 getattr(self, self._testMethodName)()
465 self.tearDown()
Michael Foordb8748742010-06-10 16:16:08 +0000466 while self._cleanups:
467 function, args, kwargs = self._cleanups.pop(-1)
468 function(*args, **kwargs)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000469
470 def skipTest(self, reason):
471 """Skip this test."""
472 raise SkipTest(reason)
473
474 def fail(self, msg=None):
475 """Fail immediately, with the given message."""
476 raise self.failureException(msg)
477
478 def assertFalse(self, expr, msg=None):
479 "Fail the test if the expression is true."
480 if expr:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000481 msg = self._formatMessage(msg, "%s is not False" % safe_repr(expr))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000482 raise self.failureException(msg)
483
484 def assertTrue(self, expr, msg=None):
485 """Fail the test unless the expression is true."""
486 if not expr:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000487 msg = self._formatMessage(msg, "%s is not True" % safe_repr(expr))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000488 raise self.failureException(msg)
489
490 def _formatMessage(self, msg, standardMsg):
491 """Honour the longMessage attribute when generating failure messages.
492 If longMessage is False this means:
493 * Use only an explicit message if it is provided
494 * Otherwise use the standard message for the assert
495
496 If longMessage is True:
497 * Use the standard message
498 * If an explicit message is provided, plus ' : ' and the explicit message
499 """
500 if not self.longMessage:
501 return msg or standardMsg
502 if msg is None:
503 return standardMsg
Benjamin Peterson847a4112010-03-14 15:04:17 +0000504 try:
505 # don't switch to '{}' formatting in Python 2.X
506 # it changes the way unicode input is handled
507 return '%s : %s' % (standardMsg, msg)
508 except UnicodeDecodeError:
509 return '%s : %s' % (safe_repr(standardMsg), safe_repr(msg))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000510
511
512 def assertRaises(self, excClass, callableObj=None, *args, **kwargs):
513 """Fail unless an exception of class excClass is thrown
514 by callableObj when invoked with arguments args and keyword
515 arguments kwargs. If a different type of exception is
516 thrown, it will not be caught, and the test case will be
517 deemed to have suffered an error, exactly as for an
518 unexpected exception.
519
520 If called with callableObj omitted or None, will return a
521 context object used like this::
522
Michael Foord1c42b122010-02-05 22:58:21 +0000523 with self.assertRaises(SomeException):
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000524 do_something()
Michael Foord1c42b122010-02-05 22:58:21 +0000525
526 The context manager keeps a reference to the exception as
Ezio Melotti49008232010-02-08 21:57:48 +0000527 the 'exception' attribute. This allows you to inspect the
Michael Foord1c42b122010-02-05 22:58:21 +0000528 exception after the assertion::
529
530 with self.assertRaises(SomeException) as cm:
531 do_something()
Ezio Melotti49008232010-02-08 21:57:48 +0000532 the_exception = cm.exception
Michael Foordb57ac6d2010-02-05 23:26:29 +0000533 self.assertEqual(the_exception.error_code, 3)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000534 """
535 context = _AssertRaisesContext(excClass, self, callableObj)
536 if callableObj is None:
537 return context
538 with context:
539 callableObj(*args, **kwargs)
540
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000541 def assertWarns(self, expected_warning, callable_obj=None, *args, **kwargs):
542 """Fail unless a warning of class warnClass is triggered
543 by callableObj when invoked with arguments args and keyword
544 arguments kwargs. If a different type of warning is
545 triggered, it will not be handled: depending on the other
546 warning filtering rules in effect, it might be silenced, printed
547 out, or raised as an exception.
548
549 If called with callableObj omitted or None, will return a
550 context object used like this::
551
552 with self.assertWarns(SomeWarning):
553 do_something()
554
555 The context manager keeps a reference to the first matching
556 warning as the 'warning' attribute; similarly, the 'filename'
557 and 'lineno' attributes give you information about the line
558 of Python code from which the warning was triggered.
559 This allows you to inspect the warning after the assertion::
560
561 with self.assertWarns(SomeWarning) as cm:
562 do_something()
563 the_warning = cm.warning
564 self.assertEqual(the_warning.some_attribute, 147)
565 """
566 context = _AssertWarnsContext(expected_warning, self, callable_obj)
567 if callable_obj is None:
568 return context
569 with context:
570 callable_obj(*args, **kwargs)
571
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000572 def _getAssertEqualityFunc(self, first, second):
573 """Get a detailed comparison function for the types of the two args.
574
575 Returns: A callable accepting (first, second, msg=None) that will
576 raise a failure exception if first != second with a useful human
577 readable error message for those types.
578 """
579 #
580 # NOTE(gregory.p.smith): I considered isinstance(first, type(second))
581 # and vice versa. I opted for the conservative approach in case
582 # subclasses are not intended to be compared in detail to their super
583 # class instances using a type equality func. This means testing
584 # subtypes won't automagically use the detailed comparison. Callers
585 # should use their type specific assertSpamEqual method to compare
586 # subclasses if the detailed comparison is desired and appropriate.
587 # See the discussion in http://bugs.python.org/issue2578.
588 #
589 if type(first) is type(second):
590 asserter = self._type_equality_funcs.get(type(first))
591 if asserter is not None:
Benjamin Peterson8f326b22009-12-13 02:10:36 +0000592 return asserter
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000593
594 return self._baseAssertEqual
595
596 def _baseAssertEqual(self, first, second, msg=None):
597 """The default assertEqual implementation, not type specific."""
598 if not first == second:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000599 standardMsg = '%s != %s' % (safe_repr(first), safe_repr(second))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000600 msg = self._formatMessage(msg, standardMsg)
601 raise self.failureException(msg)
602
603 def assertEqual(self, first, second, msg=None):
604 """Fail if the two objects are unequal as determined by the '=='
605 operator.
606 """
607 assertion_func = self._getAssertEqualityFunc(first, second)
608 assertion_func(first, second, msg=msg)
609
610 def assertNotEqual(self, first, second, msg=None):
611 """Fail if the two objects are equal as determined by the '=='
612 operator.
613 """
614 if not first != second:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000615 msg = self._formatMessage(msg, '%s == %s' % (safe_repr(first),
616 safe_repr(second)))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000617 raise self.failureException(msg)
618
Michael Foord321d0592010-11-02 13:44:51 +0000619 def assertAlmostEqual(self, first, second, places=None, msg=None,
Benjamin Petersonb48af542010-04-11 20:43:16 +0000620 delta=None):
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000621 """Fail if the two objects are unequal as determined by their
622 difference rounded to the given number of decimal places
Benjamin Petersonb48af542010-04-11 20:43:16 +0000623 (default 7) and comparing to zero, or by comparing that the
624 between the two objects is more than the given delta.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000625
626 Note that decimal places (from zero) are usually not the same
627 as significant digits (measured from the most signficant digit).
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000628
629 If the two objects compare equal then they will automatically
630 compare almost equal.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000631 """
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000632 if first == second:
Benjamin Petersonb48af542010-04-11 20:43:16 +0000633 # shortcut
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000634 return
Benjamin Petersonb48af542010-04-11 20:43:16 +0000635 if delta is not None and places is not None:
636 raise TypeError("specify delta or places not both")
637
638 if delta is not None:
639 if abs(first - second) <= delta:
640 return
641
642 standardMsg = '%s != %s within %s delta' % (safe_repr(first),
643 safe_repr(second),
644 safe_repr(delta))
645 else:
646 if places is None:
647 places = 7
648
649 if round(abs(second-first), places) == 0:
650 return
651
Benjamin Peterson847a4112010-03-14 15:04:17 +0000652 standardMsg = '%s != %s within %r places' % (safe_repr(first),
653 safe_repr(second),
654 places)
Benjamin Petersonb48af542010-04-11 20:43:16 +0000655 msg = self._formatMessage(msg, standardMsg)
656 raise self.failureException(msg)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000657
Michael Foord321d0592010-11-02 13:44:51 +0000658 def assertNotAlmostEqual(self, first, second, places=None, msg=None,
Benjamin Petersonb48af542010-04-11 20:43:16 +0000659 delta=None):
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000660 """Fail if the two objects are equal as determined by their
661 difference rounded to the given number of decimal places
Benjamin Petersonb48af542010-04-11 20:43:16 +0000662 (default 7) and comparing to zero, or by comparing that the
663 between the two objects is less than the given delta.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000664
665 Note that decimal places (from zero) are usually not the same
666 as significant digits (measured from the most signficant digit).
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000667
668 Objects that are equal automatically fail.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000669 """
Benjamin Petersonb48af542010-04-11 20:43:16 +0000670 if delta is not None and places is not None:
671 raise TypeError("specify delta or places not both")
672 if delta is not None:
673 if not (first == second) and abs(first - second) > delta:
674 return
675 standardMsg = '%s == %s within %s delta' % (safe_repr(first),
676 safe_repr(second),
677 safe_repr(delta))
678 else:
679 if places is None:
680 places = 7
681 if not (first == second) and round(abs(second-first), places) != 0:
682 return
Benjamin Peterson847a4112010-03-14 15:04:17 +0000683 standardMsg = '%s == %s within %r places' % (safe_repr(first),
Benjamin Petersonb48af542010-04-11 20:43:16 +0000684 safe_repr(second),
685 places)
686
687 msg = self._formatMessage(msg, standardMsg)
688 raise self.failureException(msg)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000689
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000690
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000691 def _deprecate(original_func):
692 def deprecated_func(*args, **kwargs):
693 warnings.warn(
694 'Please use {0} instead.'.format(original_func.__name__),
695 DeprecationWarning, 2)
696 return original_func(*args, **kwargs)
697 return deprecated_func
698
Ezio Melotti2baf1a62010-11-22 12:56:58 +0000699 # The fail* methods can be removed in 3.3, the 5 assert* methods will
700 # have to stay around for a few more versions. See #9424.
701 failUnlessEqual = assertEquals = _deprecate(assertEqual)
702 failIfEqual = assertNotEquals = _deprecate(assertNotEqual)
703 failUnlessAlmostEqual = assertAlmostEquals = _deprecate(assertAlmostEqual)
704 failIfAlmostEqual = assertNotAlmostEquals = _deprecate(assertNotAlmostEqual)
705 failUnless = assert_ = _deprecate(assertTrue)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000706 failUnlessRaises = _deprecate(assertRaises)
707 failIf = _deprecate(assertFalse)
708
Michael Foord085dfd32010-06-05 12:17:02 +0000709 def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000710 """An equality assertion for ordered sequences (like lists and tuples).
711
R. David Murrayad13f222010-01-29 22:17:58 +0000712 For the purposes of this function, a valid ordered sequence type is one
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000713 which can be indexed, has a length, and has an equality operator.
714
715 Args:
716 seq1: The first sequence to compare.
717 seq2: The second sequence to compare.
718 seq_type: The expected datatype of the sequences, or None if no
719 datatype should be enforced.
720 msg: Optional message to use on failure instead of a list of
721 differences.
722 """
723 if seq_type != None:
724 seq_type_name = seq_type.__name__
725 if not isinstance(seq1, seq_type):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000726 raise self.failureException('First sequence is not a %s: %s'
727 % (seq_type_name, safe_repr(seq1)))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000728 if not isinstance(seq2, seq_type):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000729 raise self.failureException('Second sequence is not a %s: %s'
730 % (seq_type_name, safe_repr(seq2)))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000731 else:
732 seq_type_name = "sequence"
733
734 differing = None
735 try:
736 len1 = len(seq1)
737 except (TypeError, NotImplementedError):
738 differing = 'First %s has no length. Non-sequence?' % (
739 seq_type_name)
740
741 if differing is None:
742 try:
743 len2 = len(seq2)
744 except (TypeError, NotImplementedError):
745 differing = 'Second %s has no length. Non-sequence?' % (
746 seq_type_name)
747
748 if differing is None:
749 if seq1 == seq2:
750 return
751
Benjamin Peterson847a4112010-03-14 15:04:17 +0000752 seq1_repr = safe_repr(seq1)
753 seq2_repr = safe_repr(seq2)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000754 if len(seq1_repr) > 30:
755 seq1_repr = seq1_repr[:30] + '...'
756 if len(seq2_repr) > 30:
757 seq2_repr = seq2_repr[:30] + '...'
758 elements = (seq_type_name.capitalize(), seq1_repr, seq2_repr)
759 differing = '%ss differ: %s != %s\n' % elements
760
761 for i in range(min(len1, len2)):
762 try:
763 item1 = seq1[i]
764 except (TypeError, IndexError, NotImplementedError):
765 differing += ('\nUnable to index element %d of first %s\n' %
766 (i, seq_type_name))
767 break
768
769 try:
770 item2 = seq2[i]
771 except (TypeError, IndexError, NotImplementedError):
772 differing += ('\nUnable to index element %d of second %s\n' %
773 (i, seq_type_name))
774 break
775
776 if item1 != item2:
777 differing += ('\nFirst differing element %d:\n%s\n%s\n' %
778 (i, item1, item2))
779 break
780 else:
781 if (len1 == len2 and seq_type is None and
782 type(seq1) != type(seq2)):
783 # The sequences are the same, but have differing types.
784 return
785
786 if len1 > len2:
787 differing += ('\nFirst %s contains %d additional '
788 'elements.\n' % (seq_type_name, len1 - len2))
789 try:
790 differing += ('First extra element %d:\n%s\n' %
791 (len2, seq1[len2]))
792 except (TypeError, IndexError, NotImplementedError):
793 differing += ('Unable to index element %d '
794 'of first %s\n' % (len2, seq_type_name))
795 elif len1 < len2:
796 differing += ('\nSecond %s contains %d additional '
797 'elements.\n' % (seq_type_name, len2 - len1))
798 try:
799 differing += ('First extra element %d:\n%s\n' %
800 (len1, seq2[len1]))
801 except (TypeError, IndexError, NotImplementedError):
802 differing += ('Unable to index element %d '
803 'of second %s\n' % (len1, seq_type_name))
Michael Foord2034d9a2010-06-05 11:27:52 +0000804 standardMsg = differing
805 diffMsg = '\n' + '\n'.join(
Benjamin Peterson6e8c7572009-10-04 20:19:21 +0000806 difflib.ndiff(pprint.pformat(seq1).splitlines(),
807 pprint.pformat(seq2).splitlines()))
Michael Foord085dfd32010-06-05 12:17:02 +0000808
809 standardMsg = self._truncateMessage(standardMsg, diffMsg)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000810 msg = self._formatMessage(msg, standardMsg)
811 self.fail(msg)
812
Michael Foord085dfd32010-06-05 12:17:02 +0000813 def _truncateMessage(self, message, diff):
814 max_diff = self.maxDiff
815 if max_diff is None or len(diff) <= max_diff:
816 return message + diff
Michael Foord9dad32e2010-06-05 13:49:56 +0000817 return message + (DIFF_OMITTED % len(diff))
Michael Foord085dfd32010-06-05 12:17:02 +0000818
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000819 def assertListEqual(self, list1, list2, msg=None):
820 """A list-specific equality assertion.
821
822 Args:
823 list1: The first list to compare.
824 list2: The second list to compare.
825 msg: Optional message to use on failure instead of a list of
826 differences.
827
828 """
829 self.assertSequenceEqual(list1, list2, msg, seq_type=list)
830
831 def assertTupleEqual(self, tuple1, tuple2, msg=None):
832 """A tuple-specific equality assertion.
833
834 Args:
835 tuple1: The first tuple to compare.
836 tuple2: The second tuple to compare.
837 msg: Optional message to use on failure instead of a list of
838 differences.
839 """
840 self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
841
842 def assertSetEqual(self, set1, set2, msg=None):
843 """A set-specific equality assertion.
844
845 Args:
846 set1: The first set to compare.
847 set2: The second set to compare.
848 msg: Optional message to use on failure instead of a list of
849 differences.
850
Michael Foord91c9da32010-03-20 17:21:27 +0000851 assertSetEqual uses ducktyping to support different types of sets, and
852 is optimized for sets specifically (parameters must support a
853 difference method).
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000854 """
855 try:
856 difference1 = set1.difference(set2)
857 except TypeError as e:
858 self.fail('invalid type when attempting set difference: %s' % e)
859 except AttributeError as e:
860 self.fail('first argument does not support set difference: %s' % e)
861
862 try:
863 difference2 = set2.difference(set1)
864 except TypeError as e:
865 self.fail('invalid type when attempting set difference: %s' % e)
866 except AttributeError as e:
867 self.fail('second argument does not support set difference: %s' % e)
868
869 if not (difference1 or difference2):
870 return
871
872 lines = []
873 if difference1:
874 lines.append('Items in the first set but not the second:')
875 for item in difference1:
876 lines.append(repr(item))
877 if difference2:
878 lines.append('Items in the second set but not the first:')
879 for item in difference2:
880 lines.append(repr(item))
881
882 standardMsg = '\n'.join(lines)
883 self.fail(self._formatMessage(msg, standardMsg))
884
885 def assertIn(self, member, container, msg=None):
886 """Just like self.assertTrue(a in b), but with a nicer default message."""
887 if member not in container:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000888 standardMsg = '%s not found in %s' % (safe_repr(member),
889 safe_repr(container))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000890 self.fail(self._formatMessage(msg, standardMsg))
891
892 def assertNotIn(self, member, container, msg=None):
893 """Just like self.assertTrue(a not in b), but with a nicer default message."""
894 if member in container:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000895 standardMsg = '%s unexpectedly found in %s' % (safe_repr(member),
896 safe_repr(container))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000897 self.fail(self._formatMessage(msg, standardMsg))
898
899 def assertIs(self, expr1, expr2, msg=None):
900 """Just like self.assertTrue(a is b), but with a nicer default message."""
901 if expr1 is not expr2:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000902 standardMsg = '%s is not %s' % (safe_repr(expr1),
903 safe_repr(expr2))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000904 self.fail(self._formatMessage(msg, standardMsg))
905
906 def assertIsNot(self, expr1, expr2, msg=None):
907 """Just like self.assertTrue(a is not b), but with a nicer default message."""
908 if expr1 is expr2:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000909 standardMsg = 'unexpectedly identical: %s' % (safe_repr(expr1),)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000910 self.fail(self._formatMessage(msg, standardMsg))
911
912 def assertDictEqual(self, d1, d2, msg=None):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000913 self.assertIsInstance(d1, dict, 'First argument is not a dictionary')
914 self.assertIsInstance(d2, dict, 'Second argument is not a dictionary')
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000915
916 if d1 != d2:
Michael Foordcb11b252010-06-05 13:14:43 +0000917 standardMsg = '%s != %s' % (safe_repr(d1, True), safe_repr(d2, True))
Michael Foord085dfd32010-06-05 12:17:02 +0000918 diff = ('\n' + '\n'.join(difflib.ndiff(
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000919 pprint.pformat(d1).splitlines(),
920 pprint.pformat(d2).splitlines())))
Michael Foordcb11b252010-06-05 13:14:43 +0000921 standardMsg = self._truncateMessage(standardMsg, diff)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000922 self.fail(self._formatMessage(msg, standardMsg))
923
924 def assertDictContainsSubset(self, expected, actual, msg=None):
925 """Checks whether actual is a superset of expected."""
926 missing = []
927 mismatched = []
928 for key, value in expected.items():
929 if key not in actual:
930 missing.append(key)
931 elif value != actual[key]:
Benjamin Peterson6e8c7572009-10-04 20:19:21 +0000932 mismatched.append('%s, expected: %s, actual: %s' %
Benjamin Peterson847a4112010-03-14 15:04:17 +0000933 (safe_repr(key), safe_repr(value),
934 safe_repr(actual[key])))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000935
936 if not (missing or mismatched):
937 return
938
939 standardMsg = ''
940 if missing:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000941 standardMsg = 'Missing: %s' % ','.join(safe_repr(m) for m in
942 missing)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000943 if mismatched:
944 if standardMsg:
945 standardMsg += '; '
946 standardMsg += 'Mismatched values: %s' % ','.join(mismatched)
947
948 self.fail(self._formatMessage(msg, standardMsg))
949
950 def assertSameElements(self, expected_seq, actual_seq, msg=None):
951 """An unordered sequence specific comparison.
952
953 Raises with an error message listing which elements of expected_seq
954 are missing from actual_seq and vice versa if any.
Michael Foord1c42b122010-02-05 22:58:21 +0000955
956 Duplicate elements are ignored when comparing *expected_seq* and
957 *actual_seq*. It is the equivalent of ``assertEqual(set(expected),
958 set(actual))`` but it works with sequences of unhashable objects as
959 well.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000960 """
Michael Foord91c9da32010-03-20 17:21:27 +0000961 warnings.warn('assertSameElements is deprecated',
962 DeprecationWarning)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000963 try:
964 expected = set(expected_seq)
965 actual = set(actual_seq)
Benjamin Peterson847a4112010-03-14 15:04:17 +0000966 missing = sorted(expected.difference(actual))
967 unexpected = sorted(actual.difference(expected))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000968 except TypeError:
969 # Fall back to slower list-compare if any of the objects are
970 # not hashable.
971 expected = list(expected_seq)
972 actual = list(actual_seq)
973 try:
974 expected.sort()
975 actual.sort()
976 except TypeError:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000977 missing, unexpected = unorderable_list_difference(expected,
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000978 actual)
Benjamin Peterson847a4112010-03-14 15:04:17 +0000979 else:
980 missing, unexpected = sorted_list_difference(expected, actual)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000981 errors = []
982 if missing:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000983 errors.append('Expected, but missing:\n %s' %
984 safe_repr(missing))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000985 if unexpected:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000986 errors.append('Unexpected, but present:\n %s' %
987 safe_repr(unexpected))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000988 if errors:
989 standardMsg = '\n'.join(errors)
990 self.fail(self._formatMessage(msg, standardMsg))
991
Michael Foord8442a602010-03-20 16:58:04 +0000992
993 def assertItemsEqual(self, expected_seq, actual_seq, msg=None):
994 """An unordered sequence / set specific comparison. It asserts that
995 expected_seq and actual_seq contain the same elements. It is
996 the equivalent of::
997
998 self.assertEqual(sorted(expected_seq), sorted(actual_seq))
999
1000 Raises with an error message listing which elements of expected_seq
1001 are missing from actual_seq and vice versa if any.
1002
1003 Asserts that each element has the same count in both sequences.
1004 Example:
1005 - [0, 1, 1] and [1, 0, 1] compare equal.
1006 - [0, 0, 1] and [0, 1] compare unequal.
1007 """
1008 try:
1009 expected = sorted(expected_seq)
1010 actual = sorted(actual_seq)
1011 except TypeError:
1012 # Unsortable items (example: set(), complex(), ...)
1013 expected = list(expected_seq)
1014 actual = list(actual_seq)
1015 missing, unexpected = unorderable_list_difference(expected, actual)
1016 else:
1017 return self.assertSequenceEqual(expected, actual, msg=msg)
1018
1019 errors = []
1020 if missing:
1021 errors.append('Expected, but missing:\n %s' %
1022 safe_repr(missing))
1023 if unexpected:
1024 errors.append('Unexpected, but present:\n %s' %
1025 safe_repr(unexpected))
1026 if errors:
1027 standardMsg = '\n'.join(errors)
1028 self.fail(self._formatMessage(msg, standardMsg))
1029
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001030 def assertMultiLineEqual(self, first, second, msg=None):
1031 """Assert that two multi-line strings are equal."""
Ezio Melottib3aedd42010-11-20 19:04:17 +00001032 self.assertIsInstance(first, str, 'First argument is not a string')
1033 self.assertIsInstance(second, str, 'Second argument is not a string')
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001034
1035 if first != second:
Michael Foordc653ce32010-07-10 13:52:22 +00001036 firstlines = first.splitlines(True)
1037 secondlines = second.splitlines(True)
1038 if len(firstlines) == 1 and first.strip('\r\n') == first:
1039 firstlines = [first + '\n']
1040 secondlines = [second + '\n']
1041 standardMsg = '%s != %s' % (safe_repr(first, True),
1042 safe_repr(second, True))
1043 diff = '\n' + ''.join(difflib.ndiff(firstlines, secondlines))
Michael Foordcb11b252010-06-05 13:14:43 +00001044 standardMsg = self._truncateMessage(standardMsg, diff)
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001045 self.fail(self._formatMessage(msg, standardMsg))
1046
1047 def assertLess(self, a, b, msg=None):
1048 """Just like self.assertTrue(a < b), but with a nicer default message."""
1049 if not a < b:
Benjamin Peterson847a4112010-03-14 15:04:17 +00001050 standardMsg = '%s not less than %s' % (safe_repr(a), safe_repr(b))
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001051 self.fail(self._formatMessage(msg, standardMsg))
1052
1053 def assertLessEqual(self, a, b, msg=None):
1054 """Just like self.assertTrue(a <= b), but with a nicer default message."""
1055 if not a <= b:
Benjamin Peterson847a4112010-03-14 15:04:17 +00001056 standardMsg = '%s not less than or equal to %s' % (safe_repr(a), safe_repr(b))
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001057 self.fail(self._formatMessage(msg, standardMsg))
1058
1059 def assertGreater(self, a, b, msg=None):
1060 """Just like self.assertTrue(a > b), but with a nicer default message."""
1061 if not a > b:
Benjamin Peterson847a4112010-03-14 15:04:17 +00001062 standardMsg = '%s not greater than %s' % (safe_repr(a), safe_repr(b))
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001063 self.fail(self._formatMessage(msg, standardMsg))
1064
1065 def assertGreaterEqual(self, a, b, msg=None):
1066 """Just like self.assertTrue(a >= b), but with a nicer default message."""
1067 if not a >= b:
Benjamin Peterson847a4112010-03-14 15:04:17 +00001068 standardMsg = '%s not greater than or equal to %s' % (safe_repr(a), safe_repr(b))
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001069 self.fail(self._formatMessage(msg, standardMsg))
1070
1071 def assertIsNone(self, obj, msg=None):
1072 """Same as self.assertTrue(obj is None), with a nicer default message."""
1073 if obj is not None:
Benjamin Peterson847a4112010-03-14 15:04:17 +00001074 standardMsg = '%s is not None' % (safe_repr(obj),)
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001075 self.fail(self._formatMessage(msg, standardMsg))
1076
1077 def assertIsNotNone(self, obj, msg=None):
1078 """Included for symmetry with assertIsNone."""
1079 if obj is None:
1080 standardMsg = 'unexpectedly None'
1081 self.fail(self._formatMessage(msg, standardMsg))
1082
Benjamin Peterson6e8c7572009-10-04 20:19:21 +00001083 def assertIsInstance(self, obj, cls, msg=None):
1084 """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
1085 default message."""
1086 if not isinstance(obj, cls):
Benjamin Peterson847a4112010-03-14 15:04:17 +00001087 standardMsg = '%s is not an instance of %r' % (safe_repr(obj), cls)
Benjamin Peterson6e8c7572009-10-04 20:19:21 +00001088 self.fail(self._formatMessage(msg, standardMsg))
1089
1090 def assertNotIsInstance(self, obj, cls, msg=None):
1091 """Included for symmetry with assertIsInstance."""
1092 if isinstance(obj, cls):
Benjamin Peterson847a4112010-03-14 15:04:17 +00001093 standardMsg = '%s is an instance of %r' % (safe_repr(obj), cls)
Benjamin Peterson6e8c7572009-10-04 20:19:21 +00001094 self.fail(self._formatMessage(msg, standardMsg))
1095
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001096 def assertRaisesRegexp(self, expected_exception, expected_regexp,
1097 callable_obj=None, *args, **kwargs):
1098 """Asserts that the message in a raised exception matches a regexp.
1099
1100 Args:
1101 expected_exception: Exception class expected to be raised.
1102 expected_regexp: Regexp (re pattern object or string) expected
1103 to be found in error message.
1104 callable_obj: Function to be called.
1105 args: Extra args.
1106 kwargs: Extra kwargs.
1107 """
1108 context = _AssertRaisesContext(expected_exception, self, callable_obj,
1109 expected_regexp)
1110 if callable_obj is None:
1111 return context
1112 with context:
1113 callable_obj(*args, **kwargs)
1114
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001115 def assertWarnsRegexp(self, expected_warning, expected_regexp,
1116 callable_obj=None, *args, **kwargs):
1117 """Asserts that the message in a triggered warning matches a regexp.
1118 Basic functioning is similar to assertWarns() with the addition
1119 that only warnings whose messages also match the regular expression
1120 are considered successful matches.
1121
1122 Args:
1123 expected_warning: Warning class expected to be triggered.
1124 expected_regexp: Regexp (re pattern object or string) expected
1125 to be found in error message.
1126 callable_obj: Function to be called.
1127 args: Extra args.
1128 kwargs: Extra kwargs.
1129 """
1130 context = _AssertWarnsContext(expected_warning, self, callable_obj,
1131 expected_regexp)
1132 if callable_obj is None:
1133 return context
1134 with context:
1135 callable_obj(*args, **kwargs)
1136
Georg Brandl89fad142010-03-14 10:23:39 +00001137 def assertRegexpMatches(self, text, expected_regexp, msg=None):
Michael Foorde3ef5f12010-05-08 16:46:14 +00001138 """Fail the test unless the text matches the regular expression."""
Georg Brandl89fad142010-03-14 10:23:39 +00001139 if isinstance(expected_regexp, (str, bytes)):
1140 expected_regexp = re.compile(expected_regexp)
1141 if not expected_regexp.search(text):
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001142 msg = msg or "Regexp didn't match"
Georg Brandl89fad142010-03-14 10:23:39 +00001143 msg = '%s: %r not found in %r' % (msg, expected_regexp.pattern, text)
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001144 raise self.failureException(msg)
1145
Benjamin Petersonb48af542010-04-11 20:43:16 +00001146 def assertNotRegexpMatches(self, text, unexpected_regexp, msg=None):
Michael Foorde3ef5f12010-05-08 16:46:14 +00001147 """Fail the test if the text matches the regular expression."""
Benjamin Petersonb48af542010-04-11 20:43:16 +00001148 if isinstance(unexpected_regexp, (str, bytes)):
1149 unexpected_regexp = re.compile(unexpected_regexp)
1150 match = unexpected_regexp.search(text)
1151 if match:
1152 msg = msg or "Regexp matched"
1153 msg = '%s: %r matches %r in %r' % (msg,
1154 text[match.start():match.end()],
1155 unexpected_regexp.pattern,
1156 text)
1157 raise self.failureException(msg)
1158
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001159
1160class FunctionTestCase(TestCase):
1161 """A test case that wraps a test function.
1162
1163 This is useful for slipping pre-existing test functions into the
1164 unittest framework. Optionally, set-up and tidy-up functions can be
1165 supplied. As with TestCase, the tidy-up ('tearDown') function will
1166 always be called if the set-up ('setUp') function ran successfully.
1167 """
1168
1169 def __init__(self, testFunc, setUp=None, tearDown=None, description=None):
1170 super(FunctionTestCase, self).__init__()
1171 self._setUpFunc = setUp
1172 self._tearDownFunc = tearDown
1173 self._testFunc = testFunc
1174 self._description = description
1175
1176 def setUp(self):
1177 if self._setUpFunc is not None:
1178 self._setUpFunc()
1179
1180 def tearDown(self):
1181 if self._tearDownFunc is not None:
1182 self._tearDownFunc()
1183
1184 def runTest(self):
1185 self._testFunc()
1186
1187 def id(self):
1188 return self._testFunc.__name__
1189
1190 def __eq__(self, other):
1191 if not isinstance(other, self.__class__):
1192 return NotImplemented
1193
1194 return self._setUpFunc == other._setUpFunc and \
1195 self._tearDownFunc == other._tearDownFunc and \
1196 self._testFunc == other._testFunc and \
1197 self._description == other._description
1198
1199 def __ne__(self, other):
1200 return not self == other
1201
1202 def __hash__(self):
1203 return hash((type(self), self._setUpFunc, self._tearDownFunc,
1204 self._testFunc, self._description))
1205
1206 def __str__(self):
Benjamin Peterson847a4112010-03-14 15:04:17 +00001207 return "%s (%s)" % (strclass(self.__class__),
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001208 self._testFunc.__name__)
1209
1210 def __repr__(self):
Benjamin Peterson847a4112010-03-14 15:04:17 +00001211 return "<%s tec=%s>" % (strclass(self.__class__),
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001212 self._testFunc)
1213
1214 def shortDescription(self):
1215 if self._description is not None:
1216 return self._description
1217 doc = self._testFunc.__doc__
1218 return doc and doc.split("\n")[0].strip() or None