blob: eccefe6026344abcd9e35fbf2c73f901dff93829 [file] [log] [blame]
Fred Drake02538202001-03-21 18:09:46 +00001#!/usr/bin/env python
Steve Purcell5ddd1a82001-03-22 08:45:36 +00002'''
Fred Drake02538202001-03-21 18:09:46 +00003Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's
4Smalltalk testing framework.
5
Fred Drake02538202001-03-21 18:09:46 +00006This module contains the core framework classes that form the basis of
7specific test cases and suites (TestCase, TestSuite etc.), and also a
8text-based utility class for running the tests and reporting the results
Jeremy Hyltonefef5da2001-10-22 18:14:15 +00009 (TextTestRunner).
Fred Drake02538202001-03-21 18:09:46 +000010
Steve Purcell5ddd1a82001-03-22 08:45:36 +000011Simple usage:
12
13 import unittest
14
15 class IntegerArithmenticTestCase(unittest.TestCase):
16 def testAdd(self): ## test method names begin 'test*'
17 self.assertEquals((1 + 2), 3)
18 self.assertEquals(0 + 1, 1)
Steve Purcell7b065702001-09-06 08:24:40 +000019 def testMultiply(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +000020 self.assertEquals((0 * 10), 0)
21 self.assertEquals((5 * 8), 40)
22
23 if __name__ == '__main__':
24 unittest.main()
25
26Further information is available in the bundled documentation, and from
27
Georg Brandl15c5ce92007-03-07 09:09:40 +000028 http://docs.python.org/lib/module-unittest.html
Steve Purcell5ddd1a82001-03-22 08:45:36 +000029
Steve Purcell7e743842003-09-22 11:08:12 +000030Copyright (c) 1999-2003 Steve Purcell
Fred Drake02538202001-03-21 18:09:46 +000031This module is free software, and you may redistribute it and/or modify
32it under the same terms as Python itself, so long as this copyright message
33and disclaimer are retained in their original form.
34
35IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
36SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
37THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
38DAMAGE.
39
40THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
41LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
42PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
43AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
44SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
Steve Purcell5ddd1a82001-03-22 08:45:36 +000045'''
Fred Drake02538202001-03-21 18:09:46 +000046
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 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
Steve Purcellb8d5f242003-12-06 13:03:13 +000093__unittest = 1
94
Fred Drake02538202001-03-21 18:09:46 +000095class TestResult:
96 """Holder for test result information.
97
98 Test results are automatically managed by the TestCase and TestSuite
99 classes, and do not need to be explicitly manipulated by writers of tests.
100
101 Each instance holds the total number of tests run, and collections of
102 failures and errors that occurred among those test runs. The collections
Steve Purcell7b065702001-09-06 08:24:40 +0000103 contain tuples of (testcase, exceptioninfo), where exceptioninfo is the
Fred Drake656f9ec2001-09-06 19:13:14 +0000104 formatted traceback of the error that occurred.
Fred Drake02538202001-03-21 18:09:46 +0000105 """
106 def __init__(self):
107 self.failures = []
108 self.errors = []
109 self.testsRun = 0
Georg Brandl15c5ce92007-03-07 09:09:40 +0000110 self.shouldStop = False
Fred Drake02538202001-03-21 18:09:46 +0000111
112 def startTest(self, test):
113 "Called when the given test is about to be run"
114 self.testsRun = self.testsRun + 1
115
116 def stopTest(self, test):
117 "Called when the given test has been run"
118 pass
119
120 def addError(self, test, err):
Steve Purcell7b065702001-09-06 08:24:40 +0000121 """Called when an error has occurred. 'err' is a tuple of values as
122 returned by sys.exc_info().
123 """
Steve Purcellb8d5f242003-12-06 13:03:13 +0000124 self.errors.append((test, self._exc_info_to_string(err, test)))
Fred Drake02538202001-03-21 18:09:46 +0000125
126 def addFailure(self, test, err):
Steve Purcell7b065702001-09-06 08:24:40 +0000127 """Called when an error has occurred. 'err' is a tuple of values as
128 returned by sys.exc_info()."""
Steve Purcellb8d5f242003-12-06 13:03:13 +0000129 self.failures.append((test, self._exc_info_to_string(err, test)))
Fred Drake02538202001-03-21 18:09:46 +0000130
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000131 def addSuccess(self, test):
132 "Called when a test has completed successfully"
133 pass
134
Fred Drake02538202001-03-21 18:09:46 +0000135 def wasSuccessful(self):
136 "Tells whether or not this result was a success"
137 return len(self.failures) == len(self.errors) == 0
138
139 def stop(self):
140 "Indicates that the tests should be aborted"
Steve Purcell7e743842003-09-22 11:08:12 +0000141 self.shouldStop = True
Tim Petersa19a1682001-03-29 04:36:09 +0000142
Steve Purcellb8d5f242003-12-06 13:03:13 +0000143 def _exc_info_to_string(self, err, test):
Steve Purcell7b065702001-09-06 08:24:40 +0000144 """Converts a sys.exc_info()-style tuple of values into a string."""
Steve Purcellb8d5f242003-12-06 13:03:13 +0000145 exctype, value, tb = err
146 # Skip test runner traceback levels
147 while tb and self._is_relevant_tb_level(tb):
148 tb = tb.tb_next
149 if exctype is test.failureException:
150 # Skip assert*() traceback levels
151 length = self._count_relevant_tb_levels(tb)
152 return ''.join(traceback.format_exception(exctype, value, tb, length))
153 return ''.join(traceback.format_exception(exctype, value, tb))
154
155 def _is_relevant_tb_level(self, tb):
156 return tb.tb_frame.f_globals.has_key('__unittest')
157
158 def _count_relevant_tb_levels(self, tb):
159 length = 0
160 while tb and not self._is_relevant_tb_level(tb):
161 length += 1
162 tb = tb.tb_next
163 return length
Steve Purcell7b065702001-09-06 08:24:40 +0000164
Fred Drake02538202001-03-21 18:09:46 +0000165 def __repr__(self):
166 return "<%s run=%i errors=%i failures=%i>" % \
Steve Purcelldc391a62002-08-09 09:46:23 +0000167 (_strclass(self.__class__), self.testsRun, len(self.errors),
Fred Drake02538202001-03-21 18:09:46 +0000168 len(self.failures))
169
Fred Drake02538202001-03-21 18:09:46 +0000170class TestCase:
171 """A class whose instances are single test cases.
172
Fred Drake02538202001-03-21 18:09:46 +0000173 By default, the test code itself should be placed in a method named
174 'runTest'.
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000175
Tim Petersa19a1682001-03-29 04:36:09 +0000176 If the fixture may be used for many test cases, create as
Fred Drake02538202001-03-21 18:09:46 +0000177 many test methods as are needed. When instantiating such a TestCase
178 subclass, specify in the constructor arguments the name of the test method
179 that the instance is to execute.
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000180
Tim Petersa19a1682001-03-29 04:36:09 +0000181 Test authors should subclass TestCase for their own tests. Construction
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000182 and deconstruction of the test's environment ('fixture') can be
183 implemented by overriding the 'setUp' and 'tearDown' methods respectively.
184
185 If it is necessary to override the __init__ method, the base class
186 __init__ method must always be called. It is important that subclasses
187 should not change the signature of their __init__ method, since instances
188 of the classes are instantiated automatically by parts of the framework
189 in order to be run.
Fred Drake02538202001-03-21 18:09:46 +0000190 """
Steve Purcell15d89272001-04-12 09:05:01 +0000191
192 # This attribute determines which exception will be raised when
193 # the instance's assertion methods fail; test methods raising this
194 # exception will be deemed to have 'failed' rather than 'errored'
195
196 failureException = AssertionError
197
Fred Drake02538202001-03-21 18:09:46 +0000198 def __init__(self, methodName='runTest'):
199 """Create an instance of the class that will use the named test
200 method when executed. Raises a ValueError if the instance does
201 not have a method with the specified name.
202 """
203 try:
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000204 self._testMethodName = methodName
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000205 testMethod = getattr(self, methodName)
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000206 self._testMethodDoc = testMethod.__doc__
Fred Drake02538202001-03-21 18:09:46 +0000207 except AttributeError:
208 raise ValueError, "no such test method in %s: %s" % \
209 (self.__class__, methodName)
210
211 def setUp(self):
212 "Hook method for setting up the test fixture before exercising it."
213 pass
214
215 def tearDown(self):
216 "Hook method for deconstructing the test fixture after testing it."
217 pass
218
219 def countTestCases(self):
220 return 1
221
222 def defaultTestResult(self):
223 return TestResult()
224
225 def shortDescription(self):
226 """Returns a one-line description of the test, or None if no
227 description has been provided.
228
229 The default implementation of this method returns the first line of
230 the specified test method's docstring.
231 """
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000232 doc = self._testMethodDoc
Steve Purcell7e743842003-09-22 11:08:12 +0000233 return doc and doc.split("\n")[0].strip() or None
Fred Drake02538202001-03-21 18:09:46 +0000234
235 def id(self):
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000236 return "%s.%s" % (_strclass(self.__class__), self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000237
Georg Brandl15c5ce92007-03-07 09:09:40 +0000238 def __eq__(self, other):
239 if type(self) is not type(other):
240 return False
241
242 return self._testMethodName == other._testMethodName
243
244 def __ne__(self, other):
245 return not self == other
246
247 def __hash__(self):
Collin Winter9453e5d2007-03-09 23:30:39 +0000248 return hash((type(self), self._testMethodName))
Georg Brandl15c5ce92007-03-07 09:09:40 +0000249
Fred Drake02538202001-03-21 18:09:46 +0000250 def __str__(self):
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000251 return "%s (%s)" % (self._testMethodName, _strclass(self.__class__))
Fred Drake02538202001-03-21 18:09:46 +0000252
253 def __repr__(self):
254 return "<%s testMethod=%s>" % \
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000255 (_strclass(self.__class__), self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000256
257 def run(self, result=None):
Fred Drake02538202001-03-21 18:09:46 +0000258 if result is None: result = self.defaultTestResult()
259 result.startTest(self)
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000260 testMethod = getattr(self, self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000261 try:
262 try:
263 self.setUp()
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())
Fred Drake02538202001-03-21 18:09:46 +0000268 return
269
Steve Purcell7e743842003-09-22 11:08:12 +0000270 ok = False
Fred Drake02538202001-03-21 18:09:46 +0000271 try:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000272 testMethod()
Steve Purcell7e743842003-09-22 11:08:12 +0000273 ok = True
Skip Montanaroae5c37b2003-07-13 15:18:12 +0000274 except self.failureException:
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000275 result.addFailure(self, self._exc_info())
Guido van Rossum202dd1e2001-12-07 03:39:34 +0000276 except KeyboardInterrupt:
277 raise
Fred Drake02538202001-03-21 18:09:46 +0000278 except:
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000279 result.addError(self, self._exc_info())
Fred Drake02538202001-03-21 18:09:46 +0000280
281 try:
282 self.tearDown()
Guido van Rossum202dd1e2001-12-07 03:39:34 +0000283 except KeyboardInterrupt:
284 raise
Fred Drake02538202001-03-21 18:09:46 +0000285 except:
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000286 result.addError(self, self._exc_info())
Steve Purcell7e743842003-09-22 11:08:12 +0000287 ok = False
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000288 if ok: result.addSuccess(self)
Fred Drake02538202001-03-21 18:09:46 +0000289 finally:
290 result.stopTest(self)
291
Raymond Hettinger664347b2004-12-04 21:21:53 +0000292 def __call__(self, *args, **kwds):
293 return self.run(*args, **kwds)
Steve Purcell7e743842003-09-22 11:08:12 +0000294
Fred Drake02538202001-03-21 18:09:46 +0000295 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000296 """Run the test without collecting errors in a TestResult"""
Fred Drake02538202001-03-21 18:09:46 +0000297 self.setUp()
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000298 getattr(self, self._testMethodName)()
Fred Drake02538202001-03-21 18:09:46 +0000299 self.tearDown()
300
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000301 def _exc_info(self):
Steve Purcell15d89272001-04-12 09:05:01 +0000302 """Return a version of sys.exc_info() with the traceback frame
303 minimised; usually the top level of the traceback frame is not
304 needed.
Fred Drake02538202001-03-21 18:09:46 +0000305 """
Georg Brandl15c5ce92007-03-07 09:09:40 +0000306 return sys.exc_info()
Fred Drake02538202001-03-21 18:09:46 +0000307
Steve Purcell15d89272001-04-12 09:05:01 +0000308 def fail(self, msg=None):
309 """Fail immediately, with the given message."""
310 raise self.failureException, msg
Fred Drake02538202001-03-21 18:09:46 +0000311
312 def failIf(self, expr, msg=None):
313 "Fail the test if the expression is true."
Steve Purcell15d89272001-04-12 09:05:01 +0000314 if expr: raise self.failureException, msg
Fred Drake02538202001-03-21 18:09:46 +0000315
Steve Purcell15d89272001-04-12 09:05:01 +0000316 def failUnless(self, expr, msg=None):
317 """Fail the test unless the expression is true."""
318 if not expr: raise self.failureException, msg
319
320 def failUnlessRaises(self, excClass, callableObj, *args, **kwargs):
321 """Fail unless an exception of class excClass is thrown
Fred Drake02538202001-03-21 18:09:46 +0000322 by callableObj when invoked with arguments args and keyword
323 arguments kwargs. If a different type of exception is
324 thrown, it will not be caught, and the test case will be
325 deemed to have suffered an error, exactly as for an
326 unexpected exception.
327 """
328 try:
Guido van Rossum68468eb2003-02-27 20:14:51 +0000329 callableObj(*args, **kwargs)
Fred Drake02538202001-03-21 18:09:46 +0000330 except excClass:
331 return
332 else:
333 if hasattr(excClass,'__name__'): excName = excClass.__name__
334 else: excName = str(excClass)
Steve Purcell7e743842003-09-22 11:08:12 +0000335 raise self.failureException, "%s not raised" % excName
Fred Drake02538202001-03-21 18:09:46 +0000336
Steve Purcell15d89272001-04-12 09:05:01 +0000337 def failUnlessEqual(self, first, second, msg=None):
Raymond Hettingerc377cbf2003-04-04 22:56:42 +0000338 """Fail if the two objects are unequal as determined by the '=='
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000339 operator.
340 """
Raymond Hettingerc377cbf2003-04-04 22:56:42 +0000341 if not first == second:
Steve Purcellca9aaf32001-12-17 10:13:17 +0000342 raise self.failureException, \
Walter Dörwald70a6b492004-02-12 17:35:32 +0000343 (msg or '%r != %r' % (first, second))
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000344
Steve Purcell15d89272001-04-12 09:05:01 +0000345 def failIfEqual(self, first, second, msg=None):
346 """Fail if the two objects are equal as determined by the '=='
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000347 operator.
348 """
Steve Purcell15d89272001-04-12 09:05:01 +0000349 if first == second:
Steve Purcellca9aaf32001-12-17 10:13:17 +0000350 raise self.failureException, \
Walter Dörwald70a6b492004-02-12 17:35:32 +0000351 (msg or '%r == %r' % (first, second))
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000352
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000353 def failUnlessAlmostEqual(self, first, second, places=7, msg=None):
354 """Fail if the two objects are unequal as determined by their
355 difference rounded to the given number of decimal places
356 (default 7) and comparing to zero.
357
Steve Purcell397b45d2003-10-26 10:41:03 +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 """
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000361 if round(abs(second-first), places) != 0:
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000362 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
365 def failIfAlmostEqual(self, first, second, places=7, msg=None):
366 """Fail if the two objects are equal as determined by their
367 difference rounded to the given number of decimal places
368 (default 7) and comparing to zero.
369
Steve Purcellcca34912003-10-26 16:38:16 +0000370 Note that decimal places (from zero) are usually not the same
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000371 as significant digits (measured from the most signficant digit).
372 """
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000373 if round(abs(second-first), places) == 0:
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000374 raise self.failureException, \
Walter Dörwald70a6b492004-02-12 17:35:32 +0000375 (msg or '%r == %r within %r places' % (first, second, places))
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000376
Steve Purcell7e743842003-09-22 11:08:12 +0000377 # Synonyms for assertion methods
378
Steve Purcell15d89272001-04-12 09:05:01 +0000379 assertEqual = assertEquals = failUnlessEqual
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000380
Steve Purcell15d89272001-04-12 09:05:01 +0000381 assertNotEqual = assertNotEquals = failIfEqual
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000382
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000383 assertAlmostEqual = assertAlmostEquals = failUnlessAlmostEqual
384
385 assertNotAlmostEqual = assertNotAlmostEquals = failIfAlmostEqual
386
Steve Purcell15d89272001-04-12 09:05:01 +0000387 assertRaises = failUnlessRaises
388
Steve Purcell7e743842003-09-22 11:08:12 +0000389 assert_ = assertTrue = failUnless
390
391 assertFalse = failIf
Steve Purcell15d89272001-04-12 09:05:01 +0000392
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000393
Fred Drake02538202001-03-21 18:09:46 +0000394
395class TestSuite:
396 """A test suite is a composite test consisting of a number of TestCases.
397
398 For use, create an instance of TestSuite, then add test case instances.
399 When all tests have been added, the suite can be passed to a test
400 runner, such as TextTestRunner. It will run the individual test cases
401 in the order in which they were added, aggregating the results. When
402 subclassing, do not forget to call the base class constructor.
403 """
404 def __init__(self, tests=()):
405 self._tests = []
406 self.addTests(tests)
407
408 def __repr__(self):
Steve Purcelldc391a62002-08-09 09:46:23 +0000409 return "<%s tests=%s>" % (_strclass(self.__class__), self._tests)
Fred Drake02538202001-03-21 18:09:46 +0000410
411 __str__ = __repr__
412
Georg Brandl15c5ce92007-03-07 09:09:40 +0000413 def __eq__(self, other):
414 if type(self) is not type(other):
415 return False
416 return self._tests == other._tests
417
418 def __ne__(self, other):
419 return not self == other
420
Jim Fultonfafd8742004-08-28 15:22:12 +0000421 def __iter__(self):
422 return iter(self._tests)
423
Fred Drake02538202001-03-21 18:09:46 +0000424 def countTestCases(self):
425 cases = 0
426 for test in self._tests:
Steve Purcell7e743842003-09-22 11:08:12 +0000427 cases += test.countTestCases()
Fred Drake02538202001-03-21 18:09:46 +0000428 return cases
429
430 def addTest(self, test):
Georg Brandld9e50262007-03-07 11:54:49 +0000431 # sanity checks
432 if not callable(test):
433 raise TypeError("the test to add must be callable")
434 if (isinstance(test, (type, types.ClassType)) and
435 issubclass(test, (TestCase, TestSuite))):
436 raise TypeError("TestCases and TestSuites must be instantiated "
437 "before passing them to addTest()")
Fred Drake02538202001-03-21 18:09:46 +0000438 self._tests.append(test)
439
440 def addTests(self, tests):
Georg Brandld9e50262007-03-07 11:54:49 +0000441 if isinstance(tests, basestring):
442 raise TypeError("tests must be an iterable of tests, not a string")
Fred Drake02538202001-03-21 18:09:46 +0000443 for test in tests:
444 self.addTest(test)
445
446 def run(self, result):
Fred Drake02538202001-03-21 18:09:46 +0000447 for test in self._tests:
448 if result.shouldStop:
449 break
450 test(result)
451 return result
452
Raymond Hettinger664347b2004-12-04 21:21:53 +0000453 def __call__(self, *args, **kwds):
454 return self.run(*args, **kwds)
455
Fred Drake02538202001-03-21 18:09:46 +0000456 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000457 """Run the tests without collecting errors in a TestResult"""
Fred Drake02538202001-03-21 18:09:46 +0000458 for test in self._tests: test.debug()
Fred Drake02538202001-03-21 18:09:46 +0000459
460
461class FunctionTestCase(TestCase):
462 """A test case that wraps a test function.
463
464 This is useful for slipping pre-existing test functions into the
Georg Brandl15c5ce92007-03-07 09:09:40 +0000465 unittest framework. Optionally, set-up and tidy-up functions can be
Fred Drake02538202001-03-21 18:09:46 +0000466 supplied. As with TestCase, the tidy-up ('tearDown') function will
467 always be called if the set-up ('setUp') function ran successfully.
468 """
469
470 def __init__(self, testFunc, setUp=None, tearDown=None,
471 description=None):
472 TestCase.__init__(self)
473 self.__setUpFunc = setUp
474 self.__tearDownFunc = tearDown
475 self.__testFunc = testFunc
476 self.__description = description
477
478 def setUp(self):
479 if self.__setUpFunc is not None:
480 self.__setUpFunc()
481
482 def tearDown(self):
483 if self.__tearDownFunc is not None:
484 self.__tearDownFunc()
485
486 def runTest(self):
487 self.__testFunc()
488
489 def id(self):
490 return self.__testFunc.__name__
491
Georg Brandl15c5ce92007-03-07 09:09:40 +0000492 def __eq__(self, other):
493 if type(self) is not type(other):
494 return False
495
496 return self.__setUpFunc == other.__setUpFunc and \
497 self.__tearDownFunc == other.__tearDownFunc and \
498 self.__testFunc == other.__testFunc and \
499 self.__description == other.__description
500
501 def __ne__(self, other):
502 return not self == other
503
504 def __hash__(self):
Collin Winter9453e5d2007-03-09 23:30:39 +0000505 return hash((type(self), self.__setUpFunc, self.__tearDownFunc,
506 self.__testFunc, self.__description))
Georg Brandl15c5ce92007-03-07 09:09:40 +0000507
Fred Drake02538202001-03-21 18:09:46 +0000508 def __str__(self):
Steve Purcelldc391a62002-08-09 09:46:23 +0000509 return "%s (%s)" % (_strclass(self.__class__), self.__testFunc.__name__)
Fred Drake02538202001-03-21 18:09:46 +0000510
511 def __repr__(self):
Steve Purcelldc391a62002-08-09 09:46:23 +0000512 return "<%s testFunc=%s>" % (_strclass(self.__class__), self.__testFunc)
Fred Drake02538202001-03-21 18:09:46 +0000513
514 def shortDescription(self):
515 if self.__description is not None: return self.__description
516 doc = self.__testFunc.__doc__
Steve Purcell7e743842003-09-22 11:08:12 +0000517 return doc and doc.split("\n")[0].strip() or None
Fred Drake02538202001-03-21 18:09:46 +0000518
519
520
521##############################################################################
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000522# Locating and loading tests
Fred Drake02538202001-03-21 18:09:46 +0000523##############################################################################
524
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000525class TestLoader:
526 """This class is responsible for loading tests according to various
Georg Brandl15c5ce92007-03-07 09:09:40 +0000527 criteria and returning them wrapped in a TestSuite
Fred Drake02538202001-03-21 18:09:46 +0000528 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000529 testMethodPrefix = 'test'
530 sortTestMethodsUsing = cmp
531 suiteClass = TestSuite
Fred Drake02538202001-03-21 18:09:46 +0000532
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000533 def loadTestsFromTestCase(self, testCaseClass):
Steve Purcell15d89272001-04-12 09:05:01 +0000534 """Return a suite of all tests cases contained in testCaseClass"""
Johannes Gijsbersd7b6ad42004-11-07 15:46:25 +0000535 if issubclass(testCaseClass, TestSuite):
536 raise TypeError("Test cases should not be derived from TestSuite. Maybe you meant to derive from TestCase?")
Steve Purcell7e743842003-09-22 11:08:12 +0000537 testCaseNames = self.getTestCaseNames(testCaseClass)
538 if not testCaseNames and hasattr(testCaseClass, 'runTest'):
539 testCaseNames = ['runTest']
540 return self.suiteClass(map(testCaseClass, testCaseNames))
Fred Drake02538202001-03-21 18:09:46 +0000541
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000542 def loadTestsFromModule(self, module):
Steve Purcell15d89272001-04-12 09:05:01 +0000543 """Return a suite of all tests cases contained in the given module"""
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000544 tests = []
545 for name in dir(module):
546 obj = getattr(module, name)
Guido van Rossum67911372002-09-30 19:25:56 +0000547 if (isinstance(obj, (type, types.ClassType)) and
548 issubclass(obj, TestCase)):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000549 tests.append(self.loadTestsFromTestCase(obj))
550 return self.suiteClass(tests)
Fred Drake02538202001-03-21 18:09:46 +0000551
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000552 def loadTestsFromName(self, name, module=None):
Steve Purcell15d89272001-04-12 09:05:01 +0000553 """Return a suite of all tests cases given a string specifier.
554
555 The name may resolve either to a module, a test case class, a
556 test method within a test case class, or a callable object which
557 returns a TestCase or TestSuite instance.
Tim Peters613b2222001-04-13 05:37:27 +0000558
Steve Purcell15d89272001-04-12 09:05:01 +0000559 The method optionally resolves the names relative to a given module.
560 """
Steve Purcell7e743842003-09-22 11:08:12 +0000561 parts = name.split('.')
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000562 if module is None:
Steve Purcell7e743842003-09-22 11:08:12 +0000563 parts_copy = parts[:]
564 while parts_copy:
565 try:
566 module = __import__('.'.join(parts_copy))
567 break
568 except ImportError:
569 del parts_copy[-1]
570 if not parts_copy: raise
Armin Rigo1b3c04b2003-10-24 17:15:29 +0000571 parts = parts[1:]
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000572 obj = module
573 for part in parts:
Steve Purcell7e743842003-09-22 11:08:12 +0000574 parent, obj = obj, getattr(obj, part)
Fred Drake02538202001-03-21 18:09:46 +0000575
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000576 if type(obj) == types.ModuleType:
577 return self.loadTestsFromModule(obj)
Guido van Rossum67911372002-09-30 19:25:56 +0000578 elif (isinstance(obj, (type, types.ClassType)) and
Steve Purcell397b45d2003-10-26 10:41:03 +0000579 issubclass(obj, TestCase)):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000580 return self.loadTestsFromTestCase(obj)
Georg Brandl15c5ce92007-03-07 09:09:40 +0000581 elif (type(obj) == types.UnboundMethodType and
582 isinstance(parent, (type, types.ClassType)) and
583 issubclass(parent, TestCase)):
584 return TestSuite([parent(obj.__name__)])
Steve Purcell397b45d2003-10-26 10:41:03 +0000585 elif isinstance(obj, TestSuite):
Steve Purcell7e743842003-09-22 11:08:12 +0000586 return obj
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000587 elif callable(obj):
588 test = obj()
Georg Brandl15c5ce92007-03-07 09:09:40 +0000589 if isinstance(test, TestSuite):
590 return test
591 elif isinstance(test, TestCase):
592 return TestSuite([test])
593 else:
594 raise TypeError("calling %s returned %s, not a test" %
595 (obj, test))
Fred Drake02538202001-03-21 18:09:46 +0000596 else:
Georg Brandl15c5ce92007-03-07 09:09:40 +0000597 raise TypeError("don't know how to make test from: %s" % obj)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000598
599 def loadTestsFromNames(self, names, module=None):
Steve Purcell15d89272001-04-12 09:05:01 +0000600 """Return a suite of all tests cases found using the given sequence
601 of string specifiers. See 'loadTestsFromName()'.
602 """
Steve Purcell7e743842003-09-22 11:08:12 +0000603 suites = [self.loadTestsFromName(name, module) for name in names]
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000604 return self.suiteClass(suites)
605
606 def getTestCaseNames(self, testCaseClass):
Steve Purcell15d89272001-04-12 09:05:01 +0000607 """Return a sorted sequence of method names found within testCaseClass
608 """
Steve Purcell7e743842003-09-22 11:08:12 +0000609 def isTestMethod(attrname, testCaseClass=testCaseClass, prefix=self.testMethodPrefix):
Steve Purcell31982752003-09-23 08:41:53 +0000610 return attrname.startswith(prefix) and callable(getattr(testCaseClass, attrname))
Steve Purcell7e743842003-09-22 11:08:12 +0000611 testFnNames = filter(isTestMethod, dir(testCaseClass))
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000612 if self.sortTestMethodsUsing:
613 testFnNames.sort(self.sortTestMethodsUsing)
614 return testFnNames
615
616
617
618defaultTestLoader = TestLoader()
619
620
621##############################################################################
622# Patches for old functions: these functions should be considered obsolete
623##############################################################################
624
625def _makeLoader(prefix, sortUsing, suiteClass=None):
626 loader = TestLoader()
627 loader.sortTestMethodsUsing = sortUsing
628 loader.testMethodPrefix = prefix
629 if suiteClass: loader.suiteClass = suiteClass
630 return loader
631
632def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp):
633 return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)
634
635def makeSuite(testCaseClass, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
636 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
637
638def findTestCases(module, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
639 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module)
Fred Drake02538202001-03-21 18:09:46 +0000640
641
642##############################################################################
643# Text UI
644##############################################################################
645
646class _WritelnDecorator:
647 """Used to decorate file-like objects with a handy 'writeln' method"""
648 def __init__(self,stream):
649 self.stream = stream
Fred Drake02538202001-03-21 18:09:46 +0000650
651 def __getattr__(self, attr):
652 return getattr(self.stream,attr)
653
Raymond Hettinger91dd19d2003-09-13 02:58:00 +0000654 def writeln(self, arg=None):
655 if arg: self.write(arg)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000656 self.write('\n') # text-mode streams translate to \r\n if needed
Tim Petersa19a1682001-03-29 04:36:09 +0000657
Fred Drake02538202001-03-21 18:09:46 +0000658
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000659class _TextTestResult(TestResult):
Fred Drake02538202001-03-21 18:09:46 +0000660 """A test result class that can print formatted text results to a stream.
661
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000662 Used by TextTestRunner.
Fred Drake02538202001-03-21 18:09:46 +0000663 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000664 separator1 = '=' * 70
665 separator2 = '-' * 70
Fred Drake02538202001-03-21 18:09:46 +0000666
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000667 def __init__(self, stream, descriptions, verbosity):
Fred Drake02538202001-03-21 18:09:46 +0000668 TestResult.__init__(self)
669 self.stream = stream
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000670 self.showAll = verbosity > 1
671 self.dots = verbosity == 1
Fred Drake02538202001-03-21 18:09:46 +0000672 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000673
674 def getDescription(self, test):
675 if self.descriptions:
676 return test.shortDescription() or str(test)
677 else:
678 return str(test)
679
Fred Drake02538202001-03-21 18:09:46 +0000680 def startTest(self, test):
681 TestResult.startTest(self, test)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000682 if self.showAll:
683 self.stream.write(self.getDescription(test))
684 self.stream.write(" ... ")
Fred Drake02538202001-03-21 18:09:46 +0000685
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000686 def addSuccess(self, test):
687 TestResult.addSuccess(self, test)
688 if self.showAll:
Fred Drake02538202001-03-21 18:09:46 +0000689 self.stream.writeln("ok")
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000690 elif self.dots:
691 self.stream.write('.')
Fred Drake02538202001-03-21 18:09:46 +0000692
693 def addError(self, test, err):
694 TestResult.addError(self, test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000695 if self.showAll:
696 self.stream.writeln("ERROR")
697 elif self.dots:
698 self.stream.write('E')
Fred Drake02538202001-03-21 18:09:46 +0000699
700 def addFailure(self, test, err):
701 TestResult.addFailure(self, test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000702 if self.showAll:
703 self.stream.writeln("FAIL")
704 elif self.dots:
705 self.stream.write('F')
Fred Drake02538202001-03-21 18:09:46 +0000706
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000707 def printErrors(self):
708 if self.dots or self.showAll:
Fred Drake02538202001-03-21 18:09:46 +0000709 self.stream.writeln()
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000710 self.printErrorList('ERROR', self.errors)
711 self.printErrorList('FAIL', self.failures)
712
713 def printErrorList(self, flavour, errors):
714 for test, err in errors:
715 self.stream.writeln(self.separator1)
716 self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
717 self.stream.writeln(self.separator2)
Steve Purcell7b065702001-09-06 08:24:40 +0000718 self.stream.writeln("%s" % err)
Fred Drake02538202001-03-21 18:09:46 +0000719
720
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000721class TextTestRunner:
Fred Drake02538202001-03-21 18:09:46 +0000722 """A test runner class that displays results in textual form.
Tim Petersa19a1682001-03-29 04:36:09 +0000723
Fred Drake02538202001-03-21 18:09:46 +0000724 It prints out the names of tests as they are run, errors as they
725 occur, and a summary of the results at the end of the test run.
726 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000727 def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1):
Fred Drake02538202001-03-21 18:09:46 +0000728 self.stream = _WritelnDecorator(stream)
729 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000730 self.verbosity = verbosity
731
732 def _makeResult(self):
733 return _TextTestResult(self.stream, self.descriptions, self.verbosity)
Fred Drake02538202001-03-21 18:09:46 +0000734
735 def run(self, test):
736 "Run the given test case or test suite."
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000737 result = self._makeResult()
Fred Drake02538202001-03-21 18:09:46 +0000738 startTime = time.time()
739 test(result)
740 stopTime = time.time()
Steve Purcell397b45d2003-10-26 10:41:03 +0000741 timeTaken = stopTime - startTime
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000742 result.printErrors()
743 self.stream.writeln(result.separator2)
Fred Drake02538202001-03-21 18:09:46 +0000744 run = result.testsRun
745 self.stream.writeln("Ran %d test%s in %.3fs" %
Neal Norwitz76165042002-05-31 14:15:11 +0000746 (run, run != 1 and "s" or "", timeTaken))
Fred Drake02538202001-03-21 18:09:46 +0000747 self.stream.writeln()
748 if not result.wasSuccessful():
749 self.stream.write("FAILED (")
750 failed, errored = map(len, (result.failures, result.errors))
751 if failed:
752 self.stream.write("failures=%d" % failed)
753 if errored:
754 if failed: self.stream.write(", ")
755 self.stream.write("errors=%d" % errored)
756 self.stream.writeln(")")
757 else:
758 self.stream.writeln("OK")
759 return result
Tim Petersa19a1682001-03-29 04:36:09 +0000760
Fred Drake02538202001-03-21 18:09:46 +0000761
Fred Drake02538202001-03-21 18:09:46 +0000762
763##############################################################################
764# Facilities for running tests from the command line
765##############################################################################
766
767class TestProgram:
768 """A command-line program that runs a set of tests; this is primarily
769 for making test modules conveniently executable.
770 """
771 USAGE = """\
Steve Purcell17a781b2001-04-09 15:37:31 +0000772Usage: %(progName)s [options] [test] [...]
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000773
774Options:
775 -h, --help Show this message
776 -v, --verbose Verbose output
777 -q, --quiet Minimal output
Fred Drake02538202001-03-21 18:09:46 +0000778
779Examples:
780 %(progName)s - run default set of tests
781 %(progName)s MyTestSuite - run suite 'MyTestSuite'
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000782 %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething
783 %(progName)s MyTestCase - run all 'test*' test methods
Fred Drake02538202001-03-21 18:09:46 +0000784 in MyTestCase
785"""
786 def __init__(self, module='__main__', defaultTest=None,
Georg Brandld0a96252007-03-07 09:21:06 +0000787 argv=None, testRunner=TextTestRunner,
788 testLoader=defaultTestLoader):
Fred Drake02538202001-03-21 18:09:46 +0000789 if type(module) == type(''):
790 self.module = __import__(module)
Steve Purcell7e743842003-09-22 11:08:12 +0000791 for part in module.split('.')[1:]:
Fred Drake02538202001-03-21 18:09:46 +0000792 self.module = getattr(self.module, part)
793 else:
794 self.module = module
795 if argv is None:
796 argv = sys.argv
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000797 self.verbosity = 1
Fred Drake02538202001-03-21 18:09:46 +0000798 self.defaultTest = defaultTest
799 self.testRunner = testRunner
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000800 self.testLoader = testLoader
Fred Drake02538202001-03-21 18:09:46 +0000801 self.progName = os.path.basename(argv[0])
802 self.parseArgs(argv)
Fred Drake02538202001-03-21 18:09:46 +0000803 self.runTests()
804
805 def usageExit(self, msg=None):
806 if msg: print msg
807 print self.USAGE % self.__dict__
808 sys.exit(2)
809
810 def parseArgs(self, argv):
811 import getopt
812 try:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000813 options, args = getopt.getopt(argv[1:], 'hHvq',
814 ['help','verbose','quiet'])
Fred Drake02538202001-03-21 18:09:46 +0000815 for opt, value in options:
816 if opt in ('-h','-H','--help'):
817 self.usageExit()
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000818 if opt in ('-q','--quiet'):
819 self.verbosity = 0
820 if opt in ('-v','--verbose'):
821 self.verbosity = 2
Fred Drake02538202001-03-21 18:09:46 +0000822 if len(args) == 0 and self.defaultTest is None:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000823 self.test = self.testLoader.loadTestsFromModule(self.module)
824 return
Fred Drake02538202001-03-21 18:09:46 +0000825 if len(args) > 0:
826 self.testNames = args
827 else:
828 self.testNames = (self.defaultTest,)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000829 self.createTests()
Fred Drake02538202001-03-21 18:09:46 +0000830 except getopt.error, msg:
831 self.usageExit(msg)
832
833 def createTests(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000834 self.test = self.testLoader.loadTestsFromNames(self.testNames,
835 self.module)
Fred Drake02538202001-03-21 18:09:46 +0000836
837 def runTests(self):
Georg Brandld0a96252007-03-07 09:21:06 +0000838 if isinstance(self.testRunner, (type, types.ClassType)):
839 try:
840 testRunner = self.testRunner(verbosity=self.verbosity)
841 except TypeError:
842 # didn't accept the verbosity argument
843 testRunner = self.testRunner()
844 else:
845 # it is assumed to be a TestRunner instance
846 testRunner = self.testRunner
847 result = testRunner.run(self.test)
Tim Petersa19a1682001-03-29 04:36:09 +0000848 sys.exit(not result.wasSuccessful())
Fred Drake02538202001-03-21 18:09:46 +0000849
850main = TestProgram
851
852
853##############################################################################
854# Executing this module from the command line
855##############################################################################
856
857if __name__ == "__main__":
858 main(module=None)