blob: d5c2927d641ff28513306620d29803cfded3944d [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*'
Gregory P. Smith28399852009-03-31 16:54:10 +000017 self.assertEqual((1 + 2), 3)
18 self.assertEqual(0 + 1, 1)
Steve Purcell7b065702001-09-06 08:24:40 +000019 def testMultiply(self):
Gregory P. Smith28399852009-03-31 16:54:10 +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 Peterson4e4de332009-03-24 00:37:12 +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 Peterson4e4de332009-03-24 00:37:12 +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
Gregory P. Smith28399852009-03-31 16:54:10 +000048import difflib
Benjamin Peterson692428e2009-03-23 21:50:21 +000049import functools
Gregory P. Smith28399852009-03-31 16:54:10 +000050import os
51import pprint
52import re
53import sys
54import time
55import traceback
56import types
Gregory P. Smith65ff0052009-03-31 19:59:14 +000057import warnings
Fred Drake02538202001-03-21 18:09:46 +000058
59##############################################################################
Steve Purcelld75e7e42003-09-15 11:01:21 +000060# Exported classes and functions
61##############################################################################
Benjamin Petersonc750d4d2009-03-24 00:39:24 +000062__all__ = ['TestResult', 'TestCase', 'TestSuite', 'ClassTestSuite',
63 'TextTestRunner', 'TestLoader', 'FunctionTestCase', 'main',
Benjamin Peterson03715482009-03-24 01:11:37 +000064 'defaultTestLoader', 'SkipTest', 'skip', 'skipIf', 'skipUnless',
Benjamin Petersonc750d4d2009-03-24 00:39:24 +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##############################################################################
Steve Purcell7e743842003-09-22 11:08:12 +000072# Backward compatibility
73##############################################################################
Steve Purcell7e743842003-09-22 11:08:12 +000074
Raymond Hettinger5930d8f2008-07-10 16:06:41 +000075def _CmpToKey(mycmp):
76 'Convert a cmp= function into a key= function'
77 class K(object):
78 def __init__(self, obj):
79 self.obj = obj
80 def __lt__(self, other):
81 return mycmp(self.obj, other.obj) == -1
82 return K
Steve Purcell7e743842003-09-22 11:08:12 +000083
84##############################################################################
Fred Drake02538202001-03-21 18:09:46 +000085# Test framework core
86##############################################################################
87
Steve Purcelldc391a62002-08-09 09:46:23 +000088def _strclass(cls):
89 return "%s.%s" % (cls.__module__, cls.__name__)
90
Benjamin Peterson692428e2009-03-23 21:50:21 +000091
92class SkipTest(Exception):
93 """
94 Raise this exception in a test to skip it.
95
96 Usually you can use TestResult.skip() or one of the skipping decorators
97 instead of raising this directly.
98 """
99 pass
100
101class _ExpectedFailure(Exception):
102 """
103 Raise this when a test is expected to fail.
104
105 This is an implementation detail.
106 """
107
108 def __init__(self, exc_info):
109 super(_ExpectedFailure, self).__init__()
110 self.exc_info = exc_info
111
112class _UnexpectedSuccess(Exception):
113 """
114 The test was supposed to fail, but it didn't!
115 """
116 pass
117
118def _id(obj):
119 return obj
120
121def skip(reason):
122 """
123 Unconditionally skip a test.
124 """
125 def decorator(test_item):
126 if isinstance(test_item, type) and issubclass(test_item, TestCase):
127 test_item.__unittest_skip__ = True
128 test_item.__unittest_skip_why__ = reason
129 return test_item
130 @functools.wraps(test_item)
131 def skip_wrapper(*args, **kwargs):
132 raise SkipTest(reason)
133 return skip_wrapper
134 return decorator
135
136def skipIf(condition, reason):
137 """
138 Skip a test if the condition is true.
139 """
140 if condition:
141 return skip(reason)
142 return _id
143
144def skipUnless(condition, reason):
145 """
146 Skip a test unless the condition is true.
147 """
148 if not condition:
149 return skip(reason)
150 return _id
151
152
153def expectedFailure(func):
154 @functools.wraps(func)
155 def wrapper(*args, **kwargs):
156 try:
157 func(*args, **kwargs)
158 except Exception:
159 raise _ExpectedFailure(sys.exc_info())
160 raise _UnexpectedSuccess
161 return wrapper
162
Steve Purcellb8d5f242003-12-06 13:03:13 +0000163__unittest = 1
164
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000165class TestResult(object):
Fred Drake02538202001-03-21 18:09:46 +0000166 """Holder for test result information.
167
168 Test results are automatically managed by the TestCase and TestSuite
169 classes, and do not need to be explicitly manipulated by writers of tests.
170
171 Each instance holds the total number of tests run, and collections of
172 failures and errors that occurred among those test runs. The collections
Steve Purcell7b065702001-09-06 08:24:40 +0000173 contain tuples of (testcase, exceptioninfo), where exceptioninfo is the
Fred Drake656f9ec2001-09-06 19:13:14 +0000174 formatted traceback of the error that occurred.
Fred Drake02538202001-03-21 18:09:46 +0000175 """
176 def __init__(self):
177 self.failures = []
178 self.errors = []
179 self.testsRun = 0
Benjamin Peterson692428e2009-03-23 21:50:21 +0000180 self.skipped = []
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +0000181 self.expectedFailures = []
182 self.unexpectedSuccesses = []
Georg Brandl15c5ce92007-03-07 09:09:40 +0000183 self.shouldStop = False
Fred Drake02538202001-03-21 18:09:46 +0000184
185 def startTest(self, test):
186 "Called when the given test is about to be run"
187 self.testsRun = self.testsRun + 1
188
189 def stopTest(self, test):
190 "Called when the given test has been run"
191 pass
192
193 def addError(self, test, err):
Steve Purcell7b065702001-09-06 08:24:40 +0000194 """Called when an error has occurred. 'err' is a tuple of values as
195 returned by sys.exc_info().
196 """
Steve Purcellb8d5f242003-12-06 13:03:13 +0000197 self.errors.append((test, self._exc_info_to_string(err, test)))
Fred Drake02538202001-03-21 18:09:46 +0000198
199 def addFailure(self, test, err):
Steve Purcell7b065702001-09-06 08:24:40 +0000200 """Called when an error has occurred. 'err' is a tuple of values as
201 returned by sys.exc_info()."""
Steve Purcellb8d5f242003-12-06 13:03:13 +0000202 self.failures.append((test, self._exc_info_to_string(err, test)))
Fred Drake02538202001-03-21 18:09:46 +0000203
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000204 def addSuccess(self, test):
205 "Called when a test has completed successfully"
206 pass
207
Benjamin Peterson692428e2009-03-23 21:50:21 +0000208 def addSkip(self, test, reason):
209 """Called when a test is skipped."""
210 self.skipped.append((test, reason))
211
212 def addExpectedFailure(self, test, err):
213 """Called when an expected failure/error occured."""
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +0000214 self.expectedFailures.append(
Benjamin Peterson692428e2009-03-23 21:50:21 +0000215 (test, self._exc_info_to_string(err, test)))
216
217 def addUnexpectedSuccess(self, test):
218 """Called when a test was expected to fail, but succeed."""
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +0000219 self.unexpectedSuccesses.append(test)
Benjamin Peterson692428e2009-03-23 21:50:21 +0000220
Fred Drake02538202001-03-21 18:09:46 +0000221 def wasSuccessful(self):
222 "Tells whether or not this result was a success"
223 return len(self.failures) == len(self.errors) == 0
224
225 def stop(self):
226 "Indicates that the tests should be aborted"
Steve Purcell7e743842003-09-22 11:08:12 +0000227 self.shouldStop = True
Tim Petersa19a1682001-03-29 04:36:09 +0000228
Steve Purcellb8d5f242003-12-06 13:03:13 +0000229 def _exc_info_to_string(self, err, test):
Steve Purcell7b065702001-09-06 08:24:40 +0000230 """Converts a sys.exc_info()-style tuple of values into a string."""
Steve Purcellb8d5f242003-12-06 13:03:13 +0000231 exctype, value, tb = err
232 # Skip test runner traceback levels
233 while tb and self._is_relevant_tb_level(tb):
234 tb = tb.tb_next
235 if exctype is test.failureException:
236 # Skip assert*() traceback levels
237 length = self._count_relevant_tb_levels(tb)
238 return ''.join(traceback.format_exception(exctype, value, tb, length))
239 return ''.join(traceback.format_exception(exctype, value, tb))
240
241 def _is_relevant_tb_level(self, tb):
Georg Brandl56af5fc2008-07-18 19:30:10 +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 Petersona7d441d2009-03-24 00:35:20 +0000256
Gregory P. Smith28399852009-03-31 16:54:10 +0000257class _AssertRaisesContext(object):
258 """A context manager used to implement TestCase.assertRaises* methods."""
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000259
Gregory P. Smith28399852009-03-31 16:54:10 +0000260 def __init__(self, expected, test_case, expected_regexp=None):
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000261 self.expected = expected
262 self.failureException = test_case.failureException
Gregory P. Smith28399852009-03-31 16:54:10 +0000263 self.expected_regex = expected_regexp
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000264
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000265 def __enter__(self):
266 pass
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000267
Benjamin Petersonbaba1952009-04-18 19:26:19 +0000268 def __exit__(self, exc_type, exc_value, tb):
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000269 if exc_type is None:
270 try:
271 exc_name = self.expected.__name__
272 except AttributeError:
273 exc_name = str(self.expected)
274 raise self.failureException(
275 "{0} not raised".format(exc_name))
Gregory P. Smith28399852009-03-31 16:54:10 +0000276 if not issubclass(exc_type, self.expected):
Michael Foord345b2fe2009-04-02 03:20:38 +0000277 # let unexpected exceptions pass through
Gregory P. Smith28399852009-03-31 16:54:10 +0000278 return False
279 if self.expected_regex is None:
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000280 return True
Gregory P. Smith28399852009-03-31 16:54:10 +0000281
282 expected_regexp = self.expected_regex
283 if isinstance(expected_regexp, basestring):
284 expected_regexp = re.compile(expected_regexp)
285 if not expected_regexp.search(str(exc_value)):
286 raise self.failureException('"%s" does not match "%s"' %
287 (expected_regexp.pattern, str(exc_value)))
288 return True
289
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000290
Michael Foorde2942d02009-04-02 05:51:54 +0000291class _AssertWrapper(object):
292 """Wrap entries in the _type_equality_funcs registry to make them deep
293 copyable."""
294
295 def __init__(self, function):
296 self.function = function
297
298 def __deepcopy__(self, memo):
299 memo[id(self)] = self
300
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000301
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000302class TestCase(object):
Fred Drake02538202001-03-21 18:09:46 +0000303 """A class whose instances are single test cases.
304
Fred Drake02538202001-03-21 18:09:46 +0000305 By default, the test code itself should be placed in a method named
306 'runTest'.
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000307
Tim Petersa19a1682001-03-29 04:36:09 +0000308 If the fixture may be used for many test cases, create as
Fred Drake02538202001-03-21 18:09:46 +0000309 many test methods as are needed. When instantiating such a TestCase
310 subclass, specify in the constructor arguments the name of the test method
311 that the instance is to execute.
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000312
Tim Petersa19a1682001-03-29 04:36:09 +0000313 Test authors should subclass TestCase for their own tests. Construction
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000314 and deconstruction of the test's environment ('fixture') can be
315 implemented by overriding the 'setUp' and 'tearDown' methods respectively.
316
317 If it is necessary to override the __init__ method, the base class
318 __init__ method must always be called. It is important that subclasses
319 should not change the signature of their __init__ method, since instances
320 of the classes are instantiated automatically by parts of the framework
321 in order to be run.
Fred Drake02538202001-03-21 18:09:46 +0000322 """
Steve Purcell15d89272001-04-12 09:05:01 +0000323
324 # This attribute determines which exception will be raised when
325 # the instance's assertion methods fail; test methods raising this
326 # exception will be deemed to have 'failed' rather than 'errored'
327
328 failureException = AssertionError
329
Michael Foord345b2fe2009-04-02 03:20:38 +0000330 # This attribute determines whether long messages (including repr of
331 # objects used in assert methods) will be printed on failure in *addition*
332 # to any explicit message passed.
333
334 longMessage = False
335
336
Fred Drake02538202001-03-21 18:09:46 +0000337 def __init__(self, methodName='runTest'):
338 """Create an instance of the class that will use the named test
339 method when executed. Raises a ValueError if the instance does
340 not have a method with the specified name.
341 """
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000342 self._testMethodName = methodName
Michael Foorde2fb98f2009-05-02 20:15:05 +0000343 self._result = None
Fred Drake02538202001-03-21 18:09:46 +0000344 try:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000345 testMethod = getattr(self, methodName)
Fred Drake02538202001-03-21 18:09:46 +0000346 except AttributeError:
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000347 raise ValueError("no such test method in %s: %s" % \
348 (self.__class__, methodName))
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000349 self._testMethodDoc = testMethod.__doc__
Michael Foorde2fb98f2009-05-02 20:15:05 +0000350 self._cleanups = []
Fred Drake02538202001-03-21 18:09:46 +0000351
Gregory P. Smith28399852009-03-31 16:54:10 +0000352 # Map types to custom assertEqual functions that will compare
353 # instances of said type in more detail to generate a more useful
354 # error message.
Benjamin Peterson71095ae2009-04-01 23:15:49 +0000355 self._type_equality_funcs = {}
Gregory P. Smith28399852009-03-31 16:54:10 +0000356 self.addTypeEqualityFunc(dict, self.assertDictEqual)
357 self.addTypeEqualityFunc(list, self.assertListEqual)
358 self.addTypeEqualityFunc(tuple, self.assertTupleEqual)
359 self.addTypeEqualityFunc(set, self.assertSetEqual)
360 self.addTypeEqualityFunc(frozenset, self.assertSetEqual)
361
362 def addTypeEqualityFunc(self, typeobj, function):
363 """Add a type specific assertEqual style function to compare a type.
364
365 This method is for use by TestCase subclasses that need to register
366 their own type equality functions to provide nicer error messages.
367
368 Args:
369 typeobj: The data type to call this function on when both values
370 are of the same type in assertEqual().
371 function: The callable taking two arguments and an optional
372 msg= argument that raises self.failureException with a
373 useful error message when the two arguments are not equal.
374 """
Michael Foorde2942d02009-04-02 05:51:54 +0000375 self._type_equality_funcs[typeobj] = _AssertWrapper(function)
Gregory P. Smith28399852009-03-31 16:54:10 +0000376
Michael Foorde2fb98f2009-05-02 20:15:05 +0000377 def addCleanup(self, function, *args, **kwargs):
378 """Add a function, with arguments, to be called when the test is
379 completed. Functions added are called on a LIFO basis and are
380 called after tearDown on test failure or success.
381
382 Cleanup items are called even if setUp fails (unlike tearDown)."""
383 self._cleanups.append((function, args, kwargs))
384
Fred Drake02538202001-03-21 18:09:46 +0000385 def setUp(self):
386 "Hook method for setting up the test fixture before exercising it."
387 pass
388
389 def tearDown(self):
390 "Hook method for deconstructing the test fixture after testing it."
391 pass
392
393 def countTestCases(self):
394 return 1
395
396 def defaultTestResult(self):
397 return TestResult()
398
399 def shortDescription(self):
Gregory P. Smith28399852009-03-31 16:54:10 +0000400 """Returns both the test method name and first line of its docstring.
Fred Drake02538202001-03-21 18:09:46 +0000401
Gregory P. Smith28399852009-03-31 16:54:10 +0000402 If no docstring is given, only returns the method name.
403
404 This method overrides unittest.TestCase.shortDescription(), which
405 only returns the first line of the docstring, obscuring the name
406 of the test upon failure.
Fred Drake02538202001-03-21 18:09:46 +0000407 """
Gregory P. Smith28399852009-03-31 16:54:10 +0000408 desc = str(self)
409 doc_first_line = None
410
411 if self._testMethodDoc:
412 doc_first_line = self._testMethodDoc.split("\n")[0].strip()
413 if doc_first_line:
414 desc = '\n'.join((desc, doc_first_line))
415 return desc
Fred Drake02538202001-03-21 18:09:46 +0000416
417 def id(self):
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000418 return "%s.%s" % (_strclass(self.__class__), self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000419
Georg Brandl15c5ce92007-03-07 09:09:40 +0000420 def __eq__(self, other):
421 if type(self) is not type(other):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000422 return NotImplemented
Georg Brandl15c5ce92007-03-07 09:09:40 +0000423
424 return self._testMethodName == other._testMethodName
425
426 def __ne__(self, other):
427 return not self == other
428
429 def __hash__(self):
Collin Winter9453e5d2007-03-09 23:30:39 +0000430 return hash((type(self), self._testMethodName))
Georg Brandl15c5ce92007-03-07 09:09:40 +0000431
Fred Drake02538202001-03-21 18:09:46 +0000432 def __str__(self):
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000433 return "%s (%s)" % (self._testMethodName, _strclass(self.__class__))
Fred Drake02538202001-03-21 18:09:46 +0000434
435 def __repr__(self):
436 return "<%s testMethod=%s>" % \
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000437 (_strclass(self.__class__), self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000438
439 def run(self, result=None):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000440 if result is None:
441 result = self.defaultTestResult()
Michael Foorde2fb98f2009-05-02 20:15:05 +0000442 self._result = result
Fred Drake02538202001-03-21 18:09:46 +0000443 result.startTest(self)
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000444 testMethod = getattr(self, self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000445 try:
Benjamin Peterson692428e2009-03-23 21:50:21 +0000446 success = False
Fred Drake02538202001-03-21 18:09:46 +0000447 try:
Michael Foorde2fb98f2009-05-02 20:15:05 +0000448 self.setUp()
Benjamin Peterson692428e2009-03-23 21:50:21 +0000449 except SkipTest as e:
450 result.addSkip(self, str(e))
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000451 except Exception:
Benjamin Petersonc9301352009-03-26 16:32:23 +0000452 result.addError(self, sys.exc_info())
Benjamin Peterson692428e2009-03-23 21:50:21 +0000453 else:
Michael Foorde2fb98f2009-05-02 20:15:05 +0000454 try:
455 testMethod()
456 except self.failureException:
457 result.addFailure(self, sys.exc_info())
458 except _ExpectedFailure as e:
459 result.addExpectedFailure(self, e.exc_info)
460 except _UnexpectedSuccess:
461 result.addUnexpectedSuccess(self)
462 except SkipTest as e:
463 result.addSkip(self, str(e))
464 except Exception:
465 result.addError(self, sys.exc_info())
466 else:
467 success = True
Fred Drake02538202001-03-21 18:09:46 +0000468
Michael Foorde2fb98f2009-05-02 20:15:05 +0000469 try:
470 self.tearDown()
471 except Exception:
472 result.addError(self, sys.exc_info())
473 success = False
474
475 cleanUpSuccess = self.doCleanups()
476 success = success and cleanUpSuccess
Benjamin Peterson692428e2009-03-23 21:50:21 +0000477 if success:
478 result.addSuccess(self)
Fred Drake02538202001-03-21 18:09:46 +0000479 finally:
480 result.stopTest(self)
481
Michael Foorde2fb98f2009-05-02 20:15:05 +0000482 def doCleanups(self):
483 """Execute all cleanup functions. Normally called for you after
484 tearDown."""
485 result = self._result
486 ok = True
487 while self._cleanups:
488 function, args, kwargs = self._cleanups.pop(-1)
489 try:
490 function(*args, **kwargs)
491 except Exception:
492 ok = False
493 result.addError(self, sys.exc_info())
494 return ok
495
Raymond Hettinger664347b2004-12-04 21:21:53 +0000496 def __call__(self, *args, **kwds):
497 return self.run(*args, **kwds)
Steve Purcell7e743842003-09-22 11:08:12 +0000498
Fred Drake02538202001-03-21 18:09:46 +0000499 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000500 """Run the test without collecting errors in a TestResult"""
Fred Drake02538202001-03-21 18:09:46 +0000501 self.setUp()
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000502 getattr(self, self._testMethodName)()
Fred Drake02538202001-03-21 18:09:46 +0000503 self.tearDown()
504
Benjamin Peterson47d97382009-03-26 20:05:50 +0000505 def skipTest(self, reason):
Benjamin Peterson692428e2009-03-23 21:50:21 +0000506 """Skip this test."""
507 raise SkipTest(reason)
508
Steve Purcell15d89272001-04-12 09:05:01 +0000509 def fail(self, msg=None):
510 """Fail immediately, with the given message."""
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000511 raise self.failureException(msg)
Fred Drake02538202001-03-21 18:09:46 +0000512
Gregory P. Smith7558d572009-03-31 19:03:28 +0000513 def assertFalse(self, expr, msg=None):
Fred Drake02538202001-03-21 18:09:46 +0000514 "Fail the test if the expression is true."
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000515 if expr:
Michael Foord345b2fe2009-04-02 03:20:38 +0000516 msg = self._formatMessage(msg, "%r is not False" % expr)
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000517 raise self.failureException(msg)
Fred Drake02538202001-03-21 18:09:46 +0000518
Gregory P. Smith7558d572009-03-31 19:03:28 +0000519 def assertTrue(self, expr, msg=None):
Steve Purcell15d89272001-04-12 09:05:01 +0000520 """Fail the test unless the expression is true."""
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000521 if not expr:
Michael Foord345b2fe2009-04-02 03:20:38 +0000522 msg = self._formatMessage(msg, "%r is not True" % expr)
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000523 raise self.failureException(msg)
Steve Purcell15d89272001-04-12 09:05:01 +0000524
Michael Foord345b2fe2009-04-02 03:20:38 +0000525 def _formatMessage(self, msg, standardMsg):
526 """Honour the longMessage attribute when generating failure messages.
527 If longMessage is False this means:
528 * Use only an explicit message if it is provided
529 * Otherwise use the standard message for the assert
530
531 If longMessage is True:
532 * Use the standard message
533 * If an explicit message is provided, plus ' : ' and the explicit message
534 """
535 if not self.longMessage:
536 return msg or standardMsg
537 if msg is None:
538 return standardMsg
539 return standardMsg + ' : ' + msg
540
541
Gregory P. Smith7558d572009-03-31 19:03:28 +0000542 def assertRaises(self, excClass, callableObj=None, *args, **kwargs):
Steve Purcell15d89272001-04-12 09:05:01 +0000543 """Fail unless an exception of class excClass is thrown
Fred Drake02538202001-03-21 18:09:46 +0000544 by callableObj when invoked with arguments args and keyword
545 arguments kwargs. If a different type of exception is
546 thrown, it will not be caught, and the test case will be
547 deemed to have suffered an error, exactly as for an
548 unexpected exception.
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000549
550 If called with callableObj omitted or None, will return a
551 context object used like this::
552
Gregory P. Smith7558d572009-03-31 19:03:28 +0000553 with self.assertRaises(some_error_class):
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000554 do_something()
Fred Drake02538202001-03-21 18:09:46 +0000555 """
Gregory P. Smith28399852009-03-31 16:54:10 +0000556 context = _AssertRaisesContext(excClass, self)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000557 if callableObj is None:
558 return context
559 with context:
Guido van Rossum68468eb2003-02-27 20:14:51 +0000560 callableObj(*args, **kwargs)
Fred Drake02538202001-03-21 18:09:46 +0000561
Gregory P. Smith28399852009-03-31 16:54:10 +0000562 def _getAssertEqualityFunc(self, first, second):
563 """Get a detailed comparison function for the types of the two args.
564
565 Returns: A callable accepting (first, second, msg=None) that will
566 raise a failure exception if first != second with a useful human
567 readable error message for those types.
568 """
569 #
570 # NOTE(gregory.p.smith): I considered isinstance(first, type(second))
571 # and vice versa. I opted for the conservative approach in case
572 # subclasses are not intended to be compared in detail to their super
573 # class instances using a type equality func. This means testing
574 # subtypes won't automagically use the detailed comparison. Callers
575 # should use their type specific assertSpamEqual method to compare
576 # subclasses if the detailed comparison is desired and appropriate.
577 # See the discussion in http://bugs.python.org/issue2578.
578 #
579 if type(first) is type(second):
Michael Foorde2942d02009-04-02 05:51:54 +0000580 asserter = self._type_equality_funcs.get(type(first))
581 if asserter is not None:
582 return asserter.function
583
Gregory P. Smith28399852009-03-31 16:54:10 +0000584 return self._baseAssertEqual
585
586 def _baseAssertEqual(self, first, second, msg=None):
587 """The default assertEqual implementation, not type specific."""
588 if not first == second:
Michael Foord345b2fe2009-04-02 03:20:38 +0000589 standardMsg = '%r != %r' % (first, second)
590 msg = self._formatMessage(msg, standardMsg)
591 raise self.failureException(msg)
Gregory P. Smith28399852009-03-31 16:54:10 +0000592
Gregory P. Smith7558d572009-03-31 19:03:28 +0000593 def assertEqual(self, first, second, msg=None):
Raymond Hettingerc377cbf2003-04-04 22:56:42 +0000594 """Fail if the two objects are unequal as determined by the '=='
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000595 operator.
596 """
Gregory P. Smith28399852009-03-31 16:54:10 +0000597 assertion_func = self._getAssertEqualityFunc(first, second)
598 assertion_func(first, second, msg=msg)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000599
Gregory P. Smith7558d572009-03-31 19:03:28 +0000600 def assertNotEqual(self, first, second, msg=None):
Steve Purcell15d89272001-04-12 09:05:01 +0000601 """Fail if the two objects are equal as determined by the '=='
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000602 operator.
603 """
Michael Foord345b2fe2009-04-02 03:20:38 +0000604 if not first != second:
605 msg = self._formatMessage(msg, '%r == %r' % (first, second))
606 raise self.failureException(msg)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000607
Gregory P. Smith7558d572009-03-31 19:03:28 +0000608 def assertAlmostEqual(self, first, second, places=7, msg=None):
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000609 """Fail if the two objects are unequal as determined by their
610 difference rounded to the given number of decimal places
611 (default 7) and comparing to zero.
612
Steve Purcell397b45d2003-10-26 10:41:03 +0000613 Note that decimal places (from zero) are usually not the same
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000614 as significant digits (measured from the most signficant digit).
615 """
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000616 if round(abs(second-first), places) != 0:
Michael Foord345b2fe2009-04-02 03:20:38 +0000617 standardMsg = '%r != %r within %r places' % (first, second, places)
618 msg = self._formatMessage(msg, standardMsg)
619 raise self.failureException(msg)
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000620
Gregory P. Smith7558d572009-03-31 19:03:28 +0000621 def assertNotAlmostEqual(self, first, second, places=7, msg=None):
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000622 """Fail if the two objects are equal as determined by their
623 difference rounded to the given number of decimal places
624 (default 7) and comparing to zero.
625
Steve Purcellcca34912003-10-26 16:38:16 +0000626 Note that decimal places (from zero) are usually not the same
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000627 as significant digits (measured from the most signficant digit).
628 """
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000629 if round(abs(second-first), places) == 0:
Michael Foord345b2fe2009-04-02 03:20:38 +0000630 standardMsg = '%r == %r within %r places' % (first, second, places)
631 msg = self._formatMessage(msg, standardMsg)
632 raise self.failureException(msg)
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000633
Steve Purcell7e743842003-09-22 11:08:12 +0000634 # Synonyms for assertion methods
635
Gregory P. Smith7558d572009-03-31 19:03:28 +0000636 # The plurals are undocumented. Keep them that way to discourage use.
637 # Do not add more. Do not remove.
638 # Going through a deprecation cycle on these would annoy many people.
639 assertEquals = assertEqual
640 assertNotEquals = assertNotEqual
641 assertAlmostEquals = assertAlmostEqual
642 assertNotAlmostEquals = assertNotAlmostEqual
643 assert_ = assertTrue
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000644
Gregory P. Smith7558d572009-03-31 19:03:28 +0000645 # These fail* assertion method names are pending deprecation and will
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000646 # be a DeprecationWarning in 3.2; http://bugs.python.org/issue2578
Benjamin Peterson71095ae2009-04-01 23:15:49 +0000647 def _deprecate(original_func):
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000648 def deprecated_func(*args, **kwargs):
649 warnings.warn(
650 'Please use {0} instead.'.format(original_func.__name__),
651 PendingDeprecationWarning, 2)
652 return original_func(*args, **kwargs)
653 return deprecated_func
Steve Purcell15d89272001-04-12 09:05:01 +0000654
Benjamin Peterson71095ae2009-04-01 23:15:49 +0000655 failUnlessEqual = _deprecate(assertEqual)
656 failIfEqual = _deprecate(assertNotEqual)
657 failUnlessAlmostEqual = _deprecate(assertAlmostEqual)
658 failIfAlmostEqual = _deprecate(assertNotAlmostEqual)
659 failUnless = _deprecate(assertTrue)
660 failUnlessRaises = _deprecate(assertRaises)
661 failIf = _deprecate(assertFalse)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000662
Gregory P. Smith28399852009-03-31 16:54:10 +0000663 def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
664 """An equality assertion for ordered sequences (like lists and tuples).
665
666 For the purposes of this function, a valid orderd sequence type is one
667 which can be indexed, has a length, and has an equality operator.
668
669 Args:
670 seq1: The first sequence to compare.
671 seq2: The second sequence to compare.
672 seq_type: The expected datatype of the sequences, or None if no
673 datatype should be enforced.
674 msg: Optional message to use on failure instead of a list of
675 differences.
676 """
677 if seq_type != None:
678 seq_type_name = seq_type.__name__
679 if not isinstance(seq1, seq_type):
680 raise self.failureException('First sequence is not a %s: %r'
681 % (seq_type_name, seq1))
682 if not isinstance(seq2, seq_type):
683 raise self.failureException('Second sequence is not a %s: %r'
684 % (seq_type_name, seq2))
685 else:
686 seq_type_name = "sequence"
687
688 differing = None
689 try:
690 len1 = len(seq1)
691 except (TypeError, NotImplementedError):
692 differing = 'First %s has no length. Non-sequence?' % (
693 seq_type_name)
694
695 if differing is None:
696 try:
697 len2 = len(seq2)
698 except (TypeError, NotImplementedError):
699 differing = 'Second %s has no length. Non-sequence?' % (
700 seq_type_name)
701
702 if differing is None:
703 if seq1 == seq2:
704 return
705
706 for i in xrange(min(len1, len2)):
707 try:
708 item1 = seq1[i]
709 except (TypeError, IndexError, NotImplementedError):
710 differing = ('Unable to index element %d of first %s\n' %
711 (i, seq_type_name))
712 break
713
714 try:
715 item2 = seq2[i]
716 except (TypeError, IndexError, NotImplementedError):
717 differing = ('Unable to index element %d of second %s\n' %
718 (i, seq_type_name))
719 break
720
721 if item1 != item2:
722 differing = ('First differing element %d:\n%s\n%s\n' %
723 (i, item1, item2))
724 break
725 else:
726 if (len1 == len2 and seq_type is None and
727 type(seq1) != type(seq2)):
728 # The sequences are the same, but have differing types.
729 return
730 # A catch-all message for handling arbitrary user-defined
731 # sequences.
732 differing = '%ss differ:\n' % seq_type_name.capitalize()
733 if len1 > len2:
734 differing = ('First %s contains %d additional '
735 'elements.\n' % (seq_type_name, len1 - len2))
736 try:
737 differing += ('First extra element %d:\n%s\n' %
738 (len2, seq1[len2]))
739 except (TypeError, IndexError, NotImplementedError):
740 differing += ('Unable to index element %d '
741 'of first %s\n' % (len2, seq_type_name))
742 elif len1 < len2:
743 differing = ('Second %s contains %d additional '
744 'elements.\n' % (seq_type_name, len2 - len1))
745 try:
746 differing += ('First extra element %d:\n%s\n' %
747 (len1, seq2[len1]))
748 except (TypeError, IndexError, NotImplementedError):
749 differing += ('Unable to index element %d '
750 'of second %s\n' % (len1, seq_type_name))
Michael Foord345b2fe2009-04-02 03:20:38 +0000751 standardMsg = differing + '\n'.join(difflib.ndiff(pprint.pformat(seq1).splitlines(),
752 pprint.pformat(seq2).splitlines()))
753 msg = self._formatMessage(msg, standardMsg)
754 self.fail(msg)
Gregory P. Smith28399852009-03-31 16:54:10 +0000755
756 def assertListEqual(self, list1, list2, msg=None):
757 """A list-specific equality assertion.
758
759 Args:
760 list1: The first list to compare.
761 list2: The second list to compare.
762 msg: Optional message to use on failure instead of a list of
763 differences.
764
765 """
766 self.assertSequenceEqual(list1, list2, msg, seq_type=list)
767
768 def assertTupleEqual(self, tuple1, tuple2, msg=None):
769 """A tuple-specific equality assertion.
770
771 Args:
772 tuple1: The first tuple to compare.
773 tuple2: The second tuple to compare.
774 msg: Optional message to use on failure instead of a list of
775 differences.
776 """
777 self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
778
779 def assertSetEqual(self, set1, set2, msg=None):
780 """A set-specific equality assertion.
781
782 Args:
783 set1: The first set to compare.
784 set2: The second set to compare.
785 msg: Optional message to use on failure instead of a list of
786 differences.
787
788 For more general containership equality, assertSameElements will work
789 with things other than sets. This uses ducktyping to support
790 different types of sets, and is optimized for sets specifically
791 (parameters must support a difference method).
792 """
793 try:
794 difference1 = set1.difference(set2)
795 except TypeError, e:
796 self.fail('invalid type when attempting set difference: %s' % e)
797 except AttributeError, e:
798 self.fail('first argument does not support set difference: %s' % e)
799
800 try:
801 difference2 = set2.difference(set1)
802 except TypeError, e:
803 self.fail('invalid type when attempting set difference: %s' % e)
804 except AttributeError, e:
805 self.fail('second argument does not support set difference: %s' % e)
806
807 if not (difference1 or difference2):
808 return
809
Gregory P. Smith28399852009-03-31 16:54:10 +0000810 lines = []
811 if difference1:
812 lines.append('Items in the first set but not the second:')
813 for item in difference1:
814 lines.append(repr(item))
815 if difference2:
816 lines.append('Items in the second set but not the first:')
817 for item in difference2:
818 lines.append(repr(item))
Gregory P. Smith28399852009-03-31 16:54:10 +0000819
Michael Foord345b2fe2009-04-02 03:20:38 +0000820 standardMsg = '\n'.join(lines)
821 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000822
Michael Foord345b2fe2009-04-02 03:20:38 +0000823 def assertIn(self, member, container, msg=None):
824 """Just like self.assertTrue(a in b), but with a nicer default message."""
825 if member not in container:
826 standardMsg = '%r not found in %r' % (member, container)
827 self.fail(self._formatMessage(msg, standardMsg))
828
829 def assertNotIn(self, member, container, msg=None):
830 """Just like self.assertTrue(a not in b), but with a nicer default message."""
831 if member in container:
832 standardMsg = '%r unexpectedly found in %r' % (member, container)
833 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000834
Michael Foordf2dfef12009-04-05 19:19:28 +0000835 def assertIs(self, expr1, expr2, msg=None):
836 """Just like self.assertTrue(a is b), but with a nicer default message."""
837 if expr1 is not expr2:
838 standardMsg = '%r is not %r' % (expr1, expr2)
839 self.fail(self._formatMessage(msg, standardMsg))
840
841 def assertIsNot(self, expr1, expr2, msg=None):
842 """Just like self.assertTrue(a is not b), but with a nicer default message."""
843 if expr1 is expr2:
844 standardMsg = 'unexpectedly identical: %r' % (expr1,)
845 self.fail(self._formatMessage(msg, standardMsg))
846
Gregory P. Smith28399852009-03-31 16:54:10 +0000847 def assertDictEqual(self, d1, d2, msg=None):
848 self.assert_(isinstance(d1, dict), 'First argument is not a dictionary')
849 self.assert_(isinstance(d2, dict), 'Second argument is not a dictionary')
850
851 if d1 != d2:
Michael Foord345b2fe2009-04-02 03:20:38 +0000852 standardMsg = ('\n' + '\n'.join(difflib.ndiff(
853 pprint.pformat(d1).splitlines(),
854 pprint.pformat(d2).splitlines())))
855 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000856
857 def assertDictContainsSubset(self, expected, actual, msg=None):
858 """Checks whether actual is a superset of expected."""
859 missing = []
860 mismatched = []
861 for key, value in expected.iteritems():
862 if key not in actual:
863 missing.append(key)
864 elif value != actual[key]:
Michael Foord345b2fe2009-04-02 03:20:38 +0000865 mismatched.append('%s, expected: %s, actual: %s' % (key, value, actual[key]))
Gregory P. Smith28399852009-03-31 16:54:10 +0000866
867 if not (missing or mismatched):
868 return
869
Michael Foord345b2fe2009-04-02 03:20:38 +0000870 standardMsg = ''
Gregory P. Smith28399852009-03-31 16:54:10 +0000871 if missing:
Michael Foord345b2fe2009-04-02 03:20:38 +0000872 standardMsg = 'Missing: %r' % ','.join(missing)
Gregory P. Smith28399852009-03-31 16:54:10 +0000873 if mismatched:
Michael Foord345b2fe2009-04-02 03:20:38 +0000874 if standardMsg:
875 standardMsg += '; '
876 standardMsg += 'Mismatched values: %s' % ','.join(mismatched)
Gregory P. Smith28399852009-03-31 16:54:10 +0000877
Michael Foord345b2fe2009-04-02 03:20:38 +0000878 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000879
880 def assertSameElements(self, expected_seq, actual_seq, msg=None):
881 """An unordered sequence specific comparison.
882
883 Raises with an error message listing which elements of expected_seq
884 are missing from actual_seq and vice versa if any.
885 """
886 try:
887 expected = set(expected_seq)
888 actual = set(actual_seq)
889 missing = list(expected.difference(actual))
890 unexpected = list(actual.difference(expected))
891 missing.sort()
892 unexpected.sort()
893 except TypeError:
894 # Fall back to slower list-compare if any of the objects are
895 # not hashable.
896 expected = list(expected_seq)
897 actual = list(actual_seq)
898 expected.sort()
899 actual.sort()
900 missing, unexpected = _SortedListDifference(expected, actual)
901 errors = []
902 if missing:
Michael Foord345b2fe2009-04-02 03:20:38 +0000903 errors.append('Expected, but missing:\n %r' % missing)
Gregory P. Smith28399852009-03-31 16:54:10 +0000904 if unexpected:
Michael Foord345b2fe2009-04-02 03:20:38 +0000905 errors.append('Unexpected, but present:\n %r' % unexpected)
Gregory P. Smith28399852009-03-31 16:54:10 +0000906 if errors:
Michael Foord345b2fe2009-04-02 03:20:38 +0000907 standardMsg = '\n'.join(errors)
908 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000909
910 def assertMultiLineEqual(self, first, second, msg=None):
911 """Assert that two multi-line strings are equal."""
Michael Foord345b2fe2009-04-02 03:20:38 +0000912 self.assert_(isinstance(first, basestring), (
Gregory P. Smith28399852009-03-31 16:54:10 +0000913 'First argument is not a string'))
Michael Foord345b2fe2009-04-02 03:20:38 +0000914 self.assert_(isinstance(second, basestring), (
Gregory P. Smith28399852009-03-31 16:54:10 +0000915 'Second argument is not a string'))
916
917 if first != second:
Michael Foord345b2fe2009-04-02 03:20:38 +0000918 standardMsg = '\n' + ''.join(difflib.ndiff(first.splitlines(True), second.splitlines(True)))
919 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000920
921 def assertLess(self, a, b, msg=None):
Michael Foord345b2fe2009-04-02 03:20:38 +0000922 """Just like self.assertTrue(a < b), but with a nicer default message."""
923 if not a < b:
924 standardMsg = '%r not less than %r' % (a, b)
925 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000926
927 def assertLessEqual(self, a, b, msg=None):
Michael Foord345b2fe2009-04-02 03:20:38 +0000928 """Just like self.assertTrue(a <= b), but with a nicer default message."""
929 if not a <= b:
930 standardMsg = '%r not less than or equal to %r' % (a, b)
931 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000932
933 def assertGreater(self, a, b, msg=None):
Michael Foord345b2fe2009-04-02 03:20:38 +0000934 """Just like self.assertTrue(a > b), but with a nicer default message."""
935 if not a > b:
936 standardMsg = '%r not greater than %r' % (a, b)
937 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000938
939 def assertGreaterEqual(self, a, b, msg=None):
Michael Foord345b2fe2009-04-02 03:20:38 +0000940 """Just like self.assertTrue(a >= b), but with a nicer default message."""
941 if not a >= b:
942 standardMsg = '%r not greater than or equal to %r' % (a, b)
943 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000944
945 def assertIsNone(self, obj, msg=None):
Michael Foord345b2fe2009-04-02 03:20:38 +0000946 """Same as self.assertTrue(obj is None), with a nicer default message."""
947 if obj is not None:
948 standardMsg = '%r is not None' % obj
949 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000950
Michael Foord345b2fe2009-04-02 03:20:38 +0000951 def assertIsNotNone(self, obj, msg=None):
Gregory P. Smith28399852009-03-31 16:54:10 +0000952 """Included for symmetry with assertIsNone."""
Michael Foord345b2fe2009-04-02 03:20:38 +0000953 if obj is None:
954 standardMsg = 'unexpectedly None'
955 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000956
957 def assertRaisesRegexp(self, expected_exception, expected_regexp,
958 callable_obj=None, *args, **kwargs):
959 """Asserts that the message in a raised exception matches a regexp.
960
961 Args:
962 expected_exception: Exception class expected to be raised.
963 expected_regexp: Regexp (re pattern object or string) expected
964 to be found in error message.
965 callable_obj: Function to be called.
966 args: Extra args.
967 kwargs: Extra kwargs.
968 """
969 context = _AssertRaisesContext(expected_exception, self, expected_regexp)
970 if callable_obj is None:
971 return context
972 with context:
973 callable_obj(*args, **kwargs)
974
975 def assertRegexpMatches(self, text, expected_regex, msg=None):
976 if isinstance(expected_regex, basestring):
977 expected_regex = re.compile(expected_regex)
978 if not expected_regex.search(text):
979 msg = msg or "Regexp didn't match"
980 msg = '%s: %r not found in %r' % (msg, expected_regex.pattern, text)
981 raise self.failureException(msg)
982
983
984def _SortedListDifference(expected, actual):
985 """Finds elements in only one or the other of two, sorted input lists.
986
987 Returns a two-element tuple of lists. The first list contains those
988 elements in the "expected" list but not in the "actual" list, and the
989 second contains those elements in the "actual" list but not in the
990 "expected" list. Duplicate elements in either input list are ignored.
991 """
992 i = j = 0
993 missing = []
994 unexpected = []
995 while True:
996 try:
997 e = expected[i]
998 a = actual[j]
999 if e < a:
1000 missing.append(e)
1001 i += 1
1002 while expected[i] == e:
1003 i += 1
1004 elif e > a:
1005 unexpected.append(a)
1006 j += 1
1007 while actual[j] == a:
1008 j += 1
1009 else:
1010 i += 1
1011 try:
1012 while expected[i] == e:
1013 i += 1
1014 finally:
1015 j += 1
1016 while actual[j] == a:
1017 j += 1
1018 except IndexError:
1019 missing.extend(expected[i:])
1020 unexpected.extend(actual[j:])
1021 break
1022 return missing, unexpected
1023
Fred Drake02538202001-03-21 18:09:46 +00001024
Antoine Pitroudae1a6a2008-12-28 16:01:11 +00001025class TestSuite(object):
Fred Drake02538202001-03-21 18:09:46 +00001026 """A test suite is a composite test consisting of a number of TestCases.
1027
1028 For use, create an instance of TestSuite, then add test case instances.
1029 When all tests have been added, the suite can be passed to a test
1030 runner, such as TextTestRunner. It will run the individual test cases
1031 in the order in which they were added, aggregating the results. When
1032 subclassing, do not forget to call the base class constructor.
1033 """
1034 def __init__(self, tests=()):
1035 self._tests = []
1036 self.addTests(tests)
1037
1038 def __repr__(self):
Michael Foord37d89a22009-04-05 01:15:01 +00001039 return "<%s tests=%s>" % (_strclass(self.__class__), list(self))
Fred Drake02538202001-03-21 18:09:46 +00001040
Georg Brandl15c5ce92007-03-07 09:09:40 +00001041 def __eq__(self, other):
Benjamin Peterson692428e2009-03-23 21:50:21 +00001042 if not isinstance(other, self.__class__):
1043 return NotImplemented
Michael Foord829f6b82009-05-02 11:43:06 +00001044 return list(self) == list(other)
Georg Brandl15c5ce92007-03-07 09:09:40 +00001045
1046 def __ne__(self, other):
1047 return not self == other
1048
Nick Coghlan48361f52008-08-11 15:45:58 +00001049 # Can't guarantee hash invariant, so flag as unhashable
1050 __hash__ = None
1051
Jim Fultonfafd8742004-08-28 15:22:12 +00001052 def __iter__(self):
1053 return iter(self._tests)
1054
Fred Drake02538202001-03-21 18:09:46 +00001055 def countTestCases(self):
1056 cases = 0
Michael Foord37d89a22009-04-05 01:15:01 +00001057 for test in self:
Steve Purcell7e743842003-09-22 11:08:12 +00001058 cases += test.countTestCases()
Fred Drake02538202001-03-21 18:09:46 +00001059 return cases
1060
1061 def addTest(self, test):
Georg Brandld9e50262007-03-07 11:54:49 +00001062 # sanity checks
Raymond Hettinger5930d8f2008-07-10 16:06:41 +00001063 if not hasattr(test, '__call__'):
Georg Brandld9e50262007-03-07 11:54:49 +00001064 raise TypeError("the test to add must be callable")
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001065 if isinstance(test, type) and issubclass(test, (TestCase, TestSuite)):
Georg Brandld9e50262007-03-07 11:54:49 +00001066 raise TypeError("TestCases and TestSuites must be instantiated "
1067 "before passing them to addTest()")
Fred Drake02538202001-03-21 18:09:46 +00001068 self._tests.append(test)
1069
1070 def addTests(self, tests):
Georg Brandld9e50262007-03-07 11:54:49 +00001071 if isinstance(tests, basestring):
1072 raise TypeError("tests must be an iterable of tests, not a string")
Fred Drake02538202001-03-21 18:09:46 +00001073 for test in tests:
1074 self.addTest(test)
1075
1076 def run(self, result):
Michael Foord37d89a22009-04-05 01:15:01 +00001077 for test in self:
Fred Drake02538202001-03-21 18:09:46 +00001078 if result.shouldStop:
1079 break
1080 test(result)
1081 return result
1082
Raymond Hettinger664347b2004-12-04 21:21:53 +00001083 def __call__(self, *args, **kwds):
1084 return self.run(*args, **kwds)
1085
Fred Drake02538202001-03-21 18:09:46 +00001086 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001087 """Run the tests without collecting errors in a TestResult"""
Michael Foord37d89a22009-04-05 01:15:01 +00001088 for test in self:
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001089 test.debug()
Fred Drake02538202001-03-21 18:09:46 +00001090
1091
Benjamin Peterson692428e2009-03-23 21:50:21 +00001092class ClassTestSuite(TestSuite):
1093 """
1094 Suite of tests derived from a single TestCase class.
1095 """
1096
1097 def __init__(self, tests, class_collected_from):
1098 super(ClassTestSuite, self).__init__(tests)
1099 self.collected_from = class_collected_from
1100
1101 def id(self):
1102 module = getattr(self.collected_from, "__module__", None)
1103 if module is not None:
1104 return "{0}.{1}".format(module, self.collected_from.__name__)
1105 return self.collected_from.__name__
1106
1107 def run(self, result):
1108 if getattr(self.collected_from, "__unittest_skip__", False):
1109 # ClassTestSuite result pretends to be a TestCase enough to be
1110 # reported.
1111 result.startTest(self)
1112 try:
1113 result.addSkip(self, self.collected_from.__unittest_skip_why__)
1114 finally:
1115 result.stopTest(self)
1116 else:
1117 result = super(ClassTestSuite, self).run(result)
1118 return result
1119
1120 shortDescription = id
1121
1122
Fred Drake02538202001-03-21 18:09:46 +00001123class FunctionTestCase(TestCase):
1124 """A test case that wraps a test function.
1125
1126 This is useful for slipping pre-existing test functions into the
Georg Brandl15c5ce92007-03-07 09:09:40 +00001127 unittest framework. Optionally, set-up and tidy-up functions can be
Fred Drake02538202001-03-21 18:09:46 +00001128 supplied. As with TestCase, the tidy-up ('tearDown') function will
1129 always be called if the set-up ('setUp') function ran successfully.
1130 """
1131
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001132 def __init__(self, testFunc, setUp=None, tearDown=None, description=None):
1133 super(FunctionTestCase, self).__init__()
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001134 self._setUpFunc = setUp
1135 self._tearDownFunc = tearDown
1136 self._testFunc = testFunc
1137 self._description = description
Fred Drake02538202001-03-21 18:09:46 +00001138
1139 def setUp(self):
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001140 if self._setUpFunc is not None:
1141 self._setUpFunc()
Fred Drake02538202001-03-21 18:09:46 +00001142
1143 def tearDown(self):
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001144 if self._tearDownFunc is not None:
1145 self._tearDownFunc()
Fred Drake02538202001-03-21 18:09:46 +00001146
1147 def runTest(self):
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001148 self._testFunc()
Fred Drake02538202001-03-21 18:09:46 +00001149
1150 def id(self):
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001151 return self._testFunc.__name__
Fred Drake02538202001-03-21 18:09:46 +00001152
Georg Brandl15c5ce92007-03-07 09:09:40 +00001153 def __eq__(self, other):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001154 if not isinstance(other, self.__class__):
1155 return NotImplemented
Georg Brandl15c5ce92007-03-07 09:09:40 +00001156
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001157 return self._setUpFunc == other._setUpFunc and \
1158 self._tearDownFunc == other._tearDownFunc and \
1159 self._testFunc == other._testFunc and \
1160 self._description == other._description
Georg Brandl15c5ce92007-03-07 09:09:40 +00001161
1162 def __ne__(self, other):
1163 return not self == other
1164
1165 def __hash__(self):
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001166 return hash((type(self), self._setUpFunc, self._tearDownFunc,
1167 self._testFunc, self._description))
Georg Brandl15c5ce92007-03-07 09:09:40 +00001168
Fred Drake02538202001-03-21 18:09:46 +00001169 def __str__(self):
Benjamin Petersonbaba1952009-04-18 19:26:19 +00001170 return "%s (%s)" % (_strclass(self.__class__), self._testFunc.__name__)
Fred Drake02538202001-03-21 18:09:46 +00001171
1172 def __repr__(self):
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001173 return "<%s testFunc=%s>" % (_strclass(self.__class__), self._testFunc)
Fred Drake02538202001-03-21 18:09:46 +00001174
1175 def shortDescription(self):
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001176 if self._description is not None:
1177 return self._description
1178 doc = self._testFunc.__doc__
Steve Purcell7e743842003-09-22 11:08:12 +00001179 return doc and doc.split("\n")[0].strip() or None
Fred Drake02538202001-03-21 18:09:46 +00001180
1181
1182
1183##############################################################################
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001184# Locating and loading tests
Fred Drake02538202001-03-21 18:09:46 +00001185##############################################################################
1186
Antoine Pitroudae1a6a2008-12-28 16:01:11 +00001187class TestLoader(object):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001188 """
1189 This class is responsible for loading tests according to various criteria
1190 and returning them wrapped in a TestSuite
Fred Drake02538202001-03-21 18:09:46 +00001191 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001192 testMethodPrefix = 'test'
1193 sortTestMethodsUsing = cmp
1194 suiteClass = TestSuite
Benjamin Peterson692428e2009-03-23 21:50:21 +00001195 classSuiteClass = ClassTestSuite
Fred Drake02538202001-03-21 18:09:46 +00001196
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001197 def loadTestsFromTestCase(self, testCaseClass):
Steve Purcell15d89272001-04-12 09:05:01 +00001198 """Return a suite of all tests cases contained in testCaseClass"""
Johannes Gijsbersd7b6ad42004-11-07 15:46:25 +00001199 if issubclass(testCaseClass, TestSuite):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001200 raise TypeError("Test cases should not be derived from TestSuite." \
1201 " Maybe you meant to derive from TestCase?")
Steve Purcell7e743842003-09-22 11:08:12 +00001202 testCaseNames = self.getTestCaseNames(testCaseClass)
1203 if not testCaseNames and hasattr(testCaseClass, 'runTest'):
1204 testCaseNames = ['runTest']
Benjamin Peterson692428e2009-03-23 21:50:21 +00001205 suite = self.classSuiteClass(map(testCaseClass, testCaseNames),
1206 testCaseClass)
1207 return suite
Fred Drake02538202001-03-21 18:09:46 +00001208
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001209 def loadTestsFromModule(self, module):
Steve Purcell15d89272001-04-12 09:05:01 +00001210 """Return a suite of all tests cases contained in the given module"""
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001211 tests = []
1212 for name in dir(module):
1213 obj = getattr(module, name)
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001214 if isinstance(obj, type) and issubclass(obj, TestCase):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001215 tests.append(self.loadTestsFromTestCase(obj))
1216 return self.suiteClass(tests)
Fred Drake02538202001-03-21 18:09:46 +00001217
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001218 def loadTestsFromName(self, name, module=None):
Steve Purcell15d89272001-04-12 09:05:01 +00001219 """Return a suite of all tests cases given a string specifier.
1220
1221 The name may resolve either to a module, a test case class, a
1222 test method within a test case class, or a callable object which
1223 returns a TestCase or TestSuite instance.
Tim Peters613b2222001-04-13 05:37:27 +00001224
Steve Purcell15d89272001-04-12 09:05:01 +00001225 The method optionally resolves the names relative to a given module.
1226 """
Steve Purcell7e743842003-09-22 11:08:12 +00001227 parts = name.split('.')
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001228 if module is None:
Steve Purcell7e743842003-09-22 11:08:12 +00001229 parts_copy = parts[:]
1230 while parts_copy:
1231 try:
1232 module = __import__('.'.join(parts_copy))
1233 break
1234 except ImportError:
1235 del parts_copy[-1]
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001236 if not parts_copy:
1237 raise
Armin Rigo1b3c04b2003-10-24 17:15:29 +00001238 parts = parts[1:]
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001239 obj = module
1240 for part in parts:
Steve Purcell7e743842003-09-22 11:08:12 +00001241 parent, obj = obj, getattr(obj, part)
Fred Drake02538202001-03-21 18:09:46 +00001242
Antoine Pitroudae1a6a2008-12-28 16:01:11 +00001243 if isinstance(obj, types.ModuleType):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001244 return self.loadTestsFromModule(obj)
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001245 elif isinstance(obj, type) and issubclass(obj, TestCase):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001246 return self.loadTestsFromTestCase(obj)
Antoine Pitroudae1a6a2008-12-28 16:01:11 +00001247 elif (isinstance(obj, types.UnboundMethodType) and
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001248 isinstance(parent, type) and
Georg Brandl15c5ce92007-03-07 09:09:40 +00001249 issubclass(parent, TestCase)):
1250 return TestSuite([parent(obj.__name__)])
Steve Purcell397b45d2003-10-26 10:41:03 +00001251 elif isinstance(obj, TestSuite):
Steve Purcell7e743842003-09-22 11:08:12 +00001252 return obj
Raymond Hettinger5930d8f2008-07-10 16:06:41 +00001253 elif hasattr(obj, '__call__'):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001254 test = obj()
Georg Brandl15c5ce92007-03-07 09:09:40 +00001255 if isinstance(test, TestSuite):
1256 return test
1257 elif isinstance(test, TestCase):
1258 return TestSuite([test])
1259 else:
1260 raise TypeError("calling %s returned %s, not a test" %
1261 (obj, test))
Fred Drake02538202001-03-21 18:09:46 +00001262 else:
Georg Brandl15c5ce92007-03-07 09:09:40 +00001263 raise TypeError("don't know how to make test from: %s" % obj)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001264
1265 def loadTestsFromNames(self, names, module=None):
Steve Purcell15d89272001-04-12 09:05:01 +00001266 """Return a suite of all tests cases found using the given sequence
1267 of string specifiers. See 'loadTestsFromName()'.
1268 """
Steve Purcell7e743842003-09-22 11:08:12 +00001269 suites = [self.loadTestsFromName(name, module) for name in names]
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001270 return self.suiteClass(suites)
1271
1272 def getTestCaseNames(self, testCaseClass):
Steve Purcell15d89272001-04-12 09:05:01 +00001273 """Return a sorted sequence of method names found within testCaseClass
1274 """
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001275 def isTestMethod(attrname, testCaseClass=testCaseClass,
1276 prefix=self.testMethodPrefix):
1277 return attrname.startswith(prefix) and \
1278 hasattr(getattr(testCaseClass, attrname), '__call__')
Steve Purcell7e743842003-09-22 11:08:12 +00001279 testFnNames = filter(isTestMethod, dir(testCaseClass))
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001280 if self.sortTestMethodsUsing:
Raymond Hettinger5930d8f2008-07-10 16:06:41 +00001281 testFnNames.sort(key=_CmpToKey(self.sortTestMethodsUsing))
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001282 return testFnNames
1283
1284
1285
1286defaultTestLoader = TestLoader()
1287
1288
1289##############################################################################
1290# Patches for old functions: these functions should be considered obsolete
1291##############################################################################
1292
1293def _makeLoader(prefix, sortUsing, suiteClass=None):
1294 loader = TestLoader()
1295 loader.sortTestMethodsUsing = sortUsing
1296 loader.testMethodPrefix = prefix
1297 if suiteClass: loader.suiteClass = suiteClass
1298 return loader
1299
1300def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp):
1301 return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)
1302
1303def makeSuite(testCaseClass, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
1304 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
1305
1306def findTestCases(module, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
1307 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module)
Fred Drake02538202001-03-21 18:09:46 +00001308
1309
1310##############################################################################
1311# Text UI
1312##############################################################################
1313
Antoine Pitroudae1a6a2008-12-28 16:01:11 +00001314class _WritelnDecorator(object):
Fred Drake02538202001-03-21 18:09:46 +00001315 """Used to decorate file-like objects with a handy 'writeln' method"""
1316 def __init__(self,stream):
1317 self.stream = stream
Fred Drake02538202001-03-21 18:09:46 +00001318
1319 def __getattr__(self, attr):
1320 return getattr(self.stream,attr)
1321
Raymond Hettinger91dd19d2003-09-13 02:58:00 +00001322 def writeln(self, arg=None):
Benjamin Petersond0cdb2d2009-03-24 23:07:07 +00001323 if arg:
1324 self.write(arg)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001325 self.write('\n') # text-mode streams translate to \r\n if needed
Tim Petersa19a1682001-03-29 04:36:09 +00001326
Fred Drake02538202001-03-21 18:09:46 +00001327
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001328class _TextTestResult(TestResult):
Fred Drake02538202001-03-21 18:09:46 +00001329 """A test result class that can print formatted text results to a stream.
1330
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001331 Used by TextTestRunner.
Fred Drake02538202001-03-21 18:09:46 +00001332 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001333 separator1 = '=' * 70
1334 separator2 = '-' * 70
Fred Drake02538202001-03-21 18:09:46 +00001335
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001336 def __init__(self, stream, descriptions, verbosity):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001337 super(_TextTestResult, self).__init__()
Fred Drake02538202001-03-21 18:09:46 +00001338 self.stream = stream
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001339 self.showAll = verbosity > 1
1340 self.dots = verbosity == 1
Fred Drake02538202001-03-21 18:09:46 +00001341 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001342
1343 def getDescription(self, test):
1344 if self.descriptions:
1345 return test.shortDescription() or str(test)
1346 else:
1347 return str(test)
1348
Fred Drake02538202001-03-21 18:09:46 +00001349 def startTest(self, test):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001350 super(_TextTestResult, self).startTest(test)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001351 if self.showAll:
1352 self.stream.write(self.getDescription(test))
1353 self.stream.write(" ... ")
Georg Brandld0632402008-05-11 15:17:41 +00001354 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +00001355
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001356 def addSuccess(self, test):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001357 super(_TextTestResult, self).addSuccess(test)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001358 if self.showAll:
Fred Drake02538202001-03-21 18:09:46 +00001359 self.stream.writeln("ok")
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001360 elif self.dots:
1361 self.stream.write('.')
Georg Brandld0632402008-05-11 15:17:41 +00001362 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +00001363
1364 def addError(self, test, err):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001365 super(_TextTestResult, self).addError(test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001366 if self.showAll:
1367 self.stream.writeln("ERROR")
1368 elif self.dots:
1369 self.stream.write('E')
Georg Brandld0632402008-05-11 15:17:41 +00001370 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +00001371
1372 def addFailure(self, test, err):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001373 super(_TextTestResult, self).addFailure(test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001374 if self.showAll:
1375 self.stream.writeln("FAIL")
1376 elif self.dots:
1377 self.stream.write('F')
Georg Brandld0632402008-05-11 15:17:41 +00001378 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +00001379
Benjamin Peterson692428e2009-03-23 21:50:21 +00001380 def addSkip(self, test, reason):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001381 super(_TextTestResult, self).addSkip(test, reason)
Benjamin Peterson692428e2009-03-23 21:50:21 +00001382 if self.showAll:
1383 self.stream.writeln("skipped {0!r}".format(reason))
1384 elif self.dots:
1385 self.stream.write("s")
1386 self.stream.flush()
1387
1388 def addExpectedFailure(self, test, err):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001389 super(_TextTestResult, self).addExpectedFailure(test, err)
Benjamin Peterson692428e2009-03-23 21:50:21 +00001390 if self.showAll:
1391 self.stream.writeln("expected failure")
1392 elif self.dots:
Benjamin Petersona8adceb2009-03-25 21:24:04 +00001393 self.stream.write("x")
Benjamin Peterson692428e2009-03-23 21:50:21 +00001394 self.stream.flush()
1395
1396 def addUnexpectedSuccess(self, test):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001397 super(_TextTestResult, self).addUnexpectedSuccess(test)
Benjamin Peterson692428e2009-03-23 21:50:21 +00001398 if self.showAll:
1399 self.stream.writeln("unexpected success")
1400 elif self.dots:
Benjamin Petersona8adceb2009-03-25 21:24:04 +00001401 self.stream.write("u")
Benjamin Peterson692428e2009-03-23 21:50:21 +00001402 self.stream.flush()
1403
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001404 def printErrors(self):
1405 if self.dots or self.showAll:
Fred Drake02538202001-03-21 18:09:46 +00001406 self.stream.writeln()
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001407 self.printErrorList('ERROR', self.errors)
1408 self.printErrorList('FAIL', self.failures)
1409
1410 def printErrorList(self, flavour, errors):
1411 for test, err in errors:
1412 self.stream.writeln(self.separator1)
1413 self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
1414 self.stream.writeln(self.separator2)
Steve Purcell7b065702001-09-06 08:24:40 +00001415 self.stream.writeln("%s" % err)
Fred Drake02538202001-03-21 18:09:46 +00001416
1417
Antoine Pitroudae1a6a2008-12-28 16:01:11 +00001418class TextTestRunner(object):
Fred Drake02538202001-03-21 18:09:46 +00001419 """A test runner class that displays results in textual form.
Tim Petersa19a1682001-03-29 04:36:09 +00001420
Fred Drake02538202001-03-21 18:09:46 +00001421 It prints out the names of tests as they are run, errors as they
1422 occur, and a summary of the results at the end of the test run.
1423 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001424 def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1):
Fred Drake02538202001-03-21 18:09:46 +00001425 self.stream = _WritelnDecorator(stream)
1426 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001427 self.verbosity = verbosity
1428
1429 def _makeResult(self):
1430 return _TextTestResult(self.stream, self.descriptions, self.verbosity)
Fred Drake02538202001-03-21 18:09:46 +00001431
1432 def run(self, test):
1433 "Run the given test case or test suite."
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001434 result = self._makeResult()
Fred Drake02538202001-03-21 18:09:46 +00001435 startTime = time.time()
1436 test(result)
1437 stopTime = time.time()
Steve Purcell397b45d2003-10-26 10:41:03 +00001438 timeTaken = stopTime - startTime
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001439 result.printErrors()
1440 self.stream.writeln(result.separator2)
Fred Drake02538202001-03-21 18:09:46 +00001441 run = result.testsRun
1442 self.stream.writeln("Ran %d test%s in %.3fs" %
Neal Norwitz76165042002-05-31 14:15:11 +00001443 (run, run != 1 and "s" or "", timeTaken))
Fred Drake02538202001-03-21 18:09:46 +00001444 self.stream.writeln()
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00001445 results = map(len, (result.expectedFailures,
1446 result.unexpectedSuccesses,
Benjamin Peterson692428e2009-03-23 21:50:21 +00001447 result.skipped))
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00001448 expectedFails, unexpectedSuccesses, skipped = results
Benjamin Peterson692428e2009-03-23 21:50:21 +00001449 infos = []
Fred Drake02538202001-03-21 18:09:46 +00001450 if not result.wasSuccessful():
Benjamin Peterson692428e2009-03-23 21:50:21 +00001451 self.stream.write("FAILED")
Fred Drake02538202001-03-21 18:09:46 +00001452 failed, errored = map(len, (result.failures, result.errors))
1453 if failed:
Benjamin Peterson692428e2009-03-23 21:50:21 +00001454 infos.append("failures=%d" % failed)
Fred Drake02538202001-03-21 18:09:46 +00001455 if errored:
Benjamin Peterson692428e2009-03-23 21:50:21 +00001456 infos.append("errors=%d" % errored)
Fred Drake02538202001-03-21 18:09:46 +00001457 else:
Benjamin Petersona473f002009-03-24 22:56:32 +00001458 self.stream.write("OK")
Benjamin Peterson692428e2009-03-23 21:50:21 +00001459 if skipped:
1460 infos.append("skipped=%d" % skipped)
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001461 if expectedFails:
1462 infos.append("expected failures=%d" % expectedFails)
1463 if unexpectedSuccesses:
1464 infos.append("unexpected successes=%d" % unexpectedSuccesses)
Benjamin Peterson692428e2009-03-23 21:50:21 +00001465 if infos:
1466 self.stream.writeln(" (%s)" % (", ".join(infos),))
Benjamin Petersona473f002009-03-24 22:56:32 +00001467 else:
1468 self.stream.write("\n")
Fred Drake02538202001-03-21 18:09:46 +00001469 return result
Tim Petersa19a1682001-03-29 04:36:09 +00001470
Fred Drake02538202001-03-21 18:09:46 +00001471
Fred Drake02538202001-03-21 18:09:46 +00001472
1473##############################################################################
1474# Facilities for running tests from the command line
1475##############################################################################
1476
Antoine Pitroudae1a6a2008-12-28 16:01:11 +00001477class TestProgram(object):
Fred Drake02538202001-03-21 18:09:46 +00001478 """A command-line program that runs a set of tests; this is primarily
1479 for making test modules conveniently executable.
1480 """
1481 USAGE = """\
Steve Purcell17a781b2001-04-09 15:37:31 +00001482Usage: %(progName)s [options] [test] [...]
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001483
1484Options:
1485 -h, --help Show this message
1486 -v, --verbose Verbose output
1487 -q, --quiet Minimal output
Fred Drake02538202001-03-21 18:09:46 +00001488
1489Examples:
1490 %(progName)s - run default set of tests
1491 %(progName)s MyTestSuite - run suite 'MyTestSuite'
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001492 %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething
1493 %(progName)s MyTestCase - run all 'test*' test methods
Fred Drake02538202001-03-21 18:09:46 +00001494 in MyTestCase
1495"""
1496 def __init__(self, module='__main__', defaultTest=None,
Georg Brandld0a96252007-03-07 09:21:06 +00001497 argv=None, testRunner=TextTestRunner,
Michael Foord829f6b82009-05-02 11:43:06 +00001498 testLoader=defaultTestLoader, exit=True):
Antoine Pitroudae1a6a2008-12-28 16:01:11 +00001499 if isinstance(module, basestring):
Fred Drake02538202001-03-21 18:09:46 +00001500 self.module = __import__(module)
Steve Purcell7e743842003-09-22 11:08:12 +00001501 for part in module.split('.')[1:]:
Fred Drake02538202001-03-21 18:09:46 +00001502 self.module = getattr(self.module, part)
1503 else:
1504 self.module = module
1505 if argv is None:
1506 argv = sys.argv
Michael Foord829f6b82009-05-02 11:43:06 +00001507
1508 self.exit = exit
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001509 self.verbosity = 1
Fred Drake02538202001-03-21 18:09:46 +00001510 self.defaultTest = defaultTest
1511 self.testRunner = testRunner
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001512 self.testLoader = testLoader
Fred Drake02538202001-03-21 18:09:46 +00001513 self.progName = os.path.basename(argv[0])
1514 self.parseArgs(argv)
Fred Drake02538202001-03-21 18:09:46 +00001515 self.runTests()
1516
1517 def usageExit(self, msg=None):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001518 if msg:
1519 print msg
Fred Drake02538202001-03-21 18:09:46 +00001520 print self.USAGE % self.__dict__
1521 sys.exit(2)
1522
1523 def parseArgs(self, argv):
1524 import getopt
Benjamin Peterson692428e2009-03-23 21:50:21 +00001525 long_opts = ['help','verbose','quiet']
Fred Drake02538202001-03-21 18:09:46 +00001526 try:
Benjamin Peterson692428e2009-03-23 21:50:21 +00001527 options, args = getopt.getopt(argv[1:], 'hHvq', long_opts)
Fred Drake02538202001-03-21 18:09:46 +00001528 for opt, value in options:
1529 if opt in ('-h','-H','--help'):
1530 self.usageExit()
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001531 if opt in ('-q','--quiet'):
1532 self.verbosity = 0
1533 if opt in ('-v','--verbose'):
1534 self.verbosity = 2
Fred Drake02538202001-03-21 18:09:46 +00001535 if len(args) == 0 and self.defaultTest is None:
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001536 self.test = self.testLoader.loadTestsFromModule(self.module)
1537 return
Fred Drake02538202001-03-21 18:09:46 +00001538 if len(args) > 0:
1539 self.testNames = args
1540 else:
1541 self.testNames = (self.defaultTest,)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001542 self.createTests()
Fred Drake02538202001-03-21 18:09:46 +00001543 except getopt.error, msg:
1544 self.usageExit(msg)
1545
1546 def createTests(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001547 self.test = self.testLoader.loadTestsFromNames(self.testNames,
1548 self.module)
Fred Drake02538202001-03-21 18:09:46 +00001549
1550 def runTests(self):
Georg Brandld0a96252007-03-07 09:21:06 +00001551 if isinstance(self.testRunner, (type, types.ClassType)):
1552 try:
1553 testRunner = self.testRunner(verbosity=self.verbosity)
1554 except TypeError:
1555 # didn't accept the verbosity argument
1556 testRunner = self.testRunner()
1557 else:
1558 # it is assumed to be a TestRunner instance
1559 testRunner = self.testRunner
Michael Foord829f6b82009-05-02 11:43:06 +00001560 self.result = testRunner.run(self.test)
1561 if self.exit:
1562 sys.exit(not self.result.wasSuccessful())
Fred Drake02538202001-03-21 18:09:46 +00001563
1564main = TestProgram
1565
1566
Michael Foorde2fb98f2009-05-02 20:15:05 +00001567##############################################################################
1568# Executing this module from the command line
1569##############################################################################
1570
Fred Drake02538202001-03-21 18:09:46 +00001571if __name__ == "__main__":
1572 main(module=None)