blob: 465edb1318701c6f9ae46ffea91eb501a079dd25 [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*'
17 self.assertEquals((1 + 2), 3)
18 self.assertEquals(0 + 1, 1)
Steve Purcell7b065702001-09-06 08:24:40 +000019 def testMultiply(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +000020 self.assertEquals((0 * 10), 0)
21 self.assertEquals((5 * 8), 40)
22
23 if __name__ == '__main__':
24 unittest.main()
25
26Further information is available in the bundled documentation, and from
27
Georg Brandl15c5ce92007-03-07 09:09:40 +000028 http://docs.python.org/lib/module-unittest.html
Steve Purcell5ddd1a82001-03-22 08:45:36 +000029
Steve Purcell7e743842003-09-22 11:08:12 +000030Copyright (c) 1999-2003 Steve Purcell
Fred Drake02538202001-03-21 18:09:46 +000031This module is free software, and you may redistribute it and/or modify
32it under the same terms as Python itself, so long as this copyright message
33and disclaimer are retained in their original form.
34
35IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
36SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
37THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
38DAMAGE.
39
40THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
41LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
42PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
43AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
44SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
Steve Purcell5ddd1a82001-03-22 08:45:36 +000045'''
Fred Drake02538202001-03-21 18:09:46 +000046
Fred Drake02538202001-03-21 18:09:46 +000047import time
48import sys
49import traceback
Fred Drake02538202001-03-21 18:09:46 +000050import os
Steve Purcell5ddd1a82001-03-22 08:45:36 +000051import types
Benjamin Peterson692428e2009-03-23 21:50:21 +000052import functools
Fred Drake02538202001-03-21 18:09:46 +000053
54##############################################################################
Steve Purcelld75e7e42003-09-15 11:01:21 +000055# Exported classes and functions
56##############################################################################
57__all__ = ['TestResult', 'TestCase', 'TestSuite', 'TextTestRunner',
58 'TestLoader', 'FunctionTestCase', 'main', 'defaultTestLoader']
59
Steve Purcell7e743842003-09-22 11:08:12 +000060# Expose obsolete functions for backwards compatibility
Steve Purcelld75e7e42003-09-15 11:01:21 +000061__all__.extend(['getTestCaseNames', 'makeSuite', 'findTestCases'])
62
63
64##############################################################################
Steve Purcell7e743842003-09-22 11:08:12 +000065# Backward compatibility
66##############################################################################
Steve Purcell7e743842003-09-22 11:08:12 +000067
Raymond Hettinger5930d8f2008-07-10 16:06:41 +000068def _CmpToKey(mycmp):
69 'Convert a cmp= function into a key= function'
70 class K(object):
71 def __init__(self, obj):
72 self.obj = obj
73 def __lt__(self, other):
74 return mycmp(self.obj, other.obj) == -1
75 return K
Steve Purcell7e743842003-09-22 11:08:12 +000076
77##############################################################################
Fred Drake02538202001-03-21 18:09:46 +000078# Test framework core
79##############################################################################
80
Steve Purcelldc391a62002-08-09 09:46:23 +000081def _strclass(cls):
82 return "%s.%s" % (cls.__module__, cls.__name__)
83
Benjamin Peterson692428e2009-03-23 21:50:21 +000084
85class SkipTest(Exception):
86 """
87 Raise this exception in a test to skip it.
88
89 Usually you can use TestResult.skip() or one of the skipping decorators
90 instead of raising this directly.
91 """
92 pass
93
94class _ExpectedFailure(Exception):
95 """
96 Raise this when a test is expected to fail.
97
98 This is an implementation detail.
99 """
100
101 def __init__(self, exc_info):
102 super(_ExpectedFailure, self).__init__()
103 self.exc_info = exc_info
104
105class _UnexpectedSuccess(Exception):
106 """
107 The test was supposed to fail, but it didn't!
108 """
109 pass
110
111def _id(obj):
112 return obj
113
114def skip(reason):
115 """
116 Unconditionally skip a test.
117 """
118 def decorator(test_item):
119 if isinstance(test_item, type) and issubclass(test_item, TestCase):
120 test_item.__unittest_skip__ = True
121 test_item.__unittest_skip_why__ = reason
122 return test_item
123 @functools.wraps(test_item)
124 def skip_wrapper(*args, **kwargs):
125 raise SkipTest(reason)
126 return skip_wrapper
127 return decorator
128
129def skipIf(condition, reason):
130 """
131 Skip a test if the condition is true.
132 """
133 if condition:
134 return skip(reason)
135 return _id
136
137def skipUnless(condition, reason):
138 """
139 Skip a test unless the condition is true.
140 """
141 if not condition:
142 return skip(reason)
143 return _id
144
145
146def expectedFailure(func):
147 @functools.wraps(func)
148 def wrapper(*args, **kwargs):
149 try:
150 func(*args, **kwargs)
151 except Exception:
152 raise _ExpectedFailure(sys.exc_info())
153 raise _UnexpectedSuccess
154 return wrapper
155
156
Steve Purcellb8d5f242003-12-06 13:03:13 +0000157__unittest = 1
158
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000159class TestResult(object):
Fred Drake02538202001-03-21 18:09:46 +0000160 """Holder for test result information.
161
162 Test results are automatically managed by the TestCase and TestSuite
163 classes, and do not need to be explicitly manipulated by writers of tests.
164
165 Each instance holds the total number of tests run, and collections of
166 failures and errors that occurred among those test runs. The collections
Steve Purcell7b065702001-09-06 08:24:40 +0000167 contain tuples of (testcase, exceptioninfo), where exceptioninfo is the
Fred Drake656f9ec2001-09-06 19:13:14 +0000168 formatted traceback of the error that occurred.
Fred Drake02538202001-03-21 18:09:46 +0000169 """
170 def __init__(self):
171 self.failures = []
172 self.errors = []
173 self.testsRun = 0
Benjamin Peterson692428e2009-03-23 21:50:21 +0000174 self.skipped = []
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +0000175 self.expectedFailures = []
176 self.unexpectedSuccesses = []
Georg Brandl15c5ce92007-03-07 09:09:40 +0000177 self.shouldStop = False
Fred Drake02538202001-03-21 18:09:46 +0000178
179 def startTest(self, test):
180 "Called when the given test is about to be run"
181 self.testsRun = self.testsRun + 1
182
183 def stopTest(self, test):
184 "Called when the given test has been run"
185 pass
186
187 def addError(self, test, err):
Steve Purcell7b065702001-09-06 08:24:40 +0000188 """Called when an error has occurred. 'err' is a tuple of values as
189 returned by sys.exc_info().
190 """
Steve Purcellb8d5f242003-12-06 13:03:13 +0000191 self.errors.append((test, self._exc_info_to_string(err, test)))
Fred Drake02538202001-03-21 18:09:46 +0000192
193 def addFailure(self, test, err):
Steve Purcell7b065702001-09-06 08:24:40 +0000194 """Called when an error has occurred. 'err' is a tuple of values as
195 returned by sys.exc_info()."""
Steve Purcellb8d5f242003-12-06 13:03:13 +0000196 self.failures.append((test, self._exc_info_to_string(err, test)))
Fred Drake02538202001-03-21 18:09:46 +0000197
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000198 def addSuccess(self, test):
199 "Called when a test has completed successfully"
200 pass
201
Benjamin Peterson692428e2009-03-23 21:50:21 +0000202 def addSkip(self, test, reason):
203 """Called when a test is skipped."""
204 self.skipped.append((test, reason))
205
206 def addExpectedFailure(self, test, err):
207 """Called when an expected failure/error occured."""
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +0000208 self.expectedFailures.append(
Benjamin Peterson692428e2009-03-23 21:50:21 +0000209 (test, self._exc_info_to_string(err, test)))
210
211 def addUnexpectedSuccess(self, test):
212 """Called when a test was expected to fail, but succeed."""
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +0000213 self.unexpectedSuccesses.append(test)
Benjamin Peterson692428e2009-03-23 21:50:21 +0000214
Fred Drake02538202001-03-21 18:09:46 +0000215 def wasSuccessful(self):
216 "Tells whether or not this result was a success"
217 return len(self.failures) == len(self.errors) == 0
218
219 def stop(self):
220 "Indicates that the tests should be aborted"
Steve Purcell7e743842003-09-22 11:08:12 +0000221 self.shouldStop = True
Tim Petersa19a1682001-03-29 04:36:09 +0000222
Steve Purcellb8d5f242003-12-06 13:03:13 +0000223 def _exc_info_to_string(self, err, test):
Steve Purcell7b065702001-09-06 08:24:40 +0000224 """Converts a sys.exc_info()-style tuple of values into a string."""
Steve Purcellb8d5f242003-12-06 13:03:13 +0000225 exctype, value, tb = err
226 # Skip test runner traceback levels
227 while tb and self._is_relevant_tb_level(tb):
228 tb = tb.tb_next
229 if exctype is test.failureException:
230 # Skip assert*() traceback levels
231 length = self._count_relevant_tb_levels(tb)
232 return ''.join(traceback.format_exception(exctype, value, tb, length))
233 return ''.join(traceback.format_exception(exctype, value, tb))
234
235 def _is_relevant_tb_level(self, tb):
Georg Brandl56af5fc2008-07-18 19:30:10 +0000236 return '__unittest' in tb.tb_frame.f_globals
Steve Purcellb8d5f242003-12-06 13:03:13 +0000237
238 def _count_relevant_tb_levels(self, tb):
239 length = 0
240 while tb and not self._is_relevant_tb_level(tb):
241 length += 1
242 tb = tb.tb_next
243 return length
Steve Purcell7b065702001-09-06 08:24:40 +0000244
Fred Drake02538202001-03-21 18:09:46 +0000245 def __repr__(self):
246 return "<%s run=%i errors=%i failures=%i>" % \
Steve Purcelldc391a62002-08-09 09:46:23 +0000247 (_strclass(self.__class__), self.testsRun, len(self.errors),
Fred Drake02538202001-03-21 18:09:46 +0000248 len(self.failures))
249
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000250
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000251class AssertRaisesContext(object):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000252
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000253 def __init__(self, expected, test_case):
254 self.expected = expected
255 self.failureException = test_case.failureException
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000256
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000257 def __enter__(self):
258 pass
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000259
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000260 def __exit__(self, exc_type, exc_value, traceback):
261 if exc_type is None:
262 try:
263 exc_name = self.expected.__name__
264 except AttributeError:
265 exc_name = str(self.expected)
266 raise self.failureException(
267 "{0} not raised".format(exc_name))
268 if issubclass(exc_type, self.expected):
269 return True
270 # Let unexpected exceptions skip through
271 return False
272
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000273
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000274class TestCase(object):
Fred Drake02538202001-03-21 18:09:46 +0000275 """A class whose instances are single test cases.
276
Fred Drake02538202001-03-21 18:09:46 +0000277 By default, the test code itself should be placed in a method named
278 'runTest'.
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000279
Tim Petersa19a1682001-03-29 04:36:09 +0000280 If the fixture may be used for many test cases, create as
Fred Drake02538202001-03-21 18:09:46 +0000281 many test methods as are needed. When instantiating such a TestCase
282 subclass, specify in the constructor arguments the name of the test method
283 that the instance is to execute.
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000284
Tim Petersa19a1682001-03-29 04:36:09 +0000285 Test authors should subclass TestCase for their own tests. Construction
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000286 and deconstruction of the test's environment ('fixture') can be
287 implemented by overriding the 'setUp' and 'tearDown' methods respectively.
288
289 If it is necessary to override the __init__ method, the base class
290 __init__ method must always be called. It is important that subclasses
291 should not change the signature of their __init__ method, since instances
292 of the classes are instantiated automatically by parts of the framework
293 in order to be run.
Fred Drake02538202001-03-21 18:09:46 +0000294 """
Steve Purcell15d89272001-04-12 09:05:01 +0000295
296 # This attribute determines which exception will be raised when
297 # the instance's assertion methods fail; test methods raising this
298 # exception will be deemed to have 'failed' rather than 'errored'
299
300 failureException = AssertionError
301
Fred Drake02538202001-03-21 18:09:46 +0000302 def __init__(self, methodName='runTest'):
303 """Create an instance of the class that will use the named test
304 method when executed. Raises a ValueError if the instance does
305 not have a method with the specified name.
306 """
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000307 self._testMethodName = methodName
Fred Drake02538202001-03-21 18:09:46 +0000308 try:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000309 testMethod = getattr(self, methodName)
Fred Drake02538202001-03-21 18:09:46 +0000310 except AttributeError:
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000311 raise ValueError("no such test method in %s: %s" % \
312 (self.__class__, methodName))
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000313 self._testMethodDoc = testMethod.__doc__
Fred Drake02538202001-03-21 18:09:46 +0000314
315 def setUp(self):
316 "Hook method for setting up the test fixture before exercising it."
317 pass
318
319 def tearDown(self):
320 "Hook method for deconstructing the test fixture after testing it."
321 pass
322
323 def countTestCases(self):
324 return 1
325
326 def defaultTestResult(self):
327 return TestResult()
328
329 def shortDescription(self):
330 """Returns a one-line description of the test, or None if no
331 description has been provided.
332
333 The default implementation of this method returns the first line of
334 the specified test method's docstring.
335 """
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000336 doc = self._testMethodDoc
Steve Purcell7e743842003-09-22 11:08:12 +0000337 return doc and doc.split("\n")[0].strip() or None
Fred Drake02538202001-03-21 18:09:46 +0000338
339 def id(self):
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000340 return "%s.%s" % (_strclass(self.__class__), self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000341
Georg Brandl15c5ce92007-03-07 09:09:40 +0000342 def __eq__(self, other):
343 if type(self) is not type(other):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000344 return NotImplemented
Georg Brandl15c5ce92007-03-07 09:09:40 +0000345
346 return self._testMethodName == other._testMethodName
347
348 def __ne__(self, other):
349 return not self == other
350
351 def __hash__(self):
Collin Winter9453e5d2007-03-09 23:30:39 +0000352 return hash((type(self), self._testMethodName))
Georg Brandl15c5ce92007-03-07 09:09:40 +0000353
Fred Drake02538202001-03-21 18:09:46 +0000354 def __str__(self):
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000355 return "%s (%s)" % (self._testMethodName, _strclass(self.__class__))
Fred Drake02538202001-03-21 18:09:46 +0000356
357 def __repr__(self):
358 return "<%s testMethod=%s>" % \
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000359 (_strclass(self.__class__), self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000360
361 def run(self, result=None):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000362 if result is None:
363 result = self.defaultTestResult()
Fred Drake02538202001-03-21 18:09:46 +0000364 result.startTest(self)
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000365 testMethod = getattr(self, self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000366 try:
367 try:
368 self.setUp()
Benjamin Peterson692428e2009-03-23 21:50:21 +0000369 except SkipTest as e:
370 result.addSkip(self, str(e))
371 return
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000372 except Exception:
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000373 result.addError(self, self._exc_info())
Fred Drake02538202001-03-21 18:09:46 +0000374 return
375
Benjamin Peterson692428e2009-03-23 21:50:21 +0000376 success = False
Fred Drake02538202001-03-21 18:09:46 +0000377 try:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000378 testMethod()
Skip Montanaroae5c37b2003-07-13 15:18:12 +0000379 except self.failureException:
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000380 result.addFailure(self, self._exc_info())
Benjamin Peterson692428e2009-03-23 21:50:21 +0000381 except _ExpectedFailure as e:
382 result.addExpectedFailure(self, e.exc_info)
383 except _UnexpectedSuccess:
384 result.addUnexpectedSuccess(self)
385 except SkipTest as e:
386 result.addSkip(self, str(e))
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000387 except Exception:
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000388 result.addError(self, self._exc_info())
Benjamin Peterson692428e2009-03-23 21:50:21 +0000389 else:
390 success = True
Fred Drake02538202001-03-21 18:09:46 +0000391
392 try:
393 self.tearDown()
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000394 except Exception:
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000395 result.addError(self, self._exc_info())
Benjamin Peterson692428e2009-03-23 21:50:21 +0000396 success = False
397 if success:
398 result.addSuccess(self)
Fred Drake02538202001-03-21 18:09:46 +0000399 finally:
400 result.stopTest(self)
401
Raymond Hettinger664347b2004-12-04 21:21:53 +0000402 def __call__(self, *args, **kwds):
403 return self.run(*args, **kwds)
Steve Purcell7e743842003-09-22 11:08:12 +0000404
Fred Drake02538202001-03-21 18:09:46 +0000405 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000406 """Run the test without collecting errors in a TestResult"""
Fred Drake02538202001-03-21 18:09:46 +0000407 self.setUp()
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000408 getattr(self, self._testMethodName)()
Fred Drake02538202001-03-21 18:09:46 +0000409 self.tearDown()
410
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000411 def _exc_info(self):
Steve Purcell15d89272001-04-12 09:05:01 +0000412 """Return a version of sys.exc_info() with the traceback frame
413 minimised; usually the top level of the traceback frame is not
414 needed.
Fred Drake02538202001-03-21 18:09:46 +0000415 """
Georg Brandl15c5ce92007-03-07 09:09:40 +0000416 return sys.exc_info()
Fred Drake02538202001-03-21 18:09:46 +0000417
Benjamin Peterson692428e2009-03-23 21:50:21 +0000418 def skip(self, reason):
419 """Skip this test."""
420 raise SkipTest(reason)
421
Steve Purcell15d89272001-04-12 09:05:01 +0000422 def fail(self, msg=None):
423 """Fail immediately, with the given message."""
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000424 raise self.failureException(msg)
Fred Drake02538202001-03-21 18:09:46 +0000425
426 def failIf(self, expr, msg=None):
427 "Fail the test if the expression is true."
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000428 if expr:
429 raise self.failureException(msg)
Fred Drake02538202001-03-21 18:09:46 +0000430
Steve Purcell15d89272001-04-12 09:05:01 +0000431 def failUnless(self, expr, msg=None):
432 """Fail the test unless the expression is true."""
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000433 if not expr:
434 raise self.failureException(msg)
Steve Purcell15d89272001-04-12 09:05:01 +0000435
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000436 def failUnlessRaises(self, excClass, callableObj=None, *args, **kwargs):
Steve Purcell15d89272001-04-12 09:05:01 +0000437 """Fail unless an exception of class excClass is thrown
Fred Drake02538202001-03-21 18:09:46 +0000438 by callableObj when invoked with arguments args and keyword
439 arguments kwargs. If a different type of exception is
440 thrown, it will not be caught, and the test case will be
441 deemed to have suffered an error, exactly as for an
442 unexpected exception.
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000443
444 If called with callableObj omitted or None, will return a
445 context object used like this::
446
447 with self.failUnlessRaises(some_error_class):
448 do_something()
Fred Drake02538202001-03-21 18:09:46 +0000449 """
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000450 context = AssertRaisesContext(excClass, self)
451 if callableObj is None:
452 return context
453 with context:
Guido van Rossum68468eb2003-02-27 20:14:51 +0000454 callableObj(*args, **kwargs)
Fred Drake02538202001-03-21 18:09:46 +0000455
Steve Purcell15d89272001-04-12 09:05:01 +0000456 def failUnlessEqual(self, first, second, msg=None):
Raymond Hettingerc377cbf2003-04-04 22:56:42 +0000457 """Fail if the two objects are unequal as determined by the '=='
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000458 operator.
459 """
Raymond Hettingerc377cbf2003-04-04 22:56:42 +0000460 if not first == second:
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000461 raise self.failureException(msg or '%r != %r' % (first, second))
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000462
Steve Purcell15d89272001-04-12 09:05:01 +0000463 def failIfEqual(self, first, second, msg=None):
464 """Fail if the two objects are equal as determined by the '=='
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000465 operator.
466 """
Steve Purcell15d89272001-04-12 09:05:01 +0000467 if first == second:
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000468 raise self.failureException(msg or '%r == %r' % (first, second))
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000469
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000470 def failUnlessAlmostEqual(self, first, second, places=7, msg=None):
471 """Fail if the two objects are unequal as determined by their
472 difference rounded to the given number of decimal places
473 (default 7) and comparing to zero.
474
Steve Purcell397b45d2003-10-26 10:41:03 +0000475 Note that decimal places (from zero) are usually not the same
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000476 as significant digits (measured from the most signficant digit).
477 """
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000478 if round(abs(second-first), places) != 0:
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000479 raise self.failureException(
480 msg or '%r != %r within %r places' % (first, second, places))
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000481
482 def failIfAlmostEqual(self, first, second, places=7, msg=None):
483 """Fail if the two objects are equal as determined by their
484 difference rounded to the given number of decimal places
485 (default 7) and comparing to zero.
486
Steve Purcellcca34912003-10-26 16:38:16 +0000487 Note that decimal places (from zero) are usually not the same
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000488 as significant digits (measured from the most signficant digit).
489 """
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000490 if round(abs(second-first), places) == 0:
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000491 raise self.failureException(
492 msg or '%r == %r within %r places' % (first, second, places))
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000493
Steve Purcell7e743842003-09-22 11:08:12 +0000494 # Synonyms for assertion methods
495
Steve Purcell15d89272001-04-12 09:05:01 +0000496 assertEqual = assertEquals = failUnlessEqual
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000497
Steve Purcell15d89272001-04-12 09:05:01 +0000498 assertNotEqual = assertNotEquals = failIfEqual
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000499
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000500 assertAlmostEqual = assertAlmostEquals = failUnlessAlmostEqual
501
502 assertNotAlmostEqual = assertNotAlmostEquals = failIfAlmostEqual
503
Steve Purcell15d89272001-04-12 09:05:01 +0000504 assertRaises = failUnlessRaises
505
Steve Purcell7e743842003-09-22 11:08:12 +0000506 assert_ = assertTrue = failUnless
507
508 assertFalse = failIf
Steve Purcell15d89272001-04-12 09:05:01 +0000509
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000510
Fred Drake02538202001-03-21 18:09:46 +0000511
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000512class TestSuite(object):
Fred Drake02538202001-03-21 18:09:46 +0000513 """A test suite is a composite test consisting of a number of TestCases.
514
515 For use, create an instance of TestSuite, then add test case instances.
516 When all tests have been added, the suite can be passed to a test
517 runner, such as TextTestRunner. It will run the individual test cases
518 in the order in which they were added, aggregating the results. When
519 subclassing, do not forget to call the base class constructor.
520 """
521 def __init__(self, tests=()):
522 self._tests = []
523 self.addTests(tests)
524
525 def __repr__(self):
Steve Purcelldc391a62002-08-09 09:46:23 +0000526 return "<%s tests=%s>" % (_strclass(self.__class__), self._tests)
Fred Drake02538202001-03-21 18:09:46 +0000527
Georg Brandl15c5ce92007-03-07 09:09:40 +0000528 def __eq__(self, other):
Benjamin Peterson692428e2009-03-23 21:50:21 +0000529 if not isinstance(other, self.__class__):
530 return NotImplemented
Georg Brandl15c5ce92007-03-07 09:09:40 +0000531 return self._tests == other._tests
532
533 def __ne__(self, other):
534 return not self == other
535
Nick Coghlan48361f52008-08-11 15:45:58 +0000536 # Can't guarantee hash invariant, so flag as unhashable
537 __hash__ = None
538
Jim Fultonfafd8742004-08-28 15:22:12 +0000539 def __iter__(self):
540 return iter(self._tests)
541
Fred Drake02538202001-03-21 18:09:46 +0000542 def countTestCases(self):
543 cases = 0
544 for test in self._tests:
Steve Purcell7e743842003-09-22 11:08:12 +0000545 cases += test.countTestCases()
Fred Drake02538202001-03-21 18:09:46 +0000546 return cases
547
548 def addTest(self, test):
Georg Brandld9e50262007-03-07 11:54:49 +0000549 # sanity checks
Raymond Hettinger5930d8f2008-07-10 16:06:41 +0000550 if not hasattr(test, '__call__'):
Georg Brandld9e50262007-03-07 11:54:49 +0000551 raise TypeError("the test to add must be callable")
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000552 if isinstance(test, type) and issubclass(test, (TestCase, TestSuite)):
Georg Brandld9e50262007-03-07 11:54:49 +0000553 raise TypeError("TestCases and TestSuites must be instantiated "
554 "before passing them to addTest()")
Fred Drake02538202001-03-21 18:09:46 +0000555 self._tests.append(test)
556
557 def addTests(self, tests):
Georg Brandld9e50262007-03-07 11:54:49 +0000558 if isinstance(tests, basestring):
559 raise TypeError("tests must be an iterable of tests, not a string")
Fred Drake02538202001-03-21 18:09:46 +0000560 for test in tests:
561 self.addTest(test)
562
563 def run(self, result):
Fred Drake02538202001-03-21 18:09:46 +0000564 for test in self._tests:
565 if result.shouldStop:
566 break
567 test(result)
568 return result
569
Raymond Hettinger664347b2004-12-04 21:21:53 +0000570 def __call__(self, *args, **kwds):
571 return self.run(*args, **kwds)
572
Fred Drake02538202001-03-21 18:09:46 +0000573 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000574 """Run the tests without collecting errors in a TestResult"""
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000575 for test in self._tests:
576 test.debug()
Fred Drake02538202001-03-21 18:09:46 +0000577
578
Benjamin Peterson692428e2009-03-23 21:50:21 +0000579class ClassTestSuite(TestSuite):
580 """
581 Suite of tests derived from a single TestCase class.
582 """
583
584 def __init__(self, tests, class_collected_from):
585 super(ClassTestSuite, self).__init__(tests)
586 self.collected_from = class_collected_from
587
588 def id(self):
589 module = getattr(self.collected_from, "__module__", None)
590 if module is not None:
591 return "{0}.{1}".format(module, self.collected_from.__name__)
592 return self.collected_from.__name__
593
594 def run(self, result):
595 if getattr(self.collected_from, "__unittest_skip__", False):
596 # ClassTestSuite result pretends to be a TestCase enough to be
597 # reported.
598 result.startTest(self)
599 try:
600 result.addSkip(self, self.collected_from.__unittest_skip_why__)
601 finally:
602 result.stopTest(self)
603 else:
604 result = super(ClassTestSuite, self).run(result)
605 return result
606
607 shortDescription = id
608
609
Fred Drake02538202001-03-21 18:09:46 +0000610class FunctionTestCase(TestCase):
611 """A test case that wraps a test function.
612
613 This is useful for slipping pre-existing test functions into the
Georg Brandl15c5ce92007-03-07 09:09:40 +0000614 unittest framework. Optionally, set-up and tidy-up functions can be
Fred Drake02538202001-03-21 18:09:46 +0000615 supplied. As with TestCase, the tidy-up ('tearDown') function will
616 always be called if the set-up ('setUp') function ran successfully.
617 """
618
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000619 def __init__(self, testFunc, setUp=None, tearDown=None, description=None):
620 super(FunctionTestCase, self).__init__()
Fred Drake02538202001-03-21 18:09:46 +0000621 self.__setUpFunc = setUp
622 self.__tearDownFunc = tearDown
623 self.__testFunc = testFunc
624 self.__description = description
625
626 def setUp(self):
627 if self.__setUpFunc is not None:
628 self.__setUpFunc()
629
630 def tearDown(self):
631 if self.__tearDownFunc is not None:
632 self.__tearDownFunc()
633
634 def runTest(self):
635 self.__testFunc()
636
637 def id(self):
638 return self.__testFunc.__name__
639
Georg Brandl15c5ce92007-03-07 09:09:40 +0000640 def __eq__(self, other):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000641 if not isinstance(other, self.__class__):
642 return NotImplemented
Georg Brandl15c5ce92007-03-07 09:09:40 +0000643
644 return self.__setUpFunc == other.__setUpFunc and \
645 self.__tearDownFunc == other.__tearDownFunc and \
646 self.__testFunc == other.__testFunc and \
647 self.__description == other.__description
648
649 def __ne__(self, other):
650 return not self == other
651
652 def __hash__(self):
Collin Winter9453e5d2007-03-09 23:30:39 +0000653 return hash((type(self), self.__setUpFunc, self.__tearDownFunc,
654 self.__testFunc, self.__description))
Georg Brandl15c5ce92007-03-07 09:09:40 +0000655
Fred Drake02538202001-03-21 18:09:46 +0000656 def __str__(self):
Steve Purcelldc391a62002-08-09 09:46:23 +0000657 return "%s (%s)" % (_strclass(self.__class__), self.__testFunc.__name__)
Fred Drake02538202001-03-21 18:09:46 +0000658
659 def __repr__(self):
Steve Purcelldc391a62002-08-09 09:46:23 +0000660 return "<%s testFunc=%s>" % (_strclass(self.__class__), self.__testFunc)
Fred Drake02538202001-03-21 18:09:46 +0000661
662 def shortDescription(self):
663 if self.__description is not None: return self.__description
664 doc = self.__testFunc.__doc__
Steve Purcell7e743842003-09-22 11:08:12 +0000665 return doc and doc.split("\n")[0].strip() or None
Fred Drake02538202001-03-21 18:09:46 +0000666
667
668
669##############################################################################
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000670# Locating and loading tests
Fred Drake02538202001-03-21 18:09:46 +0000671##############################################################################
672
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000673class TestLoader(object):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000674 """
675 This class is responsible for loading tests according to various criteria
676 and returning them wrapped in a TestSuite
Fred Drake02538202001-03-21 18:09:46 +0000677 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000678 testMethodPrefix = 'test'
679 sortTestMethodsUsing = cmp
680 suiteClass = TestSuite
Benjamin Peterson692428e2009-03-23 21:50:21 +0000681 classSuiteClass = ClassTestSuite
Fred Drake02538202001-03-21 18:09:46 +0000682
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000683 def loadTestsFromTestCase(self, testCaseClass):
Steve Purcell15d89272001-04-12 09:05:01 +0000684 """Return a suite of all tests cases contained in testCaseClass"""
Johannes Gijsbersd7b6ad42004-11-07 15:46:25 +0000685 if issubclass(testCaseClass, TestSuite):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000686 raise TypeError("Test cases should not be derived from TestSuite." \
687 " Maybe you meant to derive from TestCase?")
Steve Purcell7e743842003-09-22 11:08:12 +0000688 testCaseNames = self.getTestCaseNames(testCaseClass)
689 if not testCaseNames and hasattr(testCaseClass, 'runTest'):
690 testCaseNames = ['runTest']
Benjamin Peterson692428e2009-03-23 21:50:21 +0000691 suite = self.classSuiteClass(map(testCaseClass, testCaseNames),
692 testCaseClass)
693 return suite
Fred Drake02538202001-03-21 18:09:46 +0000694
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000695 def loadTestsFromModule(self, module):
Steve Purcell15d89272001-04-12 09:05:01 +0000696 """Return a suite of all tests cases contained in the given module"""
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000697 tests = []
698 for name in dir(module):
699 obj = getattr(module, name)
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000700 if isinstance(obj, type) and issubclass(obj, TestCase):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000701 tests.append(self.loadTestsFromTestCase(obj))
702 return self.suiteClass(tests)
Fred Drake02538202001-03-21 18:09:46 +0000703
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000704 def loadTestsFromName(self, name, module=None):
Steve Purcell15d89272001-04-12 09:05:01 +0000705 """Return a suite of all tests cases given a string specifier.
706
707 The name may resolve either to a module, a test case class, a
708 test method within a test case class, or a callable object which
709 returns a TestCase or TestSuite instance.
Tim Peters613b2222001-04-13 05:37:27 +0000710
Steve Purcell15d89272001-04-12 09:05:01 +0000711 The method optionally resolves the names relative to a given module.
712 """
Steve Purcell7e743842003-09-22 11:08:12 +0000713 parts = name.split('.')
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000714 if module is None:
Steve Purcell7e743842003-09-22 11:08:12 +0000715 parts_copy = parts[:]
716 while parts_copy:
717 try:
718 module = __import__('.'.join(parts_copy))
719 break
720 except ImportError:
721 del parts_copy[-1]
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000722 if not parts_copy:
723 raise
Armin Rigo1b3c04b2003-10-24 17:15:29 +0000724 parts = parts[1:]
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000725 obj = module
726 for part in parts:
Steve Purcell7e743842003-09-22 11:08:12 +0000727 parent, obj = obj, getattr(obj, part)
Fred Drake02538202001-03-21 18:09:46 +0000728
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000729 if isinstance(obj, types.ModuleType):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000730 return self.loadTestsFromModule(obj)
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000731 elif isinstance(obj, type) and issubclass(obj, TestCase):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000732 return self.loadTestsFromTestCase(obj)
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000733 elif (isinstance(obj, types.UnboundMethodType) and
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000734 isinstance(parent, type) and
Georg Brandl15c5ce92007-03-07 09:09:40 +0000735 issubclass(parent, TestCase)):
736 return TestSuite([parent(obj.__name__)])
Steve Purcell397b45d2003-10-26 10:41:03 +0000737 elif isinstance(obj, TestSuite):
Steve Purcell7e743842003-09-22 11:08:12 +0000738 return obj
Raymond Hettinger5930d8f2008-07-10 16:06:41 +0000739 elif hasattr(obj, '__call__'):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000740 test = obj()
Georg Brandl15c5ce92007-03-07 09:09:40 +0000741 if isinstance(test, TestSuite):
742 return test
743 elif isinstance(test, TestCase):
744 return TestSuite([test])
745 else:
746 raise TypeError("calling %s returned %s, not a test" %
747 (obj, test))
Fred Drake02538202001-03-21 18:09:46 +0000748 else:
Georg Brandl15c5ce92007-03-07 09:09:40 +0000749 raise TypeError("don't know how to make test from: %s" % obj)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000750
751 def loadTestsFromNames(self, names, module=None):
Steve Purcell15d89272001-04-12 09:05:01 +0000752 """Return a suite of all tests cases found using the given sequence
753 of string specifiers. See 'loadTestsFromName()'.
754 """
Steve Purcell7e743842003-09-22 11:08:12 +0000755 suites = [self.loadTestsFromName(name, module) for name in names]
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000756 return self.suiteClass(suites)
757
758 def getTestCaseNames(self, testCaseClass):
Steve Purcell15d89272001-04-12 09:05:01 +0000759 """Return a sorted sequence of method names found within testCaseClass
760 """
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000761 def isTestMethod(attrname, testCaseClass=testCaseClass,
762 prefix=self.testMethodPrefix):
763 return attrname.startswith(prefix) and \
764 hasattr(getattr(testCaseClass, attrname), '__call__')
Steve Purcell7e743842003-09-22 11:08:12 +0000765 testFnNames = filter(isTestMethod, dir(testCaseClass))
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000766 if self.sortTestMethodsUsing:
Raymond Hettinger5930d8f2008-07-10 16:06:41 +0000767 testFnNames.sort(key=_CmpToKey(self.sortTestMethodsUsing))
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000768 return testFnNames
769
770
771
772defaultTestLoader = TestLoader()
773
774
775##############################################################################
776# Patches for old functions: these functions should be considered obsolete
777##############################################################################
778
779def _makeLoader(prefix, sortUsing, suiteClass=None):
780 loader = TestLoader()
781 loader.sortTestMethodsUsing = sortUsing
782 loader.testMethodPrefix = prefix
783 if suiteClass: loader.suiteClass = suiteClass
784 return loader
785
786def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp):
787 return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)
788
789def makeSuite(testCaseClass, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
790 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
791
792def findTestCases(module, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
793 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module)
Fred Drake02538202001-03-21 18:09:46 +0000794
795
796##############################################################################
797# Text UI
798##############################################################################
799
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000800class _WritelnDecorator(object):
Fred Drake02538202001-03-21 18:09:46 +0000801 """Used to decorate file-like objects with a handy 'writeln' method"""
802 def __init__(self,stream):
803 self.stream = stream
Fred Drake02538202001-03-21 18:09:46 +0000804
805 def __getattr__(self, attr):
806 return getattr(self.stream,attr)
807
Raymond Hettinger91dd19d2003-09-13 02:58:00 +0000808 def writeln(self, arg=None):
809 if arg: self.write(arg)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000810 self.write('\n') # text-mode streams translate to \r\n if needed
Tim Petersa19a1682001-03-29 04:36:09 +0000811
Fred Drake02538202001-03-21 18:09:46 +0000812
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000813class _TextTestResult(TestResult):
Fred Drake02538202001-03-21 18:09:46 +0000814 """A test result class that can print formatted text results to a stream.
815
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000816 Used by TextTestRunner.
Fred Drake02538202001-03-21 18:09:46 +0000817 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000818 separator1 = '=' * 70
819 separator2 = '-' * 70
Fred Drake02538202001-03-21 18:09:46 +0000820
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000821 def __init__(self, stream, descriptions, verbosity):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000822 super(_TextTestResult, self).__init__()
Fred Drake02538202001-03-21 18:09:46 +0000823 self.stream = stream
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000824 self.showAll = verbosity > 1
825 self.dots = verbosity == 1
Fred Drake02538202001-03-21 18:09:46 +0000826 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000827
828 def getDescription(self, test):
829 if self.descriptions:
830 return test.shortDescription() or str(test)
831 else:
832 return str(test)
833
Fred Drake02538202001-03-21 18:09:46 +0000834 def startTest(self, test):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000835 super(_TextTestResult, self).startTest(test)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000836 if self.showAll:
837 self.stream.write(self.getDescription(test))
838 self.stream.write(" ... ")
Georg Brandld0632402008-05-11 15:17:41 +0000839 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +0000840
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000841 def addSuccess(self, test):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000842 super(_TextTestResult, self).addSuccess(test)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000843 if self.showAll:
Fred Drake02538202001-03-21 18:09:46 +0000844 self.stream.writeln("ok")
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000845 elif self.dots:
846 self.stream.write('.')
Georg Brandld0632402008-05-11 15:17:41 +0000847 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +0000848
849 def addError(self, test, err):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000850 super(_TextTestResult, self).addError(test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000851 if self.showAll:
852 self.stream.writeln("ERROR")
853 elif self.dots:
854 self.stream.write('E')
Georg Brandld0632402008-05-11 15:17:41 +0000855 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +0000856
857 def addFailure(self, test, err):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000858 super(_TextTestResult, self).addFailure(test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000859 if self.showAll:
860 self.stream.writeln("FAIL")
861 elif self.dots:
862 self.stream.write('F')
Georg Brandld0632402008-05-11 15:17:41 +0000863 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +0000864
Benjamin Peterson692428e2009-03-23 21:50:21 +0000865 def addSkip(self, test, reason):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000866 super(_TextTestResult, self).addSkip(test, reason)
Benjamin Peterson692428e2009-03-23 21:50:21 +0000867 if self.showAll:
868 self.stream.writeln("skipped {0!r}".format(reason))
869 elif self.dots:
870 self.stream.write("s")
871 self.stream.flush()
872
873 def addExpectedFailure(self, test, err):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000874 super(_TextTestResult, self).addExpectedFailure(test, err)
Benjamin Peterson692428e2009-03-23 21:50:21 +0000875 if self.showAll:
876 self.stream.writeln("expected failure")
877 elif self.dots:
878 self.stream.write(".")
879 self.stream.flush()
880
881 def addUnexpectedSuccess(self, test):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000882 super(_TextTestResult, self).addUnexpectedSuccess(test)
Benjamin Peterson692428e2009-03-23 21:50:21 +0000883 if self.showAll:
884 self.stream.writeln("unexpected success")
885 elif self.dots:
886 self.stream.write(".")
887 self.stream.flush()
888
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000889 def printErrors(self):
890 if self.dots or self.showAll:
Fred Drake02538202001-03-21 18:09:46 +0000891 self.stream.writeln()
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000892 self.printErrorList('ERROR', self.errors)
893 self.printErrorList('FAIL', self.failures)
894
895 def printErrorList(self, flavour, errors):
896 for test, err in errors:
897 self.stream.writeln(self.separator1)
898 self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
899 self.stream.writeln(self.separator2)
Steve Purcell7b065702001-09-06 08:24:40 +0000900 self.stream.writeln("%s" % err)
Fred Drake02538202001-03-21 18:09:46 +0000901
902
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000903class TextTestRunner(object):
Fred Drake02538202001-03-21 18:09:46 +0000904 """A test runner class that displays results in textual form.
Tim Petersa19a1682001-03-29 04:36:09 +0000905
Fred Drake02538202001-03-21 18:09:46 +0000906 It prints out the names of tests as they are run, errors as they
907 occur, and a summary of the results at the end of the test run.
908 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000909 def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1):
Fred Drake02538202001-03-21 18:09:46 +0000910 self.stream = _WritelnDecorator(stream)
911 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000912 self.verbosity = verbosity
913
914 def _makeResult(self):
915 return _TextTestResult(self.stream, self.descriptions, self.verbosity)
Fred Drake02538202001-03-21 18:09:46 +0000916
917 def run(self, test):
918 "Run the given test case or test suite."
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000919 result = self._makeResult()
Fred Drake02538202001-03-21 18:09:46 +0000920 startTime = time.time()
921 test(result)
922 stopTime = time.time()
Steve Purcell397b45d2003-10-26 10:41:03 +0000923 timeTaken = stopTime - startTime
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000924 result.printErrors()
925 self.stream.writeln(result.separator2)
Fred Drake02538202001-03-21 18:09:46 +0000926 run = result.testsRun
927 self.stream.writeln("Ran %d test%s in %.3fs" %
Neal Norwitz76165042002-05-31 14:15:11 +0000928 (run, run != 1 and "s" or "", timeTaken))
Fred Drake02538202001-03-21 18:09:46 +0000929 self.stream.writeln()
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +0000930 results = map(len, (result.expectedFailures,
931 result.unexpectedSuccesses,
Benjamin Peterson692428e2009-03-23 21:50:21 +0000932 result.skipped))
Benjamin Petersoncb2b0e42009-03-23 22:29:45 +0000933 expectedFails, unexpectedSuccesses, skipped = results
Benjamin Peterson692428e2009-03-23 21:50:21 +0000934 infos = []
Fred Drake02538202001-03-21 18:09:46 +0000935 if not result.wasSuccessful():
Benjamin Peterson692428e2009-03-23 21:50:21 +0000936 self.stream.write("FAILED")
Fred Drake02538202001-03-21 18:09:46 +0000937 failed, errored = map(len, (result.failures, result.errors))
938 if failed:
Benjamin Peterson692428e2009-03-23 21:50:21 +0000939 infos.append("failures=%d" % failed)
Fred Drake02538202001-03-21 18:09:46 +0000940 if errored:
Benjamin Peterson692428e2009-03-23 21:50:21 +0000941 infos.append("errors=%d" % errored)
Fred Drake02538202001-03-21 18:09:46 +0000942 else:
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000943 self.stream.writeln("OK")
Benjamin Peterson692428e2009-03-23 21:50:21 +0000944 if skipped:
945 infos.append("skipped=%d" % skipped)
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000946 if expectedFails:
947 infos.append("expected failures=%d" % expectedFails)
948 if unexpectedSuccesses:
949 infos.append("unexpected successes=%d" % unexpectedSuccesses)
Benjamin Peterson692428e2009-03-23 21:50:21 +0000950 if infos:
951 self.stream.writeln(" (%s)" % (", ".join(infos),))
Fred Drake02538202001-03-21 18:09:46 +0000952 return result
Tim Petersa19a1682001-03-29 04:36:09 +0000953
Fred Drake02538202001-03-21 18:09:46 +0000954
Fred Drake02538202001-03-21 18:09:46 +0000955
956##############################################################################
957# Facilities for running tests from the command line
958##############################################################################
959
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000960class TestProgram(object):
Fred Drake02538202001-03-21 18:09:46 +0000961 """A command-line program that runs a set of tests; this is primarily
962 for making test modules conveniently executable.
963 """
964 USAGE = """\
Steve Purcell17a781b2001-04-09 15:37:31 +0000965Usage: %(progName)s [options] [test] [...]
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000966
967Options:
968 -h, --help Show this message
969 -v, --verbose Verbose output
970 -q, --quiet Minimal output
Fred Drake02538202001-03-21 18:09:46 +0000971
972Examples:
973 %(progName)s - run default set of tests
974 %(progName)s MyTestSuite - run suite 'MyTestSuite'
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000975 %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething
976 %(progName)s MyTestCase - run all 'test*' test methods
Fred Drake02538202001-03-21 18:09:46 +0000977 in MyTestCase
978"""
979 def __init__(self, module='__main__', defaultTest=None,
Georg Brandld0a96252007-03-07 09:21:06 +0000980 argv=None, testRunner=TextTestRunner,
981 testLoader=defaultTestLoader):
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000982 if isinstance(module, basestring):
Fred Drake02538202001-03-21 18:09:46 +0000983 self.module = __import__(module)
Steve Purcell7e743842003-09-22 11:08:12 +0000984 for part in module.split('.')[1:]:
Fred Drake02538202001-03-21 18:09:46 +0000985 self.module = getattr(self.module, part)
986 else:
987 self.module = module
988 if argv is None:
989 argv = sys.argv
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000990 self.verbosity = 1
Fred Drake02538202001-03-21 18:09:46 +0000991 self.defaultTest = defaultTest
992 self.testRunner = testRunner
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000993 self.testLoader = testLoader
Fred Drake02538202001-03-21 18:09:46 +0000994 self.progName = os.path.basename(argv[0])
995 self.parseArgs(argv)
Fred Drake02538202001-03-21 18:09:46 +0000996 self.runTests()
997
998 def usageExit(self, msg=None):
Benjamin Petersona7d441d2009-03-24 00:35:20 +0000999 if msg:
1000 print msg
Fred Drake02538202001-03-21 18:09:46 +00001001 print self.USAGE % self.__dict__
1002 sys.exit(2)
1003
1004 def parseArgs(self, argv):
1005 import getopt
Benjamin Peterson692428e2009-03-23 21:50:21 +00001006 long_opts = ['help','verbose','quiet']
Fred Drake02538202001-03-21 18:09:46 +00001007 try:
Benjamin Peterson692428e2009-03-23 21:50:21 +00001008 options, args = getopt.getopt(argv[1:], 'hHvq', long_opts)
Fred Drake02538202001-03-21 18:09:46 +00001009 for opt, value in options:
1010 if opt in ('-h','-H','--help'):
1011 self.usageExit()
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001012 if opt in ('-q','--quiet'):
1013 self.verbosity = 0
1014 if opt in ('-v','--verbose'):
1015 self.verbosity = 2
Fred Drake02538202001-03-21 18:09:46 +00001016 if len(args) == 0 and self.defaultTest is None:
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001017 self.test = self.testLoader.loadTestsFromModule(self.module)
1018 return
Fred Drake02538202001-03-21 18:09:46 +00001019 if len(args) > 0:
1020 self.testNames = args
1021 else:
1022 self.testNames = (self.defaultTest,)
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001023 self.createTests()
Fred Drake02538202001-03-21 18:09:46 +00001024 except getopt.error, msg:
1025 self.usageExit(msg)
1026
1027 def createTests(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +00001028 self.test = self.testLoader.loadTestsFromNames(self.testNames,
1029 self.module)
Fred Drake02538202001-03-21 18:09:46 +00001030
1031 def runTests(self):
Georg Brandld0a96252007-03-07 09:21:06 +00001032 if isinstance(self.testRunner, (type, types.ClassType)):
1033 try:
1034 testRunner = self.testRunner(verbosity=self.verbosity)
1035 except TypeError:
1036 # didn't accept the verbosity argument
1037 testRunner = self.testRunner()
1038 else:
1039 # it is assumed to be a TestRunner instance
1040 testRunner = self.testRunner
1041 result = testRunner.run(self.test)
Tim Petersa19a1682001-03-29 04:36:09 +00001042 sys.exit(not result.wasSuccessful())
Fred Drake02538202001-03-21 18:09:46 +00001043
1044main = TestProgram
1045
1046
1047##############################################################################
1048# Executing this module from the command line
1049##############################################################################
1050
1051if __name__ == "__main__":
1052 main(module=None)