blob: 10108d33ea3310a76e8648594e2ae20cae0c7b08 [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 Purcellcca34912003-10-26 16:38:16 +000049__version__ = "#Revision: 1.62 $"[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__
74 if type(clsinfo) in (types.TupleType, types.ListType):
75 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 Purcell824574d2002-08-08 13:38:02 +000087# All classes defined herein are 'new-style' classes, allowing use of 'super()'
88__metaclass__ = type
89
Steve Purcelldc391a62002-08-09 09:46:23 +000090def _strclass(cls):
91 return "%s.%s" % (cls.__module__, cls.__name__)
92
Fred Drake02538202001-03-21 18:09:46 +000093class TestResult:
94 """Holder for test result information.
95
96 Test results are automatically managed by the TestCase and TestSuite
97 classes, and do not need to be explicitly manipulated by writers of tests.
98
99 Each instance holds the total number of tests run, and collections of
100 failures and errors that occurred among those test runs. The collections
Steve Purcell7b065702001-09-06 08:24:40 +0000101 contain tuples of (testcase, exceptioninfo), where exceptioninfo is the
Fred Drake656f9ec2001-09-06 19:13:14 +0000102 formatted traceback of the error that occurred.
Fred Drake02538202001-03-21 18:09:46 +0000103 """
104 def __init__(self):
105 self.failures = []
106 self.errors = []
107 self.testsRun = 0
108 self.shouldStop = 0
109
110 def startTest(self, test):
111 "Called when the given test is about to be run"
112 self.testsRun = self.testsRun + 1
113
114 def stopTest(self, test):
115 "Called when the given test has been run"
116 pass
117
118 def addError(self, test, err):
Steve Purcell7b065702001-09-06 08:24:40 +0000119 """Called when an error has occurred. 'err' is a tuple of values as
120 returned by sys.exc_info().
121 """
122 self.errors.append((test, self._exc_info_to_string(err)))
Fred Drake02538202001-03-21 18:09:46 +0000123
124 def addFailure(self, test, err):
Steve Purcell7b065702001-09-06 08:24:40 +0000125 """Called when an error has occurred. 'err' is a tuple of values as
126 returned by sys.exc_info()."""
127 self.failures.append((test, self._exc_info_to_string(err)))
Fred Drake02538202001-03-21 18:09:46 +0000128
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000129 def addSuccess(self, test):
130 "Called when a test has completed successfully"
131 pass
132
Fred Drake02538202001-03-21 18:09:46 +0000133 def wasSuccessful(self):
134 "Tells whether or not this result was a success"
135 return len(self.failures) == len(self.errors) == 0
136
137 def stop(self):
138 "Indicates that the tests should be aborted"
Steve Purcell7e743842003-09-22 11:08:12 +0000139 self.shouldStop = True
Tim Petersa19a1682001-03-29 04:36:09 +0000140
Steve Purcell7b065702001-09-06 08:24:40 +0000141 def _exc_info_to_string(self, err):
142 """Converts a sys.exc_info()-style tuple of values into a string."""
Steve Purcell7e743842003-09-22 11:08:12 +0000143 return ''.join(traceback.format_exception(*err))
Steve Purcell7b065702001-09-06 08:24:40 +0000144
Fred Drake02538202001-03-21 18:09:46 +0000145 def __repr__(self):
146 return "<%s run=%i errors=%i failures=%i>" % \
Steve Purcelldc391a62002-08-09 09:46:23 +0000147 (_strclass(self.__class__), self.testsRun, len(self.errors),
Fred Drake02538202001-03-21 18:09:46 +0000148 len(self.failures))
149
150
151class TestCase:
152 """A class whose instances are single test cases.
153
Fred Drake02538202001-03-21 18:09:46 +0000154 By default, the test code itself should be placed in a method named
155 'runTest'.
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000156
Tim Petersa19a1682001-03-29 04:36:09 +0000157 If the fixture may be used for many test cases, create as
Fred Drake02538202001-03-21 18:09:46 +0000158 many test methods as are needed. When instantiating such a TestCase
159 subclass, specify in the constructor arguments the name of the test method
160 that the instance is to execute.
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000161
Tim Petersa19a1682001-03-29 04:36:09 +0000162 Test authors should subclass TestCase for their own tests. Construction
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000163 and deconstruction of the test's environment ('fixture') can be
164 implemented by overriding the 'setUp' and 'tearDown' methods respectively.
165
166 If it is necessary to override the __init__ method, the base class
167 __init__ method must always be called. It is important that subclasses
168 should not change the signature of their __init__ method, since instances
169 of the classes are instantiated automatically by parts of the framework
170 in order to be run.
Fred Drake02538202001-03-21 18:09:46 +0000171 """
Steve Purcell15d89272001-04-12 09:05:01 +0000172
173 # This attribute determines which exception will be raised when
174 # the instance's assertion methods fail; test methods raising this
175 # exception will be deemed to have 'failed' rather than 'errored'
176
177 failureException = AssertionError
178
Fred Drake02538202001-03-21 18:09:46 +0000179 def __init__(self, methodName='runTest'):
180 """Create an instance of the class that will use the named test
181 method when executed. Raises a ValueError if the instance does
182 not have a method with the specified name.
183 """
184 try:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000185 self.__testMethodName = methodName
186 testMethod = getattr(self, methodName)
187 self.__testMethodDoc = testMethod.__doc__
Fred Drake02538202001-03-21 18:09:46 +0000188 except AttributeError:
189 raise ValueError, "no such test method in %s: %s" % \
190 (self.__class__, methodName)
191
192 def setUp(self):
193 "Hook method for setting up the test fixture before exercising it."
194 pass
195
196 def tearDown(self):
197 "Hook method for deconstructing the test fixture after testing it."
198 pass
199
200 def countTestCases(self):
201 return 1
202
203 def defaultTestResult(self):
204 return TestResult()
205
206 def shortDescription(self):
207 """Returns a one-line description of the test, or None if no
208 description has been provided.
209
210 The default implementation of this method returns the first line of
211 the specified test method's docstring.
212 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000213 doc = self.__testMethodDoc
Steve Purcell7e743842003-09-22 11:08:12 +0000214 return doc and doc.split("\n")[0].strip() or None
Fred Drake02538202001-03-21 18:09:46 +0000215
216 def id(self):
Steve Purcelldc391a62002-08-09 09:46:23 +0000217 return "%s.%s" % (_strclass(self.__class__), self.__testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000218
219 def __str__(self):
Jeremy Hylton22dae282002-08-13 20:43:46 +0000220 return "%s (%s)" % (self.__testMethodName, _strclass(self.__class__))
Fred Drake02538202001-03-21 18:09:46 +0000221
222 def __repr__(self):
223 return "<%s testMethod=%s>" % \
Steve Purcelldc391a62002-08-09 09:46:23 +0000224 (_strclass(self.__class__), self.__testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000225
226 def run(self, result=None):
Fred Drake02538202001-03-21 18:09:46 +0000227 if result is None: result = self.defaultTestResult()
228 result.startTest(self)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000229 testMethod = getattr(self, self.__testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000230 try:
231 try:
232 self.setUp()
Guido van Rossum202dd1e2001-12-07 03:39:34 +0000233 except KeyboardInterrupt:
234 raise
Fred Drake02538202001-03-21 18:09:46 +0000235 except:
Jeremy Hyltonefef5da2001-10-22 18:14:15 +0000236 result.addError(self, self.__exc_info())
Fred Drake02538202001-03-21 18:09:46 +0000237 return
238
Steve Purcell7e743842003-09-22 11:08:12 +0000239 ok = False
Fred Drake02538202001-03-21 18:09:46 +0000240 try:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000241 testMethod()
Steve Purcell7e743842003-09-22 11:08:12 +0000242 ok = True
Skip Montanaroae5c37b2003-07-13 15:18:12 +0000243 except self.failureException:
Jeremy Hyltonefef5da2001-10-22 18:14:15 +0000244 result.addFailure(self, self.__exc_info())
Guido van Rossum202dd1e2001-12-07 03:39:34 +0000245 except KeyboardInterrupt:
246 raise
Fred Drake02538202001-03-21 18:09:46 +0000247 except:
Jeremy Hyltonefef5da2001-10-22 18:14:15 +0000248 result.addError(self, self.__exc_info())
Fred Drake02538202001-03-21 18:09:46 +0000249
250 try:
251 self.tearDown()
Guido van Rossum202dd1e2001-12-07 03:39:34 +0000252 except KeyboardInterrupt:
253 raise
Fred Drake02538202001-03-21 18:09:46 +0000254 except:
Jeremy Hyltonefef5da2001-10-22 18:14:15 +0000255 result.addError(self, self.__exc_info())
Steve Purcell7e743842003-09-22 11:08:12 +0000256 ok = False
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000257 if ok: result.addSuccess(self)
Fred Drake02538202001-03-21 18:09:46 +0000258 finally:
259 result.stopTest(self)
260
Steve Purcell7e743842003-09-22 11:08:12 +0000261 __call__ = run
262
Fred Drake02538202001-03-21 18:09:46 +0000263 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000264 """Run the test without collecting errors in a TestResult"""
Fred Drake02538202001-03-21 18:09:46 +0000265 self.setUp()
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000266 getattr(self, self.__testMethodName)()
Fred Drake02538202001-03-21 18:09:46 +0000267 self.tearDown()
268
Steve Purcell15d89272001-04-12 09:05:01 +0000269 def __exc_info(self):
270 """Return a version of sys.exc_info() with the traceback frame
271 minimised; usually the top level of the traceback frame is not
272 needed.
Fred Drake02538202001-03-21 18:09:46 +0000273 """
Steve Purcell15d89272001-04-12 09:05:01 +0000274 exctype, excvalue, tb = sys.exc_info()
275 if sys.platform[:4] == 'java': ## tracebacks look different in Jython
276 return (exctype, excvalue, tb)
277 newtb = tb.tb_next
278 if newtb is None:
279 return (exctype, excvalue, tb)
280 return (exctype, excvalue, newtb)
Fred Drake02538202001-03-21 18:09:46 +0000281
Steve Purcell15d89272001-04-12 09:05:01 +0000282 def fail(self, msg=None):
283 """Fail immediately, with the given message."""
284 raise self.failureException, msg
Fred Drake02538202001-03-21 18:09:46 +0000285
286 def failIf(self, expr, msg=None):
287 "Fail the test if the expression is true."
Steve Purcell15d89272001-04-12 09:05:01 +0000288 if expr: raise self.failureException, msg
Fred Drake02538202001-03-21 18:09:46 +0000289
Steve Purcell15d89272001-04-12 09:05:01 +0000290 def failUnless(self, expr, msg=None):
291 """Fail the test unless the expression is true."""
292 if not expr: raise self.failureException, msg
293
294 def failUnlessRaises(self, excClass, callableObj, *args, **kwargs):
295 """Fail unless an exception of class excClass is thrown
Fred Drake02538202001-03-21 18:09:46 +0000296 by callableObj when invoked with arguments args and keyword
297 arguments kwargs. If a different type of exception is
298 thrown, it will not be caught, and the test case will be
299 deemed to have suffered an error, exactly as for an
300 unexpected exception.
301 """
302 try:
Guido van Rossum68468eb2003-02-27 20:14:51 +0000303 callableObj(*args, **kwargs)
Fred Drake02538202001-03-21 18:09:46 +0000304 except excClass:
305 return
306 else:
307 if hasattr(excClass,'__name__'): excName = excClass.__name__
308 else: excName = str(excClass)
Steve Purcell7e743842003-09-22 11:08:12 +0000309 raise self.failureException, "%s not raised" % excName
Fred Drake02538202001-03-21 18:09:46 +0000310
Steve Purcell15d89272001-04-12 09:05:01 +0000311 def failUnlessEqual(self, first, second, msg=None):
Raymond Hettingerc377cbf2003-04-04 22:56:42 +0000312 """Fail if the two objects are unequal as determined by the '=='
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000313 operator.
314 """
Raymond Hettingerc377cbf2003-04-04 22:56:42 +0000315 if not first == second:
Steve Purcellca9aaf32001-12-17 10:13:17 +0000316 raise self.failureException, \
317 (msg or '%s != %s' % (`first`, `second`))
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000318
Steve Purcell15d89272001-04-12 09:05:01 +0000319 def failIfEqual(self, first, second, msg=None):
320 """Fail if the two objects are equal as determined by the '=='
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000321 operator.
322 """
Steve Purcell15d89272001-04-12 09:05:01 +0000323 if first == second:
Steve Purcellca9aaf32001-12-17 10:13:17 +0000324 raise self.failureException, \
325 (msg or '%s == %s' % (`first`, `second`))
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000326
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000327 def failUnlessAlmostEqual(self, first, second, places=7, msg=None):
328 """Fail if the two objects are unequal as determined by their
329 difference rounded to the given number of decimal places
330 (default 7) and comparing to zero.
331
Steve Purcell397b45d2003-10-26 10:41:03 +0000332 Note that decimal places (from zero) are usually not the same
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000333 as significant digits (measured from the most signficant digit).
334 """
335 if round(second-first, places) != 0:
336 raise self.failureException, \
337 (msg or '%s != %s within %s places' % (`first`, `second`, `places` ))
338
339 def failIfAlmostEqual(self, first, second, places=7, msg=None):
340 """Fail if the two objects are equal as determined by their
341 difference rounded to the given number of decimal places
342 (default 7) and comparing to zero.
343
Steve Purcellcca34912003-10-26 16:38:16 +0000344 Note that decimal places (from zero) are usually not the same
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000345 as significant digits (measured from the most signficant digit).
346 """
347 if round(second-first, places) == 0:
348 raise self.failureException, \
349 (msg or '%s == %s within %s places' % (`first`, `second`, `places`))
350
Steve Purcell7e743842003-09-22 11:08:12 +0000351 # Synonyms for assertion methods
352
Steve Purcell15d89272001-04-12 09:05:01 +0000353 assertEqual = assertEquals = failUnlessEqual
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000354
Steve Purcell15d89272001-04-12 09:05:01 +0000355 assertNotEqual = assertNotEquals = failIfEqual
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000356
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000357 assertAlmostEqual = assertAlmostEquals = failUnlessAlmostEqual
358
359 assertNotAlmostEqual = assertNotAlmostEquals = failIfAlmostEqual
360
Steve Purcell15d89272001-04-12 09:05:01 +0000361 assertRaises = failUnlessRaises
362
Steve Purcell7e743842003-09-22 11:08:12 +0000363 assert_ = assertTrue = failUnless
364
365 assertFalse = failIf
Steve Purcell15d89272001-04-12 09:05:01 +0000366
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000367
Fred Drake02538202001-03-21 18:09:46 +0000368
369class TestSuite:
370 """A test suite is a composite test consisting of a number of TestCases.
371
372 For use, create an instance of TestSuite, then add test case instances.
373 When all tests have been added, the suite can be passed to a test
374 runner, such as TextTestRunner. It will run the individual test cases
375 in the order in which they were added, aggregating the results. When
376 subclassing, do not forget to call the base class constructor.
377 """
378 def __init__(self, tests=()):
379 self._tests = []
380 self.addTests(tests)
381
382 def __repr__(self):
Steve Purcelldc391a62002-08-09 09:46:23 +0000383 return "<%s tests=%s>" % (_strclass(self.__class__), self._tests)
Fred Drake02538202001-03-21 18:09:46 +0000384
385 __str__ = __repr__
386
387 def countTestCases(self):
388 cases = 0
389 for test in self._tests:
Steve Purcell7e743842003-09-22 11:08:12 +0000390 cases += test.countTestCases()
Fred Drake02538202001-03-21 18:09:46 +0000391 return cases
392
393 def addTest(self, test):
394 self._tests.append(test)
395
396 def addTests(self, tests):
397 for test in tests:
398 self.addTest(test)
399
400 def run(self, result):
401 return self(result)
402
403 def __call__(self, result):
404 for test in self._tests:
405 if result.shouldStop:
406 break
407 test(result)
408 return result
409
410 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000411 """Run the tests without collecting errors in a TestResult"""
Fred Drake02538202001-03-21 18:09:46 +0000412 for test in self._tests: test.debug()
Fred Drake02538202001-03-21 18:09:46 +0000413
414
415class FunctionTestCase(TestCase):
416 """A test case that wraps a test function.
417
418 This is useful for slipping pre-existing test functions into the
419 PyUnit framework. Optionally, set-up and tidy-up functions can be
420 supplied. As with TestCase, the tidy-up ('tearDown') function will
421 always be called if the set-up ('setUp') function ran successfully.
422 """
423
424 def __init__(self, testFunc, setUp=None, tearDown=None,
425 description=None):
426 TestCase.__init__(self)
427 self.__setUpFunc = setUp
428 self.__tearDownFunc = tearDown
429 self.__testFunc = testFunc
430 self.__description = description
431
432 def setUp(self):
433 if self.__setUpFunc is not None:
434 self.__setUpFunc()
435
436 def tearDown(self):
437 if self.__tearDownFunc is not None:
438 self.__tearDownFunc()
439
440 def runTest(self):
441 self.__testFunc()
442
443 def id(self):
444 return self.__testFunc.__name__
445
446 def __str__(self):
Steve Purcelldc391a62002-08-09 09:46:23 +0000447 return "%s (%s)" % (_strclass(self.__class__), self.__testFunc.__name__)
Fred Drake02538202001-03-21 18:09:46 +0000448
449 def __repr__(self):
Steve Purcelldc391a62002-08-09 09:46:23 +0000450 return "<%s testFunc=%s>" % (_strclass(self.__class__), self.__testFunc)
Fred Drake02538202001-03-21 18:09:46 +0000451
452 def shortDescription(self):
453 if self.__description is not None: return self.__description
454 doc = self.__testFunc.__doc__
Steve Purcell7e743842003-09-22 11:08:12 +0000455 return doc and doc.split("\n")[0].strip() or None
Fred Drake02538202001-03-21 18:09:46 +0000456
457
458
459##############################################################################
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000460# Locating and loading tests
Fred Drake02538202001-03-21 18:09:46 +0000461##############################################################################
462
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000463class TestLoader:
464 """This class is responsible for loading tests according to various
465 criteria and returning them wrapped in a Test
Fred Drake02538202001-03-21 18:09:46 +0000466 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000467 testMethodPrefix = 'test'
468 sortTestMethodsUsing = cmp
469 suiteClass = TestSuite
Fred Drake02538202001-03-21 18:09:46 +0000470
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000471 def loadTestsFromTestCase(self, testCaseClass):
Steve Purcell15d89272001-04-12 09:05:01 +0000472 """Return a suite of all tests cases contained in testCaseClass"""
Steve Purcell7e743842003-09-22 11:08:12 +0000473 testCaseNames = self.getTestCaseNames(testCaseClass)
474 if not testCaseNames and hasattr(testCaseClass, 'runTest'):
475 testCaseNames = ['runTest']
476 return self.suiteClass(map(testCaseClass, testCaseNames))
Fred Drake02538202001-03-21 18:09:46 +0000477
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000478 def loadTestsFromModule(self, module):
Steve Purcell15d89272001-04-12 09:05:01 +0000479 """Return a suite of all tests cases contained in the given module"""
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000480 tests = []
481 for name in dir(module):
482 obj = getattr(module, name)
Guido van Rossum67911372002-09-30 19:25:56 +0000483 if (isinstance(obj, (type, types.ClassType)) and
484 issubclass(obj, TestCase)):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000485 tests.append(self.loadTestsFromTestCase(obj))
486 return self.suiteClass(tests)
Fred Drake02538202001-03-21 18:09:46 +0000487
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000488 def loadTestsFromName(self, name, module=None):
Steve Purcell15d89272001-04-12 09:05:01 +0000489 """Return a suite of all tests cases given a string specifier.
490
491 The name may resolve either to a module, a test case class, a
492 test method within a test case class, or a callable object which
493 returns a TestCase or TestSuite instance.
Tim Peters613b2222001-04-13 05:37:27 +0000494
Steve Purcell15d89272001-04-12 09:05:01 +0000495 The method optionally resolves the names relative to a given module.
496 """
Steve Purcell7e743842003-09-22 11:08:12 +0000497 parts = name.split('.')
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000498 if module is None:
Steve Purcell7e743842003-09-22 11:08:12 +0000499 parts_copy = parts[:]
500 while parts_copy:
501 try:
502 module = __import__('.'.join(parts_copy))
503 break
504 except ImportError:
505 del parts_copy[-1]
506 if not parts_copy: raise
Armin Rigo1b3c04b2003-10-24 17:15:29 +0000507 parts = parts[1:]
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000508 obj = module
509 for part in parts:
Steve Purcell7e743842003-09-22 11:08:12 +0000510 parent, obj = obj, getattr(obj, part)
Fred Drake02538202001-03-21 18:09:46 +0000511
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000512 if type(obj) == types.ModuleType:
513 return self.loadTestsFromModule(obj)
Guido van Rossum67911372002-09-30 19:25:56 +0000514 elif (isinstance(obj, (type, types.ClassType)) and
Steve Purcell397b45d2003-10-26 10:41:03 +0000515 issubclass(obj, TestCase)):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000516 return self.loadTestsFromTestCase(obj)
517 elif type(obj) == types.UnboundMethodType:
Steve Purcell7e743842003-09-22 11:08:12 +0000518 return parent(obj.__name__)
Steve Purcell397b45d2003-10-26 10:41:03 +0000519 elif isinstance(obj, TestSuite):
Steve Purcell7e743842003-09-22 11:08:12 +0000520 return obj
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000521 elif callable(obj):
522 test = obj()
Steve Purcell397b45d2003-10-26 10:41:03 +0000523 if not isinstance(test, (TestCase, TestSuite)):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000524 raise ValueError, \
Steve Purcell4bc80852001-05-10 01:28:40 +0000525 "calling %s returned %s, not a test" % (obj,test)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000526 return test
Fred Drake02538202001-03-21 18:09:46 +0000527 else:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000528 raise ValueError, "don't know how to make test from: %s" % obj
529
530 def loadTestsFromNames(self, names, module=None):
Steve Purcell15d89272001-04-12 09:05:01 +0000531 """Return a suite of all tests cases found using the given sequence
532 of string specifiers. See 'loadTestsFromName()'.
533 """
Steve Purcell7e743842003-09-22 11:08:12 +0000534 suites = [self.loadTestsFromName(name, module) for name in names]
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000535 return self.suiteClass(suites)
536
537 def getTestCaseNames(self, testCaseClass):
Steve Purcell15d89272001-04-12 09:05:01 +0000538 """Return a sorted sequence of method names found within testCaseClass
539 """
Steve Purcell7e743842003-09-22 11:08:12 +0000540 def isTestMethod(attrname, testCaseClass=testCaseClass, prefix=self.testMethodPrefix):
Steve Purcell31982752003-09-23 08:41:53 +0000541 return attrname.startswith(prefix) and callable(getattr(testCaseClass, attrname))
Steve Purcell7e743842003-09-22 11:08:12 +0000542 testFnNames = filter(isTestMethod, dir(testCaseClass))
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000543 for baseclass in testCaseClass.__bases__:
544 for testFnName in self.getTestCaseNames(baseclass):
545 if testFnName not in testFnNames: # handle overridden methods
546 testFnNames.append(testFnName)
547 if self.sortTestMethodsUsing:
548 testFnNames.sort(self.sortTestMethodsUsing)
549 return testFnNames
550
551
552
553defaultTestLoader = TestLoader()
554
555
556##############################################################################
557# Patches for old functions: these functions should be considered obsolete
558##############################################################################
559
560def _makeLoader(prefix, sortUsing, suiteClass=None):
561 loader = TestLoader()
562 loader.sortTestMethodsUsing = sortUsing
563 loader.testMethodPrefix = prefix
564 if suiteClass: loader.suiteClass = suiteClass
565 return loader
566
567def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp):
568 return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)
569
570def makeSuite(testCaseClass, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
571 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
572
573def findTestCases(module, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
574 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module)
Fred Drake02538202001-03-21 18:09:46 +0000575
576
577##############################################################################
578# Text UI
579##############################################################################
580
581class _WritelnDecorator:
582 """Used to decorate file-like objects with a handy 'writeln' method"""
583 def __init__(self,stream):
584 self.stream = stream
Fred Drake02538202001-03-21 18:09:46 +0000585
586 def __getattr__(self, attr):
587 return getattr(self.stream,attr)
588
Raymond Hettinger91dd19d2003-09-13 02:58:00 +0000589 def writeln(self, arg=None):
590 if arg: self.write(arg)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000591 self.write('\n') # text-mode streams translate to \r\n if needed
Tim Petersa19a1682001-03-29 04:36:09 +0000592
Fred Drake02538202001-03-21 18:09:46 +0000593
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000594class _TextTestResult(TestResult):
Fred Drake02538202001-03-21 18:09:46 +0000595 """A test result class that can print formatted text results to a stream.
596
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000597 Used by TextTestRunner.
Fred Drake02538202001-03-21 18:09:46 +0000598 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000599 separator1 = '=' * 70
600 separator2 = '-' * 70
Fred Drake02538202001-03-21 18:09:46 +0000601
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000602 def __init__(self, stream, descriptions, verbosity):
Fred Drake02538202001-03-21 18:09:46 +0000603 TestResult.__init__(self)
604 self.stream = stream
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000605 self.showAll = verbosity > 1
606 self.dots = verbosity == 1
Fred Drake02538202001-03-21 18:09:46 +0000607 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000608
609 def getDescription(self, test):
610 if self.descriptions:
611 return test.shortDescription() or str(test)
612 else:
613 return str(test)
614
Fred Drake02538202001-03-21 18:09:46 +0000615 def startTest(self, test):
616 TestResult.startTest(self, test)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000617 if self.showAll:
618 self.stream.write(self.getDescription(test))
619 self.stream.write(" ... ")
Fred Drake02538202001-03-21 18:09:46 +0000620
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000621 def addSuccess(self, test):
622 TestResult.addSuccess(self, test)
623 if self.showAll:
Fred Drake02538202001-03-21 18:09:46 +0000624 self.stream.writeln("ok")
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000625 elif self.dots:
626 self.stream.write('.')
Fred Drake02538202001-03-21 18:09:46 +0000627
628 def addError(self, test, err):
629 TestResult.addError(self, test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000630 if self.showAll:
631 self.stream.writeln("ERROR")
632 elif self.dots:
633 self.stream.write('E')
Fred Drake02538202001-03-21 18:09:46 +0000634
635 def addFailure(self, test, err):
636 TestResult.addFailure(self, test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000637 if self.showAll:
638 self.stream.writeln("FAIL")
639 elif self.dots:
640 self.stream.write('F')
Fred Drake02538202001-03-21 18:09:46 +0000641
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000642 def printErrors(self):
643 if self.dots or self.showAll:
Fred Drake02538202001-03-21 18:09:46 +0000644 self.stream.writeln()
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000645 self.printErrorList('ERROR', self.errors)
646 self.printErrorList('FAIL', self.failures)
647
648 def printErrorList(self, flavour, errors):
649 for test, err in errors:
650 self.stream.writeln(self.separator1)
651 self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
652 self.stream.writeln(self.separator2)
Steve Purcell7b065702001-09-06 08:24:40 +0000653 self.stream.writeln("%s" % err)
Fred Drake02538202001-03-21 18:09:46 +0000654
655
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000656class TextTestRunner:
Fred Drake02538202001-03-21 18:09:46 +0000657 """A test runner class that displays results in textual form.
Tim Petersa19a1682001-03-29 04:36:09 +0000658
Fred Drake02538202001-03-21 18:09:46 +0000659 It prints out the names of tests as they are run, errors as they
660 occur, and a summary of the results at the end of the test run.
661 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000662 def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1):
Fred Drake02538202001-03-21 18:09:46 +0000663 self.stream = _WritelnDecorator(stream)
664 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000665 self.verbosity = verbosity
666
667 def _makeResult(self):
668 return _TextTestResult(self.stream, self.descriptions, self.verbosity)
Fred Drake02538202001-03-21 18:09:46 +0000669
670 def run(self, test):
671 "Run the given test case or test suite."
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000672 result = self._makeResult()
Fred Drake02538202001-03-21 18:09:46 +0000673 startTime = time.time()
674 test(result)
675 stopTime = time.time()
Steve Purcell397b45d2003-10-26 10:41:03 +0000676 timeTaken = stopTime - startTime
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000677 result.printErrors()
678 self.stream.writeln(result.separator2)
Fred Drake02538202001-03-21 18:09:46 +0000679 run = result.testsRun
680 self.stream.writeln("Ran %d test%s in %.3fs" %
Neal Norwitz76165042002-05-31 14:15:11 +0000681 (run, run != 1 and "s" or "", timeTaken))
Fred Drake02538202001-03-21 18:09:46 +0000682 self.stream.writeln()
683 if not result.wasSuccessful():
684 self.stream.write("FAILED (")
685 failed, errored = map(len, (result.failures, result.errors))
686 if failed:
687 self.stream.write("failures=%d" % failed)
688 if errored:
689 if failed: self.stream.write(", ")
690 self.stream.write("errors=%d" % errored)
691 self.stream.writeln(")")
692 else:
693 self.stream.writeln("OK")
694 return result
Tim Petersa19a1682001-03-29 04:36:09 +0000695
Fred Drake02538202001-03-21 18:09:46 +0000696
Fred Drake02538202001-03-21 18:09:46 +0000697
698##############################################################################
699# Facilities for running tests from the command line
700##############################################################################
701
702class TestProgram:
703 """A command-line program that runs a set of tests; this is primarily
704 for making test modules conveniently executable.
705 """
706 USAGE = """\
Steve Purcell17a781b2001-04-09 15:37:31 +0000707Usage: %(progName)s [options] [test] [...]
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000708
709Options:
710 -h, --help Show this message
711 -v, --verbose Verbose output
712 -q, --quiet Minimal output
Fred Drake02538202001-03-21 18:09:46 +0000713
714Examples:
715 %(progName)s - run default set of tests
716 %(progName)s MyTestSuite - run suite 'MyTestSuite'
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000717 %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething
718 %(progName)s MyTestCase - run all 'test*' test methods
Fred Drake02538202001-03-21 18:09:46 +0000719 in MyTestCase
720"""
721 def __init__(self, module='__main__', defaultTest=None,
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000722 argv=None, testRunner=None, testLoader=defaultTestLoader):
Fred Drake02538202001-03-21 18:09:46 +0000723 if type(module) == type(''):
724 self.module = __import__(module)
Steve Purcell7e743842003-09-22 11:08:12 +0000725 for part in module.split('.')[1:]:
Fred Drake02538202001-03-21 18:09:46 +0000726 self.module = getattr(self.module, part)
727 else:
728 self.module = module
729 if argv is None:
730 argv = sys.argv
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000731 self.verbosity = 1
Fred Drake02538202001-03-21 18:09:46 +0000732 self.defaultTest = defaultTest
733 self.testRunner = testRunner
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000734 self.testLoader = testLoader
Fred Drake02538202001-03-21 18:09:46 +0000735 self.progName = os.path.basename(argv[0])
736 self.parseArgs(argv)
Fred Drake02538202001-03-21 18:09:46 +0000737 self.runTests()
738
739 def usageExit(self, msg=None):
740 if msg: print msg
741 print self.USAGE % self.__dict__
742 sys.exit(2)
743
744 def parseArgs(self, argv):
745 import getopt
746 try:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000747 options, args = getopt.getopt(argv[1:], 'hHvq',
748 ['help','verbose','quiet'])
Fred Drake02538202001-03-21 18:09:46 +0000749 for opt, value in options:
750 if opt in ('-h','-H','--help'):
751 self.usageExit()
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000752 if opt in ('-q','--quiet'):
753 self.verbosity = 0
754 if opt in ('-v','--verbose'):
755 self.verbosity = 2
Fred Drake02538202001-03-21 18:09:46 +0000756 if len(args) == 0 and self.defaultTest is None:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000757 self.test = self.testLoader.loadTestsFromModule(self.module)
758 return
Fred Drake02538202001-03-21 18:09:46 +0000759 if len(args) > 0:
760 self.testNames = args
761 else:
762 self.testNames = (self.defaultTest,)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000763 self.createTests()
Fred Drake02538202001-03-21 18:09:46 +0000764 except getopt.error, msg:
765 self.usageExit(msg)
766
767 def createTests(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000768 self.test = self.testLoader.loadTestsFromNames(self.testNames,
769 self.module)
Fred Drake02538202001-03-21 18:09:46 +0000770
771 def runTests(self):
772 if self.testRunner is None:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000773 self.testRunner = TextTestRunner(verbosity=self.verbosity)
Fred Drake02538202001-03-21 18:09:46 +0000774 result = self.testRunner.run(self.test)
Tim Petersa19a1682001-03-29 04:36:09 +0000775 sys.exit(not result.wasSuccessful())
Fred Drake02538202001-03-21 18:09:46 +0000776
777main = TestProgram
778
779
780##############################################################################
781# Executing this module from the command line
782##############################################################################
783
784if __name__ == "__main__":
785 main(module=None)