blob: eab0372cad42799faf70e3bd03edbdd24eb5cd16 [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
28 http://pyunit.sourceforge.net/
29
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
Steve Purcell5ddd1a82001-03-22 08:45:36 +000047__author__ = "Steve Purcell"
48__email__ = "stephen_purcell at yahoo dot com"
Steve Purcellb8d5f242003-12-06 13:03:13 +000049__version__ = "#Revision: 1.63 $"[11:-2]
Fred Drake02538202001-03-21 18:09:46 +000050
51import time
52import sys
53import traceback
Fred Drake02538202001-03-21 18:09:46 +000054import os
Steve Purcell5ddd1a82001-03-22 08:45:36 +000055import types
Fred Drake02538202001-03-21 18:09:46 +000056
57##############################################################################
Steve Purcelld75e7e42003-09-15 11:01:21 +000058# Exported classes and functions
59##############################################################################
60__all__ = ['TestResult', 'TestCase', 'TestSuite', 'TextTestRunner',
61 'TestLoader', 'FunctionTestCase', 'main', 'defaultTestLoader']
62
Steve Purcell7e743842003-09-22 11:08:12 +000063# Expose obsolete functions for backwards compatibility
Steve Purcelld75e7e42003-09-15 11:01:21 +000064__all__.extend(['getTestCaseNames', 'makeSuite', 'findTestCases'])
65
66
67##############################################################################
Steve Purcell7e743842003-09-22 11:08:12 +000068# Backward compatibility
69##############################################################################
70if sys.version_info[:2] < (2, 2):
71 False, True = 0, 1
72 def isinstance(obj, clsinfo):
73 import __builtin__
Raymond Hettingerf7153662005-02-07 14:16:21 +000074 if type(clsinfo) in (tuple, list):
Steve Purcell7e743842003-09-22 11:08:12 +000075 for cls in clsinfo:
76 if cls is type: cls = types.ClassType
77 if __builtin__.isinstance(obj, cls):
78 return 1
79 return 0
80 else: return __builtin__.isinstance(obj, clsinfo)
81
82
83##############################################################################
Fred Drake02538202001-03-21 18:09:46 +000084# Test framework core
85##############################################################################
86
Steve Purcelldc391a62002-08-09 09:46:23 +000087def _strclass(cls):
88 return "%s.%s" % (cls.__module__, cls.__name__)
89
Steve Purcellb8d5f242003-12-06 13:03:13 +000090__unittest = 1
91
Fred Drake02538202001-03-21 18:09:46 +000092class TestResult:
93 """Holder for test result information.
94
95 Test results are automatically managed by the TestCase and TestSuite
96 classes, and do not need to be explicitly manipulated by writers of tests.
97
98 Each instance holds the total number of tests run, and collections of
99 failures and errors that occurred among those test runs. The collections
Steve Purcell7b065702001-09-06 08:24:40 +0000100 contain tuples of (testcase, exceptioninfo), where exceptioninfo is the
Fred Drake656f9ec2001-09-06 19:13:14 +0000101 formatted traceback of the error that occurred.
Fred Drake02538202001-03-21 18:09:46 +0000102 """
103 def __init__(self):
104 self.failures = []
105 self.errors = []
106 self.testsRun = 0
107 self.shouldStop = 0
108
109 def startTest(self, test):
110 "Called when the given test is about to be run"
111 self.testsRun = self.testsRun + 1
112
113 def stopTest(self, test):
114 "Called when the given test has been run"
115 pass
116
117 def addError(self, test, err):
Steve Purcell7b065702001-09-06 08:24:40 +0000118 """Called when an error has occurred. 'err' is a tuple of values as
119 returned by sys.exc_info().
120 """
Steve Purcellb8d5f242003-12-06 13:03:13 +0000121 self.errors.append((test, self._exc_info_to_string(err, test)))
Fred Drake02538202001-03-21 18:09:46 +0000122
123 def addFailure(self, test, err):
Steve Purcell7b065702001-09-06 08:24:40 +0000124 """Called when an error has occurred. 'err' is a tuple of values as
125 returned by sys.exc_info()."""
Steve Purcellb8d5f242003-12-06 13:03:13 +0000126 self.failures.append((test, self._exc_info_to_string(err, test)))
Fred Drake02538202001-03-21 18:09:46 +0000127
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000128 def addSuccess(self, test):
129 "Called when a test has completed successfully"
130 pass
131
Fred Drake02538202001-03-21 18:09:46 +0000132 def wasSuccessful(self):
133 "Tells whether or not this result was a success"
134 return len(self.failures) == len(self.errors) == 0
135
136 def stop(self):
137 "Indicates that the tests should be aborted"
Steve Purcell7e743842003-09-22 11:08:12 +0000138 self.shouldStop = True
Tim Petersa19a1682001-03-29 04:36:09 +0000139
Steve Purcellb8d5f242003-12-06 13:03:13 +0000140 def _exc_info_to_string(self, err, test):
Steve Purcell7b065702001-09-06 08:24:40 +0000141 """Converts a sys.exc_info()-style tuple of values into a string."""
Steve Purcellb8d5f242003-12-06 13:03:13 +0000142 exctype, value, tb = err
143 # Skip test runner traceback levels
144 while tb and self._is_relevant_tb_level(tb):
145 tb = tb.tb_next
146 if exctype is test.failureException:
147 # Skip assert*() traceback levels
148 length = self._count_relevant_tb_levels(tb)
149 return ''.join(traceback.format_exception(exctype, value, tb, length))
150 return ''.join(traceback.format_exception(exctype, value, tb))
151
152 def _is_relevant_tb_level(self, tb):
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000153 return '__unittest' in tb.tb_frame.f_globals
Steve Purcellb8d5f242003-12-06 13:03:13 +0000154
155 def _count_relevant_tb_levels(self, tb):
156 length = 0
157 while tb and not self._is_relevant_tb_level(tb):
158 length += 1
159 tb = tb.tb_next
160 return length
Steve Purcell7b065702001-09-06 08:24:40 +0000161
Fred Drake02538202001-03-21 18:09:46 +0000162 def __repr__(self):
163 return "<%s run=%i errors=%i failures=%i>" % \
Steve Purcelldc391a62002-08-09 09:46:23 +0000164 (_strclass(self.__class__), self.testsRun, len(self.errors),
Fred Drake02538202001-03-21 18:09:46 +0000165 len(self.failures))
166
Fred Drake02538202001-03-21 18:09:46 +0000167class TestCase:
168 """A class whose instances are single test cases.
169
Fred Drake02538202001-03-21 18:09:46 +0000170 By default, the test code itself should be placed in a method named
171 'runTest'.
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000172
Tim Petersa19a1682001-03-29 04:36:09 +0000173 If the fixture may be used for many test cases, create as
Fred Drake02538202001-03-21 18:09:46 +0000174 many test methods as are needed. When instantiating such a TestCase
175 subclass, specify in the constructor arguments the name of the test method
176 that the instance is to execute.
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000177
Tim Petersa19a1682001-03-29 04:36:09 +0000178 Test authors should subclass TestCase for their own tests. Construction
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000179 and deconstruction of the test's environment ('fixture') can be
180 implemented by overriding the 'setUp' and 'tearDown' methods respectively.
181
182 If it is necessary to override the __init__ method, the base class
183 __init__ method must always be called. It is important that subclasses
184 should not change the signature of their __init__ method, since instances
185 of the classes are instantiated automatically by parts of the framework
186 in order to be run.
Fred Drake02538202001-03-21 18:09:46 +0000187 """
Steve Purcell15d89272001-04-12 09:05:01 +0000188
189 # This attribute determines which exception will be raised when
190 # the instance's assertion methods fail; test methods raising this
191 # exception will be deemed to have 'failed' rather than 'errored'
192
193 failureException = AssertionError
194
Fred Drake02538202001-03-21 18:09:46 +0000195 def __init__(self, methodName='runTest'):
196 """Create an instance of the class that will use the named test
197 method when executed. Raises a ValueError if the instance does
198 not have a method with the specified name.
199 """
200 try:
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000201 self._testMethodName = methodName
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000202 testMethod = getattr(self, methodName)
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000203 self._testMethodDoc = testMethod.__doc__
Fred Drake02538202001-03-21 18:09:46 +0000204 except AttributeError:
205 raise ValueError, "no such test method in %s: %s" % \
206 (self.__class__, methodName)
207
208 def setUp(self):
209 "Hook method for setting up the test fixture before exercising it."
210 pass
211
212 def tearDown(self):
213 "Hook method for deconstructing the test fixture after testing it."
214 pass
215
216 def countTestCases(self):
217 return 1
218
219 def defaultTestResult(self):
220 return TestResult()
221
222 def shortDescription(self):
223 """Returns a one-line description of the test, or None if no
224 description has been provided.
225
226 The default implementation of this method returns the first line of
227 the specified test method's docstring.
228 """
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000229 doc = self._testMethodDoc
Steve Purcell7e743842003-09-22 11:08:12 +0000230 return doc and doc.split("\n")[0].strip() or None
Fred Drake02538202001-03-21 18:09:46 +0000231
232 def id(self):
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000233 return "%s.%s" % (_strclass(self.__class__), self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000234
235 def __str__(self):
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000236 return "%s (%s)" % (self._testMethodName, _strclass(self.__class__))
Fred Drake02538202001-03-21 18:09:46 +0000237
238 def __repr__(self):
239 return "<%s testMethod=%s>" % \
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000240 (_strclass(self.__class__), self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000241
242 def run(self, result=None):
Fred Drake02538202001-03-21 18:09:46 +0000243 if result is None: result = self.defaultTestResult()
244 result.startTest(self)
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000245 testMethod = getattr(self, self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000246 try:
247 try:
248 self.setUp()
Guido van Rossum202dd1e2001-12-07 03:39:34 +0000249 except KeyboardInterrupt:
250 raise
Fred Drake02538202001-03-21 18:09:46 +0000251 except:
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000252 result.addError(self, self._exc_info())
Fred Drake02538202001-03-21 18:09:46 +0000253 return
254
Steve Purcell7e743842003-09-22 11:08:12 +0000255 ok = False
Fred Drake02538202001-03-21 18:09:46 +0000256 try:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000257 testMethod()
Steve Purcell7e743842003-09-22 11:08:12 +0000258 ok = True
Skip Montanaroae5c37b2003-07-13 15:18:12 +0000259 except self.failureException:
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000260 result.addFailure(self, self._exc_info())
Guido van Rossum202dd1e2001-12-07 03:39:34 +0000261 except KeyboardInterrupt:
262 raise
Fred Drake02538202001-03-21 18:09:46 +0000263 except:
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000264 result.addError(self, self._exc_info())
Fred Drake02538202001-03-21 18:09:46 +0000265
266 try:
267 self.tearDown()
Guido van Rossum202dd1e2001-12-07 03:39:34 +0000268 except KeyboardInterrupt:
269 raise
Fred Drake02538202001-03-21 18:09:46 +0000270 except:
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000271 result.addError(self, self._exc_info())
Steve Purcell7e743842003-09-22 11:08:12 +0000272 ok = False
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000273 if ok: result.addSuccess(self)
Fred Drake02538202001-03-21 18:09:46 +0000274 finally:
275 result.stopTest(self)
276
Raymond Hettinger664347b2004-12-04 21:21:53 +0000277 def __call__(self, *args, **kwds):
278 return self.run(*args, **kwds)
Steve Purcell7e743842003-09-22 11:08:12 +0000279
Fred Drake02538202001-03-21 18:09:46 +0000280 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000281 """Run the test without collecting errors in a TestResult"""
Fred Drake02538202001-03-21 18:09:46 +0000282 self.setUp()
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000283 getattr(self, self._testMethodName)()
Fred Drake02538202001-03-21 18:09:46 +0000284 self.tearDown()
285
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000286 def _exc_info(self):
Steve Purcell15d89272001-04-12 09:05:01 +0000287 """Return a version of sys.exc_info() with the traceback frame
288 minimised; usually the top level of the traceback frame is not
289 needed.
Fred Drake02538202001-03-21 18:09:46 +0000290 """
Steve Purcell15d89272001-04-12 09:05:01 +0000291 exctype, excvalue, tb = sys.exc_info()
292 if sys.platform[:4] == 'java': ## tracebacks look different in Jython
293 return (exctype, excvalue, tb)
Steve Purcellb8d5f242003-12-06 13:03:13 +0000294 return (exctype, excvalue, tb)
Fred Drake02538202001-03-21 18:09:46 +0000295
Steve Purcell15d89272001-04-12 09:05:01 +0000296 def fail(self, msg=None):
297 """Fail immediately, with the given message."""
298 raise self.failureException, msg
Fred Drake02538202001-03-21 18:09:46 +0000299
300 def failIf(self, expr, msg=None):
301 "Fail the test if the expression is true."
Steve Purcell15d89272001-04-12 09:05:01 +0000302 if expr: raise self.failureException, msg
Fred Drake02538202001-03-21 18:09:46 +0000303
Steve Purcell15d89272001-04-12 09:05:01 +0000304 def failUnless(self, expr, msg=None):
305 """Fail the test unless the expression is true."""
306 if not expr: raise self.failureException, msg
307
308 def failUnlessRaises(self, excClass, callableObj, *args, **kwargs):
309 """Fail unless an exception of class excClass is thrown
Fred Drake02538202001-03-21 18:09:46 +0000310 by callableObj when invoked with arguments args and keyword
311 arguments kwargs. If a different type of exception is
312 thrown, it will not be caught, and the test case will be
313 deemed to have suffered an error, exactly as for an
314 unexpected exception.
315 """
316 try:
Guido van Rossum68468eb2003-02-27 20:14:51 +0000317 callableObj(*args, **kwargs)
Fred Drake02538202001-03-21 18:09:46 +0000318 except excClass:
319 return
320 else:
321 if hasattr(excClass,'__name__'): excName = excClass.__name__
322 else: excName = str(excClass)
Steve Purcell7e743842003-09-22 11:08:12 +0000323 raise self.failureException, "%s not raised" % excName
Fred Drake02538202001-03-21 18:09:46 +0000324
Steve Purcell15d89272001-04-12 09:05:01 +0000325 def failUnlessEqual(self, first, second, msg=None):
Raymond Hettingerc377cbf2003-04-04 22:56:42 +0000326 """Fail if the two objects are unequal as determined by the '=='
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000327 operator.
328 """
Raymond Hettingerc377cbf2003-04-04 22:56:42 +0000329 if not first == second:
Steve Purcellca9aaf32001-12-17 10:13:17 +0000330 raise self.failureException, \
Walter Dörwald70a6b492004-02-12 17:35:32 +0000331 (msg or '%r != %r' % (first, second))
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000332
Steve Purcell15d89272001-04-12 09:05:01 +0000333 def failIfEqual(self, first, second, msg=None):
334 """Fail if the two objects are equal as determined by the '=='
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000335 operator.
336 """
Steve Purcell15d89272001-04-12 09:05:01 +0000337 if first == second:
Steve Purcellca9aaf32001-12-17 10:13:17 +0000338 raise self.failureException, \
Walter Dörwald70a6b492004-02-12 17:35:32 +0000339 (msg or '%r == %r' % (first, second))
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000340
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000341 def failUnlessAlmostEqual(self, first, second, places=7, msg=None):
342 """Fail if the two objects are unequal as determined by their
343 difference rounded to the given number of decimal places
344 (default 7) and comparing to zero.
345
Steve Purcell397b45d2003-10-26 10:41:03 +0000346 Note that decimal places (from zero) are usually not the same
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000347 as significant digits (measured from the most signficant digit).
348 """
349 if round(second-first, places) != 0:
350 raise self.failureException, \
Walter Dörwald70a6b492004-02-12 17:35:32 +0000351 (msg or '%r != %r within %r places' % (first, second, places))
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000352
353 def failIfAlmostEqual(self, first, second, places=7, msg=None):
354 """Fail if the two objects are equal as determined by their
355 difference rounded to the given number of decimal places
356 (default 7) and comparing to zero.
357
Steve Purcellcca34912003-10-26 16:38:16 +0000358 Note that decimal places (from zero) are usually not the same
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000359 as significant digits (measured from the most signficant digit).
360 """
361 if round(second-first, places) == 0:
362 raise self.failureException, \
Walter Dörwald70a6b492004-02-12 17:35:32 +0000363 (msg or '%r == %r within %r places' % (first, second, places))
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000364
Steve Purcell7e743842003-09-22 11:08:12 +0000365 # Synonyms for assertion methods
366
Steve Purcell15d89272001-04-12 09:05:01 +0000367 assertEqual = assertEquals = failUnlessEqual
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000368
Steve Purcell15d89272001-04-12 09:05:01 +0000369 assertNotEqual = assertNotEquals = failIfEqual
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000370
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000371 assertAlmostEqual = assertAlmostEquals = failUnlessAlmostEqual
372
373 assertNotAlmostEqual = assertNotAlmostEquals = failIfAlmostEqual
374
Steve Purcell15d89272001-04-12 09:05:01 +0000375 assertRaises = failUnlessRaises
376
Steve Purcell7e743842003-09-22 11:08:12 +0000377 assert_ = assertTrue = failUnless
378
379 assertFalse = failIf
Steve Purcell15d89272001-04-12 09:05:01 +0000380
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000381
Fred Drake02538202001-03-21 18:09:46 +0000382
383class TestSuite:
384 """A test suite is a composite test consisting of a number of TestCases.
385
386 For use, create an instance of TestSuite, then add test case instances.
387 When all tests have been added, the suite can be passed to a test
388 runner, such as TextTestRunner. It will run the individual test cases
389 in the order in which they were added, aggregating the results. When
390 subclassing, do not forget to call the base class constructor.
391 """
392 def __init__(self, tests=()):
393 self._tests = []
394 self.addTests(tests)
395
396 def __repr__(self):
Steve Purcelldc391a62002-08-09 09:46:23 +0000397 return "<%s tests=%s>" % (_strclass(self.__class__), self._tests)
Fred Drake02538202001-03-21 18:09:46 +0000398
399 __str__ = __repr__
400
Jim Fultonfafd8742004-08-28 15:22:12 +0000401 def __iter__(self):
402 return iter(self._tests)
403
Fred Drake02538202001-03-21 18:09:46 +0000404 def countTestCases(self):
405 cases = 0
406 for test in self._tests:
Steve Purcell7e743842003-09-22 11:08:12 +0000407 cases += test.countTestCases()
Fred Drake02538202001-03-21 18:09:46 +0000408 return cases
409
410 def addTest(self, test):
411 self._tests.append(test)
412
413 def addTests(self, tests):
414 for test in tests:
415 self.addTest(test)
416
417 def run(self, result):
Fred Drake02538202001-03-21 18:09:46 +0000418 for test in self._tests:
419 if result.shouldStop:
420 break
421 test(result)
422 return result
423
Raymond Hettinger664347b2004-12-04 21:21:53 +0000424 def __call__(self, *args, **kwds):
425 return self.run(*args, **kwds)
426
Fred Drake02538202001-03-21 18:09:46 +0000427 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000428 """Run the tests without collecting errors in a TestResult"""
Fred Drake02538202001-03-21 18:09:46 +0000429 for test in self._tests: test.debug()
Fred Drake02538202001-03-21 18:09:46 +0000430
431
432class FunctionTestCase(TestCase):
433 """A test case that wraps a test function.
434
435 This is useful for slipping pre-existing test functions into the
436 PyUnit framework. Optionally, set-up and tidy-up functions can be
437 supplied. As with TestCase, the tidy-up ('tearDown') function will
438 always be called if the set-up ('setUp') function ran successfully.
439 """
440
441 def __init__(self, testFunc, setUp=None, tearDown=None,
442 description=None):
443 TestCase.__init__(self)
444 self.__setUpFunc = setUp
445 self.__tearDownFunc = tearDown
446 self.__testFunc = testFunc
447 self.__description = description
448
449 def setUp(self):
450 if self.__setUpFunc is not None:
451 self.__setUpFunc()
452
453 def tearDown(self):
454 if self.__tearDownFunc is not None:
455 self.__tearDownFunc()
456
457 def runTest(self):
458 self.__testFunc()
459
460 def id(self):
461 return self.__testFunc.__name__
462
463 def __str__(self):
Steve Purcelldc391a62002-08-09 09:46:23 +0000464 return "%s (%s)" % (_strclass(self.__class__), self.__testFunc.__name__)
Fred Drake02538202001-03-21 18:09:46 +0000465
466 def __repr__(self):
Steve Purcelldc391a62002-08-09 09:46:23 +0000467 return "<%s testFunc=%s>" % (_strclass(self.__class__), self.__testFunc)
Fred Drake02538202001-03-21 18:09:46 +0000468
469 def shortDescription(self):
470 if self.__description is not None: return self.__description
471 doc = self.__testFunc.__doc__
Steve Purcell7e743842003-09-22 11:08:12 +0000472 return doc and doc.split("\n")[0].strip() or None
Fred Drake02538202001-03-21 18:09:46 +0000473
474
475
476##############################################################################
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000477# Locating and loading tests
Fred Drake02538202001-03-21 18:09:46 +0000478##############################################################################
479
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000480class TestLoader:
481 """This class is responsible for loading tests according to various
482 criteria and returning them wrapped in a Test
Fred Drake02538202001-03-21 18:09:46 +0000483 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000484 testMethodPrefix = 'test'
485 sortTestMethodsUsing = cmp
486 suiteClass = TestSuite
Fred Drake02538202001-03-21 18:09:46 +0000487
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000488 def loadTestsFromTestCase(self, testCaseClass):
Steve Purcell15d89272001-04-12 09:05:01 +0000489 """Return a suite of all tests cases contained in testCaseClass"""
Johannes Gijsbersd7b6ad42004-11-07 15:46:25 +0000490 if issubclass(testCaseClass, TestSuite):
491 raise TypeError("Test cases should not be derived from TestSuite. Maybe you meant to derive from TestCase?")
Steve Purcell7e743842003-09-22 11:08:12 +0000492 testCaseNames = self.getTestCaseNames(testCaseClass)
493 if not testCaseNames and hasattr(testCaseClass, 'runTest'):
494 testCaseNames = ['runTest']
495 return self.suiteClass(map(testCaseClass, testCaseNames))
Fred Drake02538202001-03-21 18:09:46 +0000496
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000497 def loadTestsFromModule(self, module):
Steve Purcell15d89272001-04-12 09:05:01 +0000498 """Return a suite of all tests cases contained in the given module"""
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000499 tests = []
500 for name in dir(module):
501 obj = getattr(module, name)
Guido van Rossum67911372002-09-30 19:25:56 +0000502 if (isinstance(obj, (type, types.ClassType)) and
503 issubclass(obj, TestCase)):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000504 tests.append(self.loadTestsFromTestCase(obj))
505 return self.suiteClass(tests)
Fred Drake02538202001-03-21 18:09:46 +0000506
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000507 def loadTestsFromName(self, name, module=None):
Steve Purcell15d89272001-04-12 09:05:01 +0000508 """Return a suite of all tests cases given a string specifier.
509
510 The name may resolve either to a module, a test case class, a
511 test method within a test case class, or a callable object which
512 returns a TestCase or TestSuite instance.
Tim Peters613b2222001-04-13 05:37:27 +0000513
Steve Purcell15d89272001-04-12 09:05:01 +0000514 The method optionally resolves the names relative to a given module.
515 """
Steve Purcell7e743842003-09-22 11:08:12 +0000516 parts = name.split('.')
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000517 if module is None:
Steve Purcell7e743842003-09-22 11:08:12 +0000518 parts_copy = parts[:]
519 while parts_copy:
520 try:
521 module = __import__('.'.join(parts_copy))
522 break
523 except ImportError:
524 del parts_copy[-1]
525 if not parts_copy: raise
Armin Rigo1b3c04b2003-10-24 17:15:29 +0000526 parts = parts[1:]
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000527 obj = module
528 for part in parts:
Steve Purcell7e743842003-09-22 11:08:12 +0000529 parent, obj = obj, getattr(obj, part)
Fred Drake02538202001-03-21 18:09:46 +0000530
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000531 if type(obj) == types.ModuleType:
532 return self.loadTestsFromModule(obj)
Guido van Rossum67911372002-09-30 19:25:56 +0000533 elif (isinstance(obj, (type, types.ClassType)) and
Steve Purcell397b45d2003-10-26 10:41:03 +0000534 issubclass(obj, TestCase)):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000535 return self.loadTestsFromTestCase(obj)
536 elif type(obj) == types.UnboundMethodType:
Steve Purcell7e743842003-09-22 11:08:12 +0000537 return parent(obj.__name__)
Steve Purcell397b45d2003-10-26 10:41:03 +0000538 elif isinstance(obj, TestSuite):
Steve Purcell7e743842003-09-22 11:08:12 +0000539 return obj
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000540 elif callable(obj):
541 test = obj()
Steve Purcell397b45d2003-10-26 10:41:03 +0000542 if not isinstance(test, (TestCase, TestSuite)):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000543 raise ValueError, \
Steve Purcell4bc80852001-05-10 01:28:40 +0000544 "calling %s returned %s, not a test" % (obj,test)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000545 return test
Fred Drake02538202001-03-21 18:09:46 +0000546 else:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000547 raise ValueError, "don't know how to make test from: %s" % obj
548
549 def loadTestsFromNames(self, names, module=None):
Steve Purcell15d89272001-04-12 09:05:01 +0000550 """Return a suite of all tests cases found using the given sequence
551 of string specifiers. See 'loadTestsFromName()'.
552 """
Steve Purcell7e743842003-09-22 11:08:12 +0000553 suites = [self.loadTestsFromName(name, module) for name in names]
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000554 return self.suiteClass(suites)
555
556 def getTestCaseNames(self, testCaseClass):
Steve Purcell15d89272001-04-12 09:05:01 +0000557 """Return a sorted sequence of method names found within testCaseClass
558 """
Steve Purcell7e743842003-09-22 11:08:12 +0000559 def isTestMethod(attrname, testCaseClass=testCaseClass, prefix=self.testMethodPrefix):
Steve Purcell31982752003-09-23 08:41:53 +0000560 return attrname.startswith(prefix) and callable(getattr(testCaseClass, attrname))
Steve Purcell7e743842003-09-22 11:08:12 +0000561 testFnNames = filter(isTestMethod, dir(testCaseClass))
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000562 for baseclass in testCaseClass.__bases__:
563 for testFnName in self.getTestCaseNames(baseclass):
564 if testFnName not in testFnNames: # handle overridden methods
565 testFnNames.append(testFnName)
566 if self.sortTestMethodsUsing:
567 testFnNames.sort(self.sortTestMethodsUsing)
568 return testFnNames
569
570
571
572defaultTestLoader = TestLoader()
573
574
575##############################################################################
576# Patches for old functions: these functions should be considered obsolete
577##############################################################################
578
579def _makeLoader(prefix, sortUsing, suiteClass=None):
580 loader = TestLoader()
581 loader.sortTestMethodsUsing = sortUsing
582 loader.testMethodPrefix = prefix
583 if suiteClass: loader.suiteClass = suiteClass
584 return loader
585
586def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp):
587 return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)
588
589def makeSuite(testCaseClass, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
590 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
591
592def findTestCases(module, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
593 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module)
Fred Drake02538202001-03-21 18:09:46 +0000594
595
596##############################################################################
597# Text UI
598##############################################################################
599
600class _WritelnDecorator:
601 """Used to decorate file-like objects with a handy 'writeln' method"""
602 def __init__(self,stream):
603 self.stream = stream
Fred Drake02538202001-03-21 18:09:46 +0000604
605 def __getattr__(self, attr):
606 return getattr(self.stream,attr)
607
Raymond Hettinger91dd19d2003-09-13 02:58:00 +0000608 def writeln(self, arg=None):
609 if arg: self.write(arg)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000610 self.write('\n') # text-mode streams translate to \r\n if needed
Tim Petersa19a1682001-03-29 04:36:09 +0000611
Fred Drake02538202001-03-21 18:09:46 +0000612
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000613class _TextTestResult(TestResult):
Fred Drake02538202001-03-21 18:09:46 +0000614 """A test result class that can print formatted text results to a stream.
615
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000616 Used by TextTestRunner.
Fred Drake02538202001-03-21 18:09:46 +0000617 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000618 separator1 = '=' * 70
619 separator2 = '-' * 70
Fred Drake02538202001-03-21 18:09:46 +0000620
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000621 def __init__(self, stream, descriptions, verbosity):
Fred Drake02538202001-03-21 18:09:46 +0000622 TestResult.__init__(self)
623 self.stream = stream
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000624 self.showAll = verbosity > 1
625 self.dots = verbosity == 1
Fred Drake02538202001-03-21 18:09:46 +0000626 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000627
628 def getDescription(self, test):
629 if self.descriptions:
630 return test.shortDescription() or str(test)
631 else:
632 return str(test)
633
Fred Drake02538202001-03-21 18:09:46 +0000634 def startTest(self, test):
635 TestResult.startTest(self, test)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000636 if self.showAll:
637 self.stream.write(self.getDescription(test))
638 self.stream.write(" ... ")
Fred Drake02538202001-03-21 18:09:46 +0000639
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000640 def addSuccess(self, test):
641 TestResult.addSuccess(self, test)
642 if self.showAll:
Fred Drake02538202001-03-21 18:09:46 +0000643 self.stream.writeln("ok")
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000644 elif self.dots:
645 self.stream.write('.')
Fred Drake02538202001-03-21 18:09:46 +0000646
647 def addError(self, test, err):
648 TestResult.addError(self, test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000649 if self.showAll:
650 self.stream.writeln("ERROR")
651 elif self.dots:
652 self.stream.write('E')
Fred Drake02538202001-03-21 18:09:46 +0000653
654 def addFailure(self, test, err):
655 TestResult.addFailure(self, test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000656 if self.showAll:
657 self.stream.writeln("FAIL")
658 elif self.dots:
659 self.stream.write('F')
Fred Drake02538202001-03-21 18:09:46 +0000660
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000661 def printErrors(self):
662 if self.dots or self.showAll:
Fred Drake02538202001-03-21 18:09:46 +0000663 self.stream.writeln()
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000664 self.printErrorList('ERROR', self.errors)
665 self.printErrorList('FAIL', self.failures)
666
667 def printErrorList(self, flavour, errors):
668 for test, err in errors:
669 self.stream.writeln(self.separator1)
670 self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
671 self.stream.writeln(self.separator2)
Steve Purcell7b065702001-09-06 08:24:40 +0000672 self.stream.writeln("%s" % err)
Fred Drake02538202001-03-21 18:09:46 +0000673
674
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000675class TextTestRunner:
Fred Drake02538202001-03-21 18:09:46 +0000676 """A test runner class that displays results in textual form.
Tim Petersa19a1682001-03-29 04:36:09 +0000677
Fred Drake02538202001-03-21 18:09:46 +0000678 It prints out the names of tests as they are run, errors as they
679 occur, and a summary of the results at the end of the test run.
680 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000681 def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1):
Fred Drake02538202001-03-21 18:09:46 +0000682 self.stream = _WritelnDecorator(stream)
683 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000684 self.verbosity = verbosity
685
686 def _makeResult(self):
687 return _TextTestResult(self.stream, self.descriptions, self.verbosity)
Fred Drake02538202001-03-21 18:09:46 +0000688
689 def run(self, test):
690 "Run the given test case or test suite."
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000691 result = self._makeResult()
Fred Drake02538202001-03-21 18:09:46 +0000692 startTime = time.time()
693 test(result)
694 stopTime = time.time()
Steve Purcell397b45d2003-10-26 10:41:03 +0000695 timeTaken = stopTime - startTime
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000696 result.printErrors()
697 self.stream.writeln(result.separator2)
Fred Drake02538202001-03-21 18:09:46 +0000698 run = result.testsRun
699 self.stream.writeln("Ran %d test%s in %.3fs" %
Neal Norwitz76165042002-05-31 14:15:11 +0000700 (run, run != 1 and "s" or "", timeTaken))
Fred Drake02538202001-03-21 18:09:46 +0000701 self.stream.writeln()
702 if not result.wasSuccessful():
703 self.stream.write("FAILED (")
704 failed, errored = map(len, (result.failures, result.errors))
705 if failed:
706 self.stream.write("failures=%d" % failed)
707 if errored:
708 if failed: self.stream.write(", ")
709 self.stream.write("errors=%d" % errored)
710 self.stream.writeln(")")
711 else:
712 self.stream.writeln("OK")
713 return result
Tim Petersa19a1682001-03-29 04:36:09 +0000714
Fred Drake02538202001-03-21 18:09:46 +0000715
Fred Drake02538202001-03-21 18:09:46 +0000716
717##############################################################################
718# Facilities for running tests from the command line
719##############################################################################
720
721class TestProgram:
722 """A command-line program that runs a set of tests; this is primarily
723 for making test modules conveniently executable.
724 """
725 USAGE = """\
Steve Purcell17a781b2001-04-09 15:37:31 +0000726Usage: %(progName)s [options] [test] [...]
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000727
728Options:
729 -h, --help Show this message
730 -v, --verbose Verbose output
731 -q, --quiet Minimal output
Fred Drake02538202001-03-21 18:09:46 +0000732
733Examples:
734 %(progName)s - run default set of tests
735 %(progName)s MyTestSuite - run suite 'MyTestSuite'
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000736 %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething
737 %(progName)s MyTestCase - run all 'test*' test methods
Fred Drake02538202001-03-21 18:09:46 +0000738 in MyTestCase
739"""
740 def __init__(self, module='__main__', defaultTest=None,
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000741 argv=None, testRunner=None, testLoader=defaultTestLoader):
Fred Drake02538202001-03-21 18:09:46 +0000742 if type(module) == type(''):
743 self.module = __import__(module)
Steve Purcell7e743842003-09-22 11:08:12 +0000744 for part in module.split('.')[1:]:
Fred Drake02538202001-03-21 18:09:46 +0000745 self.module = getattr(self.module, part)
746 else:
747 self.module = module
748 if argv is None:
749 argv = sys.argv
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000750 self.verbosity = 1
Fred Drake02538202001-03-21 18:09:46 +0000751 self.defaultTest = defaultTest
752 self.testRunner = testRunner
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000753 self.testLoader = testLoader
Fred Drake02538202001-03-21 18:09:46 +0000754 self.progName = os.path.basename(argv[0])
755 self.parseArgs(argv)
Fred Drake02538202001-03-21 18:09:46 +0000756 self.runTests()
757
758 def usageExit(self, msg=None):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000759 if msg: print(msg)
760 print(self.USAGE % self.__dict__)
Fred Drake02538202001-03-21 18:09:46 +0000761 sys.exit(2)
762
763 def parseArgs(self, argv):
764 import getopt
765 try:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000766 options, args = getopt.getopt(argv[1:], 'hHvq',
767 ['help','verbose','quiet'])
Fred Drake02538202001-03-21 18:09:46 +0000768 for opt, value in options:
769 if opt in ('-h','-H','--help'):
770 self.usageExit()
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000771 if opt in ('-q','--quiet'):
772 self.verbosity = 0
773 if opt in ('-v','--verbose'):
774 self.verbosity = 2
Fred Drake02538202001-03-21 18:09:46 +0000775 if len(args) == 0 and self.defaultTest is None:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000776 self.test = self.testLoader.loadTestsFromModule(self.module)
777 return
Fred Drake02538202001-03-21 18:09:46 +0000778 if len(args) > 0:
779 self.testNames = args
780 else:
781 self.testNames = (self.defaultTest,)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000782 self.createTests()
Guido van Rossumb940e112007-01-10 16:19:56 +0000783 except getopt.error as msg:
Fred Drake02538202001-03-21 18:09:46 +0000784 self.usageExit(msg)
785
786 def createTests(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000787 self.test = self.testLoader.loadTestsFromNames(self.testNames,
788 self.module)
Fred Drake02538202001-03-21 18:09:46 +0000789
790 def runTests(self):
791 if self.testRunner is None:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000792 self.testRunner = TextTestRunner(verbosity=self.verbosity)
Fred Drake02538202001-03-21 18:09:46 +0000793 result = self.testRunner.run(self.test)
Tim Petersa19a1682001-03-29 04:36:09 +0000794 sys.exit(not result.wasSuccessful())
Fred Drake02538202001-03-21 18:09:46 +0000795
796main = TestProgram
797
798
799##############################################################################
800# Executing this module from the command line
801##############################################################################
802
803if __name__ == "__main__":
804 main(module=None)