blob: ccce746415d4bdddbee05d33674c9da0481fa1cf [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##############################################################################
Steve Purcell7e743842003-09-22 11:08:12 +000070
Raymond Hettinger5930d8f2008-07-10 16:06:41 +000071def _CmpToKey(mycmp):
72 'Convert a cmp= function into a key= function'
73 class K(object):
74 def __init__(self, obj):
75 self.obj = obj
76 def __lt__(self, other):
77 return mycmp(self.obj, other.obj) == -1
78 return K
Steve Purcell7e743842003-09-22 11:08:12 +000079
80##############################################################################
Fred Drake02538202001-03-21 18:09:46 +000081# Test framework core
82##############################################################################
83
Steve Purcelldc391a62002-08-09 09:46:23 +000084def _strclass(cls):
85 return "%s.%s" % (cls.__module__, cls.__name__)
86
Steve Purcellb8d5f242003-12-06 13:03:13 +000087__unittest = 1
88
Antoine Pitroudae1a6a2008-12-28 16:01:11 +000089class TestResult(object):
Fred Drake02538202001-03-21 18:09:46 +000090 """Holder for test result information.
91
92 Test results are automatically managed by the TestCase and TestSuite
93 classes, and do not need to be explicitly manipulated by writers of tests.
94
95 Each instance holds the total number of tests run, and collections of
96 failures and errors that occurred among those test runs. The collections
Steve Purcell7b065702001-09-06 08:24:40 +000097 contain tuples of (testcase, exceptioninfo), where exceptioninfo is the
Fred Drake656f9ec2001-09-06 19:13:14 +000098 formatted traceback of the error that occurred.
Fred Drake02538202001-03-21 18:09:46 +000099 """
100 def __init__(self):
101 self.failures = []
102 self.errors = []
103 self.testsRun = 0
Georg Brandl15c5ce92007-03-07 09:09:40 +0000104 self.shouldStop = False
Fred Drake02538202001-03-21 18:09:46 +0000105
106 def startTest(self, test):
107 "Called when the given test is about to be run"
108 self.testsRun = self.testsRun + 1
109
110 def stopTest(self, test):
111 "Called when the given test has been run"
112 pass
113
114 def addError(self, test, err):
Steve Purcell7b065702001-09-06 08:24:40 +0000115 """Called when an error has occurred. 'err' is a tuple of values as
116 returned by sys.exc_info().
117 """
Steve Purcellb8d5f242003-12-06 13:03:13 +0000118 self.errors.append((test, self._exc_info_to_string(err, test)))
Fred Drake02538202001-03-21 18:09:46 +0000119
120 def addFailure(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()."""
Steve Purcellb8d5f242003-12-06 13:03:13 +0000123 self.failures.append((test, self._exc_info_to_string(err, test)))
Fred Drake02538202001-03-21 18:09:46 +0000124
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000125 def addSuccess(self, test):
126 "Called when a test has completed successfully"
127 pass
128
Fred Drake02538202001-03-21 18:09:46 +0000129 def wasSuccessful(self):
130 "Tells whether or not this result was a success"
131 return len(self.failures) == len(self.errors) == 0
132
133 def stop(self):
134 "Indicates that the tests should be aborted"
Steve Purcell7e743842003-09-22 11:08:12 +0000135 self.shouldStop = True
Tim Petersa19a1682001-03-29 04:36:09 +0000136
Steve Purcellb8d5f242003-12-06 13:03:13 +0000137 def _exc_info_to_string(self, err, test):
Steve Purcell7b065702001-09-06 08:24:40 +0000138 """Converts a sys.exc_info()-style tuple of values into a string."""
Steve Purcellb8d5f242003-12-06 13:03:13 +0000139 exctype, value, tb = err
140 # Skip test runner traceback levels
141 while tb and self._is_relevant_tb_level(tb):
142 tb = tb.tb_next
143 if exctype is test.failureException:
144 # Skip assert*() traceback levels
145 length = self._count_relevant_tb_levels(tb)
146 return ''.join(traceback.format_exception(exctype, value, tb, length))
147 return ''.join(traceback.format_exception(exctype, value, tb))
148
149 def _is_relevant_tb_level(self, tb):
Georg Brandl56af5fc2008-07-18 19:30:10 +0000150 return '__unittest' in tb.tb_frame.f_globals
Steve Purcellb8d5f242003-12-06 13:03:13 +0000151
152 def _count_relevant_tb_levels(self, tb):
153 length = 0
154 while tb and not self._is_relevant_tb_level(tb):
155 length += 1
156 tb = tb.tb_next
157 return length
Steve Purcell7b065702001-09-06 08:24:40 +0000158
Fred Drake02538202001-03-21 18:09:46 +0000159 def __repr__(self):
160 return "<%s run=%i errors=%i failures=%i>" % \
Steve Purcelldc391a62002-08-09 09:46:23 +0000161 (_strclass(self.__class__), self.testsRun, len(self.errors),
Fred Drake02538202001-03-21 18:09:46 +0000162 len(self.failures))
163
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000164class AssertRaisesContext(object):
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000165 def __init__(self, expected, test_case):
166 self.expected = expected
167 self.failureException = test_case.failureException
168 def __enter__(self):
169 pass
170 def __exit__(self, exc_type, exc_value, traceback):
171 if exc_type is None:
172 try:
173 exc_name = self.expected.__name__
174 except AttributeError:
175 exc_name = str(self.expected)
176 raise self.failureException(
177 "{0} not raised".format(exc_name))
178 if issubclass(exc_type, self.expected):
179 return True
180 # Let unexpected exceptions skip through
181 return False
182
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000183class TestCase(object):
Fred Drake02538202001-03-21 18:09:46 +0000184 """A class whose instances are single test cases.
185
Fred Drake02538202001-03-21 18:09:46 +0000186 By default, the test code itself should be placed in a method named
187 'runTest'.
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000188
Tim Petersa19a1682001-03-29 04:36:09 +0000189 If the fixture may be used for many test cases, create as
Fred Drake02538202001-03-21 18:09:46 +0000190 many test methods as are needed. When instantiating such a TestCase
191 subclass, specify in the constructor arguments the name of the test method
192 that the instance is to execute.
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000193
Tim Petersa19a1682001-03-29 04:36:09 +0000194 Test authors should subclass TestCase for their own tests. Construction
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000195 and deconstruction of the test's environment ('fixture') can be
196 implemented by overriding the 'setUp' and 'tearDown' methods respectively.
197
198 If it is necessary to override the __init__ method, the base class
199 __init__ method must always be called. It is important that subclasses
200 should not change the signature of their __init__ method, since instances
201 of the classes are instantiated automatically by parts of the framework
202 in order to be run.
Fred Drake02538202001-03-21 18:09:46 +0000203 """
Steve Purcell15d89272001-04-12 09:05:01 +0000204
205 # This attribute determines which exception will be raised when
206 # the instance's assertion methods fail; test methods raising this
207 # exception will be deemed to have 'failed' rather than 'errored'
208
209 failureException = AssertionError
210
Fred Drake02538202001-03-21 18:09:46 +0000211 def __init__(self, methodName='runTest'):
212 """Create an instance of the class that will use the named test
213 method when executed. Raises a ValueError if the instance does
214 not have a method with the specified name.
215 """
216 try:
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000217 self._testMethodName = methodName
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000218 testMethod = getattr(self, methodName)
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000219 self._testMethodDoc = testMethod.__doc__
Fred Drake02538202001-03-21 18:09:46 +0000220 except AttributeError:
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000221 raise ValueError("no such test method in %s: %s" % \
222 (self.__class__, methodName))
Fred Drake02538202001-03-21 18:09:46 +0000223
224 def setUp(self):
225 "Hook method for setting up the test fixture before exercising it."
226 pass
227
228 def tearDown(self):
229 "Hook method for deconstructing the test fixture after testing it."
230 pass
231
232 def countTestCases(self):
233 return 1
234
235 def defaultTestResult(self):
236 return TestResult()
237
238 def shortDescription(self):
239 """Returns a one-line description of the test, or None if no
240 description has been provided.
241
242 The default implementation of this method returns the first line of
243 the specified test method's docstring.
244 """
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000245 doc = self._testMethodDoc
Steve Purcell7e743842003-09-22 11:08:12 +0000246 return doc and doc.split("\n")[0].strip() or None
Fred Drake02538202001-03-21 18:09:46 +0000247
248 def id(self):
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000249 return "%s.%s" % (_strclass(self.__class__), self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000250
Georg Brandl15c5ce92007-03-07 09:09:40 +0000251 def __eq__(self, other):
252 if type(self) is not type(other):
253 return False
254
255 return self._testMethodName == other._testMethodName
256
257 def __ne__(self, other):
258 return not self == other
259
260 def __hash__(self):
Collin Winter9453e5d2007-03-09 23:30:39 +0000261 return hash((type(self), self._testMethodName))
Georg Brandl15c5ce92007-03-07 09:09:40 +0000262
Fred Drake02538202001-03-21 18:09:46 +0000263 def __str__(self):
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000264 return "%s (%s)" % (self._testMethodName, _strclass(self.__class__))
Fred Drake02538202001-03-21 18:09:46 +0000265
266 def __repr__(self):
267 return "<%s testMethod=%s>" % \
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000268 (_strclass(self.__class__), self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000269
270 def run(self, result=None):
Fred Drake02538202001-03-21 18:09:46 +0000271 if result is None: result = self.defaultTestResult()
272 result.startTest(self)
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000273 testMethod = getattr(self, self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000274 try:
275 try:
276 self.setUp()
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000277 except Exception:
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000278 result.addError(self, self._exc_info())
Fred Drake02538202001-03-21 18:09:46 +0000279 return
280
Steve Purcell7e743842003-09-22 11:08:12 +0000281 ok = False
Fred Drake02538202001-03-21 18:09:46 +0000282 try:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000283 testMethod()
Steve Purcell7e743842003-09-22 11:08:12 +0000284 ok = True
Skip Montanaroae5c37b2003-07-13 15:18:12 +0000285 except self.failureException:
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000286 result.addFailure(self, self._exc_info())
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000287 except Exception:
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000288 result.addError(self, self._exc_info())
Fred Drake02538202001-03-21 18:09:46 +0000289
290 try:
291 self.tearDown()
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000292 except Exception:
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000293 result.addError(self, self._exc_info())
Steve Purcell7e743842003-09-22 11:08:12 +0000294 ok = False
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000295 if ok: result.addSuccess(self)
Fred Drake02538202001-03-21 18:09:46 +0000296 finally:
297 result.stopTest(self)
298
Raymond Hettinger664347b2004-12-04 21:21:53 +0000299 def __call__(self, *args, **kwds):
300 return self.run(*args, **kwds)
Steve Purcell7e743842003-09-22 11:08:12 +0000301
Fred Drake02538202001-03-21 18:09:46 +0000302 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000303 """Run the test without collecting errors in a TestResult"""
Fred Drake02538202001-03-21 18:09:46 +0000304 self.setUp()
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000305 getattr(self, self._testMethodName)()
Fred Drake02538202001-03-21 18:09:46 +0000306 self.tearDown()
307
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000308 def _exc_info(self):
Steve Purcell15d89272001-04-12 09:05:01 +0000309 """Return a version of sys.exc_info() with the traceback frame
310 minimised; usually the top level of the traceback frame is not
311 needed.
Fred Drake02538202001-03-21 18:09:46 +0000312 """
Georg Brandl15c5ce92007-03-07 09:09:40 +0000313 return sys.exc_info()
Fred Drake02538202001-03-21 18:09:46 +0000314
Steve Purcell15d89272001-04-12 09:05:01 +0000315 def fail(self, msg=None):
316 """Fail immediately, with the given message."""
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000317 raise self.failureException(msg)
Fred Drake02538202001-03-21 18:09:46 +0000318
319 def failIf(self, expr, msg=None):
320 "Fail the test if the expression is true."
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000321 if expr: raise self.failureException(msg)
Fred Drake02538202001-03-21 18:09:46 +0000322
Steve Purcell15d89272001-04-12 09:05:01 +0000323 def failUnless(self, expr, msg=None):
324 """Fail the test unless the expression is true."""
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000325 if not expr: raise self.failureException(msg)
Steve Purcell15d89272001-04-12 09:05:01 +0000326
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000327 def failUnlessRaises(self, excClass, callableObj=None, *args, **kwargs):
Steve Purcell15d89272001-04-12 09:05:01 +0000328 """Fail unless an exception of class excClass is thrown
Fred Drake02538202001-03-21 18:09:46 +0000329 by callableObj when invoked with arguments args and keyword
330 arguments kwargs. If a different type of exception is
331 thrown, it will not be caught, and the test case will be
332 deemed to have suffered an error, exactly as for an
333 unexpected exception.
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000334
335 If called with callableObj omitted or None, will return a
336 context object used like this::
337
338 with self.failUnlessRaises(some_error_class):
339 do_something()
Fred Drake02538202001-03-21 18:09:46 +0000340 """
Antoine Pitrou697ca3d2008-12-28 14:09:36 +0000341 context = AssertRaisesContext(excClass, self)
342 if callableObj is None:
343 return context
344 with context:
Guido van Rossum68468eb2003-02-27 20:14:51 +0000345 callableObj(*args, **kwargs)
Fred Drake02538202001-03-21 18:09:46 +0000346
Steve Purcell15d89272001-04-12 09:05:01 +0000347 def failUnlessEqual(self, first, second, msg=None):
Raymond Hettingerc377cbf2003-04-04 22:56:42 +0000348 """Fail if the two objects are unequal as determined by the '=='
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000349 operator.
350 """
Raymond Hettingerc377cbf2003-04-04 22:56:42 +0000351 if not first == second:
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000352 raise self.failureException(msg or '%r != %r' % (first, second))
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000353
Steve Purcell15d89272001-04-12 09:05:01 +0000354 def failIfEqual(self, first, second, msg=None):
355 """Fail if the two objects are equal as determined by the '=='
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000356 operator.
357 """
Steve Purcell15d89272001-04-12 09:05:01 +0000358 if first == second:
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000359 raise self.failureException(msg or '%r == %r' % (first, second))
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000360
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000361 def failUnlessAlmostEqual(self, first, second, places=7, msg=None):
362 """Fail if the two objects are unequal as determined by their
363 difference rounded to the given number of decimal places
364 (default 7) and comparing to zero.
365
Steve Purcell397b45d2003-10-26 10:41:03 +0000366 Note that decimal places (from zero) are usually not the same
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000367 as significant digits (measured from the most signficant digit).
368 """
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000369 if round(abs(second-first), places) != 0:
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000370 raise self.failureException(
371 msg or '%r != %r within %r places' % (first, second, places))
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000372
373 def failIfAlmostEqual(self, first, second, places=7, msg=None):
374 """Fail if the two objects are equal as determined by their
375 difference rounded to the given number of decimal places
376 (default 7) and comparing to zero.
377
Steve Purcellcca34912003-10-26 16:38:16 +0000378 Note that decimal places (from zero) are usually not the same
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000379 as significant digits (measured from the most signficant digit).
380 """
Jeffrey Yasskin2f3c16b2008-01-03 02:21:52 +0000381 if round(abs(second-first), places) == 0:
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000382 raise self.failureException(
383 msg or '%r == %r within %r places' % (first, second, places))
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000384
Steve Purcell7e743842003-09-22 11:08:12 +0000385 # Synonyms for assertion methods
386
Steve Purcell15d89272001-04-12 09:05:01 +0000387 assertEqual = assertEquals = failUnlessEqual
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000388
Steve Purcell15d89272001-04-12 09:05:01 +0000389 assertNotEqual = assertNotEquals = failIfEqual
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000390
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000391 assertAlmostEqual = assertAlmostEquals = failUnlessAlmostEqual
392
393 assertNotAlmostEqual = assertNotAlmostEquals = failIfAlmostEqual
394
Steve Purcell15d89272001-04-12 09:05:01 +0000395 assertRaises = failUnlessRaises
396
Steve Purcell7e743842003-09-22 11:08:12 +0000397 assert_ = assertTrue = failUnless
398
399 assertFalse = failIf
Steve Purcell15d89272001-04-12 09:05:01 +0000400
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000401
Fred Drake02538202001-03-21 18:09:46 +0000402
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000403class TestSuite(object):
Fred Drake02538202001-03-21 18:09:46 +0000404 """A test suite is a composite test consisting of a number of TestCases.
405
406 For use, create an instance of TestSuite, then add test case instances.
407 When all tests have been added, the suite can be passed to a test
408 runner, such as TextTestRunner. It will run the individual test cases
409 in the order in which they were added, aggregating the results. When
410 subclassing, do not forget to call the base class constructor.
411 """
412 def __init__(self, tests=()):
413 self._tests = []
414 self.addTests(tests)
415
416 def __repr__(self):
Steve Purcelldc391a62002-08-09 09:46:23 +0000417 return "<%s tests=%s>" % (_strclass(self.__class__), self._tests)
Fred Drake02538202001-03-21 18:09:46 +0000418
419 __str__ = __repr__
420
Georg Brandl15c5ce92007-03-07 09:09:40 +0000421 def __eq__(self, other):
422 if type(self) is not type(other):
423 return False
424 return self._tests == other._tests
425
426 def __ne__(self, other):
427 return not self == other
428
Nick Coghlan48361f52008-08-11 15:45:58 +0000429 # Can't guarantee hash invariant, so flag as unhashable
430 __hash__ = None
431
Jim Fultonfafd8742004-08-28 15:22:12 +0000432 def __iter__(self):
433 return iter(self._tests)
434
Fred Drake02538202001-03-21 18:09:46 +0000435 def countTestCases(self):
436 cases = 0
437 for test in self._tests:
Steve Purcell7e743842003-09-22 11:08:12 +0000438 cases += test.countTestCases()
Fred Drake02538202001-03-21 18:09:46 +0000439 return cases
440
441 def addTest(self, test):
Georg Brandld9e50262007-03-07 11:54:49 +0000442 # sanity checks
Raymond Hettinger5930d8f2008-07-10 16:06:41 +0000443 if not hasattr(test, '__call__'):
Georg Brandld9e50262007-03-07 11:54:49 +0000444 raise TypeError("the test to add must be callable")
445 if (isinstance(test, (type, types.ClassType)) and
446 issubclass(test, (TestCase, TestSuite))):
447 raise TypeError("TestCases and TestSuites must be instantiated "
448 "before passing them to addTest()")
Fred Drake02538202001-03-21 18:09:46 +0000449 self._tests.append(test)
450
451 def addTests(self, tests):
Georg Brandld9e50262007-03-07 11:54:49 +0000452 if isinstance(tests, basestring):
453 raise TypeError("tests must be an iterable of tests, not a string")
Fred Drake02538202001-03-21 18:09:46 +0000454 for test in tests:
455 self.addTest(test)
456
457 def run(self, result):
Fred Drake02538202001-03-21 18:09:46 +0000458 for test in self._tests:
459 if result.shouldStop:
460 break
461 test(result)
462 return result
463
Raymond Hettinger664347b2004-12-04 21:21:53 +0000464 def __call__(self, *args, **kwds):
465 return self.run(*args, **kwds)
466
Fred Drake02538202001-03-21 18:09:46 +0000467 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000468 """Run the tests without collecting errors in a TestResult"""
Fred Drake02538202001-03-21 18:09:46 +0000469 for test in self._tests: test.debug()
Fred Drake02538202001-03-21 18:09:46 +0000470
471
472class FunctionTestCase(TestCase):
473 """A test case that wraps a test function.
474
475 This is useful for slipping pre-existing test functions into the
Georg Brandl15c5ce92007-03-07 09:09:40 +0000476 unittest framework. Optionally, set-up and tidy-up functions can be
Fred Drake02538202001-03-21 18:09:46 +0000477 supplied. As with TestCase, the tidy-up ('tearDown') function will
478 always be called if the set-up ('setUp') function ran successfully.
479 """
480
481 def __init__(self, testFunc, setUp=None, tearDown=None,
482 description=None):
483 TestCase.__init__(self)
484 self.__setUpFunc = setUp
485 self.__tearDownFunc = tearDown
486 self.__testFunc = testFunc
487 self.__description = description
488
489 def setUp(self):
490 if self.__setUpFunc is not None:
491 self.__setUpFunc()
492
493 def tearDown(self):
494 if self.__tearDownFunc is not None:
495 self.__tearDownFunc()
496
497 def runTest(self):
498 self.__testFunc()
499
500 def id(self):
501 return self.__testFunc.__name__
502
Georg Brandl15c5ce92007-03-07 09:09:40 +0000503 def __eq__(self, other):
504 if type(self) is not type(other):
505 return False
506
507 return self.__setUpFunc == other.__setUpFunc and \
508 self.__tearDownFunc == other.__tearDownFunc and \
509 self.__testFunc == other.__testFunc and \
510 self.__description == other.__description
511
512 def __ne__(self, other):
513 return not self == other
514
515 def __hash__(self):
Collin Winter9453e5d2007-03-09 23:30:39 +0000516 return hash((type(self), self.__setUpFunc, self.__tearDownFunc,
517 self.__testFunc, self.__description))
Georg Brandl15c5ce92007-03-07 09:09:40 +0000518
Fred Drake02538202001-03-21 18:09:46 +0000519 def __str__(self):
Steve Purcelldc391a62002-08-09 09:46:23 +0000520 return "%s (%s)" % (_strclass(self.__class__), self.__testFunc.__name__)
Fred Drake02538202001-03-21 18:09:46 +0000521
522 def __repr__(self):
Steve Purcelldc391a62002-08-09 09:46:23 +0000523 return "<%s testFunc=%s>" % (_strclass(self.__class__), self.__testFunc)
Fred Drake02538202001-03-21 18:09:46 +0000524
525 def shortDescription(self):
526 if self.__description is not None: return self.__description
527 doc = self.__testFunc.__doc__
Steve Purcell7e743842003-09-22 11:08:12 +0000528 return doc and doc.split("\n")[0].strip() or None
Fred Drake02538202001-03-21 18:09:46 +0000529
530
531
532##############################################################################
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000533# Locating and loading tests
Fred Drake02538202001-03-21 18:09:46 +0000534##############################################################################
535
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000536class TestLoader(object):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000537 """This class is responsible for loading tests according to various
Georg Brandl15c5ce92007-03-07 09:09:40 +0000538 criteria and returning them wrapped in a TestSuite
Fred Drake02538202001-03-21 18:09:46 +0000539 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000540 testMethodPrefix = 'test'
541 sortTestMethodsUsing = cmp
542 suiteClass = TestSuite
Fred Drake02538202001-03-21 18:09:46 +0000543
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000544 def loadTestsFromTestCase(self, testCaseClass):
Steve Purcell15d89272001-04-12 09:05:01 +0000545 """Return a suite of all tests cases contained in testCaseClass"""
Johannes Gijsbersd7b6ad42004-11-07 15:46:25 +0000546 if issubclass(testCaseClass, TestSuite):
547 raise TypeError("Test cases should not be derived from TestSuite. Maybe you meant to derive from TestCase?")
Steve Purcell7e743842003-09-22 11:08:12 +0000548 testCaseNames = self.getTestCaseNames(testCaseClass)
549 if not testCaseNames and hasattr(testCaseClass, 'runTest'):
550 testCaseNames = ['runTest']
551 return self.suiteClass(map(testCaseClass, testCaseNames))
Fred Drake02538202001-03-21 18:09:46 +0000552
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000553 def loadTestsFromModule(self, module):
Steve Purcell15d89272001-04-12 09:05:01 +0000554 """Return a suite of all tests cases contained in the given module"""
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000555 tests = []
556 for name in dir(module):
557 obj = getattr(module, name)
Guido van Rossum67911372002-09-30 19:25:56 +0000558 if (isinstance(obj, (type, types.ClassType)) and
559 issubclass(obj, TestCase)):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000560 tests.append(self.loadTestsFromTestCase(obj))
561 return self.suiteClass(tests)
Fred Drake02538202001-03-21 18:09:46 +0000562
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000563 def loadTestsFromName(self, name, module=None):
Steve Purcell15d89272001-04-12 09:05:01 +0000564 """Return a suite of all tests cases given a string specifier.
565
566 The name may resolve either to a module, a test case class, a
567 test method within a test case class, or a callable object which
568 returns a TestCase or TestSuite instance.
Tim Peters613b2222001-04-13 05:37:27 +0000569
Steve Purcell15d89272001-04-12 09:05:01 +0000570 The method optionally resolves the names relative to a given module.
571 """
Steve Purcell7e743842003-09-22 11:08:12 +0000572 parts = name.split('.')
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000573 if module is None:
Steve Purcell7e743842003-09-22 11:08:12 +0000574 parts_copy = parts[:]
575 while parts_copy:
576 try:
577 module = __import__('.'.join(parts_copy))
578 break
579 except ImportError:
580 del parts_copy[-1]
581 if not parts_copy: raise
Armin Rigo1b3c04b2003-10-24 17:15:29 +0000582 parts = parts[1:]
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000583 obj = module
584 for part in parts:
Steve Purcell7e743842003-09-22 11:08:12 +0000585 parent, obj = obj, getattr(obj, part)
Fred Drake02538202001-03-21 18:09:46 +0000586
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000587 if isinstance(obj, types.ModuleType):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000588 return self.loadTestsFromModule(obj)
Guido van Rossum67911372002-09-30 19:25:56 +0000589 elif (isinstance(obj, (type, types.ClassType)) and
Steve Purcell397b45d2003-10-26 10:41:03 +0000590 issubclass(obj, TestCase)):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000591 return self.loadTestsFromTestCase(obj)
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000592 elif (isinstance(obj, types.UnboundMethodType) and
Georg Brandl15c5ce92007-03-07 09:09:40 +0000593 isinstance(parent, (type, types.ClassType)) and
594 issubclass(parent, TestCase)):
595 return TestSuite([parent(obj.__name__)])
Steve Purcell397b45d2003-10-26 10:41:03 +0000596 elif isinstance(obj, TestSuite):
Steve Purcell7e743842003-09-22 11:08:12 +0000597 return obj
Raymond Hettinger5930d8f2008-07-10 16:06:41 +0000598 elif hasattr(obj, '__call__'):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000599 test = obj()
Georg Brandl15c5ce92007-03-07 09:09:40 +0000600 if isinstance(test, TestSuite):
601 return test
602 elif isinstance(test, TestCase):
603 return TestSuite([test])
604 else:
605 raise TypeError("calling %s returned %s, not a test" %
606 (obj, test))
Fred Drake02538202001-03-21 18:09:46 +0000607 else:
Georg Brandl15c5ce92007-03-07 09:09:40 +0000608 raise TypeError("don't know how to make test from: %s" % obj)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000609
610 def loadTestsFromNames(self, names, module=None):
Steve Purcell15d89272001-04-12 09:05:01 +0000611 """Return a suite of all tests cases found using the given sequence
612 of string specifiers. See 'loadTestsFromName()'.
613 """
Steve Purcell7e743842003-09-22 11:08:12 +0000614 suites = [self.loadTestsFromName(name, module) for name in names]
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000615 return self.suiteClass(suites)
616
617 def getTestCaseNames(self, testCaseClass):
Steve Purcell15d89272001-04-12 09:05:01 +0000618 """Return a sorted sequence of method names found within testCaseClass
619 """
Steve Purcell7e743842003-09-22 11:08:12 +0000620 def isTestMethod(attrname, testCaseClass=testCaseClass, prefix=self.testMethodPrefix):
Raymond Hettinger5930d8f2008-07-10 16:06:41 +0000621 return attrname.startswith(prefix) and hasattr(getattr(testCaseClass, attrname), '__call__')
Steve Purcell7e743842003-09-22 11:08:12 +0000622 testFnNames = filter(isTestMethod, dir(testCaseClass))
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000623 if self.sortTestMethodsUsing:
Raymond Hettinger5930d8f2008-07-10 16:06:41 +0000624 testFnNames.sort(key=_CmpToKey(self.sortTestMethodsUsing))
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000625 return testFnNames
626
627
628
629defaultTestLoader = TestLoader()
630
631
632##############################################################################
633# Patches for old functions: these functions should be considered obsolete
634##############################################################################
635
636def _makeLoader(prefix, sortUsing, suiteClass=None):
637 loader = TestLoader()
638 loader.sortTestMethodsUsing = sortUsing
639 loader.testMethodPrefix = prefix
640 if suiteClass: loader.suiteClass = suiteClass
641 return loader
642
643def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp):
644 return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)
645
646def makeSuite(testCaseClass, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
647 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
648
649def findTestCases(module, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
650 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module)
Fred Drake02538202001-03-21 18:09:46 +0000651
652
653##############################################################################
654# Text UI
655##############################################################################
656
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000657class _WritelnDecorator(object):
Fred Drake02538202001-03-21 18:09:46 +0000658 """Used to decorate file-like objects with a handy 'writeln' method"""
659 def __init__(self,stream):
660 self.stream = stream
Fred Drake02538202001-03-21 18:09:46 +0000661
662 def __getattr__(self, attr):
663 return getattr(self.stream,attr)
664
Raymond Hettinger91dd19d2003-09-13 02:58:00 +0000665 def writeln(self, arg=None):
666 if arg: self.write(arg)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000667 self.write('\n') # text-mode streams translate to \r\n if needed
Tim Petersa19a1682001-03-29 04:36:09 +0000668
Fred Drake02538202001-03-21 18:09:46 +0000669
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000670class _TextTestResult(TestResult):
Fred Drake02538202001-03-21 18:09:46 +0000671 """A test result class that can print formatted text results to a stream.
672
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000673 Used by TextTestRunner.
Fred Drake02538202001-03-21 18:09:46 +0000674 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000675 separator1 = '=' * 70
676 separator2 = '-' * 70
Fred Drake02538202001-03-21 18:09:46 +0000677
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000678 def __init__(self, stream, descriptions, verbosity):
Fred Drake02538202001-03-21 18:09:46 +0000679 TestResult.__init__(self)
680 self.stream = stream
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000681 self.showAll = verbosity > 1
682 self.dots = verbosity == 1
Fred Drake02538202001-03-21 18:09:46 +0000683 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000684
685 def getDescription(self, test):
686 if self.descriptions:
687 return test.shortDescription() or str(test)
688 else:
689 return str(test)
690
Fred Drake02538202001-03-21 18:09:46 +0000691 def startTest(self, test):
692 TestResult.startTest(self, test)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000693 if self.showAll:
694 self.stream.write(self.getDescription(test))
695 self.stream.write(" ... ")
Georg Brandld0632402008-05-11 15:17:41 +0000696 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +0000697
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000698 def addSuccess(self, test):
699 TestResult.addSuccess(self, test)
700 if self.showAll:
Fred Drake02538202001-03-21 18:09:46 +0000701 self.stream.writeln("ok")
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000702 elif self.dots:
703 self.stream.write('.')
Georg Brandld0632402008-05-11 15:17:41 +0000704 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +0000705
706 def addError(self, test, err):
707 TestResult.addError(self, test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000708 if self.showAll:
709 self.stream.writeln("ERROR")
710 elif self.dots:
711 self.stream.write('E')
Georg Brandld0632402008-05-11 15:17:41 +0000712 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +0000713
714 def addFailure(self, test, err):
715 TestResult.addFailure(self, test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000716 if self.showAll:
717 self.stream.writeln("FAIL")
718 elif self.dots:
719 self.stream.write('F')
Georg Brandld0632402008-05-11 15:17:41 +0000720 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +0000721
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000722 def printErrors(self):
723 if self.dots or self.showAll:
Fred Drake02538202001-03-21 18:09:46 +0000724 self.stream.writeln()
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000725 self.printErrorList('ERROR', self.errors)
726 self.printErrorList('FAIL', self.failures)
727
728 def printErrorList(self, flavour, errors):
729 for test, err in errors:
730 self.stream.writeln(self.separator1)
731 self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
732 self.stream.writeln(self.separator2)
Steve Purcell7b065702001-09-06 08:24:40 +0000733 self.stream.writeln("%s" % err)
Fred Drake02538202001-03-21 18:09:46 +0000734
735
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000736class TextTestRunner(object):
Fred Drake02538202001-03-21 18:09:46 +0000737 """A test runner class that displays results in textual form.
Tim Petersa19a1682001-03-29 04:36:09 +0000738
Fred Drake02538202001-03-21 18:09:46 +0000739 It prints out the names of tests as they are run, errors as they
740 occur, and a summary of the results at the end of the test run.
741 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000742 def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1):
Fred Drake02538202001-03-21 18:09:46 +0000743 self.stream = _WritelnDecorator(stream)
744 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000745 self.verbosity = verbosity
746
747 def _makeResult(self):
748 return _TextTestResult(self.stream, self.descriptions, self.verbosity)
Fred Drake02538202001-03-21 18:09:46 +0000749
750 def run(self, test):
751 "Run the given test case or test suite."
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000752 result = self._makeResult()
Fred Drake02538202001-03-21 18:09:46 +0000753 startTime = time.time()
754 test(result)
755 stopTime = time.time()
Steve Purcell397b45d2003-10-26 10:41:03 +0000756 timeTaken = stopTime - startTime
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000757 result.printErrors()
758 self.stream.writeln(result.separator2)
Fred Drake02538202001-03-21 18:09:46 +0000759 run = result.testsRun
760 self.stream.writeln("Ran %d test%s in %.3fs" %
Neal Norwitz76165042002-05-31 14:15:11 +0000761 (run, run != 1 and "s" or "", timeTaken))
Fred Drake02538202001-03-21 18:09:46 +0000762 self.stream.writeln()
763 if not result.wasSuccessful():
764 self.stream.write("FAILED (")
765 failed, errored = map(len, (result.failures, result.errors))
766 if failed:
767 self.stream.write("failures=%d" % failed)
768 if errored:
769 if failed: self.stream.write(", ")
770 self.stream.write("errors=%d" % errored)
771 self.stream.writeln(")")
772 else:
773 self.stream.writeln("OK")
774 return result
Tim Petersa19a1682001-03-29 04:36:09 +0000775
Fred Drake02538202001-03-21 18:09:46 +0000776
Fred Drake02538202001-03-21 18:09:46 +0000777
778##############################################################################
779# Facilities for running tests from the command line
780##############################################################################
781
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000782class TestProgram(object):
Fred Drake02538202001-03-21 18:09:46 +0000783 """A command-line program that runs a set of tests; this is primarily
784 for making test modules conveniently executable.
785 """
786 USAGE = """\
Steve Purcell17a781b2001-04-09 15:37:31 +0000787Usage: %(progName)s [options] [test] [...]
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000788
789Options:
790 -h, --help Show this message
791 -v, --verbose Verbose output
792 -q, --quiet Minimal output
Fred Drake02538202001-03-21 18:09:46 +0000793
794Examples:
795 %(progName)s - run default set of tests
796 %(progName)s MyTestSuite - run suite 'MyTestSuite'
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000797 %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething
798 %(progName)s MyTestCase - run all 'test*' test methods
Fred Drake02538202001-03-21 18:09:46 +0000799 in MyTestCase
800"""
801 def __init__(self, module='__main__', defaultTest=None,
Georg Brandld0a96252007-03-07 09:21:06 +0000802 argv=None, testRunner=TextTestRunner,
803 testLoader=defaultTestLoader):
Antoine Pitroudae1a6a2008-12-28 16:01:11 +0000804 if isinstance(module, basestring):
Fred Drake02538202001-03-21 18:09:46 +0000805 self.module = __import__(module)
Steve Purcell7e743842003-09-22 11:08:12 +0000806 for part in module.split('.')[1:]:
Fred Drake02538202001-03-21 18:09:46 +0000807 self.module = getattr(self.module, part)
808 else:
809 self.module = module
810 if argv is None:
811 argv = sys.argv
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000812 self.verbosity = 1
Fred Drake02538202001-03-21 18:09:46 +0000813 self.defaultTest = defaultTest
814 self.testRunner = testRunner
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000815 self.testLoader = testLoader
Fred Drake02538202001-03-21 18:09:46 +0000816 self.progName = os.path.basename(argv[0])
817 self.parseArgs(argv)
Fred Drake02538202001-03-21 18:09:46 +0000818 self.runTests()
819
820 def usageExit(self, msg=None):
821 if msg: print msg
822 print self.USAGE % self.__dict__
823 sys.exit(2)
824
825 def parseArgs(self, argv):
826 import getopt
827 try:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000828 options, args = getopt.getopt(argv[1:], 'hHvq',
829 ['help','verbose','quiet'])
Fred Drake02538202001-03-21 18:09:46 +0000830 for opt, value in options:
831 if opt in ('-h','-H','--help'):
832 self.usageExit()
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000833 if opt in ('-q','--quiet'):
834 self.verbosity = 0
835 if opt in ('-v','--verbose'):
836 self.verbosity = 2
Fred Drake02538202001-03-21 18:09:46 +0000837 if len(args) == 0 and self.defaultTest is None:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000838 self.test = self.testLoader.loadTestsFromModule(self.module)
839 return
Fred Drake02538202001-03-21 18:09:46 +0000840 if len(args) > 0:
841 self.testNames = args
842 else:
843 self.testNames = (self.defaultTest,)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000844 self.createTests()
Fred Drake02538202001-03-21 18:09:46 +0000845 except getopt.error, msg:
846 self.usageExit(msg)
847
848 def createTests(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000849 self.test = self.testLoader.loadTestsFromNames(self.testNames,
850 self.module)
Fred Drake02538202001-03-21 18:09:46 +0000851
852 def runTests(self):
Georg Brandld0a96252007-03-07 09:21:06 +0000853 if isinstance(self.testRunner, (type, types.ClassType)):
854 try:
855 testRunner = self.testRunner(verbosity=self.verbosity)
856 except TypeError:
857 # didn't accept the verbosity argument
858 testRunner = self.testRunner()
859 else:
860 # it is assumed to be a TestRunner instance
861 testRunner = self.testRunner
862 result = testRunner.run(self.test)
Tim Petersa19a1682001-03-29 04:36:09 +0000863 sys.exit(not result.wasSuccessful())
Fred Drake02538202001-03-21 18:09:46 +0000864
865main = TestProgram
866
867
868##############################################################################
869# Executing this module from the command line
870##############################################################################
871
872if __name__ == "__main__":
873 main(module=None)