blob: c6d893ea3a74ac1db4ba4dc5356f0ee417fe7d4a [file] [log] [blame]
Fred Drake02538202001-03-21 18:09:46 +00001#!/usr/bin/env python
Steve Purcell5ddd1a82001-03-22 08:45:36 +00002'''
Fred Drake02538202001-03-21 18:09:46 +00003Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's
4Smalltalk testing framework.
5
Fred Drake02538202001-03-21 18:09:46 +00006This module contains the core framework classes that form the basis of
7specific test cases and suites (TestCase, TestSuite etc.), and also a
8text-based utility class for running the tests and reporting the results
Jeremy Hyltonefef5da2001-10-22 18:14:15 +00009 (TextTestRunner).
Fred Drake02538202001-03-21 18:09:46 +000010
Steve Purcell5ddd1a82001-03-22 08:45:36 +000011Simple usage:
12
13 import unittest
14
15 class IntegerArithmenticTestCase(unittest.TestCase):
16 def testAdd(self): ## test method names begin 'test*'
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000017 self.assertEqual((1 + 2), 3)
18 self.assertEqual(0 + 1, 1)
Steve Purcell7b065702001-09-06 08:24:40 +000019 def testMultiply(self):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000020 self.assertEqual((0 * 10), 0)
21 self.assertEqual((5 * 8), 40)
Steve Purcell5ddd1a82001-03-22 08:45:36 +000022
23 if __name__ == '__main__':
24 unittest.main()
25
26Further information is available in the bundled documentation, and from
27
Benjamin Peterson52baa292009-03-24 00:56:30 +000028 http://docs.python.org/library/unittest.html
Steve Purcell5ddd1a82001-03-22 08:45:36 +000029
Steve Purcell7e743842003-09-22 11:08:12 +000030Copyright (c) 1999-2003 Steve Purcell
Benjamin Peterson52baa292009-03-24 00:56:30 +000031Copyright (c) 2003-2009 Python Software Foundation
Fred Drake02538202001-03-21 18:09:46 +000032This module is free software, and you may redistribute it and/or modify
33it under the same terms as Python itself, so long as this copyright message
34and disclaimer are retained in their original form.
35
36IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
37SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
38THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
39DAMAGE.
40
41THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
42LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
43PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
44AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
45SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
Steve Purcell5ddd1a82001-03-22 08:45:36 +000046'''
Fred Drake02538202001-03-21 18:09:46 +000047
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000048import difflib
Benjamin Peterson5254c042009-03-23 22:25:03 +000049import functools
Benjamin Peterson7fe73a12009-04-04 16:35:46 +000050import os
51import pprint
52import re
53import sys
54import time
55import traceback
56import types
57import warnings
Fred Drake02538202001-03-21 18:09:46 +000058
59##############################################################################
Steve Purcelld75e7e42003-09-15 11:01:21 +000060# Exported classes and functions
61##############################################################################
Benjamin Peterson52baa292009-03-24 00:56:30 +000062__all__ = ['TestResult', 'TestCase', 'TestSuite', 'ClassTestSuite',
63 'TextTestRunner', 'TestLoader', 'FunctionTestCase', 'main',
Benjamin Peterson4c93dcb2009-03-24 01:33:55 +000064 'defaultTestLoader', 'SkipTest', 'skip', 'skipIf', 'skipUnless',
Benjamin Peterson52baa292009-03-24 00:56:30 +000065 'expectedFailure']
Steve Purcelld75e7e42003-09-15 11:01:21 +000066
Steve Purcell7e743842003-09-22 11:08:12 +000067# Expose obsolete functions for backwards compatibility
Steve Purcelld75e7e42003-09-15 11:01:21 +000068__all__.extend(['getTestCaseNames', 'makeSuite', 'findTestCases'])
69
70
71##############################################################################
Fred Drake02538202001-03-21 18:09:46 +000072# Test framework core
73##############################################################################
74
Steve Purcelldc391a62002-08-09 09:46:23 +000075def _strclass(cls):
76 return "%s.%s" % (cls.__module__, cls.__name__)
77
Benjamin Peterson5254c042009-03-23 22:25:03 +000078
79class SkipTest(Exception):
80 """
81 Raise this exception in a test to skip it.
82
83 Usually you can use TestResult.skip() or one of the skipping decorators
84 instead of raising this directly.
85 """
86 pass
87
88class _ExpectedFailure(Exception):
89 """
90 Raise this when a test is expected to fail.
91
92 This is an implementation detail.
93 """
94
95 def __init__(self, exc_info):
96 super(_ExpectedFailure, self).__init__()
97 self.exc_info = exc_info
98
99class _UnexpectedSuccess(Exception):
100 """
101 The test was supposed to fail, but it didn't!
102 """
103 pass
104
105def _id(obj):
106 return obj
107
108def skip(reason):
109 """
110 Unconditionally skip a test.
111 """
112 def decorator(test_item):
113 if isinstance(test_item, type) and issubclass(test_item, TestCase):
114 test_item.__unittest_skip__ = True
115 test_item.__unittest_skip_why__ = reason
116 return test_item
117 @functools.wraps(test_item)
118 def skip_wrapper(*args, **kwargs):
119 raise SkipTest(reason)
120 return skip_wrapper
121 return decorator
122
123def skipIf(condition, reason):
124 """
125 Skip a test if the condition is true.
126 """
127 if condition:
128 return skip(reason)
129 return _id
130
131def skipUnless(condition, reason):
132 """
133 Skip a test unless the condition is true.
134 """
135 if not condition:
136 return skip(reason)
137 return _id
138
139
140def expectedFailure(func):
141 @functools.wraps(func)
142 def wrapper(*args, **kwargs):
143 try:
144 func(*args, **kwargs)
145 except Exception:
146 raise _ExpectedFailure(sys.exc_info())
147 raise _UnexpectedSuccess
148 return wrapper
149
Steve Purcellb8d5f242003-12-06 13:03:13 +0000150__unittest = 1
151
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000152class TestResult(object):
Fred Drake02538202001-03-21 18:09:46 +0000153 """Holder for test result information.
154
155 Test results are automatically managed by the TestCase and TestSuite
156 classes, and do not need to be explicitly manipulated by writers of tests.
157
158 Each instance holds the total number of tests run, and collections of
159 failures and errors that occurred among those test runs. The collections
Steve Purcell7b065702001-09-06 08:24:40 +0000160 contain tuples of (testcase, exceptioninfo), where exceptioninfo is the
Fred Drake656f9ec2001-09-06 19:13:14 +0000161 formatted traceback of the error that occurred.
Fred Drake02538202001-03-21 18:09:46 +0000162 """
163 def __init__(self):
164 self.failures = []
165 self.errors = []
166 self.testsRun = 0
Benjamin Peterson5254c042009-03-23 22:25:03 +0000167 self.skipped = []
Benjamin Peterson52baa292009-03-24 00:56:30 +0000168 self.expectedFailures = []
169 self.unexpectedSuccesses = []
Guido van Rossumd8faa362007-04-27 19:54:29 +0000170 self.shouldStop = False
Fred Drake02538202001-03-21 18:09:46 +0000171
172 def startTest(self, test):
173 "Called when the given test is about to be run"
174 self.testsRun = self.testsRun + 1
175
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000176 def startTestRun(self):
177 """Called once before any tests are executed.
178
179 See startTest for a method called before each test.
180 """
181
Fred Drake02538202001-03-21 18:09:46 +0000182 def stopTest(self, test):
183 "Called when the given test has been run"
184 pass
185
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000186 def stopTestRun(self):
187 """Called once after all tests are executed.
188
189 See stopTest for a method called after each test.
190 """
191
Fred Drake02538202001-03-21 18:09:46 +0000192 def addError(self, test, err):
Steve Purcell7b065702001-09-06 08:24:40 +0000193 """Called when an error has occurred. 'err' is a tuple of values as
194 returned by sys.exc_info().
195 """
Steve Purcellb8d5f242003-12-06 13:03:13 +0000196 self.errors.append((test, self._exc_info_to_string(err, test)))
Fred Drake02538202001-03-21 18:09:46 +0000197
198 def addFailure(self, test, err):
Steve Purcell7b065702001-09-06 08:24:40 +0000199 """Called when an error has occurred. 'err' is a tuple of values as
200 returned by sys.exc_info()."""
Steve Purcellb8d5f242003-12-06 13:03:13 +0000201 self.failures.append((test, self._exc_info_to_string(err, test)))
Fred Drake02538202001-03-21 18:09:46 +0000202
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000203 def addSuccess(self, test):
204 "Called when a test has completed successfully"
205 pass
206
Benjamin Peterson5254c042009-03-23 22:25:03 +0000207 def addSkip(self, test, reason):
208 """Called when a test is skipped."""
209 self.skipped.append((test, reason))
210
211 def addExpectedFailure(self, test, err):
212 """Called when an expected failure/error occured."""
Benjamin Peterson52baa292009-03-24 00:56:30 +0000213 self.expectedFailures.append(
Benjamin Peterson5254c042009-03-23 22:25:03 +0000214 (test, self._exc_info_to_string(err, test)))
215
216 def addUnexpectedSuccess(self, test):
217 """Called when a test was expected to fail, but succeed."""
Benjamin Peterson52baa292009-03-24 00:56:30 +0000218 self.unexpectedSuccesses.append(test)
Benjamin Peterson5254c042009-03-23 22:25:03 +0000219
Fred Drake02538202001-03-21 18:09:46 +0000220 def wasSuccessful(self):
221 "Tells whether or not this result was a success"
222 return len(self.failures) == len(self.errors) == 0
223
224 def stop(self):
225 "Indicates that the tests should be aborted"
Steve Purcell7e743842003-09-22 11:08:12 +0000226 self.shouldStop = True
Tim Petersa19a1682001-03-29 04:36:09 +0000227
Steve Purcellb8d5f242003-12-06 13:03:13 +0000228 def _exc_info_to_string(self, err, test):
Steve Purcell7b065702001-09-06 08:24:40 +0000229 """Converts a sys.exc_info()-style tuple of values into a string."""
Steve Purcellb8d5f242003-12-06 13:03:13 +0000230 exctype, value, tb = err
231 # Skip test runner traceback levels
232 while tb and self._is_relevant_tb_level(tb):
233 tb = tb.tb_next
234 if exctype is test.failureException:
235 # Skip assert*() traceback levels
236 length = self._count_relevant_tb_levels(tb)
Collin Winterce36ad82007-08-30 01:19:48 +0000237 return ''.join(traceback.format_exception(exctype, value,
238 tb, length))
Steve Purcellb8d5f242003-12-06 13:03:13 +0000239 return ''.join(traceback.format_exception(exctype, value, tb))
240
241 def _is_relevant_tb_level(self, tb):
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000242 return '__unittest' in tb.tb_frame.f_globals
Steve Purcellb8d5f242003-12-06 13:03:13 +0000243
244 def _count_relevant_tb_levels(self, tb):
245 length = 0
246 while tb and not self._is_relevant_tb_level(tb):
247 length += 1
248 tb = tb.tb_next
249 return length
Steve Purcell7b065702001-09-06 08:24:40 +0000250
Fred Drake02538202001-03-21 18:09:46 +0000251 def __repr__(self):
252 return "<%s run=%i errors=%i failures=%i>" % \
Steve Purcelldc391a62002-08-09 09:46:23 +0000253 (_strclass(self.__class__), self.testsRun, len(self.errors),
Fred Drake02538202001-03-21 18:09:46 +0000254 len(self.failures))
255
Benjamin Peterson52baa292009-03-24 00:56:30 +0000256
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000257class _AssertRaisesContext(object):
258 """A context manager used to implement TestCase.assertRaises* methods."""
Benjamin Peterson52baa292009-03-24 00:56:30 +0000259
260
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000261 def __init__(self, expected, test_case, callable_obj=None,
262 expected_regexp=None):
Antoine Pitrou5acd41e2008-12-28 14:29:00 +0000263 self.expected = expected
264 self.failureException = test_case.failureException
265 if callable_obj is not None:
266 try:
267 self.obj_name = callable_obj.__name__
268 except AttributeError:
269 self.obj_name = str(callable_obj)
270 else:
271 self.obj_name = None
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000272 self.expected_regex = expected_regexp
Benjamin Peterson52baa292009-03-24 00:56:30 +0000273
Antoine Pitrou5acd41e2008-12-28 14:29:00 +0000274 def __enter__(self):
275 pass
Benjamin Peterson52baa292009-03-24 00:56:30 +0000276
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000277 def __exit__(self, exc_type, exc_value, tb):
Antoine Pitrou5acd41e2008-12-28 14:29:00 +0000278 if exc_type is None:
279 try:
280 exc_name = self.expected.__name__
281 except AttributeError:
282 exc_name = str(self.expected)
283 if self.obj_name:
284 raise self.failureException("{0} not raised by {1}"
285 .format(exc_name, self.obj_name))
286 else:
287 raise self.failureException("{0} not raised"
288 .format(exc_name))
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000289 if not issubclass(exc_type, self.expected):
290 # let unexpected exceptions pass through
291 return False
292 if self.expected_regex is None:
Antoine Pitrou5acd41e2008-12-28 14:29:00 +0000293 return True
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000294
295 expected_regexp = self.expected_regex
296 if isinstance(expected_regexp, (bytes, str)):
297 expected_regexp = re.compile(expected_regexp)
298 if not expected_regexp.search(str(exc_value)):
299 raise self.failureException('"%s" does not match "%s"' %
300 (expected_regexp.pattern, str(exc_value)))
301 return True
302
303
304class _AssertWrapper(object):
305 """Wrap entries in the _type_equality_funcs registry to make them deep
306 copyable."""
307
308 def __init__(self, function):
309 self.function = function
310
311 def __deepcopy__(self, memo):
312 memo[id(self)] = self
Antoine Pitrou5acd41e2008-12-28 14:29:00 +0000313
Benjamin Peterson52baa292009-03-24 00:56:30 +0000314
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000315class TestCase(object):
Fred Drake02538202001-03-21 18:09:46 +0000316 """A class whose instances are single test cases.
317
Fred Drake02538202001-03-21 18:09:46 +0000318 By default, the test code itself should be placed in a method named
319 'runTest'.
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000320
Tim Petersa19a1682001-03-29 04:36:09 +0000321 If the fixture may be used for many test cases, create as
Fred Drake02538202001-03-21 18:09:46 +0000322 many test methods as are needed. When instantiating such a TestCase
323 subclass, specify in the constructor arguments the name of the test method
324 that the instance is to execute.
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000325
Tim Petersa19a1682001-03-29 04:36:09 +0000326 Test authors should subclass TestCase for their own tests. Construction
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000327 and deconstruction of the test's environment ('fixture') can be
328 implemented by overriding the 'setUp' and 'tearDown' methods respectively.
329
330 If it is necessary to override the __init__ method, the base class
331 __init__ method must always be called. It is important that subclasses
332 should not change the signature of their __init__ method, since instances
333 of the classes are instantiated automatically by parts of the framework
334 in order to be run.
Fred Drake02538202001-03-21 18:09:46 +0000335 """
Steve Purcell15d89272001-04-12 09:05:01 +0000336
337 # This attribute determines which exception will be raised when
338 # the instance's assertion methods fail; test methods raising this
339 # exception will be deemed to have 'failed' rather than 'errored'
340
341 failureException = AssertionError
342
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000343 # This attribute determines whether long messages (including repr of
344 # objects used in assert methods) will be printed on failure in *addition*
345 # to any explicit message passed.
346
347 longMessage = False
348
349
Fred Drake02538202001-03-21 18:09:46 +0000350 def __init__(self, methodName='runTest'):
351 """Create an instance of the class that will use the named test
352 method when executed. Raises a ValueError if the instance does
353 not have a method with the specified name.
354 """
Benjamin Peterson52baa292009-03-24 00:56:30 +0000355 self._testMethodName = methodName
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000356 self._result = None
Fred Drake02538202001-03-21 18:09:46 +0000357 try:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000358 testMethod = getattr(self, methodName)
Fred Drake02538202001-03-21 18:09:46 +0000359 except AttributeError:
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000360 raise ValueError("no such test method in %s: %s" % \
361 (self.__class__, methodName))
Benjamin Peterson52baa292009-03-24 00:56:30 +0000362 self._testMethodDoc = testMethod.__doc__
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000363 self._cleanups = []
Fred Drake02538202001-03-21 18:09:46 +0000364
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000365 # Map types to custom assertEqual functions that will compare
366 # instances of said type in more detail to generate a more useful
367 # error message.
368 self._type_equality_funcs = {}
369 self.addTypeEqualityFunc(dict, self.assertDictEqual)
370 self.addTypeEqualityFunc(list, self.assertListEqual)
371 self.addTypeEqualityFunc(tuple, self.assertTupleEqual)
372 self.addTypeEqualityFunc(set, self.assertSetEqual)
373 self.addTypeEqualityFunc(frozenset, self.assertSetEqual)
374
375 def addTypeEqualityFunc(self, typeobj, function):
376 """Add a type specific assertEqual style function to compare a type.
377
378 This method is for use by TestCase subclasses that need to register
379 their own type equality functions to provide nicer error messages.
380
381 Args:
382 typeobj: The data type to call this function on when both values
383 are of the same type in assertEqual().
384 function: The callable taking two arguments and an optional
385 msg= argument that raises self.failureException with a
386 useful error message when the two arguments are not equal.
387 """
388 self._type_equality_funcs[typeobj] = _AssertWrapper(function)
389
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000390 def addCleanup(self, function, *args, **kwargs):
391 """Add a function, with arguments, to be called when the test is
392 completed. Functions added are called on a LIFO basis and are
393 called after tearDown on test failure or success.
394
395 Cleanup items are called even if setUp fails (unlike tearDown)."""
396 self._cleanups.append((function, args, kwargs))
397
Fred Drake02538202001-03-21 18:09:46 +0000398 def setUp(self):
399 "Hook method for setting up the test fixture before exercising it."
400 pass
401
402 def tearDown(self):
403 "Hook method for deconstructing the test fixture after testing it."
404 pass
405
406 def countTestCases(self):
407 return 1
408
409 def defaultTestResult(self):
410 return TestResult()
411
412 def shortDescription(self):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000413 """Returns both the test method name and first line of its docstring.
Fred Drake02538202001-03-21 18:09:46 +0000414
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000415 If no docstring is given, only returns the method name.
416
417 This method overrides unittest.TestCase.shortDescription(), which
418 only returns the first line of the docstring, obscuring the name
419 of the test upon failure.
Fred Drake02538202001-03-21 18:09:46 +0000420 """
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000421 desc = str(self)
422 doc_first_line = None
423
424 if self._testMethodDoc:
425 doc_first_line = self._testMethodDoc.split("\n")[0].strip()
426 if doc_first_line:
427 desc = '\n'.join((desc, doc_first_line))
428 return desc
Fred Drake02538202001-03-21 18:09:46 +0000429
430 def id(self):
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000431 return "%s.%s" % (_strclass(self.__class__), self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000432
Guido van Rossumd8faa362007-04-27 19:54:29 +0000433 def __eq__(self, other):
434 if type(self) is not type(other):
Benjamin Peterson52baa292009-03-24 00:56:30 +0000435 return NotImplemented
Guido van Rossumd8faa362007-04-27 19:54:29 +0000436
437 return self._testMethodName == other._testMethodName
438
439 def __ne__(self, other):
440 return not self == other
441
442 def __hash__(self):
443 return hash((type(self), self._testMethodName))
444
Fred Drake02538202001-03-21 18:09:46 +0000445 def __str__(self):
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000446 return "%s (%s)" % (self._testMethodName, _strclass(self.__class__))
Fred Drake02538202001-03-21 18:09:46 +0000447
448 def __repr__(self):
449 return "<%s testMethod=%s>" % \
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000450 (_strclass(self.__class__), self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000451
452 def run(self, result=None):
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000453 orig_result = result
Benjamin Peterson52baa292009-03-24 00:56:30 +0000454 if result is None:
455 result = self.defaultTestResult()
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000456 startTestRun = getattr(result, 'startTestRun', None)
457 if startTestRun is not None:
458 startTestRun()
459
460 self._result = result
Fred Drake02538202001-03-21 18:09:46 +0000461 result.startTest(self)
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000462 testMethod = getattr(self, self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000463 try:
Benjamin Peterson5254c042009-03-23 22:25:03 +0000464 success = False
Fred Drake02538202001-03-21 18:09:46 +0000465 try:
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000466 self.setUp()
Benjamin Peterson5254c042009-03-23 22:25:03 +0000467 except SkipTest as e:
468 result.addSkip(self, str(e))
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000469 except Exception:
Benjamin Petersone549ead2009-03-28 21:42:05 +0000470 result.addError(self, sys.exc_info())
Benjamin Peterson5254c042009-03-23 22:25:03 +0000471 else:
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000472 try:
473 testMethod()
474 except self.failureException:
475 result.addFailure(self, sys.exc_info())
476 except _ExpectedFailure as e:
477 result.addExpectedFailure(self, e.exc_info)
478 except _UnexpectedSuccess:
479 result.addUnexpectedSuccess(self)
480 except SkipTest as e:
481 result.addSkip(self, str(e))
482 except Exception:
483 result.addError(self, sys.exc_info())
484 else:
485 success = True
Fred Drake02538202001-03-21 18:09:46 +0000486
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000487 try:
488 self.tearDown()
489 except Exception:
490 result.addError(self, sys.exc_info())
491 success = False
492
493 cleanUpSuccess = self.doCleanups()
494 success = success and cleanUpSuccess
Benjamin Peterson5254c042009-03-23 22:25:03 +0000495 if success:
496 result.addSuccess(self)
Fred Drake02538202001-03-21 18:09:46 +0000497 finally:
498 result.stopTest(self)
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000499 if orig_result is None:
500 stopTestRun = getattr(result, 'stopTestRun', None)
501 if stopTestRun is not None:
502 stopTestRun()
503
504 def doCleanups(self):
505 """Execute all cleanup functions. Normally called for you after
506 tearDown."""
507 result = self._result
508 ok = True
509 while self._cleanups:
510 function, args, kwargs = self._cleanups.pop(-1)
511 try:
512 function(*args, **kwargs)
513 except Exception:
514 ok = False
515 result.addError(self, sys.exc_info())
516 return ok
Fred Drake02538202001-03-21 18:09:46 +0000517
Raymond Hettinger664347b2004-12-04 21:21:53 +0000518 def __call__(self, *args, **kwds):
519 return self.run(*args, **kwds)
Steve Purcell7e743842003-09-22 11:08:12 +0000520
Fred Drake02538202001-03-21 18:09:46 +0000521 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000522 """Run the test without collecting errors in a TestResult"""
Fred Drake02538202001-03-21 18:09:46 +0000523 self.setUp()
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000524 getattr(self, self._testMethodName)()
Fred Drake02538202001-03-21 18:09:46 +0000525 self.tearDown()
526
Benjamin Petersone549ead2009-03-28 21:42:05 +0000527 def skipTest(self, reason):
Benjamin Peterson5254c042009-03-23 22:25:03 +0000528 """Skip this test."""
529 raise SkipTest(reason)
530
Steve Purcell15d89272001-04-12 09:05:01 +0000531 def fail(self, msg=None):
532 """Fail immediately, with the given message."""
Collin Winterce36ad82007-08-30 01:19:48 +0000533 raise self.failureException(msg)
Fred Drake02538202001-03-21 18:09:46 +0000534
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000535 def assertFalse(self, expr, msg=None):
Fred Drake02538202001-03-21 18:09:46 +0000536 "Fail the test if the expression is true."
Benjamin Peterson52baa292009-03-24 00:56:30 +0000537 if expr:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000538 msg = self._formatMessage(msg, "%r is not False" % expr)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000539 raise self.failureException(msg)
Fred Drake02538202001-03-21 18:09:46 +0000540
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000541 def assertTrue(self, expr, msg=None):
Steve Purcell15d89272001-04-12 09:05:01 +0000542 """Fail the test unless the expression is true."""
Benjamin Peterson52baa292009-03-24 00:56:30 +0000543 if not expr:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000544 msg = self._formatMessage(msg, "%r is not True" % expr)
Benjamin Peterson52baa292009-03-24 00:56:30 +0000545 raise self.failureException(msg)
Steve Purcell15d89272001-04-12 09:05:01 +0000546
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000547 def _formatMessage(self, msg, standardMsg):
548 """Honour the longMessage attribute when generating failure messages.
549 If longMessage is False this means:
550 * Use only an explicit message if it is provided
551 * Otherwise use the standard message for the assert
552
553 If longMessage is True:
554 * Use the standard message
555 * If an explicit message is provided, plus ' : ' and the explicit message
556 """
557 if not self.longMessage:
558 return msg or standardMsg
559 if msg is None:
560 return standardMsg
561 return standardMsg + ' : ' + msg
562
563
564 def assertRaises(self, excClass, callableObj=None, *args, **kwargs):
Steve Purcell15d89272001-04-12 09:05:01 +0000565 """Fail unless an exception of class excClass is thrown
Fred Drake02538202001-03-21 18:09:46 +0000566 by callableObj when invoked with arguments args and keyword
567 arguments kwargs. If a different type of exception is
568 thrown, it will not be caught, and the test case will be
569 deemed to have suffered an error, exactly as for an
570 unexpected exception.
Antoine Pitrou5acd41e2008-12-28 14:29:00 +0000571
572 If called with callableObj omitted or None, will return a
573 context object used like this::
574
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000575 with self.assertRaises(some_error_class):
Antoine Pitrou5acd41e2008-12-28 14:29:00 +0000576 do_something()
Fred Drake02538202001-03-21 18:09:46 +0000577 """
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000578 context = _AssertRaisesContext(excClass, self, callableObj)
Antoine Pitrou5acd41e2008-12-28 14:29:00 +0000579 if callableObj is None:
580 return context
581 with context:
Guido van Rossum68468eb2003-02-27 20:14:51 +0000582 callableObj(*args, **kwargs)
Fred Drake02538202001-03-21 18:09:46 +0000583
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000584 def _getAssertEqualityFunc(self, first, second):
585 """Get a detailed comparison function for the types of the two args.
586
587 Returns: A callable accepting (first, second, msg=None) that will
588 raise a failure exception if first != second with a useful human
589 readable error message for those types.
590 """
591 #
592 # NOTE(gregory.p.smith): I considered isinstance(first, type(second))
593 # and vice versa. I opted for the conservative approach in case
594 # subclasses are not intended to be compared in detail to their super
595 # class instances using a type equality func. This means testing
596 # subtypes won't automagically use the detailed comparison. Callers
597 # should use their type specific assertSpamEqual method to compare
598 # subclasses if the detailed comparison is desired and appropriate.
599 # See the discussion in http://bugs.python.org/issue2578.
600 #
601 if type(first) is type(second):
602 asserter = self._type_equality_funcs.get(type(first))
603 if asserter is not None:
604 return asserter.function
605
606 return self._baseAssertEqual
607
608 def _baseAssertEqual(self, first, second, msg=None):
609 """The default assertEqual implementation, not type specific."""
610 if not first == second:
611 standardMsg = '%r != %r' % (first, second)
612 msg = self._formatMessage(msg, standardMsg)
613 raise self.failureException(msg)
614
615 def assertEqual(self, first, second, msg=None):
Raymond Hettingerc377cbf2003-04-04 22:56:42 +0000616 """Fail if the two objects are unequal as determined by the '=='
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000617 operator.
618 """
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000619 assertion_func = self._getAssertEqualityFunc(first, second)
620 assertion_func(first, second, msg=msg)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000621
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000622 def assertNotEqual(self, first, second, msg=None):
Steve Purcell15d89272001-04-12 09:05:01 +0000623 """Fail if the two objects are equal as determined by the '=='
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000624 operator.
625 """
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000626 if not first != second:
627 msg = self._formatMessage(msg, '%r == %r' % (first, second))
628 raise self.failureException(msg)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000629
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000630 def assertAlmostEqual(self, first, second, *, places=7, msg=None):
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000631 """Fail if the two objects are unequal as determined by their
632 difference rounded to the given number of decimal places
633 (default 7) and comparing to zero.
634
Steve Purcell397b45d2003-10-26 10:41:03 +0000635 Note that decimal places (from zero) are usually not the same
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000636 as significant digits (measured from the most signficant digit).
637 """
Jeffrey Yasskin1cc55442007-09-06 18:55:17 +0000638 if round(abs(second-first), places) != 0:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000639 standardMsg = '%r != %r within %r places' % (first, second, places)
640 msg = self._formatMessage(msg, standardMsg)
641 raise self.failureException(msg)
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000642
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000643 def assertNotAlmostEqual(self, first, second, *, places=7, msg=None):
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000644 """Fail if the two objects are equal as determined by their
645 difference rounded to the given number of decimal places
646 (default 7) and comparing to zero.
647
Steve Purcellcca34912003-10-26 16:38:16 +0000648 Note that decimal places (from zero) are usually not the same
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000649 as significant digits (measured from the most signficant digit).
650 """
Jeffrey Yasskin1cc55442007-09-06 18:55:17 +0000651 if round(abs(second-first), places) == 0:
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000652 standardMsg = '%r == %r within %r places' % (first, second, places)
653 msg = self._formatMessage(msg, standardMsg)
654 raise self.failureException(msg)
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000655
Steve Purcell7e743842003-09-22 11:08:12 +0000656 # Synonyms for assertion methods
657
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000658 # The plurals are undocumented. Keep them that way to discourage use.
659 # Do not add more. Do not remove.
660 # Going through a deprecation cycle on these would annoy many people.
661 assertEquals = assertEqual
662 assertNotEquals = assertNotEqual
663 assertAlmostEquals = assertAlmostEqual
664 assertNotAlmostEquals = assertNotAlmostEqual
665 assert_ = assertTrue
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000666
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000667 # These fail* assertion method names are pending deprecation and will
668 # be a DeprecationWarning in 3.2; http://bugs.python.org/issue2578
669 def _deprecate(original_func):
670 def deprecated_func(*args, **kwargs):
671 warnings.warn(
672 'Please use {0} instead.'.format(original_func.__name__),
673 PendingDeprecationWarning, 2)
674 return original_func(*args, **kwargs)
675 return deprecated_func
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000676
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000677 failUnlessEqual = _deprecate(assertEqual)
678 failIfEqual = _deprecate(assertNotEqual)
679 failUnlessAlmostEqual = _deprecate(assertAlmostEqual)
680 failIfAlmostEqual = _deprecate(assertNotAlmostEqual)
681 failUnless = _deprecate(assertTrue)
682 failUnlessRaises = _deprecate(assertRaises)
683 failIf = _deprecate(assertFalse)
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000684
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000685 def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
686 """An equality assertion for ordered sequences (like lists and tuples).
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000687
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000688 For the purposes of this function, a valid orderd sequence type is one
689 which can be indexed, has a length, and has an equality operator.
Steve Purcell15d89272001-04-12 09:05:01 +0000690
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000691 Args:
692 seq1: The first sequence to compare.
693 seq2: The second sequence to compare.
694 seq_type: The expected datatype of the sequences, or None if no
695 datatype should be enforced.
696 msg: Optional message to use on failure instead of a list of
697 differences.
698 """
699 if seq_type != None:
700 seq_type_name = seq_type.__name__
701 if not isinstance(seq1, seq_type):
702 raise self.failureException('First sequence is not a %s: %r'
703 % (seq_type_name, seq1))
704 if not isinstance(seq2, seq_type):
705 raise self.failureException('Second sequence is not a %s: %r'
706 % (seq_type_name, seq2))
707 else:
708 seq_type_name = "sequence"
Steve Purcell7e743842003-09-22 11:08:12 +0000709
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000710 differing = None
711 try:
712 len1 = len(seq1)
713 except (TypeError, NotImplementedError):
714 differing = 'First %s has no length. Non-sequence?' % (
715 seq_type_name)
Steve Purcell15d89272001-04-12 09:05:01 +0000716
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000717 if differing is None:
718 try:
719 len2 = len(seq2)
720 except (TypeError, NotImplementedError):
721 differing = 'Second %s has no length. Non-sequence?' % (
722 seq_type_name)
723
724 if differing is None:
725 if seq1 == seq2:
726 return
727
728 for i in range(min(len1, len2)):
729 try:
730 item1 = seq1[i]
731 except (TypeError, IndexError, NotImplementedError):
732 differing = ('Unable to index element %d of first %s\n' %
733 (i, seq_type_name))
734 break
735
736 try:
737 item2 = seq2[i]
738 except (TypeError, IndexError, NotImplementedError):
739 differing = ('Unable to index element %d of second %s\n' %
740 (i, seq_type_name))
741 break
742
743 if item1 != item2:
744 differing = ('First differing element %d:\n%s\n%s\n' %
745 (i, item1, item2))
746 break
747 else:
748 if (len1 == len2 and seq_type is None and
749 type(seq1) != type(seq2)):
750 # The sequences are the same, but have differing types.
751 return
752 # A catch-all message for handling arbitrary user-defined
753 # sequences.
754 differing = '%ss differ:\n' % seq_type_name.capitalize()
755 if len1 > len2:
756 differing = ('First %s contains %d additional '
757 'elements.\n' % (seq_type_name, len1 - len2))
758 try:
759 differing += ('First extra element %d:\n%s\n' %
760 (len2, seq1[len2]))
761 except (TypeError, IndexError, NotImplementedError):
762 differing += ('Unable to index element %d '
763 'of first %s\n' % (len2, seq_type_name))
764 elif len1 < len2:
765 differing = ('Second %s contains %d additional '
766 'elements.\n' % (seq_type_name, len2 - len1))
767 try:
768 differing += ('First extra element %d:\n%s\n' %
769 (len1, seq2[len1]))
770 except (TypeError, IndexError, NotImplementedError):
771 differing += ('Unable to index element %d '
772 'of second %s\n' % (len1, seq_type_name))
773 standardMsg = differing + '\n'.join(difflib.ndiff(pprint.pformat(seq1).splitlines(),
774 pprint.pformat(seq2).splitlines()))
775 msg = self._formatMessage(msg, standardMsg)
776 self.fail(msg)
777
778 def assertListEqual(self, list1, list2, msg=None):
779 """A list-specific equality assertion.
780
781 Args:
782 list1: The first list to compare.
783 list2: The second list to compare.
784 msg: Optional message to use on failure instead of a list of
785 differences.
786
787 """
788 self.assertSequenceEqual(list1, list2, msg, seq_type=list)
789
790 def assertTupleEqual(self, tuple1, tuple2, msg=None):
791 """A tuple-specific equality assertion.
792
793 Args:
794 tuple1: The first tuple to compare.
795 tuple2: The second tuple to compare.
796 msg: Optional message to use on failure instead of a list of
797 differences.
798 """
799 self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
800
801 def assertSetEqual(self, set1, set2, msg=None):
802 """A set-specific equality assertion.
803
804 Args:
805 set1: The first set to compare.
806 set2: The second set to compare.
807 msg: Optional message to use on failure instead of a list of
808 differences.
809
810 For more general containership equality, assertSameElements will work
811 with things other than sets. This uses ducktyping to support
812 different types of sets, and is optimized for sets specifically
813 (parameters must support a difference method).
814 """
815 try:
816 difference1 = set1.difference(set2)
817 except TypeError as e:
818 self.fail('invalid type when attempting set difference: %s' % e)
819 except AttributeError as e:
820 self.fail('first argument does not support set difference: %s' % e)
821
822 try:
823 difference2 = set2.difference(set1)
824 except TypeError as e:
825 self.fail('invalid type when attempting set difference: %s' % e)
826 except AttributeError as e:
827 self.fail('second argument does not support set difference: %s' % e)
828
829 if not (difference1 or difference2):
830 return
831
832 lines = []
833 if difference1:
834 lines.append('Items in the first set but not the second:')
835 for item in difference1:
836 lines.append(repr(item))
837 if difference2:
838 lines.append('Items in the second set but not the first:')
839 for item in difference2:
840 lines.append(repr(item))
841
842 standardMsg = '\n'.join(lines)
843 self.fail(self._formatMessage(msg, standardMsg))
844
845 def assertIn(self, member, container, msg=None):
846 """Just like self.assertTrue(a in b), but with a nicer default message."""
847 if member not in container:
848 standardMsg = '%r not found in %r' % (member, container)
849 self.fail(self._formatMessage(msg, standardMsg))
850
851 def assertNotIn(self, member, container, msg=None):
852 """Just like self.assertTrue(a not in b), but with a nicer default message."""
853 if member in container:
854 standardMsg = '%r unexpectedly found in %r' % (member, container)
855 self.fail(self._formatMessage(msg, standardMsg))
856
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +0000857 def assertIs(self, expr1, expr2, msg=None):
858 """Just like self.assertTrue(a is b), but with a nicer default message."""
859 if expr1 is not expr2:
860 standardMsg = '%r is not %r' % (expr1, expr2)
861 self.fail(self._formatMessage(msg, standardMsg))
862
863 def assertIsNot(self, expr1, expr2, msg=None):
864 """Just like self.assertTrue(a is not b), but with a nicer default message."""
865 if expr1 is expr2:
866 standardMsg = 'unexpectedly identical: %r' % (expr1,)
867 self.fail(self._formatMessage(msg, standardMsg))
868
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000869 def assertDictEqual(self, d1, d2, msg=None):
870 self.assert_(isinstance(d1, dict), 'First argument is not a dictionary')
871 self.assert_(isinstance(d2, dict), 'Second argument is not a dictionary')
872
873 if d1 != d2:
874 standardMsg = ('\n' + '\n'.join(difflib.ndiff(
875 pprint.pformat(d1).splitlines(),
876 pprint.pformat(d2).splitlines())))
877 self.fail(self._formatMessage(msg, standardMsg))
878
879 def assertDictContainsSubset(self, expected, actual, msg=None):
880 """Checks whether actual is a superset of expected."""
881 missing = []
882 mismatched = []
883 for key, value in expected.items():
884 if key not in actual:
885 missing.append(key)
886 elif value != actual[key]:
887 mismatched.append('%s, expected: %s, actual: %s' % (key, value, actual[key]))
888
889 if not (missing or mismatched):
890 return
891
892 standardMsg = ''
893 if missing:
894 standardMsg = 'Missing: %r' % ','.join(missing)
895 if mismatched:
896 if standardMsg:
897 standardMsg += '; '
898 standardMsg += 'Mismatched values: %s' % ','.join(mismatched)
899
900 self.fail(self._formatMessage(msg, standardMsg))
901
902 def assertSameElements(self, expected_seq, actual_seq, msg=None):
903 """An unordered sequence specific comparison.
904
905 Raises with an error message listing which elements of expected_seq
906 are missing from actual_seq and vice versa if any.
907 """
908 try:
909 expected = set(expected_seq)
910 actual = set(actual_seq)
911 missing = list(expected.difference(actual))
912 unexpected = list(actual.difference(expected))
913 missing.sort()
914 unexpected.sort()
915 except TypeError:
916 # Fall back to slower list-compare if any of the objects are
917 # not hashable.
918 expected = list(expected_seq)
919 actual = list(actual_seq)
Michael Foorda5809c82009-04-04 18:55:09 +0000920 try:
921 expected.sort()
922 actual.sort()
923 except TypeError:
924 missing, unexpected = _UnorderableListDifference(expected, actual)
925 else:
926 missing, unexpected = _SortedListDifference(expected, actual)
Benjamin Peterson7fe73a12009-04-04 16:35:46 +0000927 errors = []
928 if missing:
929 errors.append('Expected, but missing:\n %r' % missing)
930 if unexpected:
931 errors.append('Unexpected, but present:\n %r' % unexpected)
932 if errors:
933 standardMsg = '\n'.join(errors)
934 self.fail(self._formatMessage(msg, standardMsg))
935
936 def assertMultiLineEqual(self, first, second, msg=None):
937 """Assert that two multi-line strings are equal."""
938 self.assert_(isinstance(first, str), (
939 'First argument is not a string'))
940 self.assert_(isinstance(second, str), (
941 'Second argument is not a string'))
942
943 if first != second:
944 standardMsg = '\n' + ''.join(difflib.ndiff(first.splitlines(True), second.splitlines(True)))
945 self.fail(self._formatMessage(msg, standardMsg))
946
947 def assertLess(self, a, b, msg=None):
948 """Just like self.assertTrue(a < b), but with a nicer default message."""
949 if not a < b:
950 standardMsg = '%r not less than %r' % (a, b)
951 self.fail(self._formatMessage(msg, standardMsg))
952
953 def assertLessEqual(self, a, b, msg=None):
954 """Just like self.assertTrue(a <= b), but with a nicer default message."""
955 if not a <= b:
956 standardMsg = '%r not less than or equal to %r' % (a, b)
957 self.fail(self._formatMessage(msg, standardMsg))
958
959 def assertGreater(self, a, b, msg=None):
960 """Just like self.assertTrue(a > b), but with a nicer default message."""
961 if not a > b:
962 standardMsg = '%r not greater than %r' % (a, b)
963 self.fail(self._formatMessage(msg, standardMsg))
964
965 def assertGreaterEqual(self, a, b, msg=None):
966 """Just like self.assertTrue(a >= b), but with a nicer default message."""
967 if not a >= b:
968 standardMsg = '%r not greater than or equal to %r' % (a, b)
969 self.fail(self._formatMessage(msg, standardMsg))
970
971 def assertIsNone(self, obj, msg=None):
972 """Same as self.assertTrue(obj is None), with a nicer default message."""
973 if obj is not None:
974 standardMsg = '%r is not None' % obj
975 self.fail(self._formatMessage(msg, standardMsg))
976
977 def assertIsNotNone(self, obj, msg=None):
978 """Included for symmetry with assertIsNone."""
979 if obj is None:
980 standardMsg = 'unexpectedly None'
981 self.fail(self._formatMessage(msg, standardMsg))
982
983 def assertRaisesRegexp(self, expected_exception, expected_regexp,
984 callable_obj=None, *args, **kwargs):
985 """Asserts that the message in a raised exception matches a regexp.
986
987 Args:
988 expected_exception: Exception class expected to be raised.
989 expected_regexp: Regexp (re pattern object or string) expected
990 to be found in error message.
991 callable_obj: Function to be called.
992 args: Extra args.
993 kwargs: Extra kwargs.
994 """
995 context = _AssertRaisesContext(expected_exception, self, callable_obj,
996 expected_regexp)
997 if callable_obj is None:
998 return context
999 with context:
1000 callable_obj(*args, **kwargs)
1001
1002 def assertRegexpMatches(self, text, expected_regex, msg=None):
1003 if isinstance(expected_regex, (str, bytes)):
1004 expected_regex = re.compile(expected_regex)
1005 if not expected_regex.search(text):
1006 msg = msg or "Regexp didn't match"
1007 msg = '%s: %r not found in %r' % (msg, expected_regex.pattern, text)
1008 raise self.failureException(msg)
1009
1010
1011def _SortedListDifference(expected, actual):
1012 """Finds elements in only one or the other of two, sorted input lists.
1013
1014 Returns a two-element tuple of lists. The first list contains those
1015 elements in the "expected" list but not in the "actual" list, and the
1016 second contains those elements in the "actual" list but not in the
1017 "expected" list. Duplicate elements in either input list are ignored.
1018 """
1019 i = j = 0
1020 missing = []
1021 unexpected = []
1022 while True:
1023 try:
1024 e = expected[i]
1025 a = actual[j]
1026 if e < a:
1027 missing.append(e)
1028 i += 1
1029 while expected[i] == e:
1030 i += 1
1031 elif e > a:
1032 unexpected.append(a)
1033 j += 1
1034 while actual[j] == a:
1035 j += 1
1036 else:
1037 i += 1
1038 try:
1039 while expected[i] == e:
1040 i += 1
1041 finally:
1042 j += 1
1043 while actual[j] == a:
1044 j += 1
1045 except IndexError:
1046 missing.extend(expected[i:])
1047 unexpected.extend(actual[j:])
1048 break
1049 return missing, unexpected
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001050
Michael Foorda5809c82009-04-04 18:55:09 +00001051def _UnorderableListDifference(expected, actual):
1052 """Same behavior as _SortedListDifference but
1053 for lists of unorderable items (like dicts).
1054
1055 As it does a linear search per item (remove) it
1056 has O(n*n) performance."""
1057 missing = []
1058 while expected:
1059 item = expected.pop()
1060 try:
1061 actual.remove(item)
1062 except ValueError:
1063 missing.append(item)
1064
1065 # anything left in actual is unexpected
1066 return missing, actual
Fred Drake02538202001-03-21 18:09:46 +00001067
Benjamin Peterson1467ac82009-01-09 03:42:38 +00001068class TestSuite(object):
Fred Drake02538202001-03-21 18:09:46 +00001069 """A test suite is a composite test consisting of a number of TestCases.
1070
1071 For use, create an instance of TestSuite, then add test case instances.
1072 When all tests have been added, the suite can be passed to a test
1073 runner, such as TextTestRunner. It will run the individual test cases
1074 in the order in which they were added, aggregating the results. When
1075 subclassing, do not forget to call the base class constructor.
1076 """
1077 def __init__(self, tests=()):
1078 self._tests = []
1079 self.addTests(tests)
1080
1081 def __repr__(self):
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001082 return "<%s tests=%s>" % (_strclass(self.__class__), list(self))
Fred Drake02538202001-03-21 18:09:46 +00001083
Guido van Rossumd8faa362007-04-27 19:54:29 +00001084 def __eq__(self, other):
Benjamin Peterson5254c042009-03-23 22:25:03 +00001085 if not isinstance(other, self.__class__):
1086 return NotImplemented
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001087 return list(self) == list(other)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001088
1089 def __ne__(self, other):
1090 return not self == other
1091
Jim Fultonfafd8742004-08-28 15:22:12 +00001092 def __iter__(self):
1093 return iter(self._tests)
1094
Fred Drake02538202001-03-21 18:09:46 +00001095 def countTestCases(self):
1096 cases = 0
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001097 for test in self:
Steve Purcell7e743842003-09-22 11:08:12 +00001098 cases += test.countTestCases()
Fred Drake02538202001-03-21 18:09:46 +00001099 return cases
1100
1101 def addTest(self, test):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001102 # sanity checks
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001103 if not hasattr(test, '__call__'):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001104 raise TypeError("the test to add must be callable")
Guido van Rossum13257902007-06-07 23:15:56 +00001105 if isinstance(test, type) and issubclass(test, (TestCase, TestSuite)):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001106 raise TypeError("TestCases and TestSuites must be instantiated "
1107 "before passing them to addTest()")
Fred Drake02538202001-03-21 18:09:46 +00001108 self._tests.append(test)
1109
1110 def addTests(self, tests):
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001111 if isinstance(tests, str):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001112 raise TypeError("tests must be an iterable of tests, not a string")
Fred Drake02538202001-03-21 18:09:46 +00001113 for test in tests:
1114 self.addTest(test)
1115
1116 def run(self, result):
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001117 for test in self:
Fred Drake02538202001-03-21 18:09:46 +00001118 if result.shouldStop:
1119 break
1120 test(result)
1121 return result
1122
Raymond Hettinger664347b2004-12-04 21:21:53 +00001123 def __call__(self, *args, **kwds):
1124 return self.run(*args, **kwds)
1125
Fred Drake02538202001-03-21 18:09:46 +00001126 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001127 """Run the tests without collecting errors in a TestResult"""
Benjamin Petersonf47ed4a2009-04-11 20:45:40 +00001128 for test in self:
Benjamin Peterson52baa292009-03-24 00:56:30 +00001129 test.debug()
Fred Drake02538202001-03-21 18:09:46 +00001130
1131
Benjamin Peterson5254c042009-03-23 22:25:03 +00001132class ClassTestSuite(TestSuite):
1133 """
1134 Suite of tests derived from a single TestCase class.
1135 """
1136
1137 def __init__(self, tests, class_collected_from):
1138 super(ClassTestSuite, self).__init__(tests)
1139 self.collected_from = class_collected_from
1140
1141 def id(self):
1142 module = getattr(self.collected_from, "__module__", None)
1143 if module is not None:
1144 return "{0}.{1}".format(module, self.collected_from.__name__)
1145 return self.collected_from.__name__
1146
1147 def run(self, result):
1148 if getattr(self.collected_from, "__unittest_skip__", False):
1149 # ClassTestSuite result pretends to be a TestCase enough to be
1150 # reported.
1151 result.startTest(self)
1152 try:
1153 result.addSkip(self, self.collected_from.__unittest_skip_why__)
1154 finally:
1155 result.stopTest(self)
1156 else:
1157 result = super(ClassTestSuite, self).run(result)
1158 return result
1159
1160 shortDescription = id
1161
1162
Fred Drake02538202001-03-21 18:09:46 +00001163class FunctionTestCase(TestCase):
1164 """A test case that wraps a test function.
1165
1166 This is useful for slipping pre-existing test functions into the
Guido van Rossumd8faa362007-04-27 19:54:29 +00001167 unittest framework. Optionally, set-up and tidy-up functions can be
Fred Drake02538202001-03-21 18:09:46 +00001168 supplied. As with TestCase, the tidy-up ('tearDown') function will
1169 always be called if the set-up ('setUp') function ran successfully.
1170 """
1171
Benjamin Peterson52baa292009-03-24 00:56:30 +00001172 def __init__(self, testFunc, setUp=None, tearDown=None, description=None):
1173 super(FunctionTestCase, self).__init__()
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001174 self._setUpFunc = setUp
1175 self._tearDownFunc = tearDown
1176 self._testFunc = testFunc
1177 self._description = description
Fred Drake02538202001-03-21 18:09:46 +00001178
1179 def setUp(self):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001180 if self._setUpFunc is not None:
1181 self._setUpFunc()
Fred Drake02538202001-03-21 18:09:46 +00001182
1183 def tearDown(self):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001184 if self._tearDownFunc is not None:
1185 self._tearDownFunc()
Fred Drake02538202001-03-21 18:09:46 +00001186
1187 def runTest(self):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001188 self._testFunc()
Fred Drake02538202001-03-21 18:09:46 +00001189
1190 def id(self):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001191 return self._testFunc.__name__
Fred Drake02538202001-03-21 18:09:46 +00001192
Guido van Rossumd8faa362007-04-27 19:54:29 +00001193 def __eq__(self, other):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001194 if not isinstance(other, self.__class__):
1195 return NotImplemented
Guido van Rossumd8faa362007-04-27 19:54:29 +00001196
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001197 return self._setUpFunc == other._setUpFunc and \
1198 self._tearDownFunc == other._tearDownFunc and \
1199 self._testFunc == other._testFunc and \
1200 self._description == other._description
Guido van Rossumd8faa362007-04-27 19:54:29 +00001201
1202 def __ne__(self, other):
1203 return not self == other
1204
1205 def __hash__(self):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001206 return hash((type(self), self._setUpFunc, self._tearDownFunc,
1207 self._testFunc, self._description))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001208
Fred Drake02538202001-03-21 18:09:46 +00001209 def __str__(self):
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001210 return "%s (%s)" % (_strclass(self.__class__), self._testFunc.__name__)
Fred Drake02538202001-03-21 18:09:46 +00001211
1212 def __repr__(self):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001213 return "<%s testFunc=%s>" % (_strclass(self.__class__), self._testFunc)
Fred Drake02538202001-03-21 18:09:46 +00001214
1215 def shortDescription(self):
Benjamin Peterson7fe73a12009-04-04 16:35:46 +00001216 if self._description is not None:
1217 return self._description
1218 doc = self._testFunc.__doc__
Steve Purcell7e743842003-09-22 11:08:12 +00001219 return doc and doc.split("\n")[0].strip() or None
Fred Drake02538202001-03-21 18:09:46 +00001220
1221
1222
1223##############################################################################
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001224# Locating and loading tests
Fred Drake02538202001-03-21 18:09:46 +00001225##############################################################################
1226
Raymond Hettingerd4cb56d2008-01-30 02:55:10 +00001227def CmpToKey(mycmp):
1228 'Convert a cmp= function into a key= function'
1229 class K(object):
1230 def __init__(self, obj, *args):
1231 self.obj = obj
1232 def __lt__(self, other):
1233 return mycmp(self.obj, other.obj) == -1
1234 return K
1235
Mark Dickinsona56c4672009-01-27 18:17:45 +00001236def three_way_cmp(x, y):
1237 """Return -1 if x < y, 0 if x == y and 1 if x > y"""
1238 return (x > y) - (x < y)
1239
Benjamin Peterson1467ac82009-01-09 03:42:38 +00001240class TestLoader(object):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001241 """
1242 This class is responsible for loading tests according to various criteria
1243 and returning them wrapped in a TestSuite
Fred Drake02538202001-03-21 18:09:46 +00001244 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001245 testMethodPrefix = 'test'
Mark Dickinsona56c4672009-01-27 18:17:45 +00001246 sortTestMethodsUsing = staticmethod(three_way_cmp)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001247 suiteClass = TestSuite
Benjamin Peterson5254c042009-03-23 22:25:03 +00001248 classSuiteClass = ClassTestSuite
Fred Drake02538202001-03-21 18:09:46 +00001249
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001250 def loadTestsFromTestCase(self, testCaseClass):
Steve Purcell15d89272001-04-12 09:05:01 +00001251 """Return a suite of all tests cases contained in testCaseClass"""
Johannes Gijsbersd7b6ad42004-11-07 15:46:25 +00001252 if issubclass(testCaseClass, TestSuite):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001253 raise TypeError("Test cases should not be derived from TestSuite." \
1254 " Maybe you meant to derive from TestCase?")
Steve Purcell7e743842003-09-22 11:08:12 +00001255 testCaseNames = self.getTestCaseNames(testCaseClass)
1256 if not testCaseNames and hasattr(testCaseClass, 'runTest'):
1257 testCaseNames = ['runTest']
Benjamin Peterson5254c042009-03-23 22:25:03 +00001258 suite = self.classSuiteClass(map(testCaseClass, testCaseNames),
1259 testCaseClass)
1260 return suite
Fred Drake02538202001-03-21 18:09:46 +00001261
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001262 def loadTestsFromModule(self, module):
Steve Purcell15d89272001-04-12 09:05:01 +00001263 """Return a suite of all tests cases contained in the given module"""
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001264 tests = []
1265 for name in dir(module):
1266 obj = getattr(module, name)
Guido van Rossum13257902007-06-07 23:15:56 +00001267 if isinstance(obj, type) and issubclass(obj, TestCase):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001268 tests.append(self.loadTestsFromTestCase(obj))
1269 return self.suiteClass(tests)
Fred Drake02538202001-03-21 18:09:46 +00001270
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001271 def loadTestsFromName(self, name, module=None):
Steve Purcell15d89272001-04-12 09:05:01 +00001272 """Return a suite of all tests cases given a string specifier.
1273
1274 The name may resolve either to a module, a test case class, a
1275 test method within a test case class, or a callable object which
1276 returns a TestCase or TestSuite instance.
Tim Peters613b2222001-04-13 05:37:27 +00001277
Steve Purcell15d89272001-04-12 09:05:01 +00001278 The method optionally resolves the names relative to a given module.
1279 """
Steve Purcell7e743842003-09-22 11:08:12 +00001280 parts = name.split('.')
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001281 if module is None:
Steve Purcell7e743842003-09-22 11:08:12 +00001282 parts_copy = parts[:]
1283 while parts_copy:
1284 try:
1285 module = __import__('.'.join(parts_copy))
1286 break
1287 except ImportError:
1288 del parts_copy[-1]
Benjamin Peterson52baa292009-03-24 00:56:30 +00001289 if not parts_copy:
1290 raise
Armin Rigo1b3c04b2003-10-24 17:15:29 +00001291 parts = parts[1:]
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001292 obj = module
1293 for part in parts:
Steve Purcell7e743842003-09-22 11:08:12 +00001294 parent, obj = obj, getattr(obj, part)
Fred Drake02538202001-03-21 18:09:46 +00001295
Benjamin Peterson1467ac82009-01-09 03:42:38 +00001296 if isinstance(obj, types.ModuleType):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001297 return self.loadTestsFromModule(obj)
Guido van Rossum13257902007-06-07 23:15:56 +00001298 elif isinstance(obj, type) and issubclass(obj, TestCase):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001299 return self.loadTestsFromTestCase(obj)
Christian Heimes4a22b5d2007-11-25 09:39:14 +00001300 elif (isinstance(obj, types.FunctionType) and
Guido van Rossum13257902007-06-07 23:15:56 +00001301 isinstance(parent, type) and
Guido van Rossumd8faa362007-04-27 19:54:29 +00001302 issubclass(parent, TestCase)):
Christian Heimes4a22b5d2007-11-25 09:39:14 +00001303 name = obj.__name__
1304 inst = parent(name)
1305 # static methods follow a different path
Christian Heimes4975a1f2007-11-26 10:14:51 +00001306 if not isinstance(getattr(inst, name), types.FunctionType):
Christian Heimes4a22b5d2007-11-25 09:39:14 +00001307 return TestSuite([inst])
Steve Purcell397b45d2003-10-26 10:41:03 +00001308 elif isinstance(obj, TestSuite):
Steve Purcell7e743842003-09-22 11:08:12 +00001309 return obj
Christian Heimes4a22b5d2007-11-25 09:39:14 +00001310
1311 if hasattr(obj, '__call__'):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001312 test = obj()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001313 if isinstance(test, TestSuite):
1314 return test
1315 elif isinstance(test, TestCase):
1316 return TestSuite([test])
1317 else:
1318 raise TypeError("calling %s returned %s, not a test" %
1319 (obj, test))
Fred Drake02538202001-03-21 18:09:46 +00001320 else:
Guido van Rossumd8faa362007-04-27 19:54:29 +00001321 raise TypeError("don't know how to make test from: %s" % obj)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001322
1323 def loadTestsFromNames(self, names, module=None):
Steve Purcell15d89272001-04-12 09:05:01 +00001324 """Return a suite of all tests cases found using the given sequence
1325 of string specifiers. See 'loadTestsFromName()'.
1326 """
Steve Purcell7e743842003-09-22 11:08:12 +00001327 suites = [self.loadTestsFromName(name, module) for name in names]
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001328 return self.suiteClass(suites)
1329
1330 def getTestCaseNames(self, testCaseClass):
Steve Purcell15d89272001-04-12 09:05:01 +00001331 """Return a sorted sequence of method names found within testCaseClass
1332 """
Collin Winterce36ad82007-08-30 01:19:48 +00001333 def isTestMethod(attrname, testCaseClass=testCaseClass,
1334 prefix=self.testMethodPrefix):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001335 return attrname.startswith(prefix) and \
1336 hasattr(getattr(testCaseClass, attrname), '__call__')
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001337 testFnNames = list(filter(isTestMethod, dir(testCaseClass)))
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001338 if self.sortTestMethodsUsing:
Raymond Hettingerd4cb56d2008-01-30 02:55:10 +00001339 testFnNames.sort(key=CmpToKey(self.sortTestMethodsUsing))
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001340 return testFnNames
1341
1342
1343
1344defaultTestLoader = TestLoader()
1345
1346
1347##############################################################################
1348# Patches for old functions: these functions should be considered obsolete
1349##############################################################################
1350
1351def _makeLoader(prefix, sortUsing, suiteClass=None):
1352 loader = TestLoader()
1353 loader.sortTestMethodsUsing = sortUsing
1354 loader.testMethodPrefix = prefix
1355 if suiteClass: loader.suiteClass = suiteClass
1356 return loader
1357
Mark Dickinsonc429a832009-01-27 20:27:05 +00001358def getTestCaseNames(testCaseClass, prefix, sortUsing=three_way_cmp):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001359 return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)
1360
Mark Dickinsonc429a832009-01-27 20:27:05 +00001361def makeSuite(testCaseClass, prefix='test', sortUsing=three_way_cmp,
1362 suiteClass=TestSuite):
1363 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(
1364 testCaseClass)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001365
Mark Dickinsonc429a832009-01-27 20:27:05 +00001366def findTestCases(module, prefix='test', sortUsing=three_way_cmp,
1367 suiteClass=TestSuite):
1368 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(
1369 module)
Fred Drake02538202001-03-21 18:09:46 +00001370
1371
1372##############################################################################
1373# Text UI
1374##############################################################################
1375
Benjamin Peterson1467ac82009-01-09 03:42:38 +00001376class _WritelnDecorator(object):
Fred Drake02538202001-03-21 18:09:46 +00001377 """Used to decorate file-like objects with a handy 'writeln' method"""
1378 def __init__(self,stream):
1379 self.stream = stream
Fred Drake02538202001-03-21 18:09:46 +00001380
1381 def __getattr__(self, attr):
1382 return getattr(self.stream,attr)
1383
Raymond Hettinger91dd19d2003-09-13 02:58:00 +00001384 def writeln(self, arg=None):
Benjamin Petersone549ead2009-03-28 21:42:05 +00001385 if arg:
1386 self.write(arg)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001387 self.write('\n') # text-mode streams translate to \r\n if needed
Tim Petersa19a1682001-03-29 04:36:09 +00001388
Fred Drake02538202001-03-21 18:09:46 +00001389
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001390class _TextTestResult(TestResult):
Fred Drake02538202001-03-21 18:09:46 +00001391 """A test result class that can print formatted text results to a stream.
1392
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001393 Used by TextTestRunner.
Fred Drake02538202001-03-21 18:09:46 +00001394 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001395 separator1 = '=' * 70
1396 separator2 = '-' * 70
Fred Drake02538202001-03-21 18:09:46 +00001397
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001398 def __init__(self, stream, descriptions, verbosity):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001399 super(_TextTestResult, self).__init__()
Fred Drake02538202001-03-21 18:09:46 +00001400 self.stream = stream
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001401 self.showAll = verbosity > 1
1402 self.dots = verbosity == 1
Fred Drake02538202001-03-21 18:09:46 +00001403 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001404
1405 def getDescription(self, test):
1406 if self.descriptions:
1407 return test.shortDescription() or str(test)
1408 else:
1409 return str(test)
1410
Fred Drake02538202001-03-21 18:09:46 +00001411 def startTest(self, test):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001412 super(_TextTestResult, self).startTest(test)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001413 if self.showAll:
1414 self.stream.write(self.getDescription(test))
1415 self.stream.write(" ... ")
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001416 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +00001417
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001418 def addSuccess(self, test):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001419 super(_TextTestResult, self).addSuccess(test)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001420 if self.showAll:
Fred Drake02538202001-03-21 18:09:46 +00001421 self.stream.writeln("ok")
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001422 elif self.dots:
1423 self.stream.write('.')
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001424 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +00001425
1426 def addError(self, test, err):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001427 super(_TextTestResult, self).addError(test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001428 if self.showAll:
1429 self.stream.writeln("ERROR")
1430 elif self.dots:
1431 self.stream.write('E')
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001432 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +00001433
1434 def addFailure(self, test, err):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001435 super(_TextTestResult, self).addFailure(test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001436 if self.showAll:
1437 self.stream.writeln("FAIL")
1438 elif self.dots:
1439 self.stream.write('F')
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001440 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +00001441
Benjamin Peterson5254c042009-03-23 22:25:03 +00001442 def addSkip(self, test, reason):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001443 super(_TextTestResult, self).addSkip(test, reason)
Benjamin Peterson5254c042009-03-23 22:25:03 +00001444 if self.showAll:
1445 self.stream.writeln("skipped {0!r}".format(reason))
1446 elif self.dots:
1447 self.stream.write("s")
1448 self.stream.flush()
1449
1450 def addExpectedFailure(self, test, err):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001451 super(_TextTestResult, self).addExpectedFailure(test, err)
Benjamin Peterson5254c042009-03-23 22:25:03 +00001452 if self.showAll:
1453 self.stream.writeln("expected failure")
1454 elif self.dots:
Benjamin Petersone549ead2009-03-28 21:42:05 +00001455 self.stream.write("x")
Benjamin Peterson5254c042009-03-23 22:25:03 +00001456 self.stream.flush()
1457
1458 def addUnexpectedSuccess(self, test):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001459 super(_TextTestResult, self).addUnexpectedSuccess(test)
Benjamin Peterson5254c042009-03-23 22:25:03 +00001460 if self.showAll:
1461 self.stream.writeln("unexpected success")
1462 elif self.dots:
Benjamin Petersone549ead2009-03-28 21:42:05 +00001463 self.stream.write("u")
Benjamin Peterson5254c042009-03-23 22:25:03 +00001464 self.stream.flush()
1465
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001466 def printErrors(self):
1467 if self.dots or self.showAll:
Fred Drake02538202001-03-21 18:09:46 +00001468 self.stream.writeln()
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001469 self.printErrorList('ERROR', self.errors)
1470 self.printErrorList('FAIL', self.failures)
1471
1472 def printErrorList(self, flavour, errors):
1473 for test, err in errors:
1474 self.stream.writeln(self.separator1)
1475 self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
1476 self.stream.writeln(self.separator2)
Steve Purcell7b065702001-09-06 08:24:40 +00001477 self.stream.writeln("%s" % err)
Fred Drake02538202001-03-21 18:09:46 +00001478
1479
Benjamin Peterson1467ac82009-01-09 03:42:38 +00001480class TextTestRunner(object):
Fred Drake02538202001-03-21 18:09:46 +00001481 """A test runner class that displays results in textual form.
Tim Petersa19a1682001-03-29 04:36:09 +00001482
Fred Drake02538202001-03-21 18:09:46 +00001483 It prints out the names of tests as they are run, errors as they
1484 occur, and a summary of the results at the end of the test run.
1485 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001486 def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1):
Fred Drake02538202001-03-21 18:09:46 +00001487 self.stream = _WritelnDecorator(stream)
1488 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001489 self.verbosity = verbosity
1490
1491 def _makeResult(self):
1492 return _TextTestResult(self.stream, self.descriptions, self.verbosity)
Fred Drake02538202001-03-21 18:09:46 +00001493
1494 def run(self, test):
1495 "Run the given test case or test suite."
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001496 result = self._makeResult()
Fred Drake02538202001-03-21 18:09:46 +00001497 startTime = time.time()
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001498 startTestRun = getattr(result, 'startTestRun', None)
1499 if startTestRun is not None:
1500 startTestRun()
1501 try:
1502 test(result)
1503 finally:
1504 stopTestRun = getattr(result, 'stopTestRun', None)
1505 if stopTestRun is not None:
1506 stopTestRun()
Fred Drake02538202001-03-21 18:09:46 +00001507 stopTime = time.time()
Steve Purcell397b45d2003-10-26 10:41:03 +00001508 timeTaken = stopTime - startTime
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001509 result.printErrors()
1510 self.stream.writeln(result.separator2)
Fred Drake02538202001-03-21 18:09:46 +00001511 run = result.testsRun
1512 self.stream.writeln("Ran %d test%s in %.3fs" %
Neal Norwitz76165042002-05-31 14:15:11 +00001513 (run, run != 1 and "s" or "", timeTaken))
Fred Drake02538202001-03-21 18:09:46 +00001514 self.stream.writeln()
Benjamin Peterson52baa292009-03-24 00:56:30 +00001515 results = map(len, (result.expectedFailures,
1516 result.unexpectedSuccesses,
Benjamin Peterson5254c042009-03-23 22:25:03 +00001517 result.skipped))
Benjamin Peterson52baa292009-03-24 00:56:30 +00001518 expectedFails, unexpectedSuccesses, skipped = results
Benjamin Peterson5254c042009-03-23 22:25:03 +00001519 infos = []
Fred Drake02538202001-03-21 18:09:46 +00001520 if not result.wasSuccessful():
Benjamin Peterson5254c042009-03-23 22:25:03 +00001521 self.stream.write("FAILED")
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001522 failed, errored = len(result.failures), len(result.errors)
Fred Drake02538202001-03-21 18:09:46 +00001523 if failed:
Benjamin Peterson5254c042009-03-23 22:25:03 +00001524 infos.append("failures=%d" % failed)
Fred Drake02538202001-03-21 18:09:46 +00001525 if errored:
Benjamin Peterson5254c042009-03-23 22:25:03 +00001526 infos.append("errors=%d" % errored)
Fred Drake02538202001-03-21 18:09:46 +00001527 else:
Benjamin Petersone549ead2009-03-28 21:42:05 +00001528 self.stream.write("OK")
Benjamin Peterson5254c042009-03-23 22:25:03 +00001529 if skipped:
1530 infos.append("skipped=%d" % skipped)
Benjamin Peterson52baa292009-03-24 00:56:30 +00001531 if expectedFails:
1532 infos.append("expected failures=%d" % expectedFails)
1533 if unexpectedSuccesses:
1534 infos.append("unexpected successes=%d" % unexpectedSuccesses)
Benjamin Peterson5254c042009-03-23 22:25:03 +00001535 if infos:
1536 self.stream.writeln(" (%s)" % (", ".join(infos),))
Benjamin Petersone549ead2009-03-28 21:42:05 +00001537 else:
1538 self.stream.write("\n")
Fred Drake02538202001-03-21 18:09:46 +00001539 return result
Tim Petersa19a1682001-03-29 04:36:09 +00001540
Fred Drake02538202001-03-21 18:09:46 +00001541
Fred Drake02538202001-03-21 18:09:46 +00001542
1543##############################################################################
1544# Facilities for running tests from the command line
1545##############################################################################
1546
Benjamin Peterson1467ac82009-01-09 03:42:38 +00001547class TestProgram(object):
Fred Drake02538202001-03-21 18:09:46 +00001548 """A command-line program that runs a set of tests; this is primarily
1549 for making test modules conveniently executable.
1550 """
1551 USAGE = """\
Steve Purcell17a781b2001-04-09 15:37:31 +00001552Usage: %(progName)s [options] [test] [...]
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001553
1554Options:
1555 -h, --help Show this message
1556 -v, --verbose Verbose output
1557 -q, --quiet Minimal output
Fred Drake02538202001-03-21 18:09:46 +00001558
1559Examples:
1560 %(progName)s - run default set of tests
1561 %(progName)s MyTestSuite - run suite 'MyTestSuite'
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001562 %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething
1563 %(progName)s MyTestCase - run all 'test*' test methods
Fred Drake02538202001-03-21 18:09:46 +00001564 in MyTestCase
1565"""
1566 def __init__(self, module='__main__', defaultTest=None,
Guido van Rossumd8faa362007-04-27 19:54:29 +00001567 argv=None, testRunner=TextTestRunner,
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001568 testLoader=defaultTestLoader, exit=True):
Antoine Pitroue7bd8682009-01-09 19:29:16 +00001569 if isinstance(module, str):
Fred Drake02538202001-03-21 18:09:46 +00001570 self.module = __import__(module)
Steve Purcell7e743842003-09-22 11:08:12 +00001571 for part in module.split('.')[1:]:
Fred Drake02538202001-03-21 18:09:46 +00001572 self.module = getattr(self.module, part)
1573 else:
1574 self.module = module
1575 if argv is None:
1576 argv = sys.argv
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001577
1578 self.exit = exit
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001579 self.verbosity = 1
Fred Drake02538202001-03-21 18:09:46 +00001580 self.defaultTest = defaultTest
1581 self.testRunner = testRunner
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001582 self.testLoader = testLoader
Fred Drake02538202001-03-21 18:09:46 +00001583 self.progName = os.path.basename(argv[0])
1584 self.parseArgs(argv)
Fred Drake02538202001-03-21 18:09:46 +00001585 self.runTests()
1586
1587 def usageExit(self, msg=None):
Benjamin Peterson52baa292009-03-24 00:56:30 +00001588 if msg:
1589 print(msg)
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001590 print(self.USAGE % self.__dict__)
Fred Drake02538202001-03-21 18:09:46 +00001591 sys.exit(2)
1592
1593 def parseArgs(self, argv):
1594 import getopt
Benjamin Peterson5254c042009-03-23 22:25:03 +00001595 long_opts = ['help','verbose','quiet']
Fred Drake02538202001-03-21 18:09:46 +00001596 try:
Benjamin Peterson5254c042009-03-23 22:25:03 +00001597 options, args = getopt.getopt(argv[1:], 'hHvq', long_opts)
Fred Drake02538202001-03-21 18:09:46 +00001598 for opt, value in options:
1599 if opt in ('-h','-H','--help'):
1600 self.usageExit()
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001601 if opt in ('-q','--quiet'):
1602 self.verbosity = 0
1603 if opt in ('-v','--verbose'):
1604 self.verbosity = 2
Fred Drake02538202001-03-21 18:09:46 +00001605 if len(args) == 0 and self.defaultTest is None:
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001606 self.test = self.testLoader.loadTestsFromModule(self.module)
1607 return
Fred Drake02538202001-03-21 18:09:46 +00001608 if len(args) > 0:
1609 self.testNames = args
1610 else:
1611 self.testNames = (self.defaultTest,)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001612 self.createTests()
Guido van Rossumb940e112007-01-10 16:19:56 +00001613 except getopt.error as msg:
Fred Drake02538202001-03-21 18:09:46 +00001614 self.usageExit(msg)
1615
1616 def createTests(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001617 self.test = self.testLoader.loadTestsFromNames(self.testNames,
1618 self.module)
Fred Drake02538202001-03-21 18:09:46 +00001619
1620 def runTests(self):
Guido van Rossum13257902007-06-07 23:15:56 +00001621 if isinstance(self.testRunner, type):
Guido van Rossumd8faa362007-04-27 19:54:29 +00001622 try:
1623 testRunner = self.testRunner(verbosity=self.verbosity)
1624 except TypeError:
1625 # didn't accept the verbosity argument
1626 testRunner = self.testRunner()
1627 else:
1628 # it is assumed to be a TestRunner instance
1629 testRunner = self.testRunner
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001630 self.result = testRunner.run(self.test)
1631 if self.exit:
1632 sys.exit(not self.result.wasSuccessful())
Fred Drake02538202001-03-21 18:09:46 +00001633
1634main = TestProgram
1635
1636
1637##############################################################################
1638# Executing this module from the command line
1639##############################################################################
1640
1641if __name__ == "__main__":
1642 main(module=None)