blob: d04ea6142841d5a961d60fb4c8984567e64469dc [file] [log] [blame]
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001"""Test case implementation"""
2
3import sys
4import functools
5import difflib
6import pprint
7import re
8import warnings
Raymond Hettinger6e165b32010-11-27 09:31:37 +00009import collections
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +010010import contextlib
Benjamin Petersonbed7d042009-07-19 21:01:52 +000011
Benjamin Peterson847a4112010-03-14 15:04:17 +000012from . import result
Florent Xiclunac53ae582011-11-04 08:25:54 +010013from .util import (strclass, safe_repr, _count_diff_all_purpose,
Raymond Hettinger93e233d2010-12-24 10:02:22 +000014 _count_diff_hashable)
Benjamin Petersonbed7d042009-07-19 21:01:52 +000015
Benjamin Petersondccc1fc2010-03-22 00:15:53 +000016__unittest = True
Benjamin Petersonbed7d042009-07-19 21:01:52 +000017
Michael Foord9dad32e2010-06-05 13:49:56 +000018
19DIFF_OMITTED = ('\nDiff is %s characters long. '
20 'Set self.maxDiff to None to see it.')
21
Benjamin Petersonbed7d042009-07-19 21:01:52 +000022class SkipTest(Exception):
23 """
24 Raise this exception in a test to skip it.
25
Ezio Melotti265281a2013-03-27 20:11:55 +020026 Usually you can use TestCase.skipTest() or one of the skipping decorators
Benjamin Petersonbed7d042009-07-19 21:01:52 +000027 instead of raising this directly.
28 """
Benjamin Petersonbed7d042009-07-19 21:01:52 +000029
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +010030class _ShouldStop(Exception):
Benjamin Petersonbed7d042009-07-19 21:01:52 +000031 """
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +010032 The test should stop.
Benjamin Petersonbed7d042009-07-19 21:01:52 +000033 """
34
Benjamin Petersonbed7d042009-07-19 21:01:52 +000035class _UnexpectedSuccess(Exception):
36 """
37 The test was supposed to fail, but it didn't!
38 """
Michael Foordb3468f72010-12-19 03:19:47 +000039
40
41class _Outcome(object):
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +010042 def __init__(self, result=None):
43 self.expecting_failure = False
44 self.result = result
45 self.result_supports_subtests = hasattr(result, "addSubTest")
Michael Foordb3468f72010-12-19 03:19:47 +000046 self.success = True
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +010047 self.skipped = []
Michael Foordb3468f72010-12-19 03:19:47 +000048 self.expectedFailure = None
49 self.errors = []
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +010050
51 @contextlib.contextmanager
52 def testPartExecutor(self, test_case, isTest=False):
53 old_success = self.success
54 self.success = True
55 try:
56 yield
57 except KeyboardInterrupt:
58 raise
59 except SkipTest as e:
60 self.success = False
61 self.skipped.append((test_case, str(e)))
62 except _ShouldStop:
63 pass
64 except:
65 exc_info = sys.exc_info()
66 if self.expecting_failure:
67 self.expectedFailure = exc_info
68 else:
69 self.success = False
70 self.errors.append((test_case, exc_info))
71 else:
72 if self.result_supports_subtests and self.success:
73 self.errors.append((test_case, None))
74 finally:
75 self.success = self.success and old_success
Michael Foordb3468f72010-12-19 03:19:47 +000076
Benjamin Petersonbed7d042009-07-19 21:01:52 +000077
78def _id(obj):
79 return obj
80
81def skip(reason):
82 """
83 Unconditionally skip a test.
84 """
85 def decorator(test_item):
Antoine Pitroub05ac862012-04-25 14:56:46 +020086 if not isinstance(test_item, type):
Benjamin Peterson847a4112010-03-14 15:04:17 +000087 @functools.wraps(test_item)
88 def skip_wrapper(*args, **kwargs):
89 raise SkipTest(reason)
90 test_item = skip_wrapper
91
92 test_item.__unittest_skip__ = True
93 test_item.__unittest_skip_why__ = reason
94 return test_item
Benjamin Petersonbed7d042009-07-19 21:01:52 +000095 return decorator
96
97def skipIf(condition, reason):
98 """
99 Skip a test if the condition is true.
100 """
101 if condition:
102 return skip(reason)
103 return _id
104
105def skipUnless(condition, reason):
106 """
107 Skip a test unless the condition is true.
108 """
109 if not condition:
110 return skip(reason)
111 return _id
112
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100113def expectedFailure(test_item):
114 test_item.__unittest_expecting_failure__ = True
115 return test_item
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000116
117
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000118class _AssertRaisesBaseContext(object):
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000119
120 def __init__(self, expected, test_case, callable_obj=None,
Ezio Melottib4dc2502011-05-06 15:01:41 +0300121 expected_regex=None):
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000122 self.expected = expected
Ezio Melottib4dc2502011-05-06 15:01:41 +0300123 self.test_case = test_case
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000124 if callable_obj is not None:
125 try:
126 self.obj_name = callable_obj.__name__
127 except AttributeError:
128 self.obj_name = str(callable_obj)
129 else:
130 self.obj_name = None
Ezio Melottied3a7d22010-12-01 02:32:32 +0000131 if isinstance(expected_regex, (bytes, str)):
132 expected_regex = re.compile(expected_regex)
133 self.expected_regex = expected_regex
Ezio Melottib4dc2502011-05-06 15:01:41 +0300134 self.msg = None
135
136 def _raiseFailure(self, standardMsg):
137 msg = self.test_case._formatMessage(self.msg, standardMsg)
138 raise self.test_case.failureException(msg)
139
140 def handle(self, name, callable_obj, args, kwargs):
141 """
142 If callable_obj is None, assertRaises/Warns is being used as a
143 context manager, so check for a 'msg' kwarg and return self.
144 If callable_obj is not None, call it passing args and kwargs.
145 """
146 if callable_obj is None:
147 self.msg = kwargs.pop('msg', None)
148 return self
149 with self:
150 callable_obj(*args, **kwargs)
151
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000152
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000153
154class _AssertRaisesContext(_AssertRaisesBaseContext):
155 """A context manager used to implement TestCase.assertRaises* methods."""
156
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000157 def __enter__(self):
Ezio Melotti49008232010-02-08 21:57:48 +0000158 return self
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000159
160 def __exit__(self, exc_type, exc_value, tb):
161 if exc_type is None:
162 try:
163 exc_name = self.expected.__name__
164 except AttributeError:
165 exc_name = str(self.expected)
166 if self.obj_name:
Ezio Melottib4dc2502011-05-06 15:01:41 +0300167 self._raiseFailure("{} not raised by {}".format(exc_name,
168 self.obj_name))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000169 else:
Ezio Melottib4dc2502011-05-06 15:01:41 +0300170 self._raiseFailure("{} not raised".format(exc_name))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000171 if not issubclass(exc_type, self.expected):
172 # let unexpected exceptions pass through
173 return False
Ezio Melotti49008232010-02-08 21:57:48 +0000174 # store exception, without traceback, for later retrieval
175 self.exception = exc_value.with_traceback(None)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000176 if self.expected_regex is None:
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000177 return True
178
Ezio Melottied3a7d22010-12-01 02:32:32 +0000179 expected_regex = self.expected_regex
180 if not expected_regex.search(str(exc_value)):
Ezio Melottib4dc2502011-05-06 15:01:41 +0300181 self._raiseFailure('"{}" does not match "{}"'.format(
182 expected_regex.pattern, str(exc_value)))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000183 return True
184
185
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000186class _AssertWarnsContext(_AssertRaisesBaseContext):
187 """A context manager used to implement TestCase.assertWarns* methods."""
188
189 def __enter__(self):
190 # The __warningregistry__'s need to be in a pristine state for tests
191 # to work properly.
192 for v in sys.modules.values():
193 if getattr(v, '__warningregistry__', None):
194 v.__warningregistry__ = {}
195 self.warnings_manager = warnings.catch_warnings(record=True)
196 self.warnings = self.warnings_manager.__enter__()
197 warnings.simplefilter("always", self.expected)
198 return self
199
200 def __exit__(self, exc_type, exc_value, tb):
201 self.warnings_manager.__exit__(exc_type, exc_value, tb)
202 if exc_type is not None:
203 # let unexpected exceptions pass through
204 return
205 try:
206 exc_name = self.expected.__name__
207 except AttributeError:
208 exc_name = str(self.expected)
209 first_matching = None
210 for m in self.warnings:
211 w = m.message
212 if not isinstance(w, self.expected):
213 continue
214 if first_matching is None:
215 first_matching = w
Ezio Melottied3a7d22010-12-01 02:32:32 +0000216 if (self.expected_regex is not None and
217 not self.expected_regex.search(str(w))):
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000218 continue
219 # store warning for later retrieval
220 self.warning = w
221 self.filename = m.filename
222 self.lineno = m.lineno
223 return
224 # Now we simply try to choose a helpful failure message
225 if first_matching is not None:
Ezio Melottib4dc2502011-05-06 15:01:41 +0300226 self._raiseFailure('"{}" does not match "{}"'.format(
227 self.expected_regex.pattern, str(first_matching)))
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000228 if self.obj_name:
Ezio Melottib4dc2502011-05-06 15:01:41 +0300229 self._raiseFailure("{} not triggered by {}".format(exc_name,
230 self.obj_name))
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000231 else:
Ezio Melottib4dc2502011-05-06 15:01:41 +0300232 self._raiseFailure("{} not triggered".format(exc_name))
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000233
234
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000235class TestCase(object):
236 """A class whose instances are single test cases.
237
238 By default, the test code itself should be placed in a method named
239 'runTest'.
240
241 If the fixture may be used for many test cases, create as
242 many test methods as are needed. When instantiating such a TestCase
243 subclass, specify in the constructor arguments the name of the test method
244 that the instance is to execute.
245
246 Test authors should subclass TestCase for their own tests. Construction
247 and deconstruction of the test's environment ('fixture') can be
248 implemented by overriding the 'setUp' and 'tearDown' methods respectively.
249
250 If it is necessary to override the __init__ method, the base class
251 __init__ method must always be called. It is important that subclasses
252 should not change the signature of their __init__ method, since instances
253 of the classes are instantiated automatically by parts of the framework
254 in order to be run.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000255
Ezio Melotti31797e52013-03-29 03:42:29 +0200256 When subclassing TestCase, you can set these attributes:
257 * failureException: determines which exception will be raised when
258 the instance's assertion methods fail; test methods raising this
259 exception will be deemed to have 'failed' rather than 'errored'.
260 * longMessage: determines whether long messages (including repr of
261 objects used in assert methods) will be printed on failure in *addition*
262 to any explicit message passed.
263 * maxDiff: sets the maximum length of a diff in failure messages
264 by assert methods using difflib. It is looked up as an instance
265 attribute so can be configured by individual tests if required.
266 """
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000267
268 failureException = AssertionError
269
Michael Foord5074df62010-12-03 00:53:09 +0000270 longMessage = True
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000271
Michael Foord085dfd32010-06-05 12:17:02 +0000272 maxDiff = 80*8
273
Ezio Melottiedd117f2011-04-27 10:20:38 +0300274 # If a string is longer than _diffThreshold, use normal comparison instead
275 # of difflib. See #11763.
276 _diffThreshold = 2**16
277
Benjamin Peterson847a4112010-03-14 15:04:17 +0000278 # Attribute used by TestSuite for classSetUp
279
280 _classSetupFailed = False
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000281
282 def __init__(self, methodName='runTest'):
283 """Create an instance of the class that will use the named test
284 method when executed. Raises a ValueError if the instance does
285 not have a method with the specified name.
286 """
287 self._testMethodName = methodName
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100288 self._outcome = None
Michael Foord32e1d832011-01-03 17:00:11 +0000289 self._testMethodDoc = 'No test'
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000290 try:
291 testMethod = getattr(self, methodName)
292 except AttributeError:
Michael Foord32e1d832011-01-03 17:00:11 +0000293 if methodName != 'runTest':
294 # we allow instantiation with no explicit method name
295 # but not an *incorrect* or missing method name
296 raise ValueError("no such test method in %s: %s" %
297 (self.__class__, methodName))
298 else:
299 self._testMethodDoc = testMethod.__doc__
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000300 self._cleanups = []
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100301 self._subtest = None
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000302
303 # Map types to custom assertEqual functions that will compare
304 # instances of said type in more detail to generate a more useful
305 # error message.
Benjamin Peterson34b2b262011-07-12 19:21:42 -0500306 self._type_equality_funcs = {}
Michael Foord8ca6d982010-11-20 15:34:26 +0000307 self.addTypeEqualityFunc(dict, 'assertDictEqual')
308 self.addTypeEqualityFunc(list, 'assertListEqual')
309 self.addTypeEqualityFunc(tuple, 'assertTupleEqual')
310 self.addTypeEqualityFunc(set, 'assertSetEqual')
311 self.addTypeEqualityFunc(frozenset, 'assertSetEqual')
312 self.addTypeEqualityFunc(str, 'assertMultiLineEqual')
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000313
314 def addTypeEqualityFunc(self, typeobj, function):
315 """Add a type specific assertEqual style function to compare a type.
316
317 This method is for use by TestCase subclasses that need to register
318 their own type equality functions to provide nicer error messages.
319
320 Args:
321 typeobj: The data type to call this function on when both values
322 are of the same type in assertEqual().
323 function: The callable taking two arguments and an optional
324 msg= argument that raises self.failureException with a
325 useful error message when the two arguments are not equal.
326 """
Benjamin Peterson8f326b22009-12-13 02:10:36 +0000327 self._type_equality_funcs[typeobj] = function
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000328
329 def addCleanup(self, function, *args, **kwargs):
330 """Add a function, with arguments, to be called when the test is
331 completed. Functions added are called on a LIFO basis and are
332 called after tearDown on test failure or success.
333
334 Cleanup items are called even if setUp fails (unlike tearDown)."""
335 self._cleanups.append((function, args, kwargs))
336
337 def setUp(self):
338 "Hook method for setting up the test fixture before exercising it."
339 pass
340
341 def tearDown(self):
342 "Hook method for deconstructing the test fixture after testing it."
343 pass
344
Benjamin Peterson847a4112010-03-14 15:04:17 +0000345 @classmethod
346 def setUpClass(cls):
347 "Hook method for setting up class fixture before running tests in the class."
348
349 @classmethod
350 def tearDownClass(cls):
351 "Hook method for deconstructing the class fixture after running all tests in the class."
352
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000353 def countTestCases(self):
354 return 1
355
356 def defaultTestResult(self):
357 return result.TestResult()
358
359 def shortDescription(self):
Michael Foord34c94622010-02-10 15:51:42 +0000360 """Returns a one-line description of the test, or None if no
361 description has been provided.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000362
Michael Foord34c94622010-02-10 15:51:42 +0000363 The default implementation of this method returns the first line of
364 the specified test method's docstring.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000365 """
Michael Foord34c94622010-02-10 15:51:42 +0000366 doc = self._testMethodDoc
367 return doc and doc.split("\n")[0].strip() or None
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000368
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000369
370 def id(self):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000371 return "%s.%s" % (strclass(self.__class__), self._testMethodName)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000372
373 def __eq__(self, other):
374 if type(self) is not type(other):
375 return NotImplemented
376
377 return self._testMethodName == other._testMethodName
378
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000379 def __hash__(self):
380 return hash((type(self), self._testMethodName))
381
382 def __str__(self):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000383 return "%s (%s)" % (self._testMethodName, strclass(self.__class__))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000384
385 def __repr__(self):
386 return "<%s testMethod=%s>" % \
Benjamin Peterson847a4112010-03-14 15:04:17 +0000387 (strclass(self.__class__), self._testMethodName)
388
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100389 def _addSkip(self, result, test_case, reason):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000390 addSkip = getattr(result, 'addSkip', None)
391 if addSkip is not None:
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100392 addSkip(test_case, reason)
Benjamin Peterson847a4112010-03-14 15:04:17 +0000393 else:
394 warnings.warn("TestResult has no addSkip method, skips not reported",
395 RuntimeWarning, 2)
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100396 result.addSuccess(test_case)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000397
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100398 @contextlib.contextmanager
399 def subTest(self, msg=None, **params):
400 """Return a context manager that will return the enclosed block
401 of code in a subtest identified by the optional message and
402 keyword parameters. A failure in the subtest marks the test
403 case as failed but resumes execution at the end of the enclosed
404 block, allowing further test code to be executed.
405 """
406 if not self._outcome.result_supports_subtests:
407 yield
408 return
409 parent = self._subtest
410 if parent is None:
411 params_map = collections.ChainMap(params)
412 else:
413 params_map = parent.params.new_child(params)
414 self._subtest = _SubTest(self, msg, params_map)
Michael Foordb3468f72010-12-19 03:19:47 +0000415 try:
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100416 with self._outcome.testPartExecutor(self._subtest, isTest=True):
417 yield
418 if not self._outcome.success:
419 result = self._outcome.result
420 if result is not None and result.failfast:
421 raise _ShouldStop
422 elif self._outcome.expectedFailure:
423 # If the test is expecting a failure, we really want to
424 # stop now and register the expected failure.
425 raise _ShouldStop
426 finally:
427 self._subtest = parent
428
429 def _feedErrorsToResult(self, result, errors):
430 for test, exc_info in errors:
431 if isinstance(test, _SubTest):
432 result.addSubTest(test.test_case, test, exc_info)
433 elif exc_info is not None:
434 if issubclass(exc_info[0], self.failureException):
435 result.addFailure(test, exc_info)
436 else:
437 result.addError(test, exc_info)
438
439 def _addExpectedFailure(self, result, exc_info):
440 try:
441 addExpectedFailure = result.addExpectedFailure
442 except AttributeError:
443 warnings.warn("TestResult has no addExpectedFailure method, reporting as passes",
444 RuntimeWarning)
445 result.addSuccess(self)
446 else:
447 addExpectedFailure(self, exc_info)
448
449 def _addUnexpectedSuccess(self, result):
450 try:
451 addUnexpectedSuccess = result.addUnexpectedSuccess
452 except AttributeError:
453 warnings.warn("TestResult has no addUnexpectedSuccess method, reporting as failure",
454 RuntimeWarning)
455 # We need to pass an actual exception and traceback to addFailure,
456 # otherwise the legacy result can choke.
457 try:
458 raise _UnexpectedSuccess from None
459 except _UnexpectedSuccess:
460 result.addFailure(self, sys.exc_info())
461 else:
462 addUnexpectedSuccess(self)
Michael Foordb3468f72010-12-19 03:19:47 +0000463
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000464 def run(self, result=None):
465 orig_result = result
466 if result is None:
467 result = self.defaultTestResult()
468 startTestRun = getattr(result, 'startTestRun', None)
469 if startTestRun is not None:
470 startTestRun()
471
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000472 result.startTest(self)
Benjamin Peterson847a4112010-03-14 15:04:17 +0000473
474 testMethod = getattr(self, self._testMethodName)
475 if (getattr(self.__class__, "__unittest_skip__", False) or
476 getattr(testMethod, "__unittest_skip__", False)):
477 # If the class or method was skipped.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000478 try:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000479 skip_why = (getattr(self.__class__, '__unittest_skip_why__', '')
480 or getattr(testMethod, '__unittest_skip_why__', ''))
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100481 self._addSkip(result, self, skip_why)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000482 finally:
483 result.stopTest(self)
484 return
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100485 expecting_failure = getattr(testMethod,
486 "__unittest_expecting_failure__", False)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000487 try:
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100488 outcome = _Outcome(result)
489 self._outcome = outcome
Michael Foordb3468f72010-12-19 03:19:47 +0000490
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100491 with outcome.testPartExecutor(self):
492 self.setUp()
Michael Foordb3468f72010-12-19 03:19:47 +0000493 if outcome.success:
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100494 outcome.expecting_failure = expecting_failure
495 with outcome.testPartExecutor(self, isTest=True):
496 testMethod()
497 outcome.expecting_failure = False
498 with outcome.testPartExecutor(self):
499 self.tearDown()
Michael Foordb3468f72010-12-19 03:19:47 +0000500
501 self.doCleanups()
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100502 for test, reason in outcome.skipped:
503 self._addSkip(result, test, reason)
504 self._feedErrorsToResult(result, outcome.errors)
Michael Foordb3468f72010-12-19 03:19:47 +0000505 if outcome.success:
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100506 if expecting_failure:
507 if outcome.expectedFailure:
508 self._addExpectedFailure(result, outcome.expectedFailure)
Benjamin Peterson847a4112010-03-14 15:04:17 +0000509 else:
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100510 self._addUnexpectedSuccess(result)
511 else:
512 result.addSuccess(self)
Michael Foord1341bb02011-03-14 19:01:46 -0400513 return result
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000514 finally:
515 result.stopTest(self)
516 if orig_result is None:
517 stopTestRun = getattr(result, 'stopTestRun', None)
518 if stopTestRun is not None:
519 stopTestRun()
520
521 def doCleanups(self):
522 """Execute all cleanup functions. Normally called for you after
523 tearDown."""
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100524 outcome = self._outcome or _Outcome()
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000525 while self._cleanups:
Michael Foordb3468f72010-12-19 03:19:47 +0000526 function, args, kwargs = self._cleanups.pop()
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +0100527 with outcome.testPartExecutor(self):
528 function(*args, **kwargs)
Michael Foordb3468f72010-12-19 03:19:47 +0000529
530 # return this for backwards compatibility
531 # even though we no longer us it internally
532 return outcome.success
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000533
534 def __call__(self, *args, **kwds):
535 return self.run(*args, **kwds)
536
537 def debug(self):
538 """Run the test without collecting errors in a TestResult"""
539 self.setUp()
540 getattr(self, self._testMethodName)()
541 self.tearDown()
Michael Foordb8748742010-06-10 16:16:08 +0000542 while self._cleanups:
543 function, args, kwargs = self._cleanups.pop(-1)
544 function(*args, **kwargs)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000545
546 def skipTest(self, reason):
547 """Skip this test."""
548 raise SkipTest(reason)
549
550 def fail(self, msg=None):
551 """Fail immediately, with the given message."""
552 raise self.failureException(msg)
553
554 def assertFalse(self, expr, msg=None):
Ezio Melotti3044fa72010-12-18 17:31:58 +0000555 """Check that the expression is false."""
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000556 if expr:
Ezio Melotti3044fa72010-12-18 17:31:58 +0000557 msg = self._formatMessage(msg, "%s is not false" % safe_repr(expr))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000558 raise self.failureException(msg)
559
560 def assertTrue(self, expr, msg=None):
Ezio Melotti3044fa72010-12-18 17:31:58 +0000561 """Check that the expression is true."""
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000562 if not expr:
Ezio Melotti3044fa72010-12-18 17:31:58 +0000563 msg = self._formatMessage(msg, "%s is not true" % safe_repr(expr))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000564 raise self.failureException(msg)
565
566 def _formatMessage(self, msg, standardMsg):
567 """Honour the longMessage attribute when generating failure messages.
568 If longMessage is False this means:
569 * Use only an explicit message if it is provided
570 * Otherwise use the standard message for the assert
571
572 If longMessage is True:
573 * Use the standard message
574 * If an explicit message is provided, plus ' : ' and the explicit message
575 """
576 if not self.longMessage:
577 return msg or standardMsg
578 if msg is None:
579 return standardMsg
Benjamin Peterson847a4112010-03-14 15:04:17 +0000580 try:
581 # don't switch to '{}' formatting in Python 2.X
582 # it changes the way unicode input is handled
583 return '%s : %s' % (standardMsg, msg)
584 except UnicodeDecodeError:
585 return '%s : %s' % (safe_repr(standardMsg), safe_repr(msg))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000586
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000587 def assertRaises(self, excClass, callableObj=None, *args, **kwargs):
Andrew Svetlov737fb892012-12-18 21:14:22 +0200588 """Fail unless an exception of class excClass is raised
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000589 by callableObj when invoked with arguments args and keyword
590 arguments kwargs. If a different type of exception is
Andrew Svetlov737fb892012-12-18 21:14:22 +0200591 raised, it will not be caught, and the test case will be
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000592 deemed to have suffered an error, exactly as for an
593 unexpected exception.
594
595 If called with callableObj omitted or None, will return a
596 context object used like this::
597
Michael Foord1c42b122010-02-05 22:58:21 +0000598 with self.assertRaises(SomeException):
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000599 do_something()
Michael Foord1c42b122010-02-05 22:58:21 +0000600
Ezio Melottib4dc2502011-05-06 15:01:41 +0300601 An optional keyword argument 'msg' can be provided when assertRaises
602 is used as a context object.
603
Michael Foord1c42b122010-02-05 22:58:21 +0000604 The context manager keeps a reference to the exception as
Ezio Melotti49008232010-02-08 21:57:48 +0000605 the 'exception' attribute. This allows you to inspect the
Michael Foord1c42b122010-02-05 22:58:21 +0000606 exception after the assertion::
607
608 with self.assertRaises(SomeException) as cm:
609 do_something()
Ezio Melotti49008232010-02-08 21:57:48 +0000610 the_exception = cm.exception
Michael Foordb57ac6d2010-02-05 23:26:29 +0000611 self.assertEqual(the_exception.error_code, 3)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000612 """
613 context = _AssertRaisesContext(excClass, self, callableObj)
Ezio Melottib4dc2502011-05-06 15:01:41 +0300614 return context.handle('assertRaises', callableObj, args, kwargs)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000615
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000616 def assertWarns(self, expected_warning, callable_obj=None, *args, **kwargs):
617 """Fail unless a warning of class warnClass is triggered
Ezio Melottib4dc2502011-05-06 15:01:41 +0300618 by callable_obj when invoked with arguments args and keyword
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000619 arguments kwargs. If a different type of warning is
620 triggered, it will not be handled: depending on the other
621 warning filtering rules in effect, it might be silenced, printed
622 out, or raised as an exception.
623
Ezio Melottib4dc2502011-05-06 15:01:41 +0300624 If called with callable_obj omitted or None, will return a
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000625 context object used like this::
626
627 with self.assertWarns(SomeWarning):
628 do_something()
629
Ezio Melottib4dc2502011-05-06 15:01:41 +0300630 An optional keyword argument 'msg' can be provided when assertWarns
631 is used as a context object.
632
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000633 The context manager keeps a reference to the first matching
634 warning as the 'warning' attribute; similarly, the 'filename'
635 and 'lineno' attributes give you information about the line
636 of Python code from which the warning was triggered.
637 This allows you to inspect the warning after the assertion::
638
639 with self.assertWarns(SomeWarning) as cm:
640 do_something()
641 the_warning = cm.warning
642 self.assertEqual(the_warning.some_attribute, 147)
643 """
644 context = _AssertWarnsContext(expected_warning, self, callable_obj)
Ezio Melottib4dc2502011-05-06 15:01:41 +0300645 return context.handle('assertWarns', callable_obj, args, kwargs)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +0000646
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000647 def _getAssertEqualityFunc(self, first, second):
648 """Get a detailed comparison function for the types of the two args.
649
650 Returns: A callable accepting (first, second, msg=None) that will
651 raise a failure exception if first != second with a useful human
652 readable error message for those types.
653 """
654 #
655 # NOTE(gregory.p.smith): I considered isinstance(first, type(second))
656 # and vice versa. I opted for the conservative approach in case
657 # subclasses are not intended to be compared in detail to their super
658 # class instances using a type equality func. This means testing
659 # subtypes won't automagically use the detailed comparison. Callers
660 # should use their type specific assertSpamEqual method to compare
661 # subclasses if the detailed comparison is desired and appropriate.
662 # See the discussion in http://bugs.python.org/issue2578.
663 #
664 if type(first) is type(second):
665 asserter = self._type_equality_funcs.get(type(first))
666 if asserter is not None:
Benjamin Peterson34b2b262011-07-12 19:21:42 -0500667 if isinstance(asserter, str):
668 asserter = getattr(self, asserter)
Benjamin Peterson8f326b22009-12-13 02:10:36 +0000669 return asserter
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000670
671 return self._baseAssertEqual
672
673 def _baseAssertEqual(self, first, second, msg=None):
674 """The default assertEqual implementation, not type specific."""
675 if not first == second:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000676 standardMsg = '%s != %s' % (safe_repr(first), safe_repr(second))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000677 msg = self._formatMessage(msg, standardMsg)
678 raise self.failureException(msg)
679
680 def assertEqual(self, first, second, msg=None):
681 """Fail if the two objects are unequal as determined by the '=='
682 operator.
683 """
684 assertion_func = self._getAssertEqualityFunc(first, second)
685 assertion_func(first, second, msg=msg)
686
687 def assertNotEqual(self, first, second, msg=None):
Ezio Melotti90eea972012-11-08 11:08:39 +0200688 """Fail if the two objects are equal as determined by the '!='
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000689 operator.
690 """
691 if not first != second:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000692 msg = self._formatMessage(msg, '%s == %s' % (safe_repr(first),
693 safe_repr(second)))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000694 raise self.failureException(msg)
695
Michael Foord321d0592010-11-02 13:44:51 +0000696 def assertAlmostEqual(self, first, second, places=None, msg=None,
Benjamin Petersonb48af542010-04-11 20:43:16 +0000697 delta=None):
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000698 """Fail if the two objects are unequal as determined by their
699 difference rounded to the given number of decimal places
Benjamin Petersonb48af542010-04-11 20:43:16 +0000700 (default 7) and comparing to zero, or by comparing that the
701 between the two objects is more than the given delta.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000702
703 Note that decimal places (from zero) are usually not the same
704 as significant digits (measured from the most signficant digit).
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000705
706 If the two objects compare equal then they will automatically
707 compare almost equal.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000708 """
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000709 if first == second:
Benjamin Petersonb48af542010-04-11 20:43:16 +0000710 # shortcut
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000711 return
Benjamin Petersonb48af542010-04-11 20:43:16 +0000712 if delta is not None and places is not None:
713 raise TypeError("specify delta or places not both")
714
715 if delta is not None:
716 if abs(first - second) <= delta:
717 return
718
719 standardMsg = '%s != %s within %s delta' % (safe_repr(first),
720 safe_repr(second),
721 safe_repr(delta))
722 else:
723 if places is None:
724 places = 7
725
726 if round(abs(second-first), places) == 0:
727 return
728
Benjamin Peterson847a4112010-03-14 15:04:17 +0000729 standardMsg = '%s != %s within %r places' % (safe_repr(first),
730 safe_repr(second),
731 places)
Benjamin Petersonb48af542010-04-11 20:43:16 +0000732 msg = self._formatMessage(msg, standardMsg)
733 raise self.failureException(msg)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000734
Michael Foord321d0592010-11-02 13:44:51 +0000735 def assertNotAlmostEqual(self, first, second, places=None, msg=None,
Benjamin Petersonb48af542010-04-11 20:43:16 +0000736 delta=None):
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000737 """Fail if the two objects are equal as determined by their
738 difference rounded to the given number of decimal places
Benjamin Petersonb48af542010-04-11 20:43:16 +0000739 (default 7) and comparing to zero, or by comparing that the
740 between the two objects is less than the given delta.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000741
742 Note that decimal places (from zero) are usually not the same
743 as significant digits (measured from the most signficant digit).
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000744
745 Objects that are equal automatically fail.
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000746 """
Benjamin Petersonb48af542010-04-11 20:43:16 +0000747 if delta is not None and places is not None:
748 raise TypeError("specify delta or places not both")
749 if delta is not None:
750 if not (first == second) and abs(first - second) > delta:
751 return
752 standardMsg = '%s == %s within %s delta' % (safe_repr(first),
753 safe_repr(second),
754 safe_repr(delta))
755 else:
756 if places is None:
757 places = 7
758 if not (first == second) and round(abs(second-first), places) != 0:
759 return
Benjamin Peterson847a4112010-03-14 15:04:17 +0000760 standardMsg = '%s == %s within %r places' % (safe_repr(first),
Benjamin Petersonb48af542010-04-11 20:43:16 +0000761 safe_repr(second),
762 places)
763
764 msg = self._formatMessage(msg, standardMsg)
765 raise self.failureException(msg)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000766
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000767
Michael Foord085dfd32010-06-05 12:17:02 +0000768 def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000769 """An equality assertion for ordered sequences (like lists and tuples).
770
R. David Murrayad13f222010-01-29 22:17:58 +0000771 For the purposes of this function, a valid ordered sequence type is one
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000772 which can be indexed, has a length, and has an equality operator.
773
774 Args:
775 seq1: The first sequence to compare.
776 seq2: The second sequence to compare.
777 seq_type: The expected datatype of the sequences, or None if no
778 datatype should be enforced.
779 msg: Optional message to use on failure instead of a list of
780 differences.
781 """
Benjamin Petersonb29614e2012-10-09 11:16:03 -0400782 if seq_type is not None:
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000783 seq_type_name = seq_type.__name__
784 if not isinstance(seq1, seq_type):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000785 raise self.failureException('First sequence is not a %s: %s'
786 % (seq_type_name, safe_repr(seq1)))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000787 if not isinstance(seq2, seq_type):
Benjamin Peterson847a4112010-03-14 15:04:17 +0000788 raise self.failureException('Second sequence is not a %s: %s'
789 % (seq_type_name, safe_repr(seq2)))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000790 else:
791 seq_type_name = "sequence"
792
793 differing = None
794 try:
795 len1 = len(seq1)
796 except (TypeError, NotImplementedError):
797 differing = 'First %s has no length. Non-sequence?' % (
798 seq_type_name)
799
800 if differing is None:
801 try:
802 len2 = len(seq2)
803 except (TypeError, NotImplementedError):
804 differing = 'Second %s has no length. Non-sequence?' % (
805 seq_type_name)
806
807 if differing is None:
808 if seq1 == seq2:
809 return
810
Benjamin Peterson847a4112010-03-14 15:04:17 +0000811 seq1_repr = safe_repr(seq1)
812 seq2_repr = safe_repr(seq2)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000813 if len(seq1_repr) > 30:
814 seq1_repr = seq1_repr[:30] + '...'
815 if len(seq2_repr) > 30:
816 seq2_repr = seq2_repr[:30] + '...'
817 elements = (seq_type_name.capitalize(), seq1_repr, seq2_repr)
818 differing = '%ss differ: %s != %s\n' % elements
819
820 for i in range(min(len1, len2)):
821 try:
822 item1 = seq1[i]
823 except (TypeError, IndexError, NotImplementedError):
824 differing += ('\nUnable to index element %d of first %s\n' %
825 (i, seq_type_name))
826 break
827
828 try:
829 item2 = seq2[i]
830 except (TypeError, IndexError, NotImplementedError):
831 differing += ('\nUnable to index element %d of second %s\n' %
832 (i, seq_type_name))
833 break
834
835 if item1 != item2:
836 differing += ('\nFirst differing element %d:\n%s\n%s\n' %
837 (i, item1, item2))
838 break
839 else:
840 if (len1 == len2 and seq_type is None and
841 type(seq1) != type(seq2)):
842 # The sequences are the same, but have differing types.
843 return
844
845 if len1 > len2:
846 differing += ('\nFirst %s contains %d additional '
847 'elements.\n' % (seq_type_name, len1 - len2))
848 try:
849 differing += ('First extra element %d:\n%s\n' %
850 (len2, seq1[len2]))
851 except (TypeError, IndexError, NotImplementedError):
852 differing += ('Unable to index element %d '
853 'of first %s\n' % (len2, seq_type_name))
854 elif len1 < len2:
855 differing += ('\nSecond %s contains %d additional '
856 'elements.\n' % (seq_type_name, len2 - len1))
857 try:
858 differing += ('First extra element %d:\n%s\n' %
859 (len1, seq2[len1]))
860 except (TypeError, IndexError, NotImplementedError):
861 differing += ('Unable to index element %d '
862 'of second %s\n' % (len1, seq_type_name))
Michael Foord2034d9a2010-06-05 11:27:52 +0000863 standardMsg = differing
864 diffMsg = '\n' + '\n'.join(
Benjamin Peterson6e8c7572009-10-04 20:19:21 +0000865 difflib.ndiff(pprint.pformat(seq1).splitlines(),
866 pprint.pformat(seq2).splitlines()))
Michael Foord085dfd32010-06-05 12:17:02 +0000867
868 standardMsg = self._truncateMessage(standardMsg, diffMsg)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000869 msg = self._formatMessage(msg, standardMsg)
870 self.fail(msg)
871
Michael Foord085dfd32010-06-05 12:17:02 +0000872 def _truncateMessage(self, message, diff):
873 max_diff = self.maxDiff
874 if max_diff is None or len(diff) <= max_diff:
875 return message + diff
Michael Foord9dad32e2010-06-05 13:49:56 +0000876 return message + (DIFF_OMITTED % len(diff))
Michael Foord085dfd32010-06-05 12:17:02 +0000877
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000878 def assertListEqual(self, list1, list2, msg=None):
879 """A list-specific equality assertion.
880
881 Args:
882 list1: The first list to compare.
883 list2: The second list to compare.
884 msg: Optional message to use on failure instead of a list of
885 differences.
886
887 """
888 self.assertSequenceEqual(list1, list2, msg, seq_type=list)
889
890 def assertTupleEqual(self, tuple1, tuple2, msg=None):
891 """A tuple-specific equality assertion.
892
893 Args:
894 tuple1: The first tuple to compare.
895 tuple2: The second tuple to compare.
896 msg: Optional message to use on failure instead of a list of
897 differences.
898 """
899 self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
900
901 def assertSetEqual(self, set1, set2, msg=None):
902 """A set-specific equality assertion.
903
904 Args:
905 set1: The first set to compare.
906 set2: The second set to compare.
907 msg: Optional message to use on failure instead of a list of
908 differences.
909
Michael Foord91c9da32010-03-20 17:21:27 +0000910 assertSetEqual uses ducktyping to support different types of sets, and
911 is optimized for sets specifically (parameters must support a
912 difference method).
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000913 """
914 try:
915 difference1 = set1.difference(set2)
916 except TypeError as e:
917 self.fail('invalid type when attempting set difference: %s' % e)
918 except AttributeError as e:
919 self.fail('first argument does not support set difference: %s' % e)
920
921 try:
922 difference2 = set2.difference(set1)
923 except TypeError as e:
924 self.fail('invalid type when attempting set difference: %s' % e)
925 except AttributeError as e:
926 self.fail('second argument does not support set difference: %s' % e)
927
928 if not (difference1 or difference2):
929 return
930
931 lines = []
932 if difference1:
933 lines.append('Items in the first set but not the second:')
934 for item in difference1:
935 lines.append(repr(item))
936 if difference2:
937 lines.append('Items in the second set but not the first:')
938 for item in difference2:
939 lines.append(repr(item))
940
941 standardMsg = '\n'.join(lines)
942 self.fail(self._formatMessage(msg, standardMsg))
943
944 def assertIn(self, member, container, msg=None):
945 """Just like self.assertTrue(a in b), but with a nicer default message."""
946 if member not in container:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000947 standardMsg = '%s not found in %s' % (safe_repr(member),
948 safe_repr(container))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000949 self.fail(self._formatMessage(msg, standardMsg))
950
951 def assertNotIn(self, member, container, msg=None):
952 """Just like self.assertTrue(a not in b), but with a nicer default message."""
953 if member in container:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000954 standardMsg = '%s unexpectedly found in %s' % (safe_repr(member),
955 safe_repr(container))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000956 self.fail(self._formatMessage(msg, standardMsg))
957
958 def assertIs(self, expr1, expr2, msg=None):
959 """Just like self.assertTrue(a is b), but with a nicer default message."""
960 if expr1 is not expr2:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000961 standardMsg = '%s is not %s' % (safe_repr(expr1),
962 safe_repr(expr2))
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000963 self.fail(self._formatMessage(msg, standardMsg))
964
965 def assertIsNot(self, expr1, expr2, msg=None):
966 """Just like self.assertTrue(a is not b), but with a nicer default message."""
967 if expr1 is expr2:
Benjamin Peterson847a4112010-03-14 15:04:17 +0000968 standardMsg = 'unexpectedly identical: %s' % (safe_repr(expr1),)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000969 self.fail(self._formatMessage(msg, standardMsg))
970
971 def assertDictEqual(self, d1, d2, msg=None):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000972 self.assertIsInstance(d1, dict, 'First argument is not a dictionary')
973 self.assertIsInstance(d2, dict, 'Second argument is not a dictionary')
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000974
975 if d1 != d2:
Michael Foordcb11b252010-06-05 13:14:43 +0000976 standardMsg = '%s != %s' % (safe_repr(d1, True), safe_repr(d2, True))
Michael Foord085dfd32010-06-05 12:17:02 +0000977 diff = ('\n' + '\n'.join(difflib.ndiff(
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000978 pprint.pformat(d1).splitlines(),
979 pprint.pformat(d2).splitlines())))
Michael Foordcb11b252010-06-05 13:14:43 +0000980 standardMsg = self._truncateMessage(standardMsg, diff)
Benjamin Petersonbed7d042009-07-19 21:01:52 +0000981 self.fail(self._formatMessage(msg, standardMsg))
982
Ezio Melotti0f535012011-04-03 18:02:13 +0300983 def assertDictContainsSubset(self, subset, dictionary, msg=None):
984 """Checks whether dictionary is a superset of subset."""
985 warnings.warn('assertDictContainsSubset is deprecated',
986 DeprecationWarning)
987 missing = []
988 mismatched = []
989 for key, value in subset.items():
990 if key not in dictionary:
991 missing.append(key)
992 elif value != dictionary[key]:
993 mismatched.append('%s, expected: %s, actual: %s' %
994 (safe_repr(key), safe_repr(value),
995 safe_repr(dictionary[key])))
996
997 if not (missing or mismatched):
998 return
999
1000 standardMsg = ''
1001 if missing:
1002 standardMsg = 'Missing: %s' % ','.join(safe_repr(m) for m in
1003 missing)
1004 if mismatched:
1005 if standardMsg:
1006 standardMsg += '; '
1007 standardMsg += 'Mismatched values: %s' % ','.join(mismatched)
1008
1009 self.fail(self._formatMessage(msg, standardMsg))
1010
1011
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001012 def assertCountEqual(self, first, second, msg=None):
1013 """An unordered sequence comparison asserting that the same elements,
1014 regardless of order. If the same element occurs more than once,
1015 it verifies that the elements occur the same number of times.
Michael Foord8442a602010-03-20 16:58:04 +00001016
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001017 self.assertEqual(Counter(list(first)),
1018 Counter(list(second)))
Michael Foord8442a602010-03-20 16:58:04 +00001019
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001020 Example:
Michael Foord8442a602010-03-20 16:58:04 +00001021 - [0, 1, 1] and [1, 0, 1] compare equal.
1022 - [0, 0, 1] and [0, 1] compare unequal.
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001023
Michael Foord8442a602010-03-20 16:58:04 +00001024 """
Michael Foorde180d392011-01-28 19:51:48 +00001025 first_seq, second_seq = list(first), list(second)
Michael Foord8442a602010-03-20 16:58:04 +00001026 try:
Michael Foorde180d392011-01-28 19:51:48 +00001027 first = collections.Counter(first_seq)
1028 second = collections.Counter(second_seq)
Michael Foord8442a602010-03-20 16:58:04 +00001029 except TypeError:
Raymond Hettinger6518f5e2010-12-24 00:52:54 +00001030 # Handle case with unhashable elements
Michael Foorde180d392011-01-28 19:51:48 +00001031 differences = _count_diff_all_purpose(first_seq, second_seq)
Michael Foord8442a602010-03-20 16:58:04 +00001032 else:
Michael Foorde180d392011-01-28 19:51:48 +00001033 if first == second:
Raymond Hettinger6e165b32010-11-27 09:31:37 +00001034 return
Michael Foorde180d392011-01-28 19:51:48 +00001035 differences = _count_diff_hashable(first_seq, second_seq)
Michael Foord8442a602010-03-20 16:58:04 +00001036
Raymond Hettinger93e233d2010-12-24 10:02:22 +00001037 if differences:
1038 standardMsg = 'Element counts were not equal:\n'
Raymond Hettinger57bd00a2010-12-24 21:51:48 +00001039 lines = ['First has %d, Second has %d: %r' % diff for diff in differences]
Raymond Hettinger93e233d2010-12-24 10:02:22 +00001040 diffMsg = '\n'.join(lines)
1041 standardMsg = self._truncateMessage(standardMsg, diffMsg)
1042 msg = self._formatMessage(msg, standardMsg)
1043 self.fail(msg)
Michael Foord8442a602010-03-20 16:58:04 +00001044
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001045 def assertMultiLineEqual(self, first, second, msg=None):
1046 """Assert that two multi-line strings are equal."""
Ezio Melottib3aedd42010-11-20 19:04:17 +00001047 self.assertIsInstance(first, str, 'First argument is not a string')
1048 self.assertIsInstance(second, str, 'Second argument is not a string')
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001049
1050 if first != second:
Ezio Melottiedd117f2011-04-27 10:20:38 +03001051 # don't use difflib if the strings are too long
1052 if (len(first) > self._diffThreshold or
1053 len(second) > self._diffThreshold):
1054 self._baseAssertEqual(first, second, msg)
Ezio Melottid8b509b2011-09-28 17:37:55 +03001055 firstlines = first.splitlines(keepends=True)
1056 secondlines = second.splitlines(keepends=True)
Michael Foordc653ce32010-07-10 13:52:22 +00001057 if len(firstlines) == 1 and first.strip('\r\n') == first:
1058 firstlines = [first + '\n']
1059 secondlines = [second + '\n']
1060 standardMsg = '%s != %s' % (safe_repr(first, True),
1061 safe_repr(second, True))
1062 diff = '\n' + ''.join(difflib.ndiff(firstlines, secondlines))
Michael Foordcb11b252010-06-05 13:14:43 +00001063 standardMsg = self._truncateMessage(standardMsg, diff)
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001064 self.fail(self._formatMessage(msg, standardMsg))
1065
1066 def assertLess(self, a, b, msg=None):
1067 """Just like self.assertTrue(a < b), but with a nicer default message."""
1068 if not a < b:
Benjamin Peterson847a4112010-03-14 15:04:17 +00001069 standardMsg = '%s not less than %s' % (safe_repr(a), safe_repr(b))
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001070 self.fail(self._formatMessage(msg, standardMsg))
1071
1072 def assertLessEqual(self, a, b, msg=None):
1073 """Just like self.assertTrue(a <= b), but with a nicer default message."""
1074 if not a <= b:
Benjamin Peterson847a4112010-03-14 15:04:17 +00001075 standardMsg = '%s not less than or equal to %s' % (safe_repr(a), safe_repr(b))
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001076 self.fail(self._formatMessage(msg, standardMsg))
1077
1078 def assertGreater(self, a, b, msg=None):
1079 """Just like self.assertTrue(a > b), but with a nicer default message."""
1080 if not a > b:
Benjamin Peterson847a4112010-03-14 15:04:17 +00001081 standardMsg = '%s not greater than %s' % (safe_repr(a), safe_repr(b))
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001082 self.fail(self._formatMessage(msg, standardMsg))
1083
1084 def assertGreaterEqual(self, a, b, msg=None):
1085 """Just like self.assertTrue(a >= b), but with a nicer default message."""
1086 if not a >= b:
Benjamin Peterson847a4112010-03-14 15:04:17 +00001087 standardMsg = '%s not greater than or equal to %s' % (safe_repr(a), safe_repr(b))
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001088 self.fail(self._formatMessage(msg, standardMsg))
1089
1090 def assertIsNone(self, obj, msg=None):
1091 """Same as self.assertTrue(obj is None), with a nicer default message."""
1092 if obj is not None:
Benjamin Peterson847a4112010-03-14 15:04:17 +00001093 standardMsg = '%s is not None' % (safe_repr(obj),)
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001094 self.fail(self._formatMessage(msg, standardMsg))
1095
1096 def assertIsNotNone(self, obj, msg=None):
1097 """Included for symmetry with assertIsNone."""
1098 if obj is None:
1099 standardMsg = 'unexpectedly None'
1100 self.fail(self._formatMessage(msg, standardMsg))
1101
Benjamin Peterson6e8c7572009-10-04 20:19:21 +00001102 def assertIsInstance(self, obj, cls, msg=None):
1103 """Same as self.assertTrue(isinstance(obj, cls)), with a nicer
1104 default message."""
1105 if not isinstance(obj, cls):
Benjamin Peterson847a4112010-03-14 15:04:17 +00001106 standardMsg = '%s is not an instance of %r' % (safe_repr(obj), cls)
Benjamin Peterson6e8c7572009-10-04 20:19:21 +00001107 self.fail(self._formatMessage(msg, standardMsg))
1108
1109 def assertNotIsInstance(self, obj, cls, msg=None):
1110 """Included for symmetry with assertIsInstance."""
1111 if isinstance(obj, cls):
Benjamin Peterson847a4112010-03-14 15:04:17 +00001112 standardMsg = '%s is an instance of %r' % (safe_repr(obj), cls)
Benjamin Peterson6e8c7572009-10-04 20:19:21 +00001113 self.fail(self._formatMessage(msg, standardMsg))
1114
Ezio Melottied3a7d22010-12-01 02:32:32 +00001115 def assertRaisesRegex(self, expected_exception, expected_regex,
1116 callable_obj=None, *args, **kwargs):
1117 """Asserts that the message in a raised exception matches a regex.
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001118
1119 Args:
1120 expected_exception: Exception class expected to be raised.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001121 expected_regex: Regex (re pattern object or string) expected
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001122 to be found in error message.
1123 callable_obj: Function to be called.
Ezio Melottib4dc2502011-05-06 15:01:41 +03001124 msg: Optional message used in case of failure. Can only be used
1125 when assertRaisesRegex is used as a context manager.
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001126 args: Extra args.
1127 kwargs: Extra kwargs.
1128 """
1129 context = _AssertRaisesContext(expected_exception, self, callable_obj,
Ezio Melottied3a7d22010-12-01 02:32:32 +00001130 expected_regex)
Ezio Melottib4dc2502011-05-06 15:01:41 +03001131
1132 return context.handle('assertRaisesRegex', callable_obj, args, kwargs)
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001133
Ezio Melottied3a7d22010-12-01 02:32:32 +00001134 def assertWarnsRegex(self, expected_warning, expected_regex,
1135 callable_obj=None, *args, **kwargs):
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001136 """Asserts that the message in a triggered warning matches a regexp.
1137 Basic functioning is similar to assertWarns() with the addition
1138 that only warnings whose messages also match the regular expression
1139 are considered successful matches.
1140
1141 Args:
1142 expected_warning: Warning class expected to be triggered.
Ezio Melottied3a7d22010-12-01 02:32:32 +00001143 expected_regex: Regex (re pattern object or string) expected
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001144 to be found in error message.
1145 callable_obj: Function to be called.
Ezio Melottib4dc2502011-05-06 15:01:41 +03001146 msg: Optional message used in case of failure. Can only be used
1147 when assertWarnsRegex is used as a context manager.
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001148 args: Extra args.
1149 kwargs: Extra kwargs.
1150 """
1151 context = _AssertWarnsContext(expected_warning, self, callable_obj,
Ezio Melottied3a7d22010-12-01 02:32:32 +00001152 expected_regex)
Ezio Melottib4dc2502011-05-06 15:01:41 +03001153 return context.handle('assertWarnsRegex', callable_obj, args, kwargs)
Antoine Pitrou4bc12ef2010-09-06 19:25:46 +00001154
Ezio Melottied3a7d22010-12-01 02:32:32 +00001155 def assertRegex(self, text, expected_regex, msg=None):
Michael Foorde3ef5f12010-05-08 16:46:14 +00001156 """Fail the test unless the text matches the regular expression."""
Ezio Melottied3a7d22010-12-01 02:32:32 +00001157 if isinstance(expected_regex, (str, bytes)):
Gregory P. Smithed16bf42010-12-16 19:23:05 +00001158 assert expected_regex, "expected_regex must not be empty."
Ezio Melottied3a7d22010-12-01 02:32:32 +00001159 expected_regex = re.compile(expected_regex)
1160 if not expected_regex.search(text):
1161 msg = msg or "Regex didn't match"
1162 msg = '%s: %r not found in %r' % (msg, expected_regex.pattern, text)
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001163 raise self.failureException(msg)
1164
Ezio Melotti8f776302010-12-10 02:32:05 +00001165 def assertNotRegex(self, text, unexpected_regex, msg=None):
Michael Foorde3ef5f12010-05-08 16:46:14 +00001166 """Fail the test if the text matches the regular expression."""
Ezio Melottied3a7d22010-12-01 02:32:32 +00001167 if isinstance(unexpected_regex, (str, bytes)):
1168 unexpected_regex = re.compile(unexpected_regex)
1169 match = unexpected_regex.search(text)
Benjamin Petersonb48af542010-04-11 20:43:16 +00001170 if match:
Ezio Melottied3a7d22010-12-01 02:32:32 +00001171 msg = msg or "Regex matched"
Benjamin Petersonb48af542010-04-11 20:43:16 +00001172 msg = '%s: %r matches %r in %r' % (msg,
1173 text[match.start():match.end()],
Ezio Melottied3a7d22010-12-01 02:32:32 +00001174 unexpected_regex.pattern,
Benjamin Petersonb48af542010-04-11 20:43:16 +00001175 text)
1176 raise self.failureException(msg)
1177
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001178
Ezio Melottied3a7d22010-12-01 02:32:32 +00001179 def _deprecate(original_func):
1180 def deprecated_func(*args, **kwargs):
1181 warnings.warn(
1182 'Please use {0} instead.'.format(original_func.__name__),
1183 DeprecationWarning, 2)
1184 return original_func(*args, **kwargs)
1185 return deprecated_func
1186
Ezio Melotti361467e2011-04-03 17:37:58 +03001187 # see #9424
Ezio Melotti0f535012011-04-03 18:02:13 +03001188 failUnlessEqual = assertEquals = _deprecate(assertEqual)
1189 failIfEqual = assertNotEquals = _deprecate(assertNotEqual)
1190 failUnlessAlmostEqual = assertAlmostEquals = _deprecate(assertAlmostEqual)
1191 failIfAlmostEqual = assertNotAlmostEquals = _deprecate(assertNotAlmostEqual)
1192 failUnless = assert_ = _deprecate(assertTrue)
1193 failUnlessRaises = _deprecate(assertRaises)
1194 failIf = _deprecate(assertFalse)
Ezio Melottied3a7d22010-12-01 02:32:32 +00001195 assertRaisesRegexp = _deprecate(assertRaisesRegex)
1196 assertRegexpMatches = _deprecate(assertRegex)
1197
1198
1199
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001200class FunctionTestCase(TestCase):
1201 """A test case that wraps a test function.
1202
1203 This is useful for slipping pre-existing test functions into the
1204 unittest framework. Optionally, set-up and tidy-up functions can be
1205 supplied. As with TestCase, the tidy-up ('tearDown') function will
1206 always be called if the set-up ('setUp') function ran successfully.
1207 """
1208
1209 def __init__(self, testFunc, setUp=None, tearDown=None, description=None):
1210 super(FunctionTestCase, self).__init__()
1211 self._setUpFunc = setUp
1212 self._tearDownFunc = tearDown
1213 self._testFunc = testFunc
1214 self._description = description
1215
1216 def setUp(self):
1217 if self._setUpFunc is not None:
1218 self._setUpFunc()
1219
1220 def tearDown(self):
1221 if self._tearDownFunc is not None:
1222 self._tearDownFunc()
1223
1224 def runTest(self):
1225 self._testFunc()
1226
1227 def id(self):
1228 return self._testFunc.__name__
1229
1230 def __eq__(self, other):
1231 if not isinstance(other, self.__class__):
1232 return NotImplemented
1233
1234 return self._setUpFunc == other._setUpFunc and \
1235 self._tearDownFunc == other._tearDownFunc and \
1236 self._testFunc == other._testFunc and \
1237 self._description == other._description
1238
1239 def __ne__(self, other):
1240 return not self == other
1241
1242 def __hash__(self):
1243 return hash((type(self), self._setUpFunc, self._tearDownFunc,
1244 self._testFunc, self._description))
1245
1246 def __str__(self):
Benjamin Peterson847a4112010-03-14 15:04:17 +00001247 return "%s (%s)" % (strclass(self.__class__),
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001248 self._testFunc.__name__)
1249
1250 def __repr__(self):
Benjamin Peterson847a4112010-03-14 15:04:17 +00001251 return "<%s tec=%s>" % (strclass(self.__class__),
Benjamin Petersonbed7d042009-07-19 21:01:52 +00001252 self._testFunc)
1253
1254 def shortDescription(self):
1255 if self._description is not None:
1256 return self._description
1257 doc = self._testFunc.__doc__
1258 return doc and doc.split("\n")[0].strip() or None
Antoine Pitrouc9b3ef22013-03-20 20:16:47 +01001259
1260
1261class _SubTest(TestCase):
1262
1263 def __init__(self, test_case, message, params):
1264 super().__init__()
1265 self._message = message
1266 self.test_case = test_case
1267 self.params = params
1268 self.failureException = test_case.failureException
1269
1270 def runTest(self):
1271 raise NotImplementedError("subtests cannot be run directly")
1272
1273 def _subDescription(self):
1274 parts = []
1275 if self._message:
1276 parts.append("[{}]".format(self._message))
1277 if self.params:
1278 params_desc = ', '.join(
1279 "{}={!r}".format(k, v)
1280 for (k, v) in sorted(self.params.items()))
1281 parts.append("({})".format(params_desc))
1282 return " ".join(parts) or '(<subtest>)'
1283
1284 def id(self):
1285 return "{} {}".format(self.test_case.id(), self._subDescription())
1286
1287 def shortDescription(self):
1288 """Returns a one-line description of the subtest, or None if no
1289 description has been provided.
1290 """
1291 return self.test_case.shortDescription()
1292
1293 def __str__(self):
1294 return "{} {}".format(self.test_case, self._subDescription())