blob: d781354ba4201290256d27b5338066dd0e72c30b [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
Michael Foord07ef4872009-05-02 22:43:34 +0000189 def startTestRun(self):
190 """Called once before any tests are executed.
191
192 See startTest for a method called before each test.
193 """
194
Fred Drake02538202001-03-21 18:09:46 +0000195 def stopTest(self, test):
196 "Called when the given test has been run"
197 pass
198
Michael Foord07ef4872009-05-02 22:43:34 +0000199 def stopTestRun(self):
200 """Called once after all tests are executed.
201
202 See stopTest for a method called after each test.
203 """
204
Fred Drake02538202001-03-21 18:09:46 +0000205 def addError(self, test, err):
Steve Purcell7b065702001-09-06 08:24:40 +0000206 """Called when an error has occurred. 'err' is a tuple of values as
207 returned by sys.exc_info().
208 """
Steve Purcellb8d5f242003-12-06 13:03:13 +0000209 self.errors.append((test, self._exc_info_to_string(err, test)))
Fred Drake02538202001-03-21 18:09:46 +0000210
211 def addFailure(self, test, err):
Steve Purcell7b065702001-09-06 08:24:40 +0000212 """Called when an error has occurred. 'err' is a tuple of values as
213 returned by sys.exc_info()."""
Steve Purcellb8d5f242003-12-06 13:03:13 +0000214 self.failures.append((test, self._exc_info_to_string(err, test)))
Fred Drake02538202001-03-21 18:09:46 +0000215
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000216 def addSuccess(self, test):
217 "Called when a test has completed successfully"
218 pass
219
Benjamin Peterson692428e2009-03-23 21:50:21 +0000220 def addSkip(self, test, reason):
221 """Called when a test is skipped."""
222 self.skipped.append((test, reason))
223
224 def addExpectedFailure(self, test, err):
225 """Called when an expected failure/error occured."""
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +0000226 self.expectedFailures.append(
Benjamin Peterson692428e2009-03-23 21:50:21 +0000227 (test, self._exc_info_to_string(err, test)))
228
229 def addUnexpectedSuccess(self, test):
230 """Called when a test was expected to fail, but succeed."""
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +0000231 self.unexpectedSuccesses.append(test)
Benjamin Peterson692428e2009-03-23 21:50:21 +0000232
Fred Drake02538202001-03-21 18:09:46 +0000233 def wasSuccessful(self):
234 "Tells whether or not this result was a success"
235 return len(self.failures) == len(self.errors) == 0
236
237 def stop(self):
238 "Indicates that the tests should be aborted"
Steve Purcell7e743842003-09-22 11:08:12 +0000239 self.shouldStop = True
Tim Petersa19a1682001-03-29 04:36:09 +0000240
Steve Purcellb8d5f242003-12-06 13:03:13 +0000241 def _exc_info_to_string(self, err, test):
Steve Purcell7b065702001-09-06 08:24:40 +0000242 """Converts a sys.exc_info()-style tuple of values into a string."""
Steve Purcellb8d5f242003-12-06 13:03:13 +0000243 exctype, value, tb = err
244 # Skip test runner traceback levels
245 while tb and self._is_relevant_tb_level(tb):
246 tb = tb.tb_next
247 if exctype is test.failureException:
248 # Skip assert*() traceback levels
249 length = self._count_relevant_tb_levels(tb)
250 return ''.join(traceback.format_exception(exctype, value, tb, length))
251 return ''.join(traceback.format_exception(exctype, value, tb))
252
253 def _is_relevant_tb_level(self, tb):
Georg Brandl56af5fc2008-07-18 19:30:10 +0000254 return '__unittest' in tb.tb_frame.f_globals
Steve Purcellb8d5f242003-12-06 13:03:13 +0000255
256 def _count_relevant_tb_levels(self, tb):
257 length = 0
258 while tb and not self._is_relevant_tb_level(tb):
259 length += 1
260 tb = tb.tb_next
261 return length
Steve Purcell7b065702001-09-06 08:24:40 +0000262
Fred Drake02538202001-03-21 18:09:46 +0000263 def __repr__(self):
264 return "<%s run=%i errors=%i failures=%i>" % \
Steve Purcelldc391a62002-08-09 09:46:23 +0000265 (_strclass(self.__class__), self.testsRun, len(self.errors),
Fred Drake02538202001-03-21 18:09:46 +0000266 len(self.failures))
267
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000268
Gregory P. Smith28399852009-03-31 16:54:10 +0000269class _AssertRaisesContext(object):
270 """A context manager used to implement TestCase.assertRaises* methods."""
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000271
Gregory P. Smith28399852009-03-31 16:54:10 +0000272 def __init__(self, expected, test_case, expected_regexp=None):
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000273 self.expected = expected
274 self.failureException = test_case.failureException
Gregory P. Smith28399852009-03-31 16:54:10 +0000275 self.expected_regex = expected_regexp
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000276
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000277 def __enter__(self):
278 pass
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000279
Benjamin Petersonbaba1952009-04-18 19:26:19 +0000280 def __exit__(self, exc_type, exc_value, tb):
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000281 if exc_type is None:
282 try:
283 exc_name = self.expected.__name__
284 except AttributeError:
285 exc_name = str(self.expected)
286 raise self.failureException(
287 "{0} not raised".format(exc_name))
Gregory P. Smith28399852009-03-31 16:54:10 +0000288 if not issubclass(exc_type, self.expected):
Michael Foord345b2fe2009-04-02 03:20:38 +0000289 # let unexpected exceptions pass through
Gregory P. Smith28399852009-03-31 16:54:10 +0000290 return False
291 if self.expected_regex is None:
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000292 return True
Gregory P. Smith28399852009-03-31 16:54:10 +0000293
294 expected_regexp = self.expected_regex
295 if isinstance(expected_regexp, basestring):
296 expected_regexp = re.compile(expected_regexp)
297 if not expected_regexp.search(str(exc_value)):
298 raise self.failureException('"%s" does not match "%s"' %
299 (expected_regexp.pattern, str(exc_value)))
300 return True
301
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000302
Michael Foorde2942d02009-04-02 05:51:54 +0000303class _AssertWrapper(object):
304 """Wrap entries in the _type_equality_funcs registry to make them deep
305 copyable."""
306
307 def __init__(self, function):
308 self.function = function
309
310 def __deepcopy__(self, memo):
311 memo[id(self)] = self
312
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000313
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000314class TestCase(object):
Fred Drake02538202001-03-21 18:09:46 +0000315 """A class whose instances are single test cases.
316
Fred Drake02538202001-03-21 18:09:46 +0000317 By default, the test code itself should be placed in a method named
318 'runTest'.
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000319
Tim Petersa19a1682001-03-29 04:36:09 +0000320 If the fixture may be used for many test cases, create as
Fred Drake02538202001-03-21 18:09:46 +0000321 many test methods as are needed. When instantiating such a TestCase
322 subclass, specify in the constructor arguments the name of the test method
323 that the instance is to execute.
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000324
Tim Petersa19a1682001-03-29 04:36:09 +0000325 Test authors should subclass TestCase for their own tests. Construction
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000326 and deconstruction of the test's environment ('fixture') can be
327 implemented by overriding the 'setUp' and 'tearDown' methods respectively.
328
329 If it is necessary to override the __init__ method, the base class
330 __init__ method must always be called. It is important that subclasses
331 should not change the signature of their __init__ method, since instances
332 of the classes are instantiated automatically by parts of the framework
333 in order to be run.
Fred Drake02538202001-03-21 18:09:46 +0000334 """
Steve Purcell15d89272001-04-12 09:05:01 +0000335
336 # This attribute determines which exception will be raised when
337 # the instance's assertion methods fail; test methods raising this
338 # exception will be deemed to have 'failed' rather than 'errored'
339
340 failureException = AssertionError
341
Michael Foord345b2fe2009-04-02 03:20:38 +0000342 # This attribute determines whether long messages (including repr of
343 # objects used in assert methods) will be printed on failure in *addition*
344 # to any explicit message passed.
345
346 longMessage = False
347
348
Fred Drake02538202001-03-21 18:09:46 +0000349 def __init__(self, methodName='runTest'):
350 """Create an instance of the class that will use the named test
351 method when executed. Raises a ValueError if the instance does
352 not have a method with the specified name.
353 """
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000354 self._testMethodName = methodName
Michael Foorde2fb98f2009-05-02 20:15:05 +0000355 self._result = None
Fred Drake02538202001-03-21 18:09:46 +0000356 try:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000357 testMethod = getattr(self, methodName)
Fred Drake02538202001-03-21 18:09:46 +0000358 except AttributeError:
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000359 raise ValueError("no such test method in %s: %s" % \
360 (self.__class__, methodName))
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000361 self._testMethodDoc = testMethod.__doc__
Michael Foorde2fb98f2009-05-02 20:15:05 +0000362 self._cleanups = []
Fred Drake02538202001-03-21 18:09:46 +0000363
Gregory P. Smith28399852009-03-31 16:54:10 +0000364 # Map types to custom assertEqual functions that will compare
365 # instances of said type in more detail to generate a more useful
366 # error message.
Benjamin Peterson71095ae2009-04-01 23:15:49 +0000367 self._type_equality_funcs = {}
Gregory P. Smith28399852009-03-31 16:54:10 +0000368 self.addTypeEqualityFunc(dict, self.assertDictEqual)
369 self.addTypeEqualityFunc(list, self.assertListEqual)
370 self.addTypeEqualityFunc(tuple, self.assertTupleEqual)
371 self.addTypeEqualityFunc(set, self.assertSetEqual)
372 self.addTypeEqualityFunc(frozenset, self.assertSetEqual)
373
374 def addTypeEqualityFunc(self, typeobj, function):
375 """Add a type specific assertEqual style function to compare a type.
376
377 This method is for use by TestCase subclasses that need to register
378 their own type equality functions to provide nicer error messages.
379
380 Args:
381 typeobj: The data type to call this function on when both values
382 are of the same type in assertEqual().
383 function: The callable taking two arguments and an optional
384 msg= argument that raises self.failureException with a
385 useful error message when the two arguments are not equal.
386 """
Michael Foorde2942d02009-04-02 05:51:54 +0000387 self._type_equality_funcs[typeobj] = _AssertWrapper(function)
Gregory P. Smith28399852009-03-31 16:54:10 +0000388
Michael Foorde2fb98f2009-05-02 20:15:05 +0000389 def addCleanup(self, function, *args, **kwargs):
390 """Add a function, with arguments, to be called when the test is
391 completed. Functions added are called on a LIFO basis and are
392 called after tearDown on test failure or success.
393
394 Cleanup items are called even if setUp fails (unlike tearDown)."""
395 self._cleanups.append((function, args, kwargs))
396
Fred Drake02538202001-03-21 18:09:46 +0000397 def setUp(self):
398 "Hook method for setting up the test fixture before exercising it."
399 pass
400
401 def tearDown(self):
402 "Hook method for deconstructing the test fixture after testing it."
403 pass
404
405 def countTestCases(self):
406 return 1
407
408 def defaultTestResult(self):
409 return TestResult()
410
411 def shortDescription(self):
Gregory P. Smith28399852009-03-31 16:54:10 +0000412 """Returns both the test method name and first line of its docstring.
Fred Drake02538202001-03-21 18:09:46 +0000413
Gregory P. Smith28399852009-03-31 16:54:10 +0000414 If no docstring is given, only returns the method name.
415
416 This method overrides unittest.TestCase.shortDescription(), which
417 only returns the first line of the docstring, obscuring the name
418 of the test upon failure.
Fred Drake02538202001-03-21 18:09:46 +0000419 """
Gregory P. Smith28399852009-03-31 16:54:10 +0000420 desc = str(self)
421 doc_first_line = None
422
423 if self._testMethodDoc:
424 doc_first_line = self._testMethodDoc.split("\n")[0].strip()
425 if doc_first_line:
426 desc = '\n'.join((desc, doc_first_line))
427 return desc
Fred Drake02538202001-03-21 18:09:46 +0000428
429 def id(self):
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000430 return "%s.%s" % (_strclass(self.__class__), self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000431
Georg Brandl15c5ce92007-03-07 09:09:40 +0000432 def __eq__(self, other):
433 if type(self) is not type(other):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000434 return NotImplemented
Georg Brandl15c5ce92007-03-07 09:09:40 +0000435
436 return self._testMethodName == other._testMethodName
437
438 def __ne__(self, other):
439 return not self == other
440
441 def __hash__(self):
Collin Winter9453e5d2007-03-09 23:30:39 +0000442 return hash((type(self), self._testMethodName))
Georg Brandl15c5ce92007-03-07 09:09:40 +0000443
Fred Drake02538202001-03-21 18:09:46 +0000444 def __str__(self):
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000445 return "%s (%s)" % (self._testMethodName, _strclass(self.__class__))
Fred Drake02538202001-03-21 18:09:46 +0000446
447 def __repr__(self):
448 return "<%s testMethod=%s>" % \
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000449 (_strclass(self.__class__), self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000450
451 def run(self, result=None):
Michael Foord07ef4872009-05-02 22:43:34 +0000452 orig_result = result
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000453 if result is None:
454 result = self.defaultTestResult()
Michael Foord07ef4872009-05-02 22:43:34 +0000455 startTestRun = getattr(result, 'startTestRun', None)
456 if startTestRun is not None:
457 startTestRun()
458
Michael Foorde2fb98f2009-05-02 20:15:05 +0000459 self._result = result
Fred Drake02538202001-03-21 18:09:46 +0000460 result.startTest(self)
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000461 testMethod = getattr(self, self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000462 try:
Benjamin Peterson692428e2009-03-23 21:50:21 +0000463 success = False
Fred Drake02538202001-03-21 18:09:46 +0000464 try:
Michael Foorde2fb98f2009-05-02 20:15:05 +0000465 self.setUp()
Benjamin Peterson692428e2009-03-23 21:50:21 +0000466 except SkipTest as e:
467 result.addSkip(self, str(e))
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000468 except Exception:
Benjamin Petersonc9301352009-03-26 16:32:23 +0000469 result.addError(self, sys.exc_info())
Benjamin Peterson692428e2009-03-23 21:50:21 +0000470 else:
Michael Foorde2fb98f2009-05-02 20:15:05 +0000471 try:
472 testMethod()
473 except self.failureException:
474 result.addFailure(self, sys.exc_info())
475 except _ExpectedFailure as e:
476 result.addExpectedFailure(self, e.exc_info)
477 except _UnexpectedSuccess:
478 result.addUnexpectedSuccess(self)
479 except SkipTest as e:
480 result.addSkip(self, str(e))
481 except Exception:
482 result.addError(self, sys.exc_info())
483 else:
484 success = True
Fred Drake02538202001-03-21 18:09:46 +0000485
Michael Foorde2fb98f2009-05-02 20:15:05 +0000486 try:
487 self.tearDown()
488 except Exception:
489 result.addError(self, sys.exc_info())
490 success = False
491
492 cleanUpSuccess = self.doCleanups()
493 success = success and cleanUpSuccess
Benjamin Peterson692428e2009-03-23 21:50:21 +0000494 if success:
495 result.addSuccess(self)
Fred Drake02538202001-03-21 18:09:46 +0000496 finally:
497 result.stopTest(self)
Michael Foord07ef4872009-05-02 22:43:34 +0000498 if orig_result is None:
499 stopTestRun = getattr(result, 'stopTestRun', None)
500 if stopTestRun is not None:
501 stopTestRun()
Fred Drake02538202001-03-21 18:09:46 +0000502
Michael Foorde2fb98f2009-05-02 20:15:05 +0000503 def doCleanups(self):
504 """Execute all cleanup functions. Normally called for you after
505 tearDown."""
506 result = self._result
507 ok = True
508 while self._cleanups:
509 function, args, kwargs = self._cleanups.pop(-1)
510 try:
511 function(*args, **kwargs)
512 except Exception:
513 ok = False
514 result.addError(self, sys.exc_info())
515 return ok
516
Raymond Hettinger664347b2004-12-04 21:21:53 +0000517 def __call__(self, *args, **kwds):
518 return self.run(*args, **kwds)
Steve Purcell7e743842003-09-22 11:08:12 +0000519
Fred Drake02538202001-03-21 18:09:46 +0000520 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000521 """Run the test without collecting errors in a TestResult"""
Fred Drake02538202001-03-21 18:09:46 +0000522 self.setUp()
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000523 getattr(self, self._testMethodName)()
Fred Drake02538202001-03-21 18:09:46 +0000524 self.tearDown()
525
Benjamin Peterson47d97382009-03-26 20:05:50 +0000526 def skipTest(self, reason):
Benjamin Peterson692428e2009-03-23 21:50:21 +0000527 """Skip this test."""
528 raise SkipTest(reason)
529
Steve Purcell15d89272001-04-12 09:05:01 +0000530 def fail(self, msg=None):
531 """Fail immediately, with the given message."""
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000532 raise self.failureException(msg)
Fred Drake02538202001-03-21 18:09:46 +0000533
Gregory P. Smith7558d572009-03-31 19:03:28 +0000534 def assertFalse(self, expr, msg=None):
Fred Drake02538202001-03-21 18:09:46 +0000535 "Fail the test if the expression is true."
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000536 if expr:
Michael Foord345b2fe2009-04-02 03:20:38 +0000537 msg = self._formatMessage(msg, "%r is not False" % expr)
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000538 raise self.failureException(msg)
Fred Drake02538202001-03-21 18:09:46 +0000539
Gregory P. Smith7558d572009-03-31 19:03:28 +0000540 def assertTrue(self, expr, msg=None):
Steve Purcell15d89272001-04-12 09:05:01 +0000541 """Fail the test unless the expression is true."""
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000542 if not expr:
Michael Foord345b2fe2009-04-02 03:20:38 +0000543 msg = self._formatMessage(msg, "%r is not True" % expr)
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000544 raise self.failureException(msg)
Steve Purcell15d89272001-04-12 09:05:01 +0000545
Michael Foord345b2fe2009-04-02 03:20:38 +0000546 def _formatMessage(self, msg, standardMsg):
547 """Honour the longMessage attribute when generating failure messages.
548 If longMessage is False this means:
549 * Use only an explicit message if it is provided
550 * Otherwise use the standard message for the assert
551
552 If longMessage is True:
553 * Use the standard message
554 * If an explicit message is provided, plus ' : ' and the explicit message
555 """
556 if not self.longMessage:
557 return msg or standardMsg
558 if msg is None:
559 return standardMsg
560 return standardMsg + ' : ' + msg
561
562
Gregory P. Smith7558d572009-03-31 19:03:28 +0000563 def assertRaises(self, excClass, callableObj=None, *args, **kwargs):
Steve Purcell15d89272001-04-12 09:05:01 +0000564 """Fail unless an exception of class excClass is thrown
Fred Drake02538202001-03-21 18:09:46 +0000565 by callableObj when invoked with arguments args and keyword
566 arguments kwargs. If a different type of exception is
567 thrown, it will not be caught, and the test case will be
568 deemed to have suffered an error, exactly as for an
569 unexpected exception.
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000570
571 If called with callableObj omitted or None, will return a
572 context object used like this::
573
Gregory P. Smith7558d572009-03-31 19:03:28 +0000574 with self.assertRaises(some_error_class):
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000575 do_something()
Fred Drake02538202001-03-21 18:09:46 +0000576 """
Gregory P. Smith28399852009-03-31 16:54:10 +0000577 context = _AssertRaisesContext(excClass, self)
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000578 if callableObj is None:
579 return context
580 with context:
Guido van Rossum68468eb2003-02-27 20:14:51 +0000581 callableObj(*args, **kwargs)
Fred Drake02538202001-03-21 18:09:46 +0000582
Gregory P. Smith28399852009-03-31 16:54:10 +0000583 def _getAssertEqualityFunc(self, first, second):
584 """Get a detailed comparison function for the types of the two args.
585
586 Returns: A callable accepting (first, second, msg=None) that will
587 raise a failure exception if first != second with a useful human
588 readable error message for those types.
589 """
590 #
591 # NOTE(gregory.p.smith): I considered isinstance(first, type(second))
592 # and vice versa. I opted for the conservative approach in case
593 # subclasses are not intended to be compared in detail to their super
594 # class instances using a type equality func. This means testing
595 # subtypes won't automagically use the detailed comparison. Callers
596 # should use their type specific assertSpamEqual method to compare
597 # subclasses if the detailed comparison is desired and appropriate.
598 # See the discussion in http://bugs.python.org/issue2578.
599 #
600 if type(first) is type(second):
Michael Foorde2942d02009-04-02 05:51:54 +0000601 asserter = self._type_equality_funcs.get(type(first))
602 if asserter is not None:
603 return asserter.function
604
Gregory P. Smith28399852009-03-31 16:54:10 +0000605 return self._baseAssertEqual
606
607 def _baseAssertEqual(self, first, second, msg=None):
608 """The default assertEqual implementation, not type specific."""
609 if not first == second:
Michael Foord345b2fe2009-04-02 03:20:38 +0000610 standardMsg = '%r != %r' % (first, second)
611 msg = self._formatMessage(msg, standardMsg)
612 raise self.failureException(msg)
Gregory P. Smith28399852009-03-31 16:54:10 +0000613
Gregory P. Smith7558d572009-03-31 19:03:28 +0000614 def assertEqual(self, first, second, msg=None):
Raymond Hettingerc377cbf2003-04-04 22:56:42 +0000615 """Fail if the two objects are unequal as determined by the '=='
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000616 operator.
617 """
Gregory P. Smith28399852009-03-31 16:54:10 +0000618 assertion_func = self._getAssertEqualityFunc(first, second)
619 assertion_func(first, second, msg=msg)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000620
Gregory P. Smith7558d572009-03-31 19:03:28 +0000621 def assertNotEqual(self, first, second, msg=None):
Steve Purcell15d89272001-04-12 09:05:01 +0000622 """Fail if the two objects are equal as determined by the '=='
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000623 operator.
624 """
Michael Foord345b2fe2009-04-02 03:20:38 +0000625 if not first != second:
626 msg = self._formatMessage(msg, '%r == %r' % (first, second))
627 raise self.failureException(msg)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000628
Gregory P. Smith7558d572009-03-31 19:03:28 +0000629 def assertAlmostEqual(self, first, second, places=7, msg=None):
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000630 """Fail if the two objects are unequal as determined by their
631 difference rounded to the given number of decimal places
632 (default 7) and comparing to zero.
633
Steve Purcell397b45d2003-10-26 10:41:03 +0000634 Note that decimal places (from zero) are usually not the same
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000635 as significant digits (measured from the most signficant digit).
636 """
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000637 if round(abs(second-first), places) != 0:
Michael Foord345b2fe2009-04-02 03:20:38 +0000638 standardMsg = '%r != %r within %r places' % (first, second, places)
639 msg = self._formatMessage(msg, standardMsg)
640 raise self.failureException(msg)
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000641
Gregory P. Smith7558d572009-03-31 19:03:28 +0000642 def assertNotAlmostEqual(self, first, second, places=7, msg=None):
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000643 """Fail if the two objects are equal as determined by their
644 difference rounded to the given number of decimal places
645 (default 7) and comparing to zero.
646
Steve Purcellcca34912003-10-26 16:38:16 +0000647 Note that decimal places (from zero) are usually not the same
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000648 as significant digits (measured from the most signficant digit).
649 """
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000650 if round(abs(second-first), places) == 0:
Michael Foord345b2fe2009-04-02 03:20:38 +0000651 standardMsg = '%r == %r within %r places' % (first, second, places)
652 msg = self._formatMessage(msg, standardMsg)
653 raise self.failureException(msg)
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000654
Steve Purcell7e743842003-09-22 11:08:12 +0000655 # Synonyms for assertion methods
656
Gregory P. Smith7558d572009-03-31 19:03:28 +0000657 # The plurals are undocumented. Keep them that way to discourage use.
658 # Do not add more. Do not remove.
659 # Going through a deprecation cycle on these would annoy many people.
660 assertEquals = assertEqual
661 assertNotEquals = assertNotEqual
662 assertAlmostEquals = assertAlmostEqual
663 assertNotAlmostEquals = assertNotAlmostEqual
664 assert_ = assertTrue
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000665
Gregory P. Smith7558d572009-03-31 19:03:28 +0000666 # These fail* assertion method names are pending deprecation and will
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000667 # be a DeprecationWarning in 3.2; http://bugs.python.org/issue2578
Benjamin Peterson71095ae2009-04-01 23:15:49 +0000668 def _deprecate(original_func):
Gregory P. Smith65ff0052009-03-31 19:59:14 +0000669 def deprecated_func(*args, **kwargs):
670 warnings.warn(
671 'Please use {0} instead.'.format(original_func.__name__),
672 PendingDeprecationWarning, 2)
673 return original_func(*args, **kwargs)
674 return deprecated_func
Steve Purcell15d89272001-04-12 09:05:01 +0000675
Benjamin Peterson71095ae2009-04-01 23:15:49 +0000676 failUnlessEqual = _deprecate(assertEqual)
677 failIfEqual = _deprecate(assertNotEqual)
678 failUnlessAlmostEqual = _deprecate(assertAlmostEqual)
679 failIfAlmostEqual = _deprecate(assertNotAlmostEqual)
680 failUnless = _deprecate(assertTrue)
681 failUnlessRaises = _deprecate(assertRaises)
682 failIf = _deprecate(assertFalse)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000683
Gregory P. Smith28399852009-03-31 16:54:10 +0000684 def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
685 """An equality assertion for ordered sequences (like lists and tuples).
686
687 For the purposes of this function, a valid orderd sequence type is one
688 which can be indexed, has a length, and has an equality operator.
689
690 Args:
691 seq1: The first sequence to compare.
692 seq2: The second sequence to compare.
693 seq_type: The expected datatype of the sequences, or None if no
694 datatype should be enforced.
695 msg: Optional message to use on failure instead of a list of
696 differences.
697 """
698 if seq_type != None:
699 seq_type_name = seq_type.__name__
700 if not isinstance(seq1, seq_type):
701 raise self.failureException('First sequence is not a %s: %r'
702 % (seq_type_name, seq1))
703 if not isinstance(seq2, seq_type):
704 raise self.failureException('Second sequence is not a %s: %r'
705 % (seq_type_name, seq2))
706 else:
707 seq_type_name = "sequence"
708
709 differing = None
710 try:
711 len1 = len(seq1)
712 except (TypeError, NotImplementedError):
713 differing = 'First %s has no length. Non-sequence?' % (
714 seq_type_name)
715
716 if differing is None:
717 try:
718 len2 = len(seq2)
719 except (TypeError, NotImplementedError):
720 differing = 'Second %s has no length. Non-sequence?' % (
721 seq_type_name)
722
723 if differing is None:
724 if seq1 == seq2:
725 return
726
727 for i in xrange(min(len1, len2)):
728 try:
729 item1 = seq1[i]
730 except (TypeError, IndexError, NotImplementedError):
731 differing = ('Unable to index element %d of first %s\n' %
732 (i, seq_type_name))
733 break
734
735 try:
736 item2 = seq2[i]
737 except (TypeError, IndexError, NotImplementedError):
738 differing = ('Unable to index element %d of second %s\n' %
739 (i, seq_type_name))
740 break
741
742 if item1 != item2:
743 differing = ('First differing element %d:\n%s\n%s\n' %
744 (i, item1, item2))
745 break
746 else:
747 if (len1 == len2 and seq_type is None and
748 type(seq1) != type(seq2)):
749 # The sequences are the same, but have differing types.
750 return
751 # A catch-all message for handling arbitrary user-defined
752 # sequences.
753 differing = '%ss differ:\n' % seq_type_name.capitalize()
754 if len1 > len2:
755 differing = ('First %s contains %d additional '
756 'elements.\n' % (seq_type_name, len1 - len2))
757 try:
758 differing += ('First extra element %d:\n%s\n' %
759 (len2, seq1[len2]))
760 except (TypeError, IndexError, NotImplementedError):
761 differing += ('Unable to index element %d '
762 'of first %s\n' % (len2, seq_type_name))
763 elif len1 < len2:
764 differing = ('Second %s contains %d additional '
765 'elements.\n' % (seq_type_name, len2 - len1))
766 try:
767 differing += ('First extra element %d:\n%s\n' %
768 (len1, seq2[len1]))
769 except (TypeError, IndexError, NotImplementedError):
770 differing += ('Unable to index element %d '
771 'of second %s\n' % (len1, seq_type_name))
Michael Foord345b2fe2009-04-02 03:20:38 +0000772 standardMsg = differing + '\n'.join(difflib.ndiff(pprint.pformat(seq1).splitlines(),
773 pprint.pformat(seq2).splitlines()))
774 msg = self._formatMessage(msg, standardMsg)
775 self.fail(msg)
Gregory P. Smith28399852009-03-31 16:54:10 +0000776
777 def assertListEqual(self, list1, list2, msg=None):
778 """A list-specific equality assertion.
779
780 Args:
781 list1: The first list to compare.
782 list2: The second list to compare.
783 msg: Optional message to use on failure instead of a list of
784 differences.
785
786 """
787 self.assertSequenceEqual(list1, list2, msg, seq_type=list)
788
789 def assertTupleEqual(self, tuple1, tuple2, msg=None):
790 """A tuple-specific equality assertion.
791
792 Args:
793 tuple1: The first tuple to compare.
794 tuple2: The second tuple to compare.
795 msg: Optional message to use on failure instead of a list of
796 differences.
797 """
798 self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)
799
800 def assertSetEqual(self, set1, set2, msg=None):
801 """A set-specific equality assertion.
802
803 Args:
804 set1: The first set to compare.
805 set2: The second set to compare.
806 msg: Optional message to use on failure instead of a list of
807 differences.
808
809 For more general containership equality, assertSameElements will work
810 with things other than sets. This uses ducktyping to support
811 different types of sets, and is optimized for sets specifically
812 (parameters must support a difference method).
813 """
814 try:
815 difference1 = set1.difference(set2)
816 except TypeError, e:
817 self.fail('invalid type when attempting set difference: %s' % e)
818 except AttributeError, e:
819 self.fail('first argument does not support set difference: %s' % e)
820
821 try:
822 difference2 = set2.difference(set1)
823 except TypeError, e:
824 self.fail('invalid type when attempting set difference: %s' % e)
825 except AttributeError, e:
826 self.fail('second argument does not support set difference: %s' % e)
827
828 if not (difference1 or difference2):
829 return
830
Gregory P. Smith28399852009-03-31 16:54:10 +0000831 lines = []
832 if difference1:
833 lines.append('Items in the first set but not the second:')
834 for item in difference1:
835 lines.append(repr(item))
836 if difference2:
837 lines.append('Items in the second set but not the first:')
838 for item in difference2:
839 lines.append(repr(item))
Gregory P. Smith28399852009-03-31 16:54:10 +0000840
Michael Foord345b2fe2009-04-02 03:20:38 +0000841 standardMsg = '\n'.join(lines)
842 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000843
Michael Foord345b2fe2009-04-02 03:20:38 +0000844 def assertIn(self, member, container, msg=None):
845 """Just like self.assertTrue(a in b), but with a nicer default message."""
846 if member not in container:
847 standardMsg = '%r not found in %r' % (member, container)
848 self.fail(self._formatMessage(msg, standardMsg))
849
850 def assertNotIn(self, member, container, msg=None):
851 """Just like self.assertTrue(a not in b), but with a nicer default message."""
852 if member in container:
853 standardMsg = '%r unexpectedly found in %r' % (member, container)
854 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000855
Michael Foordf2dfef12009-04-05 19:19:28 +0000856 def assertIs(self, expr1, expr2, msg=None):
857 """Just like self.assertTrue(a is b), but with a nicer default message."""
858 if expr1 is not expr2:
859 standardMsg = '%r is not %r' % (expr1, expr2)
860 self.fail(self._formatMessage(msg, standardMsg))
861
862 def assertIsNot(self, expr1, expr2, msg=None):
863 """Just like self.assertTrue(a is not b), but with a nicer default message."""
864 if expr1 is expr2:
865 standardMsg = 'unexpectedly identical: %r' % (expr1,)
866 self.fail(self._formatMessage(msg, standardMsg))
867
Gregory P. Smith28399852009-03-31 16:54:10 +0000868 def assertDictEqual(self, d1, d2, msg=None):
869 self.assert_(isinstance(d1, dict), 'First argument is not a dictionary')
870 self.assert_(isinstance(d2, dict), 'Second argument is not a dictionary')
871
872 if d1 != d2:
Michael Foord345b2fe2009-04-02 03:20:38 +0000873 standardMsg = ('\n' + '\n'.join(difflib.ndiff(
874 pprint.pformat(d1).splitlines(),
875 pprint.pformat(d2).splitlines())))
876 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000877
878 def assertDictContainsSubset(self, expected, actual, msg=None):
879 """Checks whether actual is a superset of expected."""
880 missing = []
881 mismatched = []
882 for key, value in expected.iteritems():
883 if key not in actual:
884 missing.append(key)
885 elif value != actual[key]:
Michael Foord345b2fe2009-04-02 03:20:38 +0000886 mismatched.append('%s, expected: %s, actual: %s' % (key, value, actual[key]))
Gregory P. Smith28399852009-03-31 16:54:10 +0000887
888 if not (missing or mismatched):
889 return
890
Michael Foord345b2fe2009-04-02 03:20:38 +0000891 standardMsg = ''
Gregory P. Smith28399852009-03-31 16:54:10 +0000892 if missing:
Michael Foord345b2fe2009-04-02 03:20:38 +0000893 standardMsg = 'Missing: %r' % ','.join(missing)
Gregory P. Smith28399852009-03-31 16:54:10 +0000894 if mismatched:
Michael Foord345b2fe2009-04-02 03:20:38 +0000895 if standardMsg:
896 standardMsg += '; '
897 standardMsg += 'Mismatched values: %s' % ','.join(mismatched)
Gregory P. Smith28399852009-03-31 16:54:10 +0000898
Michael Foord345b2fe2009-04-02 03:20:38 +0000899 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000900
901 def assertSameElements(self, expected_seq, actual_seq, msg=None):
902 """An unordered sequence specific comparison.
903
904 Raises with an error message listing which elements of expected_seq
905 are missing from actual_seq and vice versa if any.
906 """
907 try:
908 expected = set(expected_seq)
909 actual = set(actual_seq)
910 missing = list(expected.difference(actual))
911 unexpected = list(actual.difference(expected))
912 missing.sort()
913 unexpected.sort()
914 except TypeError:
915 # Fall back to slower list-compare if any of the objects are
916 # not hashable.
917 expected = list(expected_seq)
918 actual = list(actual_seq)
919 expected.sort()
920 actual.sort()
921 missing, unexpected = _SortedListDifference(expected, actual)
922 errors = []
923 if missing:
Michael Foord345b2fe2009-04-02 03:20:38 +0000924 errors.append('Expected, but missing:\n %r' % missing)
Gregory P. Smith28399852009-03-31 16:54:10 +0000925 if unexpected:
Michael Foord345b2fe2009-04-02 03:20:38 +0000926 errors.append('Unexpected, but present:\n %r' % unexpected)
Gregory P. Smith28399852009-03-31 16:54:10 +0000927 if errors:
Michael Foord345b2fe2009-04-02 03:20:38 +0000928 standardMsg = '\n'.join(errors)
929 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000930
931 def assertMultiLineEqual(self, first, second, msg=None):
932 """Assert that two multi-line strings are equal."""
Michael Foord345b2fe2009-04-02 03:20:38 +0000933 self.assert_(isinstance(first, basestring), (
Gregory P. Smith28399852009-03-31 16:54:10 +0000934 'First argument is not a string'))
Michael Foord345b2fe2009-04-02 03:20:38 +0000935 self.assert_(isinstance(second, basestring), (
Gregory P. Smith28399852009-03-31 16:54:10 +0000936 'Second argument is not a string'))
937
938 if first != second:
Michael Foord345b2fe2009-04-02 03:20:38 +0000939 standardMsg = '\n' + ''.join(difflib.ndiff(first.splitlines(True), second.splitlines(True)))
940 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000941
942 def assertLess(self, a, b, msg=None):
Michael Foord345b2fe2009-04-02 03:20:38 +0000943 """Just like self.assertTrue(a < b), but with a nicer default message."""
944 if not a < b:
945 standardMsg = '%r not less than %r' % (a, b)
946 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000947
948 def assertLessEqual(self, a, b, msg=None):
Michael Foord345b2fe2009-04-02 03:20:38 +0000949 """Just like self.assertTrue(a <= b), but with a nicer default message."""
950 if not a <= b:
951 standardMsg = '%r not less than or equal to %r' % (a, b)
952 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000953
954 def assertGreater(self, a, b, msg=None):
Michael Foord345b2fe2009-04-02 03:20:38 +0000955 """Just like self.assertTrue(a > b), but with a nicer default message."""
956 if not a > b:
957 standardMsg = '%r not greater than %r' % (a, b)
958 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000959
960 def assertGreaterEqual(self, a, b, msg=None):
Michael Foord345b2fe2009-04-02 03:20:38 +0000961 """Just like self.assertTrue(a >= b), but with a nicer default message."""
962 if not a >= b:
963 standardMsg = '%r not greater than or equal to %r' % (a, b)
964 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000965
966 def assertIsNone(self, obj, msg=None):
Michael Foord345b2fe2009-04-02 03:20:38 +0000967 """Same as self.assertTrue(obj is None), with a nicer default message."""
968 if obj is not None:
969 standardMsg = '%r is not None' % obj
970 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000971
Michael Foord345b2fe2009-04-02 03:20:38 +0000972 def assertIsNotNone(self, obj, msg=None):
Gregory P. Smith28399852009-03-31 16:54:10 +0000973 """Included for symmetry with assertIsNone."""
Michael Foord345b2fe2009-04-02 03:20:38 +0000974 if obj is None:
975 standardMsg = 'unexpectedly None'
976 self.fail(self._formatMessage(msg, standardMsg))
Gregory P. Smith28399852009-03-31 16:54:10 +0000977
978 def assertRaisesRegexp(self, expected_exception, expected_regexp,
979 callable_obj=None, *args, **kwargs):
980 """Asserts that the message in a raised exception matches a regexp.
981
982 Args:
983 expected_exception: Exception class expected to be raised.
984 expected_regexp: Regexp (re pattern object or string) expected
985 to be found in error message.
986 callable_obj: Function to be called.
987 args: Extra args.
988 kwargs: Extra kwargs.
989 """
990 context = _AssertRaisesContext(expected_exception, self, expected_regexp)
991 if callable_obj is None:
992 return context
993 with context:
994 callable_obj(*args, **kwargs)
995
996 def assertRegexpMatches(self, text, expected_regex, msg=None):
997 if isinstance(expected_regex, basestring):
998 expected_regex = re.compile(expected_regex)
999 if not expected_regex.search(text):
1000 msg = msg or "Regexp didn't match"
1001 msg = '%s: %r not found in %r' % (msg, expected_regex.pattern, text)
1002 raise self.failureException(msg)
1003
1004
1005def _SortedListDifference(expected, actual):
1006 """Finds elements in only one or the other of two, sorted input lists.
1007
1008 Returns a two-element tuple of lists. The first list contains those
1009 elements in the "expected" list but not in the "actual" list, and the
1010 second contains those elements in the "actual" list but not in the
1011 "expected" list. Duplicate elements in either input list are ignored.
1012 """
1013 i = j = 0
1014 missing = []
1015 unexpected = []
1016 while True:
1017 try:
1018 e = expected[i]
1019 a = actual[j]
1020 if e < a:
1021 missing.append(e)
1022 i += 1
1023 while expected[i] == e:
1024 i += 1
1025 elif e > a:
1026 unexpected.append(a)
1027 j += 1
1028 while actual[j] == a:
1029 j += 1
1030 else:
1031 i += 1
1032 try:
1033 while expected[i] == e:
1034 i += 1
1035 finally:
1036 j += 1
1037 while actual[j] == a:
1038 j += 1
1039 except IndexError:
1040 missing.extend(expected[i:])
1041 unexpected.extend(actual[j:])
1042 break
1043 return missing, unexpected
1044
Fred Drake02538202001-03-21 18:09:46 +00001045
Antoine Pitroudae1a6a2008-12-28 16:01:11 +00001046class TestSuite(object):
Fred Drake02538202001-03-21 18:09:46 +00001047 """A test suite is a composite test consisting of a number of TestCases.
1048
1049 For use, create an instance of TestSuite, then add test case instances.
1050 When all tests have been added, the suite can be passed to a test
1051 runner, such as TextTestRunner. It will run the individual test cases
1052 in the order in which they were added, aggregating the results. When
1053 subclassing, do not forget to call the base class constructor.
1054 """
1055 def __init__(self, tests=()):
1056 self._tests = []
1057 self.addTests(tests)
1058
1059 def __repr__(self):
Michael Foord37d89a22009-04-05 01:15:01 +00001060 return "<%s tests=%s>" % (_strclass(self.__class__), list(self))
Fred Drake02538202001-03-21 18:09:46 +00001061
Georg Brandl15c5ce92007-03-07 09:09:40 +00001062 def __eq__(self, other):
Benjamin Peterson692428e2009-03-23 21:50:21 +00001063 if not isinstance(other, self.__class__):
1064 return NotImplemented
Michael Foord829f6b82009-05-02 11:43:06 +00001065 return list(self) == list(other)
Georg Brandl15c5ce92007-03-07 09:09:40 +00001066
1067 def __ne__(self, other):
1068 return not self == other
1069
Nick Coghlan48361f52008-08-11 15:45:58 +00001070 # Can't guarantee hash invariant, so flag as unhashable
1071 __hash__ = None
1072
Jim Fultonfafd8742004-08-28 15:22:12 +00001073 def __iter__(self):
1074 return iter(self._tests)
1075
Fred Drake02538202001-03-21 18:09:46 +00001076 def countTestCases(self):
1077 cases = 0
Michael Foord37d89a22009-04-05 01:15:01 +00001078 for test in self:
Steve Purcell7e743842003-09-22 11:08:12 +00001079 cases += test.countTestCases()
Fred Drake02538202001-03-21 18:09:46 +00001080 return cases
1081
1082 def addTest(self, test):
Georg Brandld9e50262007-03-07 11:54:49 +00001083 # sanity checks
Raymond Hettinger5930d8f2008-07-10 16:06:41 +00001084 if not hasattr(test, '__call__'):
Georg Brandld9e50262007-03-07 11:54:49 +00001085 raise TypeError("the test to add must be callable")
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001086 if isinstance(test, type) and issubclass(test, (TestCase, TestSuite)):
Georg Brandld9e50262007-03-07 11:54:49 +00001087 raise TypeError("TestCases and TestSuites must be instantiated "
1088 "before passing them to addTest()")
Fred Drake02538202001-03-21 18:09:46 +00001089 self._tests.append(test)
1090
1091 def addTests(self, tests):
Georg Brandld9e50262007-03-07 11:54:49 +00001092 if isinstance(tests, basestring):
1093 raise TypeError("tests must be an iterable of tests, not a string")
Fred Drake02538202001-03-21 18:09:46 +00001094 for test in tests:
1095 self.addTest(test)
1096
1097 def run(self, result):
Michael Foord37d89a22009-04-05 01:15:01 +00001098 for test in self:
Fred Drake02538202001-03-21 18:09:46 +00001099 if result.shouldStop:
1100 break
1101 test(result)
1102 return result
1103
Raymond Hettinger664347b2004-12-04 21:21:53 +00001104 def __call__(self, *args, **kwds):
1105 return self.run(*args, **kwds)
1106
Fred Drake02538202001-03-21 18:09:46 +00001107 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001108 """Run the tests without collecting errors in a TestResult"""
Michael Foord37d89a22009-04-05 01:15:01 +00001109 for test in self:
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001110 test.debug()
Fred Drake02538202001-03-21 18:09:46 +00001111
1112
Benjamin Peterson692428e2009-03-23 21:50:21 +00001113class ClassTestSuite(TestSuite):
1114 """
1115 Suite of tests derived from a single TestCase class.
1116 """
1117
1118 def __init__(self, tests, class_collected_from):
1119 super(ClassTestSuite, self).__init__(tests)
1120 self.collected_from = class_collected_from
1121
1122 def id(self):
1123 module = getattr(self.collected_from, "__module__", None)
1124 if module is not None:
1125 return "{0}.{1}".format(module, self.collected_from.__name__)
1126 return self.collected_from.__name__
1127
1128 def run(self, result):
1129 if getattr(self.collected_from, "__unittest_skip__", False):
1130 # ClassTestSuite result pretends to be a TestCase enough to be
1131 # reported.
1132 result.startTest(self)
1133 try:
1134 result.addSkip(self, self.collected_from.__unittest_skip_why__)
1135 finally:
1136 result.stopTest(self)
1137 else:
1138 result = super(ClassTestSuite, self).run(result)
1139 return result
1140
1141 shortDescription = id
1142
1143
Fred Drake02538202001-03-21 18:09:46 +00001144class FunctionTestCase(TestCase):
1145 """A test case that wraps a test function.
1146
1147 This is useful for slipping pre-existing test functions into the
Georg Brandl15c5ce92007-03-07 09:09:40 +00001148 unittest framework. Optionally, set-up and tidy-up functions can be
Fred Drake02538202001-03-21 18:09:46 +00001149 supplied. As with TestCase, the tidy-up ('tearDown') function will
1150 always be called if the set-up ('setUp') function ran successfully.
1151 """
1152
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001153 def __init__(self, testFunc, setUp=None, tearDown=None, description=None):
1154 super(FunctionTestCase, self).__init__()
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001155 self._setUpFunc = setUp
1156 self._tearDownFunc = tearDown
1157 self._testFunc = testFunc
1158 self._description = description
Fred Drake02538202001-03-21 18:09:46 +00001159
1160 def setUp(self):
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001161 if self._setUpFunc is not None:
1162 self._setUpFunc()
Fred Drake02538202001-03-21 18:09:46 +00001163
1164 def tearDown(self):
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001165 if self._tearDownFunc is not None:
1166 self._tearDownFunc()
Fred Drake02538202001-03-21 18:09:46 +00001167
1168 def runTest(self):
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001169 self._testFunc()
Fred Drake02538202001-03-21 18:09:46 +00001170
1171 def id(self):
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001172 return self._testFunc.__name__
Fred Drake02538202001-03-21 18:09:46 +00001173
Georg Brandl15c5ce92007-03-07 09:09:40 +00001174 def __eq__(self, other):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001175 if not isinstance(other, self.__class__):
1176 return NotImplemented
Georg Brandl15c5ce92007-03-07 09:09:40 +00001177
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001178 return self._setUpFunc == other._setUpFunc and \
1179 self._tearDownFunc == other._tearDownFunc and \
1180 self._testFunc == other._testFunc and \
1181 self._description == other._description
Georg Brandl15c5ce92007-03-07 09:09:40 +00001182
1183 def __ne__(self, other):
1184 return not self == other
1185
1186 def __hash__(self):
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001187 return hash((type(self), self._setUpFunc, self._tearDownFunc,
1188 self._testFunc, self._description))
Georg Brandl15c5ce92007-03-07 09:09:40 +00001189
Fred Drake02538202001-03-21 18:09:46 +00001190 def __str__(self):
Benjamin Petersonbaba1952009-04-18 19:26:19 +00001191 return "%s (%s)" % (_strclass(self.__class__), self._testFunc.__name__)
Fred Drake02538202001-03-21 18:09:46 +00001192
1193 def __repr__(self):
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001194 return "<%s testFunc=%s>" % (_strclass(self.__class__), self._testFunc)
Fred Drake02538202001-03-21 18:09:46 +00001195
1196 def shortDescription(self):
Benjamin Peterson71095ae2009-04-01 23:15:49 +00001197 if self._description is not None:
1198 return self._description
1199 doc = self._testFunc.__doc__
Steve Purcell7e743842003-09-22 11:08:12 +00001200 return doc and doc.split("\n")[0].strip() or None
Fred Drake02538202001-03-21 18:09:46 +00001201
1202
1203
1204##############################################################################
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001205# Locating and loading tests
Fred Drake02538202001-03-21 18:09:46 +00001206##############################################################################
1207
Antoine Pitroudae1a6a2008-12-28 16:01:11 +00001208class TestLoader(object):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001209 """
1210 This class is responsible for loading tests according to various criteria
1211 and returning them wrapped in a TestSuite
Fred Drake02538202001-03-21 18:09:46 +00001212 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001213 testMethodPrefix = 'test'
1214 sortTestMethodsUsing = cmp
1215 suiteClass = TestSuite
Benjamin Peterson692428e2009-03-23 21:50:21 +00001216 classSuiteClass = ClassTestSuite
Fred Drake02538202001-03-21 18:09:46 +00001217
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001218 def loadTestsFromTestCase(self, testCaseClass):
Steve Purcell15d89272001-04-12 09:05:01 +00001219 """Return a suite of all tests cases contained in testCaseClass"""
Johannes Gijsbersd7b6ad42004-11-07 15:46:25 +00001220 if issubclass(testCaseClass, TestSuite):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001221 raise TypeError("Test cases should not be derived from TestSuite." \
1222 " Maybe you meant to derive from TestCase?")
Steve Purcell7e743842003-09-22 11:08:12 +00001223 testCaseNames = self.getTestCaseNames(testCaseClass)
1224 if not testCaseNames and hasattr(testCaseClass, 'runTest'):
1225 testCaseNames = ['runTest']
Benjamin Peterson692428e2009-03-23 21:50:21 +00001226 suite = self.classSuiteClass(map(testCaseClass, testCaseNames),
1227 testCaseClass)
1228 return suite
Fred Drake02538202001-03-21 18:09:46 +00001229
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001230 def loadTestsFromModule(self, module):
Steve Purcell15d89272001-04-12 09:05:01 +00001231 """Return a suite of all tests cases contained in the given module"""
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001232 tests = []
1233 for name in dir(module):
1234 obj = getattr(module, name)
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001235 if isinstance(obj, type) and issubclass(obj, TestCase):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001236 tests.append(self.loadTestsFromTestCase(obj))
1237 return self.suiteClass(tests)
Fred Drake02538202001-03-21 18:09:46 +00001238
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001239 def loadTestsFromName(self, name, module=None):
Steve Purcell15d89272001-04-12 09:05:01 +00001240 """Return a suite of all tests cases given a string specifier.
1241
1242 The name may resolve either to a module, a test case class, a
1243 test method within a test case class, or a callable object which
1244 returns a TestCase or TestSuite instance.
Tim Peters613b2222001-04-13 05:37:27 +00001245
Steve Purcell15d89272001-04-12 09:05:01 +00001246 The method optionally resolves the names relative to a given module.
1247 """
Steve Purcell7e743842003-09-22 11:08:12 +00001248 parts = name.split('.')
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001249 if module is None:
Steve Purcell7e743842003-09-22 11:08:12 +00001250 parts_copy = parts[:]
1251 while parts_copy:
1252 try:
1253 module = __import__('.'.join(parts_copy))
1254 break
1255 except ImportError:
1256 del parts_copy[-1]
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001257 if not parts_copy:
1258 raise
Armin Rigo1b3c04b2003-10-24 17:15:29 +00001259 parts = parts[1:]
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001260 obj = module
1261 for part in parts:
Steve Purcell7e743842003-09-22 11:08:12 +00001262 parent, obj = obj, getattr(obj, part)
Fred Drake02538202001-03-21 18:09:46 +00001263
Antoine Pitroudae1a6a2008-12-28 16:01:11 +00001264 if isinstance(obj, types.ModuleType):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001265 return self.loadTestsFromModule(obj)
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001266 elif isinstance(obj, type) and issubclass(obj, TestCase):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001267 return self.loadTestsFromTestCase(obj)
Antoine Pitroudae1a6a2008-12-28 16:01:11 +00001268 elif (isinstance(obj, types.UnboundMethodType) and
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001269 isinstance(parent, type) and
Georg Brandl15c5ce92007-03-07 09:09:40 +00001270 issubclass(parent, TestCase)):
1271 return TestSuite([parent(obj.__name__)])
Steve Purcell397b45d2003-10-26 10:41:03 +00001272 elif isinstance(obj, TestSuite):
Steve Purcell7e743842003-09-22 11:08:12 +00001273 return obj
Raymond Hettinger5930d8f2008-07-10 16:06:41 +00001274 elif hasattr(obj, '__call__'):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001275 test = obj()
Georg Brandl15c5ce92007-03-07 09:09:40 +00001276 if isinstance(test, TestSuite):
1277 return test
1278 elif isinstance(test, TestCase):
1279 return TestSuite([test])
1280 else:
1281 raise TypeError("calling %s returned %s, not a test" %
1282 (obj, test))
Fred Drake02538202001-03-21 18:09:46 +00001283 else:
Georg Brandl15c5ce92007-03-07 09:09:40 +00001284 raise TypeError("don't know how to make test from: %s" % obj)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001285
1286 def loadTestsFromNames(self, names, module=None):
Steve Purcell15d89272001-04-12 09:05:01 +00001287 """Return a suite of all tests cases found using the given sequence
1288 of string specifiers. See 'loadTestsFromName()'.
1289 """
Steve Purcell7e743842003-09-22 11:08:12 +00001290 suites = [self.loadTestsFromName(name, module) for name in names]
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001291 return self.suiteClass(suites)
1292
1293 def getTestCaseNames(self, testCaseClass):
Steve Purcell15d89272001-04-12 09:05:01 +00001294 """Return a sorted sequence of method names found within testCaseClass
1295 """
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001296 def isTestMethod(attrname, testCaseClass=testCaseClass,
1297 prefix=self.testMethodPrefix):
1298 return attrname.startswith(prefix) and \
1299 hasattr(getattr(testCaseClass, attrname), '__call__')
Steve Purcell7e743842003-09-22 11:08:12 +00001300 testFnNames = filter(isTestMethod, dir(testCaseClass))
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001301 if self.sortTestMethodsUsing:
Raymond Hettinger5930d8f2008-07-10 16:06:41 +00001302 testFnNames.sort(key=_CmpToKey(self.sortTestMethodsUsing))
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001303 return testFnNames
1304
1305
1306
1307defaultTestLoader = TestLoader()
1308
1309
1310##############################################################################
1311# Patches for old functions: these functions should be considered obsolete
1312##############################################################################
1313
1314def _makeLoader(prefix, sortUsing, suiteClass=None):
1315 loader = TestLoader()
1316 loader.sortTestMethodsUsing = sortUsing
1317 loader.testMethodPrefix = prefix
1318 if suiteClass: loader.suiteClass = suiteClass
1319 return loader
1320
1321def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp):
1322 return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)
1323
1324def makeSuite(testCaseClass, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
1325 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
1326
1327def findTestCases(module, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
1328 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module)
Fred Drake02538202001-03-21 18:09:46 +00001329
1330
1331##############################################################################
1332# Text UI
1333##############################################################################
1334
Antoine Pitroudae1a6a2008-12-28 16:01:11 +00001335class _WritelnDecorator(object):
Fred Drake02538202001-03-21 18:09:46 +00001336 """Used to decorate file-like objects with a handy 'writeln' method"""
1337 def __init__(self,stream):
1338 self.stream = stream
Fred Drake02538202001-03-21 18:09:46 +00001339
1340 def __getattr__(self, attr):
1341 return getattr(self.stream,attr)
1342
Raymond Hettinger91dd19d2003-09-13 02:58:00 +00001343 def writeln(self, arg=None):
Benjamin Petersond0cdb2d2009-03-24 23:07:07 +00001344 if arg:
1345 self.write(arg)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001346 self.write('\n') # text-mode streams translate to \r\n if needed
Tim Petersa19a1682001-03-29 04:36:09 +00001347
Fred Drake02538202001-03-21 18:09:46 +00001348
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001349class _TextTestResult(TestResult):
Fred Drake02538202001-03-21 18:09:46 +00001350 """A test result class that can print formatted text results to a stream.
1351
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001352 Used by TextTestRunner.
Fred Drake02538202001-03-21 18:09:46 +00001353 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001354 separator1 = '=' * 70
1355 separator2 = '-' * 70
Fred Drake02538202001-03-21 18:09:46 +00001356
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001357 def __init__(self, stream, descriptions, verbosity):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001358 super(_TextTestResult, self).__init__()
Fred Drake02538202001-03-21 18:09:46 +00001359 self.stream = stream
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001360 self.showAll = verbosity > 1
1361 self.dots = verbosity == 1
Fred Drake02538202001-03-21 18:09:46 +00001362 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001363
1364 def getDescription(self, test):
1365 if self.descriptions:
1366 return test.shortDescription() or str(test)
1367 else:
1368 return str(test)
1369
Fred Drake02538202001-03-21 18:09:46 +00001370 def startTest(self, test):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001371 super(_TextTestResult, self).startTest(test)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001372 if self.showAll:
1373 self.stream.write(self.getDescription(test))
1374 self.stream.write(" ... ")
Georg Brandld0632402008-05-11 15:17:41 +00001375 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +00001376
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001377 def addSuccess(self, test):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001378 super(_TextTestResult, self).addSuccess(test)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001379 if self.showAll:
Fred Drake02538202001-03-21 18:09:46 +00001380 self.stream.writeln("ok")
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001381 elif self.dots:
1382 self.stream.write('.')
Georg Brandld0632402008-05-11 15:17:41 +00001383 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +00001384
1385 def addError(self, test, err):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001386 super(_TextTestResult, self).addError(test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001387 if self.showAll:
1388 self.stream.writeln("ERROR")
1389 elif self.dots:
1390 self.stream.write('E')
Georg Brandld0632402008-05-11 15:17:41 +00001391 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +00001392
1393 def addFailure(self, test, err):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001394 super(_TextTestResult, self).addFailure(test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001395 if self.showAll:
1396 self.stream.writeln("FAIL")
1397 elif self.dots:
1398 self.stream.write('F')
Georg Brandld0632402008-05-11 15:17:41 +00001399 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +00001400
Benjamin Peterson692428e2009-03-23 21:50:21 +00001401 def addSkip(self, test, reason):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001402 super(_TextTestResult, self).addSkip(test, reason)
Benjamin Peterson692428e2009-03-23 21:50:21 +00001403 if self.showAll:
1404 self.stream.writeln("skipped {0!r}".format(reason))
1405 elif self.dots:
1406 self.stream.write("s")
1407 self.stream.flush()
1408
1409 def addExpectedFailure(self, test, err):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001410 super(_TextTestResult, self).addExpectedFailure(test, err)
Benjamin Peterson692428e2009-03-23 21:50:21 +00001411 if self.showAll:
1412 self.stream.writeln("expected failure")
1413 elif self.dots:
Benjamin Petersona8adceb2009-03-25 21:24:04 +00001414 self.stream.write("x")
Benjamin Peterson692428e2009-03-23 21:50:21 +00001415 self.stream.flush()
1416
1417 def addUnexpectedSuccess(self, test):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001418 super(_TextTestResult, self).addUnexpectedSuccess(test)
Benjamin Peterson692428e2009-03-23 21:50:21 +00001419 if self.showAll:
1420 self.stream.writeln("unexpected success")
1421 elif self.dots:
Benjamin Petersona8adceb2009-03-25 21:24:04 +00001422 self.stream.write("u")
Benjamin Peterson692428e2009-03-23 21:50:21 +00001423 self.stream.flush()
1424
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001425 def printErrors(self):
1426 if self.dots or self.showAll:
Fred Drake02538202001-03-21 18:09:46 +00001427 self.stream.writeln()
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001428 self.printErrorList('ERROR', self.errors)
1429 self.printErrorList('FAIL', self.failures)
1430
1431 def printErrorList(self, flavour, errors):
1432 for test, err in errors:
1433 self.stream.writeln(self.separator1)
1434 self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
1435 self.stream.writeln(self.separator2)
Steve Purcell7b065702001-09-06 08:24:40 +00001436 self.stream.writeln("%s" % err)
Fred Drake02538202001-03-21 18:09:46 +00001437
1438
Antoine Pitroudae1a6a2008-12-28 16:01:11 +00001439class TextTestRunner(object):
Fred Drake02538202001-03-21 18:09:46 +00001440 """A test runner class that displays results in textual form.
Tim Petersa19a1682001-03-29 04:36:09 +00001441
Fred Drake02538202001-03-21 18:09:46 +00001442 It prints out the names of tests as they are run, errors as they
1443 occur, and a summary of the results at the end of the test run.
1444 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001445 def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1):
Fred Drake02538202001-03-21 18:09:46 +00001446 self.stream = _WritelnDecorator(stream)
1447 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001448 self.verbosity = verbosity
1449
1450 def _makeResult(self):
1451 return _TextTestResult(self.stream, self.descriptions, self.verbosity)
Fred Drake02538202001-03-21 18:09:46 +00001452
1453 def run(self, test):
1454 "Run the given test case or test suite."
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001455 result = self._makeResult()
Fred Drake02538202001-03-21 18:09:46 +00001456 startTime = time.time()
Michael Foord07ef4872009-05-02 22:43:34 +00001457 startTestRun = getattr(result, 'startTestRun', None)
1458 if startTestRun is not None:
1459 startTestRun()
1460 try:
1461 test(result)
1462 finally:
1463 stopTestRun = getattr(result, 'stopTestRun', None)
1464 if stopTestRun is not None:
1465 stopTestRun()
Fred Drake02538202001-03-21 18:09:46 +00001466 stopTime = time.time()
Steve Purcell397b45d2003-10-26 10:41:03 +00001467 timeTaken = stopTime - startTime
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001468 result.printErrors()
1469 self.stream.writeln(result.separator2)
Fred Drake02538202001-03-21 18:09:46 +00001470 run = result.testsRun
1471 self.stream.writeln("Ran %d test%s in %.3fs" %
Neal Norwitz76165042002-05-31 14:15:11 +00001472 (run, run != 1 and "s" or "", timeTaken))
Fred Drake02538202001-03-21 18:09:46 +00001473 self.stream.writeln()
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00001474 results = map(len, (result.expectedFailures,
1475 result.unexpectedSuccesses,
Benjamin Peterson692428e2009-03-23 21:50:21 +00001476 result.skipped))
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +00001477 expectedFails, unexpectedSuccesses, skipped = results
Benjamin Peterson692428e2009-03-23 21:50:21 +00001478 infos = []
Fred Drake02538202001-03-21 18:09:46 +00001479 if not result.wasSuccessful():
Benjamin Peterson692428e2009-03-23 21:50:21 +00001480 self.stream.write("FAILED")
Fred Drake02538202001-03-21 18:09:46 +00001481 failed, errored = map(len, (result.failures, result.errors))
1482 if failed:
Benjamin Peterson692428e2009-03-23 21:50:21 +00001483 infos.append("failures=%d" % failed)
Fred Drake02538202001-03-21 18:09:46 +00001484 if errored:
Benjamin Peterson692428e2009-03-23 21:50:21 +00001485 infos.append("errors=%d" % errored)
Fred Drake02538202001-03-21 18:09:46 +00001486 else:
Benjamin Petersona473f002009-03-24 22:56:32 +00001487 self.stream.write("OK")
Benjamin Peterson692428e2009-03-23 21:50:21 +00001488 if skipped:
1489 infos.append("skipped=%d" % skipped)
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001490 if expectedFails:
1491 infos.append("expected failures=%d" % expectedFails)
1492 if unexpectedSuccesses:
1493 infos.append("unexpected successes=%d" % unexpectedSuccesses)
Benjamin Peterson692428e2009-03-23 21:50:21 +00001494 if infos:
1495 self.stream.writeln(" (%s)" % (", ".join(infos),))
Benjamin Petersona473f002009-03-24 22:56:32 +00001496 else:
1497 self.stream.write("\n")
Fred Drake02538202001-03-21 18:09:46 +00001498 return result
Tim Petersa19a1682001-03-29 04:36:09 +00001499
Fred Drake02538202001-03-21 18:09:46 +00001500
Fred Drake02538202001-03-21 18:09:46 +00001501
1502##############################################################################
1503# Facilities for running tests from the command line
1504##############################################################################
1505
Antoine Pitroudae1a6a2008-12-28 16:01:11 +00001506class TestProgram(object):
Fred Drake02538202001-03-21 18:09:46 +00001507 """A command-line program that runs a set of tests; this is primarily
1508 for making test modules conveniently executable.
1509 """
1510 USAGE = """\
Steve Purcell17a781b2001-04-09 15:37:31 +00001511Usage: %(progName)s [options] [test] [...]
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001512
1513Options:
1514 -h, --help Show this message
1515 -v, --verbose Verbose output
1516 -q, --quiet Minimal output
Fred Drake02538202001-03-21 18:09:46 +00001517
1518Examples:
1519 %(progName)s - run default set of tests
1520 %(progName)s MyTestSuite - run suite 'MyTestSuite'
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001521 %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething
1522 %(progName)s MyTestCase - run all 'test*' test methods
Fred Drake02538202001-03-21 18:09:46 +00001523 in MyTestCase
1524"""
1525 def __init__(self, module='__main__', defaultTest=None,
Georg Brandld0a96252007-03-07 09:21:06 +00001526 argv=None, testRunner=TextTestRunner,
Michael Foord5d31e052009-05-11 17:59:43 +00001527 testLoader=defaultTestLoader, exit=True,
1528 verbosity=1):
Antoine Pitroudae1a6a2008-12-28 16:01:11 +00001529 if isinstance(module, basestring):
Fred Drake02538202001-03-21 18:09:46 +00001530 self.module = __import__(module)
Steve Purcell7e743842003-09-22 11:08:12 +00001531 for part in module.split('.')[1:]:
Fred Drake02538202001-03-21 18:09:46 +00001532 self.module = getattr(self.module, part)
1533 else:
1534 self.module = module
1535 if argv is None:
1536 argv = sys.argv
Michael Foord829f6b82009-05-02 11:43:06 +00001537
1538 self.exit = exit
Michael Foord5d31e052009-05-11 17:59:43 +00001539 self.verbosity = verbosity
Fred Drake02538202001-03-21 18:09:46 +00001540 self.defaultTest = defaultTest
1541 self.testRunner = testRunner
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001542 self.testLoader = testLoader
Fred Drake02538202001-03-21 18:09:46 +00001543 self.progName = os.path.basename(argv[0])
1544 self.parseArgs(argv)
Fred Drake02538202001-03-21 18:09:46 +00001545 self.runTests()
1546
1547 def usageExit(self, msg=None):
Benjamin Petersona7d441d2009-03-24 00:35:20 +00001548 if msg:
1549 print msg
Fred Drake02538202001-03-21 18:09:46 +00001550 print self.USAGE % self.__dict__
1551 sys.exit(2)
1552
1553 def parseArgs(self, argv):
1554 import getopt
Benjamin Peterson692428e2009-03-23 21:50:21 +00001555 long_opts = ['help','verbose','quiet']
Fred Drake02538202001-03-21 18:09:46 +00001556 try:
Benjamin Peterson692428e2009-03-23 21:50:21 +00001557 options, args = getopt.getopt(argv[1:], 'hHvq', long_opts)
Fred Drake02538202001-03-21 18:09:46 +00001558 for opt, value in options:
1559 if opt in ('-h','-H','--help'):
1560 self.usageExit()
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001561 if opt in ('-q','--quiet'):
1562 self.verbosity = 0
1563 if opt in ('-v','--verbose'):
1564 self.verbosity = 2
Fred Drake02538202001-03-21 18:09:46 +00001565 if len(args) == 0 and self.defaultTest is None:
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001566 self.test = self.testLoader.loadTestsFromModule(self.module)
1567 return
Fred Drake02538202001-03-21 18:09:46 +00001568 if len(args) > 0:
1569 self.testNames = args
Michael Foord7df82c92009-05-12 10:46:23 +00001570 if os.path.splitext(os.path.basename(__file__))[0] == 'unitest':
1571 self.module = None
Fred Drake02538202001-03-21 18:09:46 +00001572 else:
1573 self.testNames = (self.defaultTest,)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001574 self.createTests()
Fred Drake02538202001-03-21 18:09:46 +00001575 except getopt.error, msg:
1576 self.usageExit(msg)
1577
1578 def createTests(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001579 self.test = self.testLoader.loadTestsFromNames(self.testNames,
1580 self.module)
Fred Drake02538202001-03-21 18:09:46 +00001581
1582 def runTests(self):
Georg Brandld0a96252007-03-07 09:21:06 +00001583 if isinstance(self.testRunner, (type, types.ClassType)):
1584 try:
1585 testRunner = self.testRunner(verbosity=self.verbosity)
1586 except TypeError:
1587 # didn't accept the verbosity argument
1588 testRunner = self.testRunner()
1589 else:
1590 # it is assumed to be a TestRunner instance
1591 testRunner = self.testRunner
Michael Foord829f6b82009-05-02 11:43:06 +00001592 self.result = testRunner.run(self.test)
1593 if self.exit:
1594 sys.exit(not self.result.wasSuccessful())
Fred Drake02538202001-03-21 18:09:46 +00001595
1596main = TestProgram
1597
1598
Michael Foorde2fb98f2009-05-02 20:15:05 +00001599##############################################################################
1600# Executing this module from the command line
1601##############################################################################
1602
Fred Drake02538202001-03-21 18:09:46 +00001603if __name__ == "__main__":
Michael Foord5d31e052009-05-11 17:59:43 +00001604 sys.modules['unittest'] = sys.modules['__main__']
Fred Drake02538202001-03-21 18:09:46 +00001605 main(module=None)