blob: 1df19dca59ea285a3af7a4a7b8b49661f9c59ca5 [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
690 # Synonyms for assertion methods
691
692 # The plurals are undocumented. Keep them that way to discourage use.
693 # Do not add more. Do not remove.
694 # Going through a deprecation cycle on these would annoy many people.
695 assertEquals = assertEqual
696 assertNotEquals = assertNotEqual
697 assertAlmostEquals = assertAlmostEqual
698 assertNotAlmostEquals = assertNotAlmostEqual
Michael Foord0e31b992010-02-10 15:52:56 +0000699 assert_ = assertTrue
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000700
701 # These fail* assertion method names are pending deprecation and will
702 # be a DeprecationWarning in 3.2; http://bugs.python.org/issue2578
703 def _deprecate(original_func):
704 def deprecated_func(*args, **kwargs):
705 warnings.warn(
706 'Please use {0} instead.'.format(original_func.__name__),
707 DeprecationWarning, 2)
708 return original_func(*args, **kwargs)
709 return deprecated_func
710
711 failUnlessEqual = _deprecate(assertEqual)
712 failIfEqual = _deprecate(assertNotEqual)
713 failUnlessAlmostEqual = _deprecate(assertAlmostEqual)
714 failIfAlmostEqual = _deprecate(assertNotAlmostEqual)
715 failUnless = _deprecate(assertTrue)
716 failUnlessRaises = _deprecate(assertRaises)
717 failIf = _deprecate(assertFalse)
718
Michael Foord085dfd32010-06-05 12:17:02 +0000719 def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000720 """An equality assertion for ordered sequences (like lists and tuples).
721
R. David Murrayad13f222010-01-29 22:17:58 +0000722 For the purposes of this function, a valid ordered sequence type is one
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000723 which can be indexed, has a length, and has an equality operator.
724
725 Args:
726 seq1: The first sequence to compare.
727 seq2: The second sequence to compare.
728 seq_type: The expected datatype of the sequences, or None if no
729 datatype should be enforced.
730 msg: Optional message to use on failure instead of a list of
731 differences.
732 """
733 if seq_type != None:
734 seq_type_name = seq_type.__name__
735 if not isinstance(seq1, seq_type):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000736 raise self.failureException('First sequence is not a %s: %s'
737 % (seq_type_name, safe_repr(seq1)))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000738 if not isinstance(seq2, seq_type):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000739 raise self.failureException('Second sequence is not a %s: %s'
740 % (seq_type_name, safe_repr(seq2)))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000741 else:
742 seq_type_name = "sequence"
743
744 differing = None
745 try:
746 len1 = len(seq1)
747 except (TypeError, NotImplementedError):
748 differing = 'First %s has no length. Non-sequence?' % (
749 seq_type_name)
750
751 if differing is None:
752 try:
753 len2 = len(seq2)
754 except (TypeError, NotImplementedError):
755 differing = 'Second %s has no length. Non-sequence?' % (
756 seq_type_name)
757
758 if differing is None:
759 if seq1 == seq2:
760 return
761
Benjamin Peterson847a4112010-03-14 15:04:17 +0000762 seq1_repr = safe_repr(seq1)
763 seq2_repr = safe_repr(seq2)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000764 if len(seq1_repr) > 30:
765 seq1_repr = seq1_repr[:30] + '...'
766 if len(seq2_repr) > 30:
767 seq2_repr = seq2_repr[:30] + '...'
768 elements = (seq_type_name.capitalize(), seq1_repr, seq2_repr)
769 differing = '%ss differ: %s != %s\n' % elements
770
771 for i in range(min(len1, len2)):
772 try:
773 item1 = seq1[i]
774 except (TypeError, IndexError, NotImplementedError):
775 differing += ('\nUnable to index element %d of first %s\n' %
776 (i, seq_type_name))
777 break
778
779 try:
780 item2 = seq2[i]
781 except (TypeError, IndexError, NotImplementedError):
782 differing += ('\nUnable to index element %d of second %s\n' %
783 (i, seq_type_name))
784 break
785
786 if item1 != item2:
787 differing += ('\nFirst differing element %d:\n%s\n%s\n' %
788 (i, item1, item2))
789 break
790 else:
791 if (len1 == len2 and seq_type is None and
792 type(seq1) != type(seq2)):
793 # The sequences are the same, but have differing types.
794 return
795
796 if len1 > len2:
797 differing += ('\nFirst %s contains %d additional '
798 'elements.\n' % (seq_type_name, len1 - len2))
799 try:
800 differing += ('First extra element %d:\n%s\n' %
801 (len2, seq1[len2]))
802 except (TypeError, IndexError, NotImplementedError):
803 differing += ('Unable to index element %d '
804 'of first %s\n' % (len2, seq_type_name))
805 elif len1 < len2:
806 differing += ('\nSecond %s contains %d additional '
807 'elements.\n' % (seq_type_name, len2 - len1))
808 try:
809 differing += ('First extra element %d:\n%s\n' %
810 (len1, seq2[len1]))
811 except (TypeError, IndexError, NotImplementedError):
812 differing += ('Unable to index element %d '
813 'of second %s\n' % (len1, seq_type_name))
Michael Foord2034d9a2010-06-05 11:27:52 +0000814 standardMsg = differing
815 diffMsg = '\n' + '\n'.join(
Benjamin Peterson6e8c7572009-10-04 20:19:21 +0000816 difflib.ndiff(pprint.pformat(seq1).splitlines(),
817 pprint.pformat(seq2).splitlines()))
Michael Foord085dfd32010-06-05 12:17:02 +0000818
819 standardMsg = self._truncateMessage(standardMsg, diffMsg)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000820 msg = self._formatMessage(msg, standardMsg)
821 self.fail(msg)
822
Michael Foord085dfd32010-06-05 12:17:02 +0000823 def _truncateMessage(self, message, diff):
824 max_diff = self.maxDiff
825 if max_diff is None or len(diff) <= max_diff:
826 return message + diff
Michael Foord9dad32e2010-06-05 13:49:56 +0000827 return message + (DIFF_OMITTED % len(diff))
Michael Foord085dfd32010-06-05 12:17:02 +0000828
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000829 def assertListEqual(self, list1, list2, msg=None):
830 """A list-specific equality assertion.
831
832 Args:
833 list1: The first list to compare.
834 list2: The second list to compare.
835 msg: Optional message to use on failure instead of a list of
836 differences.
837
838 """
839 self.assertSequenceEqual(list1, list2, msg, seq_type=list)
840
841 def assertTupleEqual(self, tuple1, tuple2, msg=None):
842 """A tuple-specific equality assertion.
843
844 Args:
845 tuple1: The first tuple to compare.
846 tuple2: The second tuple to compare.
847 msg: Optional message to use on failure instead of a list of
848 differences.
849 """
850 self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
851
852 def assertSetEqual(self, set1, set2, msg=None):
853 """A set-specific equality assertion.
854
855 Args:
856 set1: The first set to compare.
857 set2: The second set to compare.
858 msg: Optional message to use on failure instead of a list of
859 differences.
860
Michael Foord91c9da32010-03-20 17:21:27 +0000861 assertSetEqual uses ducktyping to support different types of sets, and
862 is optimized for sets specifically (parameters must support a
863 difference method).
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000864 """
865 try:
866 difference1 = set1.difference(set2)
867 except TypeError as e:
868 self.fail('invalid type when attempting set difference: %s' % e)
869 except AttributeError as e:
870 self.fail('first argument does not support set difference: %s' % e)
871
872 try:
873 difference2 = set2.difference(set1)
874 except TypeError as e:
875 self.fail('invalid type when attempting set difference: %s' % e)
876 except AttributeError as e:
877 self.fail('second argument does not support set difference: %s' % e)
878
879 if not (difference1 or difference2):
880 return
881
882 lines = []
883 if difference1:
884 lines.append('Items in the first set but not the second:')
885 for item in difference1:
886 lines.append(repr(item))
887 if difference2:
888 lines.append('Items in the second set but not the first:')
889 for item in difference2:
890 lines.append(repr(item))
891
892 standardMsg = '\n'.join(lines)
893 self.fail(self._formatMessage(msg, standardMsg))
894
895 def assertIn(self, member, container, msg=None):
896 """Just like self.assertTrue(a in b), but with a nicer default message."""
897 if member not in container:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000898 standardMsg = '%s not found in %s' % (safe_repr(member),
899 safe_repr(container))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000900 self.fail(self._formatMessage(msg, standardMsg))
901
902 def assertNotIn(self, member, container, msg=None):
903 """Just like self.assertTrue(a not in b), but with a nicer default message."""
904 if member in container:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000905 standardMsg = '%s unexpectedly found in %s' % (safe_repr(member),
906 safe_repr(container))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000907 self.fail(self._formatMessage(msg, standardMsg))
908
909 def assertIs(self, expr1, expr2, msg=None):
910 """Just like self.assertTrue(a is b), but with a nicer default message."""
911 if expr1 is not expr2:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000912 standardMsg = '%s is not %s' % (safe_repr(expr1),
913 safe_repr(expr2))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000914 self.fail(self._formatMessage(msg, standardMsg))
915
916 def assertIsNot(self, expr1, expr2, msg=None):
917 """Just like self.assertTrue(a is not b), but with a nicer default message."""
918 if expr1 is expr2:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000919 standardMsg = 'unexpectedly identical: %s' % (safe_repr(expr1),)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000920 self.fail(self._formatMessage(msg, standardMsg))
921
922 def assertDictEqual(self, d1, d2, msg=None):
923 self.assert_(isinstance(d1, dict), 'First argument is not a dictionary')
924 self.assert_(isinstance(d2, dict), 'Second argument is not a dictionary')
925
926 if d1 != d2:
Michael Foordcb11b252010-06-05 13:14:43 +0000927 standardMsg = '%s != %s' % (safe_repr(d1, True), safe_repr(d2, True))
Michael Foord085dfd32010-06-05 12:17:02 +0000928 diff = ('\n' + '\n'.join(difflib.ndiff(
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000929 pprint.pformat(d1).splitlines(),
930 pprint.pformat(d2).splitlines())))
Michael Foordcb11b252010-06-05 13:14:43 +0000931 standardMsg = self._truncateMessage(standardMsg, diff)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000932 self.fail(self._formatMessage(msg, standardMsg))
933
934 def assertDictContainsSubset(self, expected, actual, msg=None):
935 """Checks whether actual is a superset of expected."""
936 missing = []
937 mismatched = []
938 for key, value in expected.items():
939 if key not in actual:
940 missing.append(key)
941 elif value != actual[key]:
Benjamin Peterson6e8c7572009-10-04 20:19:21 +0000942 mismatched.append('%s, expected: %s, actual: %s' %
Benjamin Peterson847a4112010-03-14 15:04:17 +0000943 (safe_repr(key), safe_repr(value),
944 safe_repr(actual[key])))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000945
946 if not (missing or mismatched):
947 return
948
949 standardMsg = ''
950 if missing:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000951 standardMsg = 'Missing: %s' % ','.join(safe_repr(m) for m in
952 missing)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000953 if mismatched:
954 if standardMsg:
955 standardMsg += '; '
956 standardMsg += 'Mismatched values: %s' % ','.join(mismatched)
957
958 self.fail(self._formatMessage(msg, standardMsg))
959
960 def assertSameElements(self, expected_seq, actual_seq, msg=None):
961 """An unordered sequence specific comparison.
962
963 Raises with an error message listing which elements of expected_seq
964 are missing from actual_seq and vice versa if any.
Michael Foord1c42b122010-02-05 22:58:21 +0000965
966 Duplicate elements are ignored when comparing *expected_seq* and
967 *actual_seq*. It is the equivalent of ``assertEqual(set(expected),
968 set(actual))`` but it works with sequences of unhashable objects as
969 well.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000970 """
Michael Foord91c9da32010-03-20 17:21:27 +0000971 warnings.warn('assertSameElements is deprecated',
972 DeprecationWarning)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000973 try:
974 expected = set(expected_seq)
975 actual = set(actual_seq)
Benjamin Peterson847a4112010-03-14 15:04:17 +0000976 missing = sorted(expected.difference(actual))
977 unexpected = sorted(actual.difference(expected))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000978 except TypeError:
979 # Fall back to slower list-compare if any of the objects are
980 # not hashable.
981 expected = list(expected_seq)
982 actual = list(actual_seq)
983 try:
984 expected.sort()
985 actual.sort()
986 except TypeError:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000987 missing, unexpected = unorderable_list_difference(expected,
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000988 actual)
Benjamin Peterson847a4112010-03-14 15:04:17 +0000989 else:
990 missing, unexpected = sorted_list_difference(expected, actual)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000991 errors = []
992 if missing:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000993 errors.append('Expected, but missing:\n %s' %
994 safe_repr(missing))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000995 if unexpected:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000996 errors.append('Unexpected, but present:\n %s' %
997 safe_repr(unexpected))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000998 if errors:
999 standardMsg = '\n'.join(errors)
1000 self.fail(self._formatMessage(msg, standardMsg))
1001
Michael Foord8442a602010-03-20 16:58:04 +00001002
1003 def assertItemsEqual(self, expected_seq, actual_seq, msg=None):
1004 """An unordered sequence / set specific comparison. It asserts that
1005 expected_seq and actual_seq contain the same elements. It is
1006 the equivalent of::
1007
1008 self.assertEqual(sorted(expected_seq), sorted(actual_seq))
1009
1010 Raises with an error message listing which elements of expected_seq
1011 are missing from actual_seq and vice versa if any.
1012
1013 Asserts that each element has the same count in both sequences.
1014 Example:
1015 - [0, 1, 1] and [1, 0, 1] compare equal.
1016 - [0, 0, 1] and [0, 1] compare unequal.
1017 """
1018 try:
1019 expected = sorted(expected_seq)
1020 actual = sorted(actual_seq)
1021 except TypeError:
1022 # Unsortable items (example: set(), complex(), ...)
1023 expected = list(expected_seq)
1024 actual = list(actual_seq)
1025 missing, unexpected = unorderable_list_difference(expected, actual)
1026 else:
1027 return self.assertSequenceEqual(expected, actual, msg=msg)
1028
1029 errors = []
1030 if missing:
1031 errors.append('Expected, but missing:\n %s' %
1032 safe_repr(missing))
1033 if unexpected:
1034 errors.append('Unexpected, but present:\n %s' %
1035 safe_repr(unexpected))
1036 if errors:
1037 standardMsg = '\n'.join(errors)
1038 self.fail(self._formatMessage(msg, standardMsg))
1039
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001040 def assertMultiLineEqual(self, first, second, msg=None):
1041 """Assert that two multi-line strings are equal."""
1042 self.assert_(isinstance(first, str), (
1043 'First argument is not a string'))
1044 self.assert_(isinstance(second, str), (
1045 'Second argument is not a string'))
1046
1047 if first != second:
Michael Foordc653ce32010-07-10 13:52:22 +00001048 firstlines = first.splitlines(True)
1049 secondlines = second.splitlines(True)
1050 if len(firstlines) == 1 and first.strip('\r\n') == first:
1051 firstlines = [first + '\n']
1052 secondlines = [second + '\n']
1053 standardMsg = '%s != %s' % (safe_repr(first, True),
1054 safe_repr(second, True))
1055 diff = '\n' + ''.join(difflib.ndiff(firstlines, secondlines))
Michael Foordcb11b252010-06-05 13:14:43 +00001056 standardMsg = self._truncateMessage(standardMsg, diff)
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001057 self.fail(self._formatMessage(msg, standardMsg))
1058
1059 def assertLess(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 less 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 assertLessEqual(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 less 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 assertGreater(self, a, b, msg=None):
1072 """Just like self.assertTrue(a > b), but with a nicer default message."""
1073 if not a > b:
Benjamin Peterson847a4112010-03-14 15:04:17 +00001074 standardMsg = '%s not greater than %s' % (safe_repr(a), safe_repr(b))
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001075 self.fail(self._formatMessage(msg, standardMsg))
1076
1077 def assertGreaterEqual(self, a, b, msg=None):
1078 """Just like self.assertTrue(a >= b), but with a nicer default message."""
1079 if not a >= b:
Benjamin Peterson847a4112010-03-14 15:04:17 +00001080 standardMsg = '%s not greater than or equal to %s' % (safe_repr(a), safe_repr(b))
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001081 self.fail(self._formatMessage(msg, standardMsg))
1082
1083 def assertIsNone(self, obj, msg=None):
1084 """Same as self.assertTrue(obj is None), with a nicer default message."""
1085 if obj is not None:
Benjamin Peterson847a4112010-03-14 15:04:17 +00001086 standardMsg = '%s is not None' % (safe_repr(obj),)
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001087 self.fail(self._formatMessage(msg, standardMsg))
1088
1089 def assertIsNotNone(self, obj, msg=None):
1090 """Included for symmetry with assertIsNone."""
1091 if obj is None:
1092 standardMsg = 'unexpectedly None'
1093 self.fail(self._formatMessage(msg, standardMsg))
1094
Benjamin Peterson6e8c7572009-10-04 20:19:21 +00001095 def assertIsInstance(self, obj, cls, msg=None):
1096 """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
1097 default message."""
1098 if not isinstance(obj, cls):
Benjamin Peterson847a4112010-03-14 15:04:17 +00001099 standardMsg = '%s is not an instance of %r' % (safe_repr(obj), cls)
Benjamin Peterson6e8c7572009-10-04 20:19:21 +00001100 self.fail(self._formatMessage(msg, standardMsg))
1101
1102 def assertNotIsInstance(self, obj, cls, msg=None):
1103 """Included for symmetry with assertIsInstance."""
1104 if isinstance(obj, cls):
Benjamin Peterson847a4112010-03-14 15:04:17 +00001105 standardMsg = '%s is an instance of %r' % (safe_repr(obj), cls)
Benjamin Peterson6e8c7572009-10-04 20:19:21 +00001106 self.fail(self._formatMessage(msg, standardMsg))
1107
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001108 def assertRaisesRegexp(self, expected_exception, expected_regexp,
1109 callable_obj=None, *args, **kwargs):
1110 """Asserts that the message in a raised exception matches a regexp.
1111
1112 Args:
1113 expected_exception: Exception class expected to be raised.
1114 expected_regexp: Regexp (re pattern object or string) expected
1115 to be found in error message.
1116 callable_obj: Function to be called.
1117 args: Extra args.
1118 kwargs: Extra kwargs.
1119 """
1120 context = _AssertRaisesContext(expected_exception, self, callable_obj,
1121 expected_regexp)
1122 if callable_obj is None:
1123 return context
1124 with context:
1125 callable_obj(*args, **kwargs)
1126
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001127 def assertWarnsRegexp(self, expected_warning, expected_regexp,
1128 callable_obj=None, *args, **kwargs):
1129 """Asserts that the message in a triggered warning matches a regexp.
1130 Basic functioning is similar to assertWarns() with the addition
1131 that only warnings whose messages also match the regular expression
1132 are considered successful matches.
1133
1134 Args:
1135 expected_warning: Warning class expected to be triggered.
1136 expected_regexp: Regexp (re pattern object or string) expected
1137 to be found in error message.
1138 callable_obj: Function to be called.
1139 args: Extra args.
1140 kwargs: Extra kwargs.
1141 """
1142 context = _AssertWarnsContext(expected_warning, self, callable_obj,
1143 expected_regexp)
1144 if callable_obj is None:
1145 return context
1146 with context:
1147 callable_obj(*args, **kwargs)
1148
Georg Brandl89fad142010-03-14 10:23:39 +00001149 def assertRegexpMatches(self, text, expected_regexp, msg=None):
Michael Foorde3ef5f12010-05-08 16:46:14 +00001150 """Fail the test unless the text matches the regular expression."""
Georg Brandl89fad142010-03-14 10:23:39 +00001151 if isinstance(expected_regexp, (str, bytes)):
1152 expected_regexp = re.compile(expected_regexp)
1153 if not expected_regexp.search(text):
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001154 msg = msg or "Regexp didn't match"
Georg Brandl89fad142010-03-14 10:23:39 +00001155 msg = '%s: %r not found in %r' % (msg, expected_regexp.pattern, text)
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001156 raise self.failureException(msg)
1157
Benjamin Petersonb48af542010-04-11 20:43:16 +00001158 def assertNotRegexpMatches(self, text, unexpected_regexp, msg=None):
Michael Foorde3ef5f12010-05-08 16:46:14 +00001159 """Fail the test if the text matches the regular expression."""
Benjamin Petersonb48af542010-04-11 20:43:16 +00001160 if isinstance(unexpected_regexp, (str, bytes)):
1161 unexpected_regexp = re.compile(unexpected_regexp)
1162 match = unexpected_regexp.search(text)
1163 if match:
1164 msg = msg or "Regexp matched"
1165 msg = '%s: %r matches %r in %r' % (msg,
1166 text[match.start():match.end()],
1167 unexpected_regexp.pattern,
1168 text)
1169 raise self.failureException(msg)
1170
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001171
1172class FunctionTestCase(TestCase):
1173 """A test case that wraps a test function.
1174
1175 This is useful for slipping pre-existing test functions into the
1176 unittest framework. Optionally, set-up and tidy-up functions can be
1177 supplied. As with TestCase, the tidy-up ('tearDown') function will
1178 always be called if the set-up ('setUp') function ran successfully.
1179 """
1180
1181 def __init__(self, testFunc, setUp=None, tearDown=None, description=None):
1182 super(FunctionTestCase, self).__init__()
1183 self._setUpFunc = setUp
1184 self._tearDownFunc = tearDown
1185 self._testFunc = testFunc
1186 self._description = description
1187
1188 def setUp(self):
1189 if self._setUpFunc is not None:
1190 self._setUpFunc()
1191
1192 def tearDown(self):
1193 if self._tearDownFunc is not None:
1194 self._tearDownFunc()
1195
1196 def runTest(self):
1197 self._testFunc()
1198
1199 def id(self):
1200 return self._testFunc.__name__
1201
1202 def __eq__(self, other):
1203 if not isinstance(other, self.__class__):
1204 return NotImplemented
1205
1206 return self._setUpFunc == other._setUpFunc and \
1207 self._tearDownFunc == other._tearDownFunc and \
1208 self._testFunc == other._testFunc and \
1209 self._description == other._description
1210
1211 def __ne__(self, other):
1212 return not self == other
1213
1214 def __hash__(self):
1215 return hash((type(self), self._setUpFunc, self._tearDownFunc,
1216 self._testFunc, self._description))
1217
1218 def __str__(self):
Benjamin Peterson847a4112010-03-14 15:04:17 +00001219 return "%s (%s)" % (strclass(self.__class__),
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001220 self._testFunc.__name__)
1221
1222 def __repr__(self):
Benjamin Peterson847a4112010-03-14 15:04:17 +00001223 return "<%s tec=%s>" % (strclass(self.__class__),
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001224 self._testFunc)
1225
1226 def shortDescription(self):
1227 if self._description is not None:
1228 return self._description
1229 doc = self._testFunc.__doc__
1230 return doc and doc.split("\n")[0].strip() or None