blob: b6b96b357c05c1a8af20425a3ea299ed1a1f42a6 [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
163
Steve Purcellb8d5f242003-12-06 13:03:13 +0000164__unittest = 1
165
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000166class TestResult(object):
Fred Drake02538202001-03-21 18:09:46 +0000167 """Holder for test result information.
168
169 Test results are automatically managed by the TestCase and TestSuite
170 classes, and do not need to be explicitly manipulated by writers of tests.
171
172 Each instance holds the total number of tests run, and collections of
173 failures and errors that occurred among those test runs. The collections
Steve Purcell7b065702001-09-06 08:24:40 +0000174 contain tuples of (testcase, exceptioninfo), where exceptioninfo is the
Fred Drake656f9ec2001-09-06 19:13:14 +0000175 formatted traceback of the error that occurred.
Fred Drake02538202001-03-21 18:09:46 +0000176 """
177 def __init__(self):
178 self.failures = []
179 self.errors = []
180 self.testsRun = 0
Benjamin Peterson692428e2009-03-23 21:50:21 +0000181 self.skipped = []
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +0000182 self.expectedFailures = []
183 self.unexpectedSuccesses = []
Georg Brandl15c5ce92007-03-07 09:09:40 +0000184 self.shouldStop = False
Fred Drake02538202001-03-21 18:09:46 +0000185
186 def startTest(self, test):
187 "Called when the given test is about to be run"
188 self.testsRun = self.testsRun + 1
189
190 def stopTest(self, test):
191 "Called when the given test has been run"
192 pass
193
194 def addError(self, test, err):
Steve Purcell7b065702001-09-06 08:24:40 +0000195 """Called when an error has occurred. 'err' is a tuple of values as
196 returned by sys.exc_info().
197 """
Steve Purcellb8d5f242003-12-06 13:03:13 +0000198 self.errors.append((test, self._exc_info_to_string(err, test)))
Fred Drake02538202001-03-21 18:09:46 +0000199
200 def addFailure(self, test, err):
Steve Purcell7b065702001-09-06 08:24:40 +0000201 """Called when an error has occurred. 'err' is a tuple of values as
202 returned by sys.exc_info()."""
Steve Purcellb8d5f242003-12-06 13:03:13 +0000203 self.failures.append((test, self._exc_info_to_string(err, test)))
Fred Drake02538202001-03-21 18:09:46 +0000204
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000205 def addSuccess(self, test):
206 "Called when a test has completed successfully"
207 pass
208
Benjamin Peterson692428e2009-03-23 21:50:21 +0000209 def addSkip(self, test, reason):
210 """Called when a test is skipped."""
211 self.skipped.append((test, reason))
212
213 def addExpectedFailure(self, test, err):
214 """Called when an expected failure/error occured."""
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +0000215 self.expectedFailures.append(
Benjamin Peterson692428e2009-03-23 21:50:21 +0000216 (test, self._exc_info_to_string(err, test)))
217
218 def addUnexpectedSuccess(self, test):
219 """Called when a test was expected to fail, but succeed."""
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +0000220 self.unexpectedSuccesses.append(test)
Benjamin Peterson692428e2009-03-23 21:50:21 +0000221
Fred Drake02538202001-03-21 18:09:46 +0000222 def wasSuccessful(self):
223 "Tells whether or not this result was a success"
224 return len(self.failures) == len(self.errors) == 0
225
226 def stop(self):
227 "Indicates that the tests should be aborted"
Steve Purcell7e743842003-09-22 11:08:12 +0000228 self.shouldStop = True
Tim Petersa19a1682001-03-29 04:36:09 +0000229
Steve Purcellb8d5f242003-12-06 13:03:13 +0000230 def _exc_info_to_string(self, err, test):
Steve Purcell7b065702001-09-06 08:24:40 +0000231 """Converts a sys.exc_info()-style tuple of values into a string."""
Steve Purcellb8d5f242003-12-06 13:03:13 +0000232 exctype, value, tb = err
233 # Skip test runner traceback levels
234 while tb and self._is_relevant_tb_level(tb):
235 tb = tb.tb_next
236 if exctype is test.failureException:
237 # Skip assert*() traceback levels
238 length = self._count_relevant_tb_levels(tb)
239 return ''.join(traceback.format_exception(exctype, value, tb, length))
240 return ''.join(traceback.format_exception(exctype, value, tb))
241
242 def _is_relevant_tb_level(self, tb):
Georg Brandl56af5fc2008-07-18 19:30:10 +0000243 return '__unittest' in tb.tb_frame.f_globals
Steve Purcellb8d5f242003-12-06 13:03:13 +0000244
245 def _count_relevant_tb_levels(self, tb):
246 length = 0
247 while tb and not self._is_relevant_tb_level(tb):
248 length += 1
249 tb = tb.tb_next
250 return length
Steve Purcell7b065702001-09-06 08:24:40 +0000251
Fred Drake02538202001-03-21 18:09:46 +0000252 def __repr__(self):
253 return "<%s run=%i errors=%i failures=%i>" % \
Steve Purcelldc391a62002-08-09 09:46:23 +0000254 (_strclass(self.__class__), self.testsRun, len(self.errors),
Fred Drake02538202001-03-21 18:09:46 +0000255 len(self.failures))
256
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000257
Gregory P. Smith28399852009-03-31 16:54:10 +0000258class _AssertRaisesContext(object):
259 """A context manager used to implement TestCase.assertRaises* methods."""
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000260
Gregory P. Smith28399852009-03-31 16:54:10 +0000261 def __init__(self, expected, test_case, expected_regexp=None):
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000262 self.expected = expected
263 self.failureException = test_case.failureException
Gregory P. Smith28399852009-03-31 16:54:10 +0000264 self.expected_regex = expected_regexp
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000265
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000266 def __enter__(self):
267 pass
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000268
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000269 def __exit__(self, exc_type, exc_value, traceback):
270 if exc_type is None:
271 try:
272 exc_name = self.expected.__name__
273 except AttributeError:
274 exc_name = str(self.expected)
275 raise self.failureException(
276 "{0} not raised".format(exc_name))
Gregory P. Smith28399852009-03-31 16:54:10 +0000277 if not issubclass(exc_type, self.expected):
Michael Foord345b2fe2009-04-02 03:20:38 +0000278 # let unexpected exceptions pass through
Gregory P. Smith28399852009-03-31 16:54:10 +0000279 return False
280 if self.expected_regex is None:
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000281 return True
Gregory P. Smith28399852009-03-31 16:54:10 +0000282
283 expected_regexp = self.expected_regex
284 if isinstance(expected_regexp, basestring):
285 expected_regexp = re.compile(expected_regexp)
286 if not expected_regexp.search(str(exc_value)):
287 raise self.failureException('"%s" does not match "%s"' %
288 (expected_regexp.pattern, str(exc_value)))
289 return True
290
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000291
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000292
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000293class TestCase(object):
Fred Drake02538202001-03-21 18:09:46 +0000294 """A class whose instances are single test cases.
295
Fred Drake02538202001-03-21 18:09:46 +0000296 By default, the test code itself should be placed in a method named
297 'runTest'.
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000298
Tim Petersa19a1682001-03-29 04:36:09 +0000299 If the fixture may be used for many test cases, create as
Fred Drake02538202001-03-21 18:09:46 +0000300 many test methods as are needed. When instantiating such a TestCase
301 subclass, specify in the constructor arguments the name of the test method
302 that the instance is to execute.
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000303
Tim Petersa19a1682001-03-29 04:36:09 +0000304 Test authors should subclass TestCase for their own tests. Construction
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000305 and deconstruction of the test's environment ('fixture') can be
306 implemented by overriding the 'setUp' and 'tearDown' methods respectively.
307
308 If it is necessary to override the __init__ method, the base class
309 __init__ method must always be called. It is important that subclasses
310 should not change the signature of their __init__ method, since instances
311 of the classes are instantiated automatically by parts of the framework
312 in order to be run.
Fred Drake02538202001-03-21 18:09:46 +0000313 """
Steve Purcell15d89272001-04-12 09:05:01 +0000314
315 # This attribute determines which exception will be raised when
316 # the instance's assertion methods fail; test methods raising this
317 # exception will be deemed to have 'failed' rather than 'errored'
318
319 failureException = AssertionError
320
Michael Foord345b2fe2009-04-02 03:20:38 +0000321 # This attribute determines whether long messages (including repr of
322 # objects used in assert methods) will be printed on failure in *addition*
323 # to any explicit message passed.
324
325 longMessage = False
326
327
Fred Drake02538202001-03-21 18:09:46 +0000328 def __init__(self, methodName='runTest'):
329 """Create an instance of the class that will use the named test
330 method when executed. Raises a ValueError if the instance does
331 not have a method with the specified name.
332 """
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000333 self._testMethodName = methodName
Fred Drake02538202001-03-21 18:09:46 +0000334 try:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000335 testMethod = getattr(self, methodName)
Fred Drake02538202001-03-21 18:09:46 +0000336 except AttributeError:
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000337 raise ValueError("no such test method in %s: %s" % \
338 (self.__class__, methodName))
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000339 self._testMethodDoc = testMethod.__doc__
Fred Drake02538202001-03-21 18:09:46 +0000340
Gregory P. Smith28399852009-03-31 16:54:10 +0000341 # Map types to custom assertEqual functions that will compare
342 # instances of said type in more detail to generate a more useful
343 # error message.
Benjamin Peterson71095ae2009-04-01 23:15:49 +0000344 self._type_equality_funcs = {}
Gregory P. Smith28399852009-03-31 16:54:10 +0000345 self.addTypeEqualityFunc(dict, self.assertDictEqual)
346 self.addTypeEqualityFunc(list, self.assertListEqual)
347 self.addTypeEqualityFunc(tuple, self.assertTupleEqual)
348 self.addTypeEqualityFunc(set, self.assertSetEqual)
349 self.addTypeEqualityFunc(frozenset, self.assertSetEqual)
350
351 def addTypeEqualityFunc(self, typeobj, function):
352 """Add a type specific assertEqual style function to compare a type.
353
354 This method is for use by TestCase subclasses that need to register
355 their own type equality functions to provide nicer error messages.
356
357 Args:
358 typeobj: The data type to call this function on when both values
359 are of the same type in assertEqual().
360 function: The callable taking two arguments and an optional
361 msg= argument that raises self.failureException with a
362 useful error message when the two arguments are not equal.
363 """
Benjamin Peterson71095ae2009-04-01 23:15:49 +0000364 self._type_equality_funcs[typeobj] = function
Gregory P. Smith28399852009-03-31 16:54:10 +0000365
Fred Drake02538202001-03-21 18:09:46 +0000366 def setUp(self):
367 "Hook method for setting up the test fixture before exercising it."
368 pass
369
370 def tearDown(self):
371 "Hook method for deconstructing the test fixture after testing it."
372 pass
373
374 def countTestCases(self):
375 return 1
376
377 def defaultTestResult(self):
378 return TestResult()
379
380 def shortDescription(self):
Gregory P. Smith28399852009-03-31 16:54:10 +0000381 """Returns both the test method name and first line of its docstring.
Fred Drake02538202001-03-21 18:09:46 +0000382
Gregory P. Smith28399852009-03-31 16:54:10 +0000383 If no docstring is given, only returns the method name.
384
385 This method overrides unittest.TestCase.shortDescription(), which
386 only returns the first line of the docstring, obscuring the name
387 of the test upon failure.
Fred Drake02538202001-03-21 18:09:46 +0000388 """
Gregory P. Smith28399852009-03-31 16:54:10 +0000389 desc = str(self)
390 doc_first_line = None
391
392 if self._testMethodDoc:
393 doc_first_line = self._testMethodDoc.split("\n")[0].strip()
394 if doc_first_line:
395 desc = '\n'.join((desc, doc_first_line))
396 return desc
Fred Drake02538202001-03-21 18:09:46 +0000397
398 def id(self):
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000399 return "%s.%s" % (_strclass(self.__class__), self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000400
Georg Brandl15c5ce92007-03-07 09:09:40 +0000401 def __eq__(self, other):
402 if type(self) is not type(other):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000403 return NotImplemented
Georg Brandl15c5ce92007-03-07 09:09:40 +0000404
405 return self._testMethodName == other._testMethodName
406
407 def __ne__(self, other):
408 return not self == other
409
410 def __hash__(self):
Collin Winter9453e5d2007-03-09 23:30:39 +0000411 return hash((type(self), self._testMethodName))
Georg Brandl15c5ce92007-03-07 09:09:40 +0000412
Fred Drake02538202001-03-21 18:09:46 +0000413 def __str__(self):
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000414 return "%s (%s)" % (self._testMethodName, _strclass(self.__class__))
Fred Drake02538202001-03-21 18:09:46 +0000415
416 def __repr__(self):
417 return "<%s testMethod=%s>" % \
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000418 (_strclass(self.__class__), self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000419
420 def run(self, result=None):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000421 if result is None:
422 result = self.defaultTestResult()
Fred Drake02538202001-03-21 18:09:46 +0000423 result.startTest(self)
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000424 testMethod = getattr(self, self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000425 try:
426 try:
427 self.setUp()
Benjamin Peterson692428e2009-03-23 21:50:21 +0000428 except SkipTest as e:
429 result.addSkip(self, str(e))
430 return
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000431 except Exception:
Benjamin Petersonc9301352009-03-26 16:32:23 +0000432 result.addError(self, sys.exc_info())
Fred Drake02538202001-03-21 18:09:46 +0000433 return
434
Benjamin Peterson692428e2009-03-23 21:50:21 +0000435 success = False
Fred Drake02538202001-03-21 18:09:46 +0000436 try:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000437 testMethod()
Skip Montanaroae5c37b2003-07-13 15:18:12 +0000438 except self.failureException:
Benjamin Petersonc9301352009-03-26 16:32:23 +0000439 result.addFailure(self, sys.exc_info())
Benjamin Peterson692428e2009-03-23 21:50:21 +0000440 except _ExpectedFailure as e:
441 result.addExpectedFailure(self, e.exc_info)
442 except _UnexpectedSuccess:
443 result.addUnexpectedSuccess(self)
444 except SkipTest as e:
445 result.addSkip(self, str(e))
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000446 except Exception:
Benjamin Petersonc9301352009-03-26 16:32:23 +0000447 result.addError(self, sys.exc_info())
Benjamin Peterson692428e2009-03-23 21:50:21 +0000448 else:
449 success = True
Fred Drake02538202001-03-21 18:09:46 +0000450
451 try:
452 self.tearDown()
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000453 except Exception:
Benjamin Petersonc9301352009-03-26 16:32:23 +0000454 result.addError(self, sys.exc_info())
Benjamin Peterson692428e2009-03-23 21:50:21 +0000455 success = False
456 if success:
457 result.addSuccess(self)
Fred Drake02538202001-03-21 18:09:46 +0000458 finally:
459 result.stopTest(self)
460
Raymond Hettinger664347b2004-12-04 21:21:53 +0000461 def __call__(self, *args, **kwds):
462 return self.run(*args, **kwds)
Steve Purcell7e743842003-09-22 11:08:12 +0000463
Fred Drake02538202001-03-21 18:09:46 +0000464 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000465 """Run the test without collecting errors in a TestResult"""
Fred Drake02538202001-03-21 18:09:46 +0000466 self.setUp()
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000467 getattr(self, self._testMethodName)()
Fred Drake02538202001-03-21 18:09:46 +0000468 self.tearDown()
469
Benjamin Peterson47d97382009-03-26 20:05:50 +0000470 def skipTest(self, reason):
Benjamin Peterson692428e2009-03-23 21:50:21 +0000471 """Skip this test."""
472 raise SkipTest(reason)
473
Steve Purcell15d89272001-04-12 09:05:01 +0000474 def fail(self, msg=None):
475 """Fail immediately, with the given message."""
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000476 raise self.failureException(msg)
Fred Drake02538202001-03-21 18:09:46 +0000477
Gregory P. Smith7558d572009-03-31 19:03:28 +0000478 def assertFalse(self, expr, msg=None):
Fred Drake02538202001-03-21 18:09:46 +0000479 "Fail the test if the expression is true."
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000480 if expr:
Michael Foord345b2fe2009-04-02 03:20:38 +0000481 msg = self._formatMessage(msg, "%r is not False" % expr)
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000482 raise self.failureException(msg)
Fred Drake02538202001-03-21 18:09:46 +0000483
Gregory P. Smith7558d572009-03-31 19:03:28 +0000484 def assertTrue(self, expr, msg=None):
Steve Purcell15d89272001-04-12 09:05:01 +0000485 """Fail the test unless the expression is true."""
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000486 if not expr:
Michael Foord345b2fe2009-04-02 03:20:38 +0000487 msg = self._formatMessage(msg, "%r is not True" % expr)
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000488 raise self.failureException(msg)
Steve Purcell15d89272001-04-12 09:05:01 +0000489
Michael Foord345b2fe2009-04-02 03:20:38 +0000490 def _formatMessage(self, msg, standardMsg):
491 """Honour the longMessage attribute when generating failure messages.
492 If longMessage is False this means:
493 * Use only an explicit message if it is provided
494 * Otherwise use the standard message for the assert
495
496 If longMessage is True:
497 * Use the standard message
498 * If an explicit message is provided, plus ' : ' and the explicit message
499 """
500 if not self.longMessage:
501 return msg or standardMsg
502 if msg is None:
503 return standardMsg
504 return standardMsg + ' : ' + msg
505
506
Gregory P. Smith7558d572009-03-31 19:03:28 +0000507 def assertRaises(self, excClass, callableObj=None, *args, **kwargs):
Steve Purcell15d89272001-04-12 09:05:01 +0000508 """Fail unless an exception of class excClass is thrown
Fred Drake02538202001-03-21 18:09:46 +0000509 by callableObj when invoked with arguments args and keyword
510 arguments kwargs. If a different type of exception is
511 thrown, it will not be caught, and the test case will be
512 deemed to have suffered an error, exactly as for an
513 unexpected exception.
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000514
515 If called with callableObj omitted or None, will return a
516 context object used like this::
517
Gregory P. Smith7558d572009-03-31 19:03:28 +0000518 with self.assertRaises(some_error_class):
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000519 do_something()
Fred Drake02538202001-03-21 18:09:46 +0000520 """
Gregory P. Smith28399852009-03-31 16:54:10 +0000521 context = _AssertRaisesContext(excClass, self)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000522 if callableObj is None:
523 return context
524 with context:
Guido van Rossum68468eb2003-02-27 20:14:51 +0000525 callableObj(*args, **kwargs)
Fred Drake02538202001-03-21 18:09:46 +0000526
Gregory P. Smith28399852009-03-31 16:54:10 +0000527 def _getAssertEqualityFunc(self, first, second):
528 """Get a detailed comparison function for the types of the two args.
529
530 Returns: A callable accepting (first, second, msg=None) that will
531 raise a failure exception if first != second with a useful human
532 readable error message for those types.
533 """
534 #
535 # NOTE(gregory.p.smith): I considered isinstance(first, type(second))
536 # and vice versa. I opted for the conservative approach in case
537 # subclasses are not intended to be compared in detail to their super
538 # class instances using a type equality func. This means testing
539 # subtypes won't automagically use the detailed comparison. Callers
540 # should use their type specific assertSpamEqual method to compare
541 # subclasses if the detailed comparison is desired and appropriate.
542 # See the discussion in http://bugs.python.org/issue2578.
543 #
544 if type(first) is type(second):
Benjamin Peterson71095ae2009-04-01 23:15:49 +0000545 return self._type_equality_funcs.get(type(first),
546 self._baseAssertEqual)
Gregory P. Smith28399852009-03-31 16:54:10 +0000547 return self._baseAssertEqual
548
549 def _baseAssertEqual(self, first, second, msg=None):
550 """The default assertEqual implementation, not type specific."""
551 if not first == second:
Michael Foord345b2fe2009-04-02 03:20:38 +0000552 standardMsg = '%r != %r' % (first, second)
553 msg = self._formatMessage(msg, standardMsg)
554 raise self.failureException(msg)
Gregory P. Smith28399852009-03-31 16:54:10 +0000555
Gregory P. Smith7558d572009-03-31 19:03:28 +0000556 def assertEqual(self, first, second, msg=None):
Raymond Hettingerc377cbf2003-04-04 22:56:42 +0000557 """Fail if the two objects are unequal as determined by the '=='
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000558 operator.
559 """
Gregory P. Smith28399852009-03-31 16:54:10 +0000560 assertion_func = self._getAssertEqualityFunc(first, second)
561 assertion_func(first, second, msg=msg)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000562
Gregory P. Smith7558d572009-03-31 19:03:28 +0000563 def assertNotEqual(self, first, second, msg=None):
Steve Purcell15d89272001-04-12 09:05:01 +0000564 """Fail if the two objects are equal as determined by the '=='
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000565 operator.
566 """
Michael Foord345b2fe2009-04-02 03:20:38 +0000567 if not first != second:
568 msg = self._formatMessage(msg, '%r == %r' % (first, second))
569 raise self.failureException(msg)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000570
Gregory P. Smith7558d572009-03-31 19:03:28 +0000571 def assertAlmostEqual(self, first, second, places=7, msg=None):
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000572 """Fail if the two objects are unequal as determined by their
573 difference rounded to the given number of decimal places
574 (default 7) and comparing to zero.
575
Steve Purcell397b45d2003-10-26 10:41:03 +0000576 Note that decimal places (from zero) are usually not the same
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000577 as significant digits (measured from the most signficant digit).
578 """
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000579 if round(abs(second-first), places) != 0:
Michael Foord345b2fe2009-04-02 03:20:38 +0000580 standardMsg = '%r != %r within %r places' % (first, second, places)
581 msg = self._formatMessage(msg, standardMsg)
582 raise self.failureException(msg)
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000583
Gregory P. Smith7558d572009-03-31 19:03:28 +0000584 def assertNotAlmostEqual(self, first, second, places=7, msg=None):
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000585 """Fail if the two objects are equal as determined by their
586 difference rounded to the given number of decimal places
587 (default 7) and comparing to zero.
588
Steve Purcellcca34912003-10-26 16:38:16 +0000589 Note that decimal places (from zero) are usually not the same
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000590 as significant digits (measured from the most signficant digit).
591 """
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000592 if round(abs(second-first), places) == 0:
Michael Foord345b2fe2009-04-02 03:20:38 +0000593 standardMsg = '%r == %r within %r places' % (first, second, places)
594 msg = self._formatMessage(msg, standardMsg)
595 raise self.failureException(msg)
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000596
Steve Purcell7e743842003-09-22 11:08:12 +0000597 # Synonyms for assertion methods
598
Gregory P. Smith7558d572009-03-31 19:03:28 +0000599 # The plurals are undocumented. Keep them that way to discourage use.
600 # Do not add more. Do not remove.
601 # Going through a deprecation cycle on these would annoy many people.
602 assertEquals = assertEqual
603 assertNotEquals = assertNotEqual
604 assertAlmostEquals = assertAlmostEqual
605 assertNotAlmostEquals = assertNotAlmostEqual
606 assert_ = assertTrue
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000607
Gregory P. Smith7558d572009-03-31 19:03:28 +0000608 # These fail* assertion method names are pending deprecation and will
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000609 # be a DeprecationWarning in 3.2; http://bugs.python.org/issue2578
Benjamin Peterson71095ae2009-04-01 23:15:49 +0000610 def _deprecate(original_func):
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000611 def deprecated_func(*args, **kwargs):
612 warnings.warn(
613 'Please use {0} instead.'.format(original_func.__name__),
614 PendingDeprecationWarning, 2)
615 return original_func(*args, **kwargs)
616 return deprecated_func
Steve Purcell15d89272001-04-12 09:05:01 +0000617
Benjamin Peterson71095ae2009-04-01 23:15:49 +0000618 failUnlessEqual = _deprecate(assertEqual)
619 failIfEqual = _deprecate(assertNotEqual)
620 failUnlessAlmostEqual = _deprecate(assertAlmostEqual)
621 failIfAlmostEqual = _deprecate(assertNotAlmostEqual)
622 failUnless = _deprecate(assertTrue)
623 failUnlessRaises = _deprecate(assertRaises)
624 failIf = _deprecate(assertFalse)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000625
Gregory P. Smith28399852009-03-31 16:54:10 +0000626 def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
627 """An equality assertion for ordered sequences (like lists and tuples).
628
629 For the purposes of this function, a valid orderd sequence type is one
630 which can be indexed, has a length, and has an equality operator.
631
632 Args:
633 seq1: The first sequence to compare.
634 seq2: The second sequence to compare.
635 seq_type: The expected datatype of the sequences, or None if no
636 datatype should be enforced.
637 msg: Optional message to use on failure instead of a list of
638 differences.
639 """
640 if seq_type != None:
641 seq_type_name = seq_type.__name__
642 if not isinstance(seq1, seq_type):
643 raise self.failureException('First sequence is not a %s: %r'
644 % (seq_type_name, seq1))
645 if not isinstance(seq2, seq_type):
646 raise self.failureException('Second sequence is not a %s: %r'
647 % (seq_type_name, seq2))
648 else:
649 seq_type_name = "sequence"
650
651 differing = None
652 try:
653 len1 = len(seq1)
654 except (TypeError, NotImplementedError):
655 differing = 'First %s has no length. Non-sequence?' % (
656 seq_type_name)
657
658 if differing is None:
659 try:
660 len2 = len(seq2)
661 except (TypeError, NotImplementedError):
662 differing = 'Second %s has no length. Non-sequence?' % (
663 seq_type_name)
664
665 if differing is None:
666 if seq1 == seq2:
667 return
668
669 for i in xrange(min(len1, len2)):
670 try:
671 item1 = seq1[i]
672 except (TypeError, IndexError, NotImplementedError):
673 differing = ('Unable to index element %d of first %s\n' %
674 (i, seq_type_name))
675 break
676
677 try:
678 item2 = seq2[i]
679 except (TypeError, IndexError, NotImplementedError):
680 differing = ('Unable to index element %d of second %s\n' %
681 (i, seq_type_name))
682 break
683
684 if item1 != item2:
685 differing = ('First differing element %d:\n%s\n%s\n' %
686 (i, item1, item2))
687 break
688 else:
689 if (len1 == len2 and seq_type is None and
690 type(seq1) != type(seq2)):
691 # The sequences are the same, but have differing types.
692 return
693 # A catch-all message for handling arbitrary user-defined
694 # sequences.
695 differing = '%ss differ:\n' % seq_type_name.capitalize()
696 if len1 > len2:
697 differing = ('First %s contains %d additional '
698 'elements.\n' % (seq_type_name, len1 - len2))
699 try:
700 differing += ('First extra element %d:\n%s\n' %
701 (len2, seq1[len2]))
702 except (TypeError, IndexError, NotImplementedError):
703 differing += ('Unable to index element %d '
704 'of first %s\n' % (len2, seq_type_name))
705 elif len1 < len2:
706 differing = ('Second %s contains %d additional '
707 'elements.\n' % (seq_type_name, len2 - len1))
708 try:
709 differing += ('First extra element %d:\n%s\n' %
710 (len1, seq2[len1]))
711 except (TypeError, IndexError, NotImplementedError):
712 differing += ('Unable to index element %d '
713 'of second %s\n' % (len1, seq_type_name))
Michael Foord345b2fe2009-04-02 03:20:38 +0000714 standardMsg = differing + '\n'.join(difflib.ndiff(pprint.pformat(seq1).splitlines(),
715 pprint.pformat(seq2).splitlines()))
716 msg = self._formatMessage(msg, standardMsg)
717 self.fail(msg)
Gregory P. Smith28399852009-03-31 16:54:10 +0000718
719 def assertListEqual(self, list1, list2, msg=None):
720 """A list-specific equality assertion.
721
722 Args:
723 list1: The first list to compare.
724 list2: The second list to compare.
725 msg: Optional message to use on failure instead of a list of
726 differences.
727
728 """
729 self.assertSequenceEqual(list1, list2, msg, seq_type=list)
730
731 def assertTupleEqual(self, tuple1, tuple2, msg=None):
732 """A tuple-specific equality assertion.
733
734 Args:
735 tuple1: The first tuple to compare.
736 tuple2: The second tuple to compare.
737 msg: Optional message to use on failure instead of a list of
738 differences.
739 """
740 self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
741
742 def assertSetEqual(self, set1, set2, msg=None):
743 """A set-specific equality assertion.
744
745 Args:
746 set1: The first set to compare.
747 set2: The second set to compare.
748 msg: Optional message to use on failure instead of a list of
749 differences.
750
751 For more general containership equality, assertSameElements will work
752 with things other than sets. This uses ducktyping to support
753 different types of sets, and is optimized for sets specifically
754 (parameters must support a difference method).
755 """
756 try:
757 difference1 = set1.difference(set2)
758 except TypeError, e:
759 self.fail('invalid type when attempting set difference: %s' % e)
760 except AttributeError, e:
761 self.fail('first argument does not support set difference: %s' % e)
762
763 try:
764 difference2 = set2.difference(set1)
765 except TypeError, e:
766 self.fail('invalid type when attempting set difference: %s' % e)
767 except AttributeError, e:
768 self.fail('second argument does not support set difference: %s' % e)
769
770 if not (difference1 or difference2):
771 return
772
Gregory P. Smith28399852009-03-31 16:54:10 +0000773 lines = []
774 if difference1:
775 lines.append('Items in the first set but not the second:')
776 for item in difference1:
777 lines.append(repr(item))
778 if difference2:
779 lines.append('Items in the second set but not the first:')
780 for item in difference2:
781 lines.append(repr(item))
Gregory P. Smith28399852009-03-31 16:54:10 +0000782
Michael Foord345b2fe2009-04-02 03:20:38 +0000783 standardMsg = '\n'.join(lines)
784 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000785
Michael Foord345b2fe2009-04-02 03:20:38 +0000786 def assertIn(self, member, container, msg=None):
787 """Just like self.assertTrue(a in b), but with a nicer default message."""
788 if member not in container:
789 standardMsg = '%r not found in %r' % (member, container)
790 self.fail(self._formatMessage(msg, standardMsg))
791
792 def assertNotIn(self, member, container, msg=None):
793 """Just like self.assertTrue(a not in b), but with a nicer default message."""
794 if member in container:
795 standardMsg = '%r unexpectedly found in %r' % (member, container)
796 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000797
798 def assertDictEqual(self, d1, d2, msg=None):
799 self.assert_(isinstance(d1, dict), 'First argument is not a dictionary')
800 self.assert_(isinstance(d2, dict), 'Second argument is not a dictionary')
801
802 if d1 != d2:
Michael Foord345b2fe2009-04-02 03:20:38 +0000803 standardMsg = ('\n' + '\n'.join(difflib.ndiff(
804 pprint.pformat(d1).splitlines(),
805 pprint.pformat(d2).splitlines())))
806 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000807
808 def assertDictContainsSubset(self, expected, actual, msg=None):
809 """Checks whether actual is a superset of expected."""
810 missing = []
811 mismatched = []
812 for key, value in expected.iteritems():
813 if key not in actual:
814 missing.append(key)
815 elif value != actual[key]:
Michael Foord345b2fe2009-04-02 03:20:38 +0000816 mismatched.append('%s, expected: %s, actual: %s' % (key, value, actual[key]))
Gregory P. Smith28399852009-03-31 16:54:10 +0000817
818 if not (missing or mismatched):
819 return
820
Michael Foord345b2fe2009-04-02 03:20:38 +0000821 standardMsg = ''
Gregory P. Smith28399852009-03-31 16:54:10 +0000822 if missing:
Michael Foord345b2fe2009-04-02 03:20:38 +0000823 standardMsg = 'Missing: %r' % ','.join(missing)
Gregory P. Smith28399852009-03-31 16:54:10 +0000824 if mismatched:
Michael Foord345b2fe2009-04-02 03:20:38 +0000825 if standardMsg:
826 standardMsg += '; '
827 standardMsg += 'Mismatched values: %s' % ','.join(mismatched)
Gregory P. Smith28399852009-03-31 16:54:10 +0000828
Michael Foord345b2fe2009-04-02 03:20:38 +0000829 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000830
831 def assertSameElements(self, expected_seq, actual_seq, msg=None):
832 """An unordered sequence specific comparison.
833
834 Raises with an error message listing which elements of expected_seq
835 are missing from actual_seq and vice versa if any.
836 """
837 try:
838 expected = set(expected_seq)
839 actual = set(actual_seq)
840 missing = list(expected.difference(actual))
841 unexpected = list(actual.difference(expected))
842 missing.sort()
843 unexpected.sort()
844 except TypeError:
845 # Fall back to slower list-compare if any of the objects are
846 # not hashable.
847 expected = list(expected_seq)
848 actual = list(actual_seq)
849 expected.sort()
850 actual.sort()
851 missing, unexpected = _SortedListDifference(expected, actual)
852 errors = []
853 if missing:
Michael Foord345b2fe2009-04-02 03:20:38 +0000854 errors.append('Expected, but missing:\n %r' % missing)
Gregory P. Smith28399852009-03-31 16:54:10 +0000855 if unexpected:
Michael Foord345b2fe2009-04-02 03:20:38 +0000856 errors.append('Unexpected, but present:\n %r' % unexpected)
Gregory P. Smith28399852009-03-31 16:54:10 +0000857 if errors:
Michael Foord345b2fe2009-04-02 03:20:38 +0000858 standardMsg = '\n'.join(errors)
859 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000860
861 def assertMultiLineEqual(self, first, second, msg=None):
862 """Assert that two multi-line strings are equal."""
Michael Foord345b2fe2009-04-02 03:20:38 +0000863 self.assert_(isinstance(first, basestring), (
Gregory P. Smith28399852009-03-31 16:54:10 +0000864 'First argument is not a string'))
Michael Foord345b2fe2009-04-02 03:20:38 +0000865 self.assert_(isinstance(second, basestring), (
Gregory P. Smith28399852009-03-31 16:54:10 +0000866 'Second argument is not a string'))
867
868 if first != second:
Michael Foord345b2fe2009-04-02 03:20:38 +0000869 standardMsg = '\n' + ''.join(difflib.ndiff(first.splitlines(True), second.splitlines(True)))
870 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000871
872 def assertLess(self, a, b, msg=None):
Michael Foord345b2fe2009-04-02 03:20:38 +0000873 """Just like self.assertTrue(a < b), but with a nicer default message."""
874 if not a < b:
875 standardMsg = '%r not less than %r' % (a, b)
876 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000877
878 def assertLessEqual(self, a, b, msg=None):
Michael Foord345b2fe2009-04-02 03:20:38 +0000879 """Just like self.assertTrue(a <= b), but with a nicer default message."""
880 if not a <= b:
881 standardMsg = '%r not less than or equal to %r' % (a, b)
882 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000883
884 def assertGreater(self, a, b, msg=None):
Michael Foord345b2fe2009-04-02 03:20:38 +0000885 """Just like self.assertTrue(a > b), but with a nicer default message."""
886 if not a > b:
887 standardMsg = '%r not greater than %r' % (a, b)
888 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000889
890 def assertGreaterEqual(self, a, b, msg=None):
Michael Foord345b2fe2009-04-02 03:20:38 +0000891 """Just like self.assertTrue(a >= b), but with a nicer default message."""
892 if not a >= b:
893 standardMsg = '%r not greater than or equal to %r' % (a, b)
894 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000895
896 def assertIsNone(self, obj, msg=None):
Michael Foord345b2fe2009-04-02 03:20:38 +0000897 """Same as self.assertTrue(obj is None), with a nicer default message."""
898 if obj is not None:
899 standardMsg = '%r is not None' % obj
900 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000901
Michael Foord345b2fe2009-04-02 03:20:38 +0000902 def assertIsNotNone(self, obj, msg=None):
Gregory P. Smith28399852009-03-31 16:54:10 +0000903 """Included for symmetry with assertIsNone."""
Michael Foord345b2fe2009-04-02 03:20:38 +0000904 if obj is None:
905 standardMsg = 'unexpectedly None'
906 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000907
908 def assertRaisesRegexp(self, expected_exception, expected_regexp,
909 callable_obj=None, *args, **kwargs):
910 """Asserts that the message in a raised exception matches a regexp.
911
912 Args:
913 expected_exception: Exception class expected to be raised.
914 expected_regexp: Regexp (re pattern object or string) expected
915 to be found in error message.
916 callable_obj: Function to be called.
917 args: Extra args.
918 kwargs: Extra kwargs.
919 """
920 context = _AssertRaisesContext(expected_exception, self, expected_regexp)
921 if callable_obj is None:
922 return context
923 with context:
924 callable_obj(*args, **kwargs)
925
926 def assertRegexpMatches(self, text, expected_regex, msg=None):
927 if isinstance(expected_regex, basestring):
928 expected_regex = re.compile(expected_regex)
929 if not expected_regex.search(text):
930 msg = msg or "Regexp didn't match"
931 msg = '%s: %r not found in %r' % (msg, expected_regex.pattern, text)
932 raise self.failureException(msg)
933
934
935def _SortedListDifference(expected, actual):
936 """Finds elements in only one or the other of two, sorted input lists.
937
938 Returns a two-element tuple of lists. The first list contains those
939 elements in the "expected" list but not in the "actual" list, and the
940 second contains those elements in the "actual" list but not in the
941 "expected" list. Duplicate elements in either input list are ignored.
942 """
943 i = j = 0
944 missing = []
945 unexpected = []
946 while True:
947 try:
948 e = expected[i]
949 a = actual[j]
950 if e < a:
951 missing.append(e)
952 i += 1
953 while expected[i] == e:
954 i += 1
955 elif e > a:
956 unexpected.append(a)
957 j += 1
958 while actual[j] == a:
959 j += 1
960 else:
961 i += 1
962 try:
963 while expected[i] == e:
964 i += 1
965 finally:
966 j += 1
967 while actual[j] == a:
968 j += 1
969 except IndexError:
970 missing.extend(expected[i:])
971 unexpected.extend(actual[j:])
972 break
973 return missing, unexpected
974
Fred Drake02538202001-03-21 18:09:46 +0000975
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000976class TestSuite(object):
Fred Drake02538202001-03-21 18:09:46 +0000977 """A test suite is a composite test consisting of a number of TestCases.
978
979 For use, create an instance of TestSuite, then add test case instances.
980 When all tests have been added, the suite can be passed to a test
981 runner, such as TextTestRunner. It will run the individual test cases
982 in the order in which they were added, aggregating the results. When
983 subclassing, do not forget to call the base class constructor.
984 """
985 def __init__(self, tests=()):
986 self._tests = []
987 self.addTests(tests)
988
989 def __repr__(self):
Steve Purcelldc391a62002-08-09 09:46:23 +0000990 return "<%s tests=%s>" % (_strclass(self.__class__), self._tests)
Fred Drake02538202001-03-21 18:09:46 +0000991
Georg Brandl15c5ce92007-03-07 09:09:40 +0000992 def __eq__(self, other):
Benjamin Peterson692428e2009-03-23 21:50:21 +0000993 if not isinstance(other, self.__class__):
994 return NotImplemented
Georg Brandl15c5ce92007-03-07 09:09:40 +0000995 return self._tests == other._tests
996
997 def __ne__(self, other):
998 return not self == other
999
Nick Coghlan48361f52008-08-11 15:45:58 +00001000 # Can't guarantee hash invariant, so flag as unhashable
1001 __hash__ = None
1002
Jim Fultonfafd8742004-08-28 15:22:12 +00001003 def __iter__(self):
1004 return iter(self._tests)
1005
Fred Drake02538202001-03-21 18:09:46 +00001006 def countTestCases(self):
1007 cases = 0
1008 for test in self._tests:
Steve Purcell7e743842003-09-22 11:08:12 +00001009 cases += test.countTestCases()
Fred Drake02538202001-03-21 18:09:46 +00001010 return cases
1011
1012 def addTest(self, test):
Georg Brandld9e50262007-03-07 11:54:49 +00001013 # sanity checks
Raymond Hettinger5930d8f2008-07-10 16:06:41 +00001014 if not hasattr(test, '__call__'):
Georg Brandld9e50262007-03-07 11:54:49 +00001015 raise TypeError("the test to add must be callable")
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001016 if isinstance(test, type) and issubclass(test, (TestCase, TestSuite)):
Georg Brandld9e50262007-03-07 11:54:49 +00001017 raise TypeError("TestCases and TestSuites must be instantiated "
1018 "before passing them to addTest()")
Fred Drake02538202001-03-21 18:09:46 +00001019 self._tests.append(test)
1020
1021 def addTests(self, tests):
Georg Brandld9e50262007-03-07 11:54:49 +00001022 if isinstance(tests, basestring):
1023 raise TypeError("tests must be an iterable of tests, not a string")
Fred Drake02538202001-03-21 18:09:46 +00001024 for test in tests:
1025 self.addTest(test)
1026
1027 def run(self, result):
Fred Drake02538202001-03-21 18:09:46 +00001028 for test in self._tests:
1029 if result.shouldStop:
1030 break
1031 test(result)
1032 return result
1033
Raymond Hettinger664347b2004-12-04 21:21:53 +00001034 def __call__(self, *args, **kwds):
1035 return self.run(*args, **kwds)
1036
Fred Drake02538202001-03-21 18:09:46 +00001037 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001038 """Run the tests without collecting errors in a TestResult"""
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001039 for test in self._tests:
1040 test.debug()
Fred Drake02538202001-03-21 18:09:46 +00001041
1042
Benjamin Peterson692428e2009-03-23 21:50:21 +00001043class ClassTestSuite(TestSuite):
1044 """
1045 Suite of tests derived from a single TestCase class.
1046 """
1047
1048 def __init__(self, tests, class_collected_from):
1049 super(ClassTestSuite, self).__init__(tests)
1050 self.collected_from = class_collected_from
1051
1052 def id(self):
1053 module = getattr(self.collected_from, "__module__", None)
1054 if module is not None:
1055 return "{0}.{1}".format(module, self.collected_from.__name__)
1056 return self.collected_from.__name__
1057
1058 def run(self, result):
1059 if getattr(self.collected_from, "__unittest_skip__", False):
1060 # ClassTestSuite result pretends to be a TestCase enough to be
1061 # reported.
1062 result.startTest(self)
1063 try:
1064 result.addSkip(self, self.collected_from.__unittest_skip_why__)
1065 finally:
1066 result.stopTest(self)
1067 else:
1068 result = super(ClassTestSuite, self).run(result)
1069 return result
1070
1071 shortDescription = id
1072
1073
Fred Drake02538202001-03-21 18:09:46 +00001074class FunctionTestCase(TestCase):
1075 """A test case that wraps a test function.
1076
1077 This is useful for slipping pre-existing test functions into the
Georg Brandl15c5ce92007-03-07 09:09:40 +00001078 unittest framework. Optionally, set-up and tidy-up functions can be
Fred Drake02538202001-03-21 18:09:46 +00001079 supplied. As with TestCase, the tidy-up ('tearDown') function will
1080 always be called if the set-up ('setUp') function ran successfully.
1081 """
1082
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001083 def __init__(self, testFunc, setUp=None, tearDown=None, description=None):
1084 super(FunctionTestCase, self).__init__()
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001085 self._setUpFunc = setUp
1086 self._tearDownFunc = tearDown
1087 self._testFunc = testFunc
1088 self._description = description
Fred Drake02538202001-03-21 18:09:46 +00001089
1090 def setUp(self):
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001091 if self._setUpFunc is not None:
1092 self._setUpFunc()
Fred Drake02538202001-03-21 18:09:46 +00001093
1094 def tearDown(self):
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001095 if self._tearDownFunc is not None:
1096 self._tearDownFunc()
Fred Drake02538202001-03-21 18:09:46 +00001097
1098 def runTest(self):
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001099 self._testFunc()
Fred Drake02538202001-03-21 18:09:46 +00001100
1101 def id(self):
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001102 return self._testFunc.__name__
Fred Drake02538202001-03-21 18:09:46 +00001103
Georg Brandl15c5ce92007-03-07 09:09:40 +00001104 def __eq__(self, other):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001105 if not isinstance(other, self.__class__):
1106 return NotImplemented
Georg Brandl15c5ce92007-03-07 09:09:40 +00001107
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001108 return self._setUpFunc == other._setUpFunc and \
1109 self._tearDownFunc == other._tearDownFunc and \
1110 self._testFunc == other._testFunc and \
1111 self._description == other._description
Georg Brandl15c5ce92007-03-07 09:09:40 +00001112
1113 def __ne__(self, other):
1114 return not self == other
1115
1116 def __hash__(self):
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001117 return hash((type(self), self._setUpFunc, self._tearDownFunc,
1118 self._testFunc, self._description))
Georg Brandl15c5ce92007-03-07 09:09:40 +00001119
Fred Drake02538202001-03-21 18:09:46 +00001120 def __str__(self):
Steve Purcelldc391a62002-08-09 09:46:23 +00001121 return "%s (%s)" % (_strclass(self.__class__), self.__testFunc.__name__)
Fred Drake02538202001-03-21 18:09:46 +00001122
1123 def __repr__(self):
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001124 return "<%s testFunc=%s>" % (_strclass(self.__class__), self._testFunc)
Fred Drake02538202001-03-21 18:09:46 +00001125
1126 def shortDescription(self):
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001127 if self._description is not None:
1128 return self._description
1129 doc = self._testFunc.__doc__
Steve Purcell7e743842003-09-22 11:08:12 +00001130 return doc and doc.split("\n")[0].strip() or None
Fred Drake02538202001-03-21 18:09:46 +00001131
1132
1133
1134##############################################################################
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001135# Locating and loading tests
Fred Drake02538202001-03-21 18:09:46 +00001136##############################################################################
1137
Antoine Pitroudae1a6a2008-12-28 16:01:11 +00001138class TestLoader(object):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001139 """
1140 This class is responsible for loading tests according to various criteria
1141 and returning them wrapped in a TestSuite
Fred Drake02538202001-03-21 18:09:46 +00001142 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001143 testMethodPrefix = 'test'
1144 sortTestMethodsUsing = cmp
1145 suiteClass = TestSuite
Benjamin Peterson692428e2009-03-23 21:50:21 +00001146 classSuiteClass = ClassTestSuite
Fred Drake02538202001-03-21 18:09:46 +00001147
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001148 def loadTestsFromTestCase(self, testCaseClass):
Steve Purcell15d89272001-04-12 09:05:01 +00001149 """Return a suite of all tests cases contained in testCaseClass"""
Johannes Gijsbersd7b6ad42004-11-07 15:46:25 +00001150 if issubclass(testCaseClass, TestSuite):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001151 raise TypeError("Test cases should not be derived from TestSuite." \
1152 " Maybe you meant to derive from TestCase?")
Steve Purcell7e743842003-09-22 11:08:12 +00001153 testCaseNames = self.getTestCaseNames(testCaseClass)
1154 if not testCaseNames and hasattr(testCaseClass, 'runTest'):
1155 testCaseNames = ['runTest']
Benjamin Peterson692428e2009-03-23 21:50:21 +00001156 suite = self.classSuiteClass(map(testCaseClass, testCaseNames),
1157 testCaseClass)
1158 return suite
Fred Drake02538202001-03-21 18:09:46 +00001159
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001160 def loadTestsFromModule(self, module):
Steve Purcell15d89272001-04-12 09:05:01 +00001161 """Return a suite of all tests cases contained in the given module"""
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001162 tests = []
1163 for name in dir(module):
1164 obj = getattr(module, name)
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001165 if isinstance(obj, type) and issubclass(obj, TestCase):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001166 tests.append(self.loadTestsFromTestCase(obj))
1167 return self.suiteClass(tests)
Fred Drake02538202001-03-21 18:09:46 +00001168
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001169 def loadTestsFromName(self, name, module=None):
Steve Purcell15d89272001-04-12 09:05:01 +00001170 """Return a suite of all tests cases given a string specifier.
1171
1172 The name may resolve either to a module, a test case class, a
1173 test method within a test case class, or a callable object which
1174 returns a TestCase or TestSuite instance.
Tim Peters613b2222001-04-13 05:37:27 +00001175
Steve Purcell15d89272001-04-12 09:05:01 +00001176 The method optionally resolves the names relative to a given module.
1177 """
Steve Purcell7e743842003-09-22 11:08:12 +00001178 parts = name.split('.')
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001179 if module is None:
Steve Purcell7e743842003-09-22 11:08:12 +00001180 parts_copy = parts[:]
1181 while parts_copy:
1182 try:
1183 module = __import__('.'.join(parts_copy))
1184 break
1185 except ImportError:
1186 del parts_copy[-1]
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001187 if not parts_copy:
1188 raise
Armin Rigo1b3c04b2003-10-24 17:15:29 +00001189 parts = parts[1:]
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001190 obj = module
1191 for part in parts:
Steve Purcell7e743842003-09-22 11:08:12 +00001192 parent, obj = obj, getattr(obj, part)
Fred Drake02538202001-03-21 18:09:46 +00001193
Antoine Pitroudae1a6a2008-12-28 16:01:11 +00001194 if isinstance(obj, types.ModuleType):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001195 return self.loadTestsFromModule(obj)
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001196 elif isinstance(obj, type) and issubclass(obj, TestCase):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001197 return self.loadTestsFromTestCase(obj)
Antoine Pitroudae1a6a2008-12-28 16:01:11 +00001198 elif (isinstance(obj, types.UnboundMethodType) and
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001199 isinstance(parent, type) and
Georg Brandl15c5ce92007-03-07 09:09:40 +00001200 issubclass(parent, TestCase)):
1201 return TestSuite([parent(obj.__name__)])
Steve Purcell397b45d2003-10-26 10:41:03 +00001202 elif isinstance(obj, TestSuite):
Steve Purcell7e743842003-09-22 11:08:12 +00001203 return obj
Raymond Hettinger5930d8f2008-07-10 16:06:41 +00001204 elif hasattr(obj, '__call__'):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001205 test = obj()
Georg Brandl15c5ce92007-03-07 09:09:40 +00001206 if isinstance(test, TestSuite):
1207 return test
1208 elif isinstance(test, TestCase):
1209 return TestSuite([test])
1210 else:
1211 raise TypeError("calling %s returned %s, not a test" %
1212 (obj, test))
Fred Drake02538202001-03-21 18:09:46 +00001213 else:
Georg Brandl15c5ce92007-03-07 09:09:40 +00001214 raise TypeError("don't know how to make test from: %s" % obj)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001215
1216 def loadTestsFromNames(self, names, module=None):
Steve Purcell15d89272001-04-12 09:05:01 +00001217 """Return a suite of all tests cases found using the given sequence
1218 of string specifiers. See 'loadTestsFromName()'.
1219 """
Steve Purcell7e743842003-09-22 11:08:12 +00001220 suites = [self.loadTestsFromName(name, module) for name in names]
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001221 return self.suiteClass(suites)
1222
1223 def getTestCaseNames(self, testCaseClass):
Steve Purcell15d89272001-04-12 09:05:01 +00001224 """Return a sorted sequence of method names found within testCaseClass
1225 """
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001226 def isTestMethod(attrname, testCaseClass=testCaseClass,
1227 prefix=self.testMethodPrefix):
1228 return attrname.startswith(prefix) and \
1229 hasattr(getattr(testCaseClass, attrname), '__call__')
Steve Purcell7e743842003-09-22 11:08:12 +00001230 testFnNames = filter(isTestMethod, dir(testCaseClass))
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001231 if self.sortTestMethodsUsing:
Raymond Hettinger5930d8f2008-07-10 16:06:41 +00001232 testFnNames.sort(key=_CmpToKey(self.sortTestMethodsUsing))
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001233 return testFnNames
1234
1235
1236
1237defaultTestLoader = TestLoader()
1238
1239
1240##############################################################################
1241# Patches for old functions: these functions should be considered obsolete
1242##############################################################################
1243
1244def _makeLoader(prefix, sortUsing, suiteClass=None):
1245 loader = TestLoader()
1246 loader.sortTestMethodsUsing = sortUsing
1247 loader.testMethodPrefix = prefix
1248 if suiteClass: loader.suiteClass = suiteClass
1249 return loader
1250
1251def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp):
1252 return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)
1253
1254def makeSuite(testCaseClass, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
1255 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
1256
1257def findTestCases(module, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
1258 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module)
Fred Drake02538202001-03-21 18:09:46 +00001259
1260
1261##############################################################################
1262# Text UI
1263##############################################################################
1264
Antoine Pitroudae1a6a2008-12-28 16:01:11 +00001265class _WritelnDecorator(object):
Fred Drake02538202001-03-21 18:09:46 +00001266 """Used to decorate file-like objects with a handy 'writeln' method"""
1267 def __init__(self,stream):
1268 self.stream = stream
Fred Drake02538202001-03-21 18:09:46 +00001269
1270 def __getattr__(self, attr):
1271 return getattr(self.stream,attr)
1272
Raymond Hettinger91dd19d2003-09-13 02:58:00 +00001273 def writeln(self, arg=None):
Benjamin Petersond0cdb2d2009-03-24 23:07:07 +00001274 if arg:
1275 self.write(arg)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001276 self.write('\n') # text-mode streams translate to \r\n if needed
Tim Petersa19a1682001-03-29 04:36:09 +00001277
Fred Drake02538202001-03-21 18:09:46 +00001278
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001279class _TextTestResult(TestResult):
Fred Drake02538202001-03-21 18:09:46 +00001280 """A test result class that can print formatted text results to a stream.
1281
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001282 Used by TextTestRunner.
Fred Drake02538202001-03-21 18:09:46 +00001283 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001284 separator1 = '=' * 70
1285 separator2 = '-' * 70
Fred Drake02538202001-03-21 18:09:46 +00001286
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001287 def __init__(self, stream, descriptions, verbosity):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001288 super(_TextTestResult, self).__init__()
Fred Drake02538202001-03-21 18:09:46 +00001289 self.stream = stream
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001290 self.showAll = verbosity > 1
1291 self.dots = verbosity == 1
Fred Drake02538202001-03-21 18:09:46 +00001292 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001293
1294 def getDescription(self, test):
1295 if self.descriptions:
1296 return test.shortDescription() or str(test)
1297 else:
1298 return str(test)
1299
Fred Drake02538202001-03-21 18:09:46 +00001300 def startTest(self, test):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001301 super(_TextTestResult, self).startTest(test)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001302 if self.showAll:
1303 self.stream.write(self.getDescription(test))
1304 self.stream.write(" ... ")
Georg Brandld0632402008-05-11 15:17:41 +00001305 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +00001306
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001307 def addSuccess(self, test):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001308 super(_TextTestResult, self).addSuccess(test)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001309 if self.showAll:
Fred Drake02538202001-03-21 18:09:46 +00001310 self.stream.writeln("ok")
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001311 elif self.dots:
1312 self.stream.write('.')
Georg Brandld0632402008-05-11 15:17:41 +00001313 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +00001314
1315 def addError(self, test, err):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001316 super(_TextTestResult, self).addError(test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001317 if self.showAll:
1318 self.stream.writeln("ERROR")
1319 elif self.dots:
1320 self.stream.write('E')
Georg Brandld0632402008-05-11 15:17:41 +00001321 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +00001322
1323 def addFailure(self, test, err):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001324 super(_TextTestResult, self).addFailure(test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001325 if self.showAll:
1326 self.stream.writeln("FAIL")
1327 elif self.dots:
1328 self.stream.write('F')
Georg Brandld0632402008-05-11 15:17:41 +00001329 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +00001330
Benjamin Peterson692428e2009-03-23 21:50:21 +00001331 def addSkip(self, test, reason):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001332 super(_TextTestResult, self).addSkip(test, reason)
Benjamin Peterson692428e2009-03-23 21:50:21 +00001333 if self.showAll:
1334 self.stream.writeln("skipped {0!r}".format(reason))
1335 elif self.dots:
1336 self.stream.write("s")
1337 self.stream.flush()
1338
1339 def addExpectedFailure(self, test, err):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001340 super(_TextTestResult, self).addExpectedFailure(test, err)
Benjamin Peterson692428e2009-03-23 21:50:21 +00001341 if self.showAll:
1342 self.stream.writeln("expected failure")
1343 elif self.dots:
Benjamin Petersona8adceb2009-03-25 21:24:04 +00001344 self.stream.write("x")
Benjamin Peterson692428e2009-03-23 21:50:21 +00001345 self.stream.flush()
1346
1347 def addUnexpectedSuccess(self, test):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001348 super(_TextTestResult, self).addUnexpectedSuccess(test)
Benjamin Peterson692428e2009-03-23 21:50:21 +00001349 if self.showAll:
1350 self.stream.writeln("unexpected success")
1351 elif self.dots:
Benjamin Petersona8adceb2009-03-25 21:24:04 +00001352 self.stream.write("u")
Benjamin Peterson692428e2009-03-23 21:50:21 +00001353 self.stream.flush()
1354
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001355 def printErrors(self):
1356 if self.dots or self.showAll:
Fred Drake02538202001-03-21 18:09:46 +00001357 self.stream.writeln()
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001358 self.printErrorList('ERROR', self.errors)
1359 self.printErrorList('FAIL', self.failures)
1360
1361 def printErrorList(self, flavour, errors):
1362 for test, err in errors:
1363 self.stream.writeln(self.separator1)
1364 self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
1365 self.stream.writeln(self.separator2)
Steve Purcell7b065702001-09-06 08:24:40 +00001366 self.stream.writeln("%s" % err)
Fred Drake02538202001-03-21 18:09:46 +00001367
1368
Antoine Pitroudae1a6a2008-12-28 16:01:11 +00001369class TextTestRunner(object):
Fred Drake02538202001-03-21 18:09:46 +00001370 """A test runner class that displays results in textual form.
Tim Petersa19a1682001-03-29 04:36:09 +00001371
Fred Drake02538202001-03-21 18:09:46 +00001372 It prints out the names of tests as they are run, errors as they
1373 occur, and a summary of the results at the end of the test run.
1374 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001375 def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1):
Fred Drake02538202001-03-21 18:09:46 +00001376 self.stream = _WritelnDecorator(stream)
1377 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001378 self.verbosity = verbosity
1379
1380 def _makeResult(self):
1381 return _TextTestResult(self.stream, self.descriptions, self.verbosity)
Fred Drake02538202001-03-21 18:09:46 +00001382
1383 def run(self, test):
1384 "Run the given test case or test suite."
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001385 result = self._makeResult()
Fred Drake02538202001-03-21 18:09:46 +00001386 startTime = time.time()
1387 test(result)
1388 stopTime = time.time()
Steve Purcell397b45d2003-10-26 10:41:03 +00001389 timeTaken = stopTime - startTime
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001390 result.printErrors()
1391 self.stream.writeln(result.separator2)
Fred Drake02538202001-03-21 18:09:46 +00001392 run = result.testsRun
1393 self.stream.writeln("Ran %d test%s in %.3fs" %
Neal Norwitz76165042002-05-31 14:15:11 +00001394 (run, run != 1 and "s" or "", timeTaken))
Fred Drake02538202001-03-21 18:09:46 +00001395 self.stream.writeln()
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00001396 results = map(len, (result.expectedFailures,
1397 result.unexpectedSuccesses,
Benjamin Peterson692428e2009-03-23 21:50:21 +00001398 result.skipped))
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00001399 expectedFails, unexpectedSuccesses, skipped = results
Benjamin Peterson692428e2009-03-23 21:50:21 +00001400 infos = []
Fred Drake02538202001-03-21 18:09:46 +00001401 if not result.wasSuccessful():
Benjamin Peterson692428e2009-03-23 21:50:21 +00001402 self.stream.write("FAILED")
Fred Drake02538202001-03-21 18:09:46 +00001403 failed, errored = map(len, (result.failures, result.errors))
1404 if failed:
Benjamin Peterson692428e2009-03-23 21:50:21 +00001405 infos.append("failures=%d" % failed)
Fred Drake02538202001-03-21 18:09:46 +00001406 if errored:
Benjamin Peterson692428e2009-03-23 21:50:21 +00001407 infos.append("errors=%d" % errored)
Fred Drake02538202001-03-21 18:09:46 +00001408 else:
Benjamin Petersona473f002009-03-24 22:56:32 +00001409 self.stream.write("OK")
Benjamin Peterson692428e2009-03-23 21:50:21 +00001410 if skipped:
1411 infos.append("skipped=%d" % skipped)
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001412 if expectedFails:
1413 infos.append("expected failures=%d" % expectedFails)
1414 if unexpectedSuccesses:
1415 infos.append("unexpected successes=%d" % unexpectedSuccesses)
Benjamin Peterson692428e2009-03-23 21:50:21 +00001416 if infos:
1417 self.stream.writeln(" (%s)" % (", ".join(infos),))
Benjamin Petersona473f002009-03-24 22:56:32 +00001418 else:
1419 self.stream.write("\n")
Fred Drake02538202001-03-21 18:09:46 +00001420 return result
Tim Petersa19a1682001-03-29 04:36:09 +00001421
Fred Drake02538202001-03-21 18:09:46 +00001422
Fred Drake02538202001-03-21 18:09:46 +00001423
1424##############################################################################
1425# Facilities for running tests from the command line
1426##############################################################################
1427
Antoine Pitroudae1a6a2008-12-28 16:01:11 +00001428class TestProgram(object):
Fred Drake02538202001-03-21 18:09:46 +00001429 """A command-line program that runs a set of tests; this is primarily
1430 for making test modules conveniently executable.
1431 """
1432 USAGE = """\
Steve Purcell17a781b2001-04-09 15:37:31 +00001433Usage: %(progName)s [options] [test] [...]
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001434
1435Options:
1436 -h, --help Show this message
1437 -v, --verbose Verbose output
1438 -q, --quiet Minimal output
Fred Drake02538202001-03-21 18:09:46 +00001439
1440Examples:
1441 %(progName)s - run default set of tests
1442 %(progName)s MyTestSuite - run suite 'MyTestSuite'
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001443 %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething
1444 %(progName)s MyTestCase - run all 'test*' test methods
Fred Drake02538202001-03-21 18:09:46 +00001445 in MyTestCase
1446"""
1447 def __init__(self, module='__main__', defaultTest=None,
Georg Brandld0a96252007-03-07 09:21:06 +00001448 argv=None, testRunner=TextTestRunner,
1449 testLoader=defaultTestLoader):
Antoine Pitroudae1a6a2008-12-28 16:01:11 +00001450 if isinstance(module, basestring):
Fred Drake02538202001-03-21 18:09:46 +00001451 self.module = __import__(module)
Steve Purcell7e743842003-09-22 11:08:12 +00001452 for part in module.split('.')[1:]:
Fred Drake02538202001-03-21 18:09:46 +00001453 self.module = getattr(self.module, part)
1454 else:
1455 self.module = module
1456 if argv is None:
1457 argv = sys.argv
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001458 self.verbosity = 1
Fred Drake02538202001-03-21 18:09:46 +00001459 self.defaultTest = defaultTest
1460 self.testRunner = testRunner
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001461 self.testLoader = testLoader
Fred Drake02538202001-03-21 18:09:46 +00001462 self.progName = os.path.basename(argv[0])
1463 self.parseArgs(argv)
Fred Drake02538202001-03-21 18:09:46 +00001464 self.runTests()
1465
1466 def usageExit(self, msg=None):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001467 if msg:
1468 print msg
Fred Drake02538202001-03-21 18:09:46 +00001469 print self.USAGE % self.__dict__
1470 sys.exit(2)
1471
1472 def parseArgs(self, argv):
1473 import getopt
Benjamin Peterson692428e2009-03-23 21:50:21 +00001474 long_opts = ['help','verbose','quiet']
Fred Drake02538202001-03-21 18:09:46 +00001475 try:
Benjamin Peterson692428e2009-03-23 21:50:21 +00001476 options, args = getopt.getopt(argv[1:], 'hHvq', long_opts)
Fred Drake02538202001-03-21 18:09:46 +00001477 for opt, value in options:
1478 if opt in ('-h','-H','--help'):
1479 self.usageExit()
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001480 if opt in ('-q','--quiet'):
1481 self.verbosity = 0
1482 if opt in ('-v','--verbose'):
1483 self.verbosity = 2
Fred Drake02538202001-03-21 18:09:46 +00001484 if len(args) == 0 and self.defaultTest is None:
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001485 self.test = self.testLoader.loadTestsFromModule(self.module)
1486 return
Fred Drake02538202001-03-21 18:09:46 +00001487 if len(args) > 0:
1488 self.testNames = args
1489 else:
1490 self.testNames = (self.defaultTest,)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001491 self.createTests()
Fred Drake02538202001-03-21 18:09:46 +00001492 except getopt.error, msg:
1493 self.usageExit(msg)
1494
1495 def createTests(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001496 self.test = self.testLoader.loadTestsFromNames(self.testNames,
1497 self.module)
Fred Drake02538202001-03-21 18:09:46 +00001498
1499 def runTests(self):
Georg Brandld0a96252007-03-07 09:21:06 +00001500 if isinstance(self.testRunner, (type, types.ClassType)):
1501 try:
1502 testRunner = self.testRunner(verbosity=self.verbosity)
1503 except TypeError:
1504 # didn't accept the verbosity argument
1505 testRunner = self.testRunner()
1506 else:
1507 # it is assumed to be a TestRunner instance
1508 testRunner = self.testRunner
1509 result = testRunner.run(self.test)
Tim Petersa19a1682001-03-29 04:36:09 +00001510 sys.exit(not result.wasSuccessful())
Fred Drake02538202001-03-21 18:09:46 +00001511
1512main = TestProgram
1513
1514
1515##############################################################################
1516# Executing this module from the command line
1517##############################################################################
1518
1519if __name__ == "__main__":
1520 main(module=None)