blob: 16f062b3ab5cabe7d21dfd586c7c3e69334b2715 [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
Guido van Rossumd8faa362007-04-27 19:54:29 +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
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##############################################################################
Fred Drake02538202001-03-21 18:09:46 +000068# Test framework core
69##############################################################################
70
Steve Purcelldc391a62002-08-09 09:46:23 +000071def _strclass(cls):
72 return "%s.%s" % (cls.__module__, cls.__name__)
73
Steve Purcellb8d5f242003-12-06 13:03:13 +000074__unittest = 1
75
Fred Drake02538202001-03-21 18:09:46 +000076class TestResult:
77 """Holder for test result information.
78
79 Test results are automatically managed by the TestCase and TestSuite
80 classes, and do not need to be explicitly manipulated by writers of tests.
81
82 Each instance holds the total number of tests run, and collections of
83 failures and errors that occurred among those test runs. The collections
Steve Purcell7b065702001-09-06 08:24:40 +000084 contain tuples of (testcase, exceptioninfo), where exceptioninfo is the
Fred Drake656f9ec2001-09-06 19:13:14 +000085 formatted traceback of the error that occurred.
Fred Drake02538202001-03-21 18:09:46 +000086 """
87 def __init__(self):
88 self.failures = []
89 self.errors = []
90 self.testsRun = 0
Guido van Rossumd8faa362007-04-27 19:54:29 +000091 self.shouldStop = False
Fred Drake02538202001-03-21 18:09:46 +000092
93 def startTest(self, test):
94 "Called when the given test is about to be run"
95 self.testsRun = self.testsRun + 1
96
97 def stopTest(self, test):
98 "Called when the given test has been run"
99 pass
100
101 def addError(self, test, err):
Steve Purcell7b065702001-09-06 08:24:40 +0000102 """Called when an error has occurred. 'err' is a tuple of values as
103 returned by sys.exc_info().
104 """
Steve Purcellb8d5f242003-12-06 13:03:13 +0000105 self.errors.append((test, self._exc_info_to_string(err, test)))
Fred Drake02538202001-03-21 18:09:46 +0000106
107 def addFailure(self, test, err):
Steve Purcell7b065702001-09-06 08:24:40 +0000108 """Called when an error has occurred. 'err' is a tuple of values as
109 returned by sys.exc_info()."""
Steve Purcellb8d5f242003-12-06 13:03:13 +0000110 self.failures.append((test, self._exc_info_to_string(err, test)))
Fred Drake02538202001-03-21 18:09:46 +0000111
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000112 def addSuccess(self, test):
113 "Called when a test has completed successfully"
114 pass
115
Fred Drake02538202001-03-21 18:09:46 +0000116 def wasSuccessful(self):
117 "Tells whether or not this result was a success"
118 return len(self.failures) == len(self.errors) == 0
119
120 def stop(self):
121 "Indicates that the tests should be aborted"
Steve Purcell7e743842003-09-22 11:08:12 +0000122 self.shouldStop = True
Tim Petersa19a1682001-03-29 04:36:09 +0000123
Steve Purcellb8d5f242003-12-06 13:03:13 +0000124 def _exc_info_to_string(self, err, test):
Steve Purcell7b065702001-09-06 08:24:40 +0000125 """Converts a sys.exc_info()-style tuple of values into a string."""
Steve Purcellb8d5f242003-12-06 13:03:13 +0000126 exctype, value, tb = err
127 # Skip test runner traceback levels
128 while tb and self._is_relevant_tb_level(tb):
129 tb = tb.tb_next
130 if exctype is test.failureException:
131 # Skip assert*() traceback levels
132 length = self._count_relevant_tb_levels(tb)
133 return ''.join(traceback.format_exception(exctype, value, tb, length))
134 return ''.join(traceback.format_exception(exctype, value, tb))
135
136 def _is_relevant_tb_level(self, tb):
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000137 return '__unittest' in tb.tb_frame.f_globals
Steve Purcellb8d5f242003-12-06 13:03:13 +0000138
139 def _count_relevant_tb_levels(self, tb):
140 length = 0
141 while tb and not self._is_relevant_tb_level(tb):
142 length += 1
143 tb = tb.tb_next
144 return length
Steve Purcell7b065702001-09-06 08:24:40 +0000145
Fred Drake02538202001-03-21 18:09:46 +0000146 def __repr__(self):
147 return "<%s run=%i errors=%i failures=%i>" % \
Steve Purcelldc391a62002-08-09 09:46:23 +0000148 (_strclass(self.__class__), self.testsRun, len(self.errors),
Fred Drake02538202001-03-21 18:09:46 +0000149 len(self.failures))
150
Fred Drake02538202001-03-21 18:09:46 +0000151class 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:
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000185 self._testMethodName = methodName
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000186 testMethod = getattr(self, methodName)
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000187 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 """
Georg Brandl81cdb4e2006-01-20 17:55:00 +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):
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000217 return "%s.%s" % (_strclass(self.__class__), self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000218
Guido van Rossumd8faa362007-04-27 19:54:29 +0000219 def __eq__(self, other):
220 if type(self) is not type(other):
221 return False
222
223 return self._testMethodName == other._testMethodName
224
225 def __ne__(self, other):
226 return not self == other
227
228 def __hash__(self):
229 return hash((type(self), self._testMethodName))
230
Fred Drake02538202001-03-21 18:09:46 +0000231 def __str__(self):
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000232 return "%s (%s)" % (self._testMethodName, _strclass(self.__class__))
Fred Drake02538202001-03-21 18:09:46 +0000233
234 def __repr__(self):
235 return "<%s testMethod=%s>" % \
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000236 (_strclass(self.__class__), self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000237
238 def run(self, result=None):
Fred Drake02538202001-03-21 18:09:46 +0000239 if result is None: result = self.defaultTestResult()
240 result.startTest(self)
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000241 testMethod = getattr(self, self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000242 try:
243 try:
244 self.setUp()
Guido van Rossum202dd1e2001-12-07 03:39:34 +0000245 except KeyboardInterrupt:
246 raise
Fred Drake02538202001-03-21 18:09:46 +0000247 except:
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000248 result.addError(self, self._exc_info())
Fred Drake02538202001-03-21 18:09:46 +0000249 return
250
Steve Purcell7e743842003-09-22 11:08:12 +0000251 ok = False
Fred Drake02538202001-03-21 18:09:46 +0000252 try:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000253 testMethod()
Steve Purcell7e743842003-09-22 11:08:12 +0000254 ok = True
Skip Montanaroae5c37b2003-07-13 15:18:12 +0000255 except self.failureException:
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000256 result.addFailure(self, self._exc_info())
Guido van Rossum202dd1e2001-12-07 03:39:34 +0000257 except KeyboardInterrupt:
258 raise
Fred Drake02538202001-03-21 18:09:46 +0000259 except:
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000260 result.addError(self, self._exc_info())
Fred Drake02538202001-03-21 18:09:46 +0000261
262 try:
263 self.tearDown()
Guido van Rossum202dd1e2001-12-07 03:39:34 +0000264 except KeyboardInterrupt:
265 raise
Fred Drake02538202001-03-21 18:09:46 +0000266 except:
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000267 result.addError(self, self._exc_info())
Steve Purcell7e743842003-09-22 11:08:12 +0000268 ok = False
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000269 if ok: result.addSuccess(self)
Fred Drake02538202001-03-21 18:09:46 +0000270 finally:
271 result.stopTest(self)
272
Raymond Hettinger664347b2004-12-04 21:21:53 +0000273 def __call__(self, *args, **kwds):
274 return self.run(*args, **kwds)
Steve Purcell7e743842003-09-22 11:08:12 +0000275
Fred Drake02538202001-03-21 18:09:46 +0000276 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000277 """Run the test without collecting errors in a TestResult"""
Fred Drake02538202001-03-21 18:09:46 +0000278 self.setUp()
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000279 getattr(self, self._testMethodName)()
Fred Drake02538202001-03-21 18:09:46 +0000280 self.tearDown()
281
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000282 def _exc_info(self):
Steve Purcell15d89272001-04-12 09:05:01 +0000283 """Return a version of sys.exc_info() with the traceback frame
284 minimised; usually the top level of the traceback frame is not
285 needed.
Fred Drake02538202001-03-21 18:09:46 +0000286 """
Guido van Rossumd8faa362007-04-27 19:54:29 +0000287 return sys.exc_info()
Fred Drake02538202001-03-21 18:09:46 +0000288
Steve Purcell15d89272001-04-12 09:05:01 +0000289 def fail(self, msg=None):
290 """Fail immediately, with the given message."""
291 raise self.failureException, msg
Fred Drake02538202001-03-21 18:09:46 +0000292
293 def failIf(self, expr, msg=None):
294 "Fail the test if the expression is true."
Steve Purcell15d89272001-04-12 09:05:01 +0000295 if expr: raise self.failureException, msg
Fred Drake02538202001-03-21 18:09:46 +0000296
Steve Purcell15d89272001-04-12 09:05:01 +0000297 def failUnless(self, expr, msg=None):
298 """Fail the test unless the expression is true."""
299 if not expr: raise self.failureException, msg
300
301 def failUnlessRaises(self, excClass, callableObj, *args, **kwargs):
302 """Fail unless an exception of class excClass is thrown
Fred Drake02538202001-03-21 18:09:46 +0000303 by callableObj when invoked with arguments args and keyword
304 arguments kwargs. If a different type of exception is
305 thrown, it will not be caught, and the test case will be
306 deemed to have suffered an error, exactly as for an
307 unexpected exception.
308 """
309 try:
Guido van Rossum68468eb2003-02-27 20:14:51 +0000310 callableObj(*args, **kwargs)
Fred Drake02538202001-03-21 18:09:46 +0000311 except excClass:
312 return
313 else:
314 if hasattr(excClass,'__name__'): excName = excClass.__name__
315 else: excName = str(excClass)
Steve Purcell7e743842003-09-22 11:08:12 +0000316 raise self.failureException, "%s not raised" % excName
Fred Drake02538202001-03-21 18:09:46 +0000317
Steve Purcell15d89272001-04-12 09:05:01 +0000318 def failUnlessEqual(self, first, second, msg=None):
Raymond Hettingerc377cbf2003-04-04 22:56:42 +0000319 """Fail if the two objects are unequal as determined by the '=='
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000320 operator.
321 """
Raymond Hettingerc377cbf2003-04-04 22:56:42 +0000322 if not first == second:
Steve Purcellca9aaf32001-12-17 10:13:17 +0000323 raise self.failureException, \
Walter Dörwald70a6b492004-02-12 17:35:32 +0000324 (msg or '%r != %r' % (first, second))
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000325
Steve Purcell15d89272001-04-12 09:05:01 +0000326 def failIfEqual(self, first, second, msg=None):
327 """Fail if the two objects are equal as determined by the '=='
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000328 operator.
329 """
Steve Purcell15d89272001-04-12 09:05:01 +0000330 if first == second:
Steve Purcellca9aaf32001-12-17 10:13:17 +0000331 raise self.failureException, \
Walter Dörwald70a6b492004-02-12 17:35:32 +0000332 (msg or '%r == %r' % (first, second))
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000333
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000334 def failUnlessAlmostEqual(self, first, second, places=7, msg=None):
335 """Fail if the two objects are unequal as determined by their
336 difference rounded to the given number of decimal places
337 (default 7) and comparing to zero.
338
Steve Purcell397b45d2003-10-26 10:41:03 +0000339 Note that decimal places (from zero) are usually not the same
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000340 as significant digits (measured from the most signficant digit).
341 """
342 if round(second-first, places) != 0:
343 raise self.failureException, \
Walter Dörwald70a6b492004-02-12 17:35:32 +0000344 (msg or '%r != %r within %r places' % (first, second, places))
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000345
346 def failIfAlmostEqual(self, first, second, places=7, msg=None):
347 """Fail if the two objects are equal as determined by their
348 difference rounded to the given number of decimal places
349 (default 7) and comparing to zero.
350
Steve Purcellcca34912003-10-26 16:38:16 +0000351 Note that decimal places (from zero) are usually not the same
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000352 as significant digits (measured from the most signficant digit).
353 """
354 if round(second-first, places) == 0:
355 raise self.failureException, \
Walter Dörwald70a6b492004-02-12 17:35:32 +0000356 (msg or '%r == %r within %r places' % (first, second, places))
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000357
Steve Purcell7e743842003-09-22 11:08:12 +0000358 # Synonyms for assertion methods
359
Steve Purcell15d89272001-04-12 09:05:01 +0000360 assertEqual = assertEquals = failUnlessEqual
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000361
Steve Purcell15d89272001-04-12 09:05:01 +0000362 assertNotEqual = assertNotEquals = failIfEqual
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000363
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000364 assertAlmostEqual = assertAlmostEquals = failUnlessAlmostEqual
365
366 assertNotAlmostEqual = assertNotAlmostEquals = failIfAlmostEqual
367
Steve Purcell15d89272001-04-12 09:05:01 +0000368 assertRaises = failUnlessRaises
369
Steve Purcell7e743842003-09-22 11:08:12 +0000370 assert_ = assertTrue = failUnless
371
372 assertFalse = failIf
Steve Purcell15d89272001-04-12 09:05:01 +0000373
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000374
Fred Drake02538202001-03-21 18:09:46 +0000375
376class TestSuite:
377 """A test suite is a composite test consisting of a number of TestCases.
378
379 For use, create an instance of TestSuite, then add test case instances.
380 When all tests have been added, the suite can be passed to a test
381 runner, such as TextTestRunner. It will run the individual test cases
382 in the order in which they were added, aggregating the results. When
383 subclassing, do not forget to call the base class constructor.
384 """
385 def __init__(self, tests=()):
386 self._tests = []
387 self.addTests(tests)
388
389 def __repr__(self):
Steve Purcelldc391a62002-08-09 09:46:23 +0000390 return "<%s tests=%s>" % (_strclass(self.__class__), self._tests)
Fred Drake02538202001-03-21 18:09:46 +0000391
392 __str__ = __repr__
393
Guido van Rossumd8faa362007-04-27 19:54:29 +0000394 def __eq__(self, other):
395 if type(self) is not type(other):
396 return False
397 return self._tests == other._tests
398
399 def __ne__(self, other):
400 return not self == other
401
Jim Fultonfafd8742004-08-28 15:22:12 +0000402 def __iter__(self):
403 return iter(self._tests)
404
Fred Drake02538202001-03-21 18:09:46 +0000405 def countTestCases(self):
406 cases = 0
407 for test in self._tests:
Steve Purcell7e743842003-09-22 11:08:12 +0000408 cases += test.countTestCases()
Fred Drake02538202001-03-21 18:09:46 +0000409 return cases
410
411 def addTest(self, test):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000412 # sanity checks
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000413 if not hasattr(test, '__call__'):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000414 raise TypeError("the test to add must be callable")
Guido van Rossum13257902007-06-07 23:15:56 +0000415 if isinstance(test, type) and issubclass(test, (TestCase, TestSuite)):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000416 raise TypeError("TestCases and TestSuites must be instantiated "
417 "before passing them to addTest()")
Fred Drake02538202001-03-21 18:09:46 +0000418 self._tests.append(test)
419
420 def addTests(self, tests):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000421 if isinstance(tests, basestring):
422 raise TypeError("tests must be an iterable of tests, not a string")
Fred Drake02538202001-03-21 18:09:46 +0000423 for test in tests:
424 self.addTest(test)
425
426 def run(self, result):
Fred Drake02538202001-03-21 18:09:46 +0000427 for test in self._tests:
428 if result.shouldStop:
429 break
430 test(result)
431 return result
432
Raymond Hettinger664347b2004-12-04 21:21:53 +0000433 def __call__(self, *args, **kwds):
434 return self.run(*args, **kwds)
435
Fred Drake02538202001-03-21 18:09:46 +0000436 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000437 """Run the tests without collecting errors in a TestResult"""
Fred Drake02538202001-03-21 18:09:46 +0000438 for test in self._tests: test.debug()
Fred Drake02538202001-03-21 18:09:46 +0000439
440
441class FunctionTestCase(TestCase):
442 """A test case that wraps a test function.
443
444 This is useful for slipping pre-existing test functions into the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000445 unittest framework. Optionally, set-up and tidy-up functions can be
Fred Drake02538202001-03-21 18:09:46 +0000446 supplied. As with TestCase, the tidy-up ('tearDown') function will
447 always be called if the set-up ('setUp') function ran successfully.
448 """
449
450 def __init__(self, testFunc, setUp=None, tearDown=None,
451 description=None):
452 TestCase.__init__(self)
453 self.__setUpFunc = setUp
454 self.__tearDownFunc = tearDown
455 self.__testFunc = testFunc
456 self.__description = description
457
458 def setUp(self):
459 if self.__setUpFunc is not None:
460 self.__setUpFunc()
461
462 def tearDown(self):
463 if self.__tearDownFunc is not None:
464 self.__tearDownFunc()
465
466 def runTest(self):
467 self.__testFunc()
468
469 def id(self):
470 return self.__testFunc.__name__
471
Guido van Rossumd8faa362007-04-27 19:54:29 +0000472 def __eq__(self, other):
473 if type(self) is not type(other):
474 return False
475
476 return self.__setUpFunc == other.__setUpFunc and \
477 self.__tearDownFunc == other.__tearDownFunc and \
478 self.__testFunc == other.__testFunc and \
479 self.__description == other.__description
480
481 def __ne__(self, other):
482 return not self == other
483
484 def __hash__(self):
485 return hash((type(self), self.__setUpFunc, self.__tearDownFunc,
486 self.__testFunc, self.__description))
487
Fred Drake02538202001-03-21 18:09:46 +0000488 def __str__(self):
Steve Purcelldc391a62002-08-09 09:46:23 +0000489 return "%s (%s)" % (_strclass(self.__class__), self.__testFunc.__name__)
Fred Drake02538202001-03-21 18:09:46 +0000490
491 def __repr__(self):
Steve Purcelldc391a62002-08-09 09:46:23 +0000492 return "<%s testFunc=%s>" % (_strclass(self.__class__), self.__testFunc)
Fred Drake02538202001-03-21 18:09:46 +0000493
494 def shortDescription(self):
495 if self.__description is not None: return self.__description
496 doc = self.__testFunc.__doc__
Steve Purcell7e743842003-09-22 11:08:12 +0000497 return doc and doc.split("\n")[0].strip() or None
Fred Drake02538202001-03-21 18:09:46 +0000498
499
500
501##############################################################################
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000502# Locating and loading tests
Fred Drake02538202001-03-21 18:09:46 +0000503##############################################################################
504
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000505class TestLoader:
506 """This class is responsible for loading tests according to various
Guido van Rossumd8faa362007-04-27 19:54:29 +0000507 criteria and returning them wrapped in a TestSuite
Fred Drake02538202001-03-21 18:09:46 +0000508 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000509 testMethodPrefix = 'test'
510 sortTestMethodsUsing = cmp
511 suiteClass = TestSuite
Fred Drake02538202001-03-21 18:09:46 +0000512
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000513 def loadTestsFromTestCase(self, testCaseClass):
Steve Purcell15d89272001-04-12 09:05:01 +0000514 """Return a suite of all tests cases contained in testCaseClass"""
Johannes Gijsbersd7b6ad42004-11-07 15:46:25 +0000515 if issubclass(testCaseClass, TestSuite):
516 raise TypeError("Test cases should not be derived from TestSuite. Maybe you meant to derive from TestCase?")
Steve Purcell7e743842003-09-22 11:08:12 +0000517 testCaseNames = self.getTestCaseNames(testCaseClass)
518 if not testCaseNames and hasattr(testCaseClass, 'runTest'):
519 testCaseNames = ['runTest']
520 return self.suiteClass(map(testCaseClass, testCaseNames))
Fred Drake02538202001-03-21 18:09:46 +0000521
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000522 def loadTestsFromModule(self, module):
Steve Purcell15d89272001-04-12 09:05:01 +0000523 """Return a suite of all tests cases contained in the given module"""
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000524 tests = []
525 for name in dir(module):
526 obj = getattr(module, name)
Guido van Rossum13257902007-06-07 23:15:56 +0000527 if isinstance(obj, type) and issubclass(obj, TestCase):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000528 tests.append(self.loadTestsFromTestCase(obj))
529 return self.suiteClass(tests)
Fred Drake02538202001-03-21 18:09:46 +0000530
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000531 def loadTestsFromName(self, name, module=None):
Steve Purcell15d89272001-04-12 09:05:01 +0000532 """Return a suite of all tests cases given a string specifier.
533
534 The name may resolve either to a module, a test case class, a
535 test method within a test case class, or a callable object which
536 returns a TestCase or TestSuite instance.
Tim Peters613b2222001-04-13 05:37:27 +0000537
Steve Purcell15d89272001-04-12 09:05:01 +0000538 The method optionally resolves the names relative to a given module.
539 """
Steve Purcell7e743842003-09-22 11:08:12 +0000540 parts = name.split('.')
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000541 if module is None:
Steve Purcell7e743842003-09-22 11:08:12 +0000542 parts_copy = parts[:]
543 while parts_copy:
544 try:
545 module = __import__('.'.join(parts_copy))
546 break
547 except ImportError:
548 del parts_copy[-1]
549 if not parts_copy: raise
Armin Rigo1b3c04b2003-10-24 17:15:29 +0000550 parts = parts[1:]
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000551 obj = module
552 for part in parts:
Steve Purcell7e743842003-09-22 11:08:12 +0000553 parent, obj = obj, getattr(obj, part)
Fred Drake02538202001-03-21 18:09:46 +0000554
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000555 if type(obj) == types.ModuleType:
556 return self.loadTestsFromModule(obj)
Guido van Rossum13257902007-06-07 23:15:56 +0000557 elif isinstance(obj, type) and issubclass(obj, TestCase):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000558 return self.loadTestsFromTestCase(obj)
Guido van Rossum13257902007-06-07 23:15:56 +0000559 elif (isinstance(obj, types.UnboundMethodType) and
560 isinstance(parent, type) and
Guido van Rossumd8faa362007-04-27 19:54:29 +0000561 issubclass(parent, TestCase)):
562 return TestSuite([parent(obj.__name__)])
Steve Purcell397b45d2003-10-26 10:41:03 +0000563 elif isinstance(obj, TestSuite):
Steve Purcell7e743842003-09-22 11:08:12 +0000564 return obj
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000565 elif hasattr(obj, '__call__'):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000566 test = obj()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000567 if isinstance(test, TestSuite):
568 return test
569 elif isinstance(test, TestCase):
570 return TestSuite([test])
571 else:
572 raise TypeError("calling %s returned %s, not a test" %
573 (obj, test))
Fred Drake02538202001-03-21 18:09:46 +0000574 else:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000575 raise TypeError("don't know how to make test from: %s" % obj)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000576
577 def loadTestsFromNames(self, names, module=None):
Steve Purcell15d89272001-04-12 09:05:01 +0000578 """Return a suite of all tests cases found using the given sequence
579 of string specifiers. See 'loadTestsFromName()'.
580 """
Steve Purcell7e743842003-09-22 11:08:12 +0000581 suites = [self.loadTestsFromName(name, module) for name in names]
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000582 return self.suiteClass(suites)
583
584 def getTestCaseNames(self, testCaseClass):
Steve Purcell15d89272001-04-12 09:05:01 +0000585 """Return a sorted sequence of method names found within testCaseClass
586 """
Steve Purcell7e743842003-09-22 11:08:12 +0000587 def isTestMethod(attrname, testCaseClass=testCaseClass, prefix=self.testMethodPrefix):
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000588 return attrname.startswith(prefix) and hasattr(getattr(testCaseClass, attrname), '__call__')
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000589 testFnNames = list(filter(isTestMethod, dir(testCaseClass)))
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000590 if self.sortTestMethodsUsing:
591 testFnNames.sort(self.sortTestMethodsUsing)
592 return testFnNames
593
594
595
596defaultTestLoader = TestLoader()
597
598
599##############################################################################
600# Patches for old functions: these functions should be considered obsolete
601##############################################################################
602
603def _makeLoader(prefix, sortUsing, suiteClass=None):
604 loader = TestLoader()
605 loader.sortTestMethodsUsing = sortUsing
606 loader.testMethodPrefix = prefix
607 if suiteClass: loader.suiteClass = suiteClass
608 return loader
609
610def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp):
611 return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)
612
613def makeSuite(testCaseClass, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
614 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
615
616def findTestCases(module, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
617 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module)
Fred Drake02538202001-03-21 18:09:46 +0000618
619
620##############################################################################
621# Text UI
622##############################################################################
623
624class _WritelnDecorator:
625 """Used to decorate file-like objects with a handy 'writeln' method"""
626 def __init__(self,stream):
627 self.stream = stream
Fred Drake02538202001-03-21 18:09:46 +0000628
629 def __getattr__(self, attr):
630 return getattr(self.stream,attr)
631
Raymond Hettinger91dd19d2003-09-13 02:58:00 +0000632 def writeln(self, arg=None):
633 if arg: self.write(arg)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000634 self.write('\n') # text-mode streams translate to \r\n if needed
Tim Petersa19a1682001-03-29 04:36:09 +0000635
Fred Drake02538202001-03-21 18:09:46 +0000636
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000637class _TextTestResult(TestResult):
Fred Drake02538202001-03-21 18:09:46 +0000638 """A test result class that can print formatted text results to a stream.
639
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000640 Used by TextTestRunner.
Fred Drake02538202001-03-21 18:09:46 +0000641 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000642 separator1 = '=' * 70
643 separator2 = '-' * 70
Fred Drake02538202001-03-21 18:09:46 +0000644
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000645 def __init__(self, stream, descriptions, verbosity):
Fred Drake02538202001-03-21 18:09:46 +0000646 TestResult.__init__(self)
647 self.stream = stream
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000648 self.showAll = verbosity > 1
649 self.dots = verbosity == 1
Fred Drake02538202001-03-21 18:09:46 +0000650 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000651
652 def getDescription(self, test):
653 if self.descriptions:
654 return test.shortDescription() or str(test)
655 else:
656 return str(test)
657
Fred Drake02538202001-03-21 18:09:46 +0000658 def startTest(self, test):
659 TestResult.startTest(self, test)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000660 if self.showAll:
661 self.stream.write(self.getDescription(test))
662 self.stream.write(" ... ")
Fred Drake02538202001-03-21 18:09:46 +0000663
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000664 def addSuccess(self, test):
665 TestResult.addSuccess(self, test)
666 if self.showAll:
Fred Drake02538202001-03-21 18:09:46 +0000667 self.stream.writeln("ok")
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000668 elif self.dots:
669 self.stream.write('.')
Fred Drake02538202001-03-21 18:09:46 +0000670
671 def addError(self, test, err):
672 TestResult.addError(self, test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000673 if self.showAll:
674 self.stream.writeln("ERROR")
675 elif self.dots:
676 self.stream.write('E')
Fred Drake02538202001-03-21 18:09:46 +0000677
678 def addFailure(self, test, err):
679 TestResult.addFailure(self, test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000680 if self.showAll:
681 self.stream.writeln("FAIL")
682 elif self.dots:
683 self.stream.write('F')
Fred Drake02538202001-03-21 18:09:46 +0000684
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000685 def printErrors(self):
686 if self.dots or self.showAll:
Fred Drake02538202001-03-21 18:09:46 +0000687 self.stream.writeln()
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000688 self.printErrorList('ERROR', self.errors)
689 self.printErrorList('FAIL', self.failures)
690
691 def printErrorList(self, flavour, errors):
692 for test, err in errors:
693 self.stream.writeln(self.separator1)
694 self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
695 self.stream.writeln(self.separator2)
Steve Purcell7b065702001-09-06 08:24:40 +0000696 self.stream.writeln("%s" % err)
Fred Drake02538202001-03-21 18:09:46 +0000697
698
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000699class TextTestRunner:
Fred Drake02538202001-03-21 18:09:46 +0000700 """A test runner class that displays results in textual form.
Tim Petersa19a1682001-03-29 04:36:09 +0000701
Fred Drake02538202001-03-21 18:09:46 +0000702 It prints out the names of tests as they are run, errors as they
703 occur, and a summary of the results at the end of the test run.
704 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000705 def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1):
Fred Drake02538202001-03-21 18:09:46 +0000706 self.stream = _WritelnDecorator(stream)
707 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000708 self.verbosity = verbosity
709
710 def _makeResult(self):
711 return _TextTestResult(self.stream, self.descriptions, self.verbosity)
Fred Drake02538202001-03-21 18:09:46 +0000712
713 def run(self, test):
714 "Run the given test case or test suite."
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000715 result = self._makeResult()
Fred Drake02538202001-03-21 18:09:46 +0000716 startTime = time.time()
717 test(result)
718 stopTime = time.time()
Steve Purcell397b45d2003-10-26 10:41:03 +0000719 timeTaken = stopTime - startTime
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000720 result.printErrors()
721 self.stream.writeln(result.separator2)
Fred Drake02538202001-03-21 18:09:46 +0000722 run = result.testsRun
723 self.stream.writeln("Ran %d test%s in %.3fs" %
Neal Norwitz76165042002-05-31 14:15:11 +0000724 (run, run != 1 and "s" or "", timeTaken))
Fred Drake02538202001-03-21 18:09:46 +0000725 self.stream.writeln()
726 if not result.wasSuccessful():
727 self.stream.write("FAILED (")
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000728 failed, errored = len(result.failures), len(result.errors)
Fred Drake02538202001-03-21 18:09:46 +0000729 if failed:
730 self.stream.write("failures=%d" % failed)
731 if errored:
732 if failed: self.stream.write(", ")
733 self.stream.write("errors=%d" % errored)
734 self.stream.writeln(")")
735 else:
736 self.stream.writeln("OK")
737 return result
Tim Petersa19a1682001-03-29 04:36:09 +0000738
Fred Drake02538202001-03-21 18:09:46 +0000739
Fred Drake02538202001-03-21 18:09:46 +0000740
741##############################################################################
742# Facilities for running tests from the command line
743##############################################################################
744
745class TestProgram:
746 """A command-line program that runs a set of tests; this is primarily
747 for making test modules conveniently executable.
748 """
749 USAGE = """\
Steve Purcell17a781b2001-04-09 15:37:31 +0000750Usage: %(progName)s [options] [test] [...]
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000751
752Options:
753 -h, --help Show this message
754 -v, --verbose Verbose output
755 -q, --quiet Minimal output
Fred Drake02538202001-03-21 18:09:46 +0000756
757Examples:
758 %(progName)s - run default set of tests
759 %(progName)s MyTestSuite - run suite 'MyTestSuite'
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000760 %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething
761 %(progName)s MyTestCase - run all 'test*' test methods
Fred Drake02538202001-03-21 18:09:46 +0000762 in MyTestCase
763"""
764 def __init__(self, module='__main__', defaultTest=None,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000765 argv=None, testRunner=TextTestRunner,
766 testLoader=defaultTestLoader):
Fred Drake02538202001-03-21 18:09:46 +0000767 if type(module) == type(''):
768 self.module = __import__(module)
Steve Purcell7e743842003-09-22 11:08:12 +0000769 for part in module.split('.')[1:]:
Fred Drake02538202001-03-21 18:09:46 +0000770 self.module = getattr(self.module, part)
771 else:
772 self.module = module
773 if argv is None:
774 argv = sys.argv
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000775 self.verbosity = 1
Fred Drake02538202001-03-21 18:09:46 +0000776 self.defaultTest = defaultTest
777 self.testRunner = testRunner
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000778 self.testLoader = testLoader
Fred Drake02538202001-03-21 18:09:46 +0000779 self.progName = os.path.basename(argv[0])
780 self.parseArgs(argv)
Fred Drake02538202001-03-21 18:09:46 +0000781 self.runTests()
782
783 def usageExit(self, msg=None):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000784 if msg: print(msg)
785 print(self.USAGE % self.__dict__)
Fred Drake02538202001-03-21 18:09:46 +0000786 sys.exit(2)
787
788 def parseArgs(self, argv):
789 import getopt
790 try:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000791 options, args = getopt.getopt(argv[1:], 'hHvq',
792 ['help','verbose','quiet'])
Fred Drake02538202001-03-21 18:09:46 +0000793 for opt, value in options:
794 if opt in ('-h','-H','--help'):
795 self.usageExit()
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000796 if opt in ('-q','--quiet'):
797 self.verbosity = 0
798 if opt in ('-v','--verbose'):
799 self.verbosity = 2
Fred Drake02538202001-03-21 18:09:46 +0000800 if len(args) == 0 and self.defaultTest is None:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000801 self.test = self.testLoader.loadTestsFromModule(self.module)
802 return
Fred Drake02538202001-03-21 18:09:46 +0000803 if len(args) > 0:
804 self.testNames = args
805 else:
806 self.testNames = (self.defaultTest,)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000807 self.createTests()
Guido van Rossumb940e112007-01-10 16:19:56 +0000808 except getopt.error as msg:
Fred Drake02538202001-03-21 18:09:46 +0000809 self.usageExit(msg)
810
811 def createTests(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000812 self.test = self.testLoader.loadTestsFromNames(self.testNames,
813 self.module)
Fred Drake02538202001-03-21 18:09:46 +0000814
815 def runTests(self):
Guido van Rossum13257902007-06-07 23:15:56 +0000816 if isinstance(self.testRunner, type):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000817 try:
818 testRunner = self.testRunner(verbosity=self.verbosity)
819 except TypeError:
820 # didn't accept the verbosity argument
821 testRunner = self.testRunner()
822 else:
823 # it is assumed to be a TestRunner instance
824 testRunner = self.testRunner
825 result = testRunner.run(self.test)
Tim Petersa19a1682001-03-29 04:36:09 +0000826 sys.exit(not result.wasSuccessful())
Fred Drake02538202001-03-21 18:09:46 +0000827
828main = TestProgram
829
830
831##############################################################################
832# Executing this module from the command line
833##############################################################################
834
835if __name__ == "__main__":
836 main(module=None)