blob: fec41cac30718e42262d887956d4f27abe04741b [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
Benjamin Peterson1467ac82009-01-09 03:42:38 +000076class TestResult(object):
Fred Drake02538202001-03-21 18:09:46 +000077 """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)
Collin Winterce36ad82007-08-30 01:19:48 +0000133 return ''.join(traceback.format_exception(exctype, value,
134 tb, length))
Steve Purcellb8d5f242003-12-06 13:03:13 +0000135 return ''.join(traceback.format_exception(exctype, value, tb))
136
137 def _is_relevant_tb_level(self, tb):
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000138 return '__unittest' in tb.tb_frame.f_globals
Steve Purcellb8d5f242003-12-06 13:03:13 +0000139
140 def _count_relevant_tb_levels(self, tb):
141 length = 0
142 while tb and not self._is_relevant_tb_level(tb):
143 length += 1
144 tb = tb.tb_next
145 return length
Steve Purcell7b065702001-09-06 08:24:40 +0000146
Fred Drake02538202001-03-21 18:09:46 +0000147 def __repr__(self):
148 return "<%s run=%i errors=%i failures=%i>" % \
Steve Purcelldc391a62002-08-09 09:46:23 +0000149 (_strclass(self.__class__), self.testsRun, len(self.errors),
Fred Drake02538202001-03-21 18:09:46 +0000150 len(self.failures))
151
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000152class AssertRaisesContext(object):
Antoine Pitrou5acd41e2008-12-28 14:29:00 +0000153 def __init__(self, expected, test_case, callable_obj=None):
154 self.expected = expected
155 self.failureException = test_case.failureException
156 if callable_obj is not None:
157 try:
158 self.obj_name = callable_obj.__name__
159 except AttributeError:
160 self.obj_name = str(callable_obj)
161 else:
162 self.obj_name = None
163 def __enter__(self):
164 pass
165 def __exit__(self, exc_type, exc_value, traceback):
166 if exc_type is None:
167 try:
168 exc_name = self.expected.__name__
169 except AttributeError:
170 exc_name = str(self.expected)
171 if self.obj_name:
172 raise self.failureException("{0} not raised by {1}"
173 .format(exc_name, self.obj_name))
174 else:
175 raise self.failureException("{0} not raised"
176 .format(exc_name))
177 if issubclass(exc_type, self.expected):
178 return True
179 # Let unexpected exceptions skip through
180 return False
181
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000182class TestCase(object):
Fred Drake02538202001-03-21 18:09:46 +0000183 """A class whose instances are single test cases.
184
Fred Drake02538202001-03-21 18:09:46 +0000185 By default, the test code itself should be placed in a method named
186 'runTest'.
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000187
Tim Petersa19a1682001-03-29 04:36:09 +0000188 If the fixture may be used for many test cases, create as
Fred Drake02538202001-03-21 18:09:46 +0000189 many test methods as are needed. When instantiating such a TestCase
190 subclass, specify in the constructor arguments the name of the test method
191 that the instance is to execute.
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000192
Tim Petersa19a1682001-03-29 04:36:09 +0000193 Test authors should subclass TestCase for their own tests. Construction
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000194 and deconstruction of the test's environment ('fixture') can be
195 implemented by overriding the 'setUp' and 'tearDown' methods respectively.
196
197 If it is necessary to override the __init__ method, the base class
198 __init__ method must always be called. It is important that subclasses
199 should not change the signature of their __init__ method, since instances
200 of the classes are instantiated automatically by parts of the framework
201 in order to be run.
Fred Drake02538202001-03-21 18:09:46 +0000202 """
Steve Purcell15d89272001-04-12 09:05:01 +0000203
204 # This attribute determines which exception will be raised when
205 # the instance's assertion methods fail; test methods raising this
206 # exception will be deemed to have 'failed' rather than 'errored'
207
208 failureException = AssertionError
209
Fred Drake02538202001-03-21 18:09:46 +0000210 def __init__(self, methodName='runTest'):
211 """Create an instance of the class that will use the named test
212 method when executed. Raises a ValueError if the instance does
213 not have a method with the specified name.
214 """
215 try:
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000216 self._testMethodName = methodName
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000217 testMethod = getattr(self, methodName)
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000218 self._testMethodDoc = testMethod.__doc__
Fred Drake02538202001-03-21 18:09:46 +0000219 except AttributeError:
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000220 raise ValueError("no such test method in %s: %s" % \
221 (self.__class__, methodName))
Fred Drake02538202001-03-21 18:09:46 +0000222
223 def setUp(self):
224 "Hook method for setting up the test fixture before exercising it."
225 pass
226
227 def tearDown(self):
228 "Hook method for deconstructing the test fixture after testing it."
229 pass
230
231 def countTestCases(self):
232 return 1
233
234 def defaultTestResult(self):
235 return TestResult()
236
237 def shortDescription(self):
238 """Returns a one-line description of the test, or None if no
239 description has been provided.
240
241 The default implementation of this method returns the first line of
242 the specified test method's docstring.
243 """
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000244 doc = self._testMethodDoc
Steve Purcell7e743842003-09-22 11:08:12 +0000245 return doc and doc.split("\n")[0].strip() or None
Fred Drake02538202001-03-21 18:09:46 +0000246
247 def id(self):
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000248 return "%s.%s" % (_strclass(self.__class__), self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000249
Guido van Rossumd8faa362007-04-27 19:54:29 +0000250 def __eq__(self, other):
251 if type(self) is not type(other):
252 return False
253
254 return self._testMethodName == other._testMethodName
255
256 def __ne__(self, other):
257 return not self == other
258
259 def __hash__(self):
260 return hash((type(self), self._testMethodName))
261
Fred Drake02538202001-03-21 18:09:46 +0000262 def __str__(self):
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000263 return "%s (%s)" % (self._testMethodName, _strclass(self.__class__))
Fred Drake02538202001-03-21 18:09:46 +0000264
265 def __repr__(self):
266 return "<%s testMethod=%s>" % \
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000267 (_strclass(self.__class__), self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000268
269 def run(self, result=None):
Fred Drake02538202001-03-21 18:09:46 +0000270 if result is None: result = self.defaultTestResult()
271 result.startTest(self)
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000272 testMethod = getattr(self, self._testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000273 try:
274 try:
275 self.setUp()
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000276 except Exception:
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000277 result.addError(self, self._exc_info())
Fred Drake02538202001-03-21 18:09:46 +0000278 return
279
Steve Purcell7e743842003-09-22 11:08:12 +0000280 ok = False
Fred Drake02538202001-03-21 18:09:46 +0000281 try:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000282 testMethod()
Steve Purcell7e743842003-09-22 11:08:12 +0000283 ok = True
Skip Montanaroae5c37b2003-07-13 15:18:12 +0000284 except self.failureException:
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000285 result.addFailure(self, self._exc_info())
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000286 except Exception:
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000287 result.addError(self, self._exc_info())
Fred Drake02538202001-03-21 18:09:46 +0000288
289 try:
290 self.tearDown()
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000291 except Exception:
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000292 result.addError(self, self._exc_info())
Steve Purcell7e743842003-09-22 11:08:12 +0000293 ok = False
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000294 if ok: result.addSuccess(self)
Fred Drake02538202001-03-21 18:09:46 +0000295 finally:
296 result.stopTest(self)
297
Raymond Hettinger664347b2004-12-04 21:21:53 +0000298 def __call__(self, *args, **kwds):
299 return self.run(*args, **kwds)
Steve Purcell7e743842003-09-22 11:08:12 +0000300
Fred Drake02538202001-03-21 18:09:46 +0000301 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000302 """Run the test without collecting errors in a TestResult"""
Fred Drake02538202001-03-21 18:09:46 +0000303 self.setUp()
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000304 getattr(self, self._testMethodName)()
Fred Drake02538202001-03-21 18:09:46 +0000305 self.tearDown()
306
Georg Brandl81cdb4e2006-01-20 17:55:00 +0000307 def _exc_info(self):
Steve Purcell15d89272001-04-12 09:05:01 +0000308 """Return a version of sys.exc_info() with the traceback frame
309 minimised; usually the top level of the traceback frame is not
310 needed.
Fred Drake02538202001-03-21 18:09:46 +0000311 """
Guido van Rossumd8faa362007-04-27 19:54:29 +0000312 return sys.exc_info()
Fred Drake02538202001-03-21 18:09:46 +0000313
Steve Purcell15d89272001-04-12 09:05:01 +0000314 def fail(self, msg=None):
315 """Fail immediately, with the given message."""
Collin Winterce36ad82007-08-30 01:19:48 +0000316 raise self.failureException(msg)
Fred Drake02538202001-03-21 18:09:46 +0000317
318 def failIf(self, expr, msg=None):
319 "Fail the test if the expression is true."
Collin Winterce36ad82007-08-30 01:19:48 +0000320 if expr: raise self.failureException(msg)
Fred Drake02538202001-03-21 18:09:46 +0000321
Steve Purcell15d89272001-04-12 09:05:01 +0000322 def failUnless(self, expr, msg=None):
323 """Fail the test unless the expression is true."""
Collin Winterce36ad82007-08-30 01:19:48 +0000324 if not expr: raise self.failureException(msg)
Steve Purcell15d89272001-04-12 09:05:01 +0000325
Antoine Pitrou5acd41e2008-12-28 14:29:00 +0000326 def failUnlessRaises(self, excClass, callableObj=None, *args, **kwargs):
Steve Purcell15d89272001-04-12 09:05:01 +0000327 """Fail unless an exception of class excClass is thrown
Fred Drake02538202001-03-21 18:09:46 +0000328 by callableObj when invoked with arguments args and keyword
329 arguments kwargs. If a different type of exception is
330 thrown, it will not be caught, and the test case will be
331 deemed to have suffered an error, exactly as for an
332 unexpected exception.
Antoine Pitrou5acd41e2008-12-28 14:29:00 +0000333
334 If called with callableObj omitted or None, will return a
335 context object used like this::
336
337 with self.failUnlessRaises(some_error_class):
338 do_something()
Fred Drake02538202001-03-21 18:09:46 +0000339 """
Antoine Pitrou5acd41e2008-12-28 14:29:00 +0000340 context = AssertRaisesContext(excClass, self, callableObj)
341 if callableObj is None:
342 return context
343 with context:
Guido van Rossum68468eb2003-02-27 20:14:51 +0000344 callableObj(*args, **kwargs)
Fred Drake02538202001-03-21 18:09:46 +0000345
Steve Purcell15d89272001-04-12 09:05:01 +0000346 def failUnlessEqual(self, first, second, msg=None):
Raymond Hettingerc377cbf2003-04-04 22:56:42 +0000347 """Fail if the two objects are unequal as determined by the '=='
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000348 operator.
349 """
Raymond Hettingerc377cbf2003-04-04 22:56:42 +0000350 if not first == second:
Collin Winterce36ad82007-08-30 01:19:48 +0000351 raise self.failureException(msg or '%r != %r' % (first, second))
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000352
Steve Purcell15d89272001-04-12 09:05:01 +0000353 def failIfEqual(self, first, second, msg=None):
354 """Fail if the two objects are equal as determined by the '=='
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000355 operator.
356 """
Steve Purcell15d89272001-04-12 09:05:01 +0000357 if first == second:
Collin Winterce36ad82007-08-30 01:19:48 +0000358 raise self.failureException(msg or '%r == %r' % (first, second))
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000359
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +0000360 def failUnlessAlmostEqual(self, first, second, *, places=7, msg=None):
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000361 """Fail if the two objects are unequal as determined by their
362 difference rounded to the given number of decimal places
363 (default 7) and comparing to zero.
364
Steve Purcell397b45d2003-10-26 10:41:03 +0000365 Note that decimal places (from zero) are usually not the same
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000366 as significant digits (measured from the most signficant digit).
367 """
Jeffrey Yasskin1cc55442007-09-06 18:55:17 +0000368 if round(abs(second-first), places) != 0:
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000369 raise self.failureException(
370 msg or '%r != %r within %r places' % (first, second, places))
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000371
Jeffrey Yasskinaaaef112007-09-07 15:00:39 +0000372 def failIfAlmostEqual(self, first, second, *, places=7, msg=None):
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000373 """Fail if the two objects are equal as determined by their
374 difference rounded to the given number of decimal places
375 (default 7) and comparing to zero.
376
Steve Purcellcca34912003-10-26 16:38:16 +0000377 Note that decimal places (from zero) are usually not the same
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000378 as significant digits (measured from the most signficant digit).
379 """
Jeffrey Yasskin1cc55442007-09-06 18:55:17 +0000380 if round(abs(second-first), places) == 0:
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000381 raise self.failureException(
382 msg or '%r == %r within %r places' % (first, second, places))
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000383
Steve Purcell7e743842003-09-22 11:08:12 +0000384 # Synonyms for assertion methods
385
Steve Purcell15d89272001-04-12 09:05:01 +0000386 assertEqual = assertEquals = failUnlessEqual
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000387
Steve Purcell15d89272001-04-12 09:05:01 +0000388 assertNotEqual = assertNotEquals = failIfEqual
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000389
Raymond Hettingerc7b07692002-12-29 17:59:24 +0000390 assertAlmostEqual = assertAlmostEquals = failUnlessAlmostEqual
391
392 assertNotAlmostEqual = assertNotAlmostEquals = failIfAlmostEqual
393
Steve Purcell15d89272001-04-12 09:05:01 +0000394 assertRaises = failUnlessRaises
395
Steve Purcell7e743842003-09-22 11:08:12 +0000396 assert_ = assertTrue = failUnless
397
398 assertFalse = failIf
Steve Purcell15d89272001-04-12 09:05:01 +0000399
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000400
Fred Drake02538202001-03-21 18:09:46 +0000401
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000402class TestSuite(object):
Fred Drake02538202001-03-21 18:09:46 +0000403 """A test suite is a composite test consisting of a number of TestCases.
404
405 For use, create an instance of TestSuite, then add test case instances.
406 When all tests have been added, the suite can be passed to a test
407 runner, such as TextTestRunner. It will run the individual test cases
408 in the order in which they were added, aggregating the results. When
409 subclassing, do not forget to call the base class constructor.
410 """
411 def __init__(self, tests=()):
412 self._tests = []
413 self.addTests(tests)
414
415 def __repr__(self):
Steve Purcelldc391a62002-08-09 09:46:23 +0000416 return "<%s tests=%s>" % (_strclass(self.__class__), self._tests)
Fred Drake02538202001-03-21 18:09:46 +0000417
418 __str__ = __repr__
419
Guido van Rossumd8faa362007-04-27 19:54:29 +0000420 def __eq__(self, other):
421 if type(self) is not type(other):
422 return False
423 return self._tests == other._tests
424
425 def __ne__(self, other):
426 return not self == other
427
Jim Fultonfafd8742004-08-28 15:22:12 +0000428 def __iter__(self):
429 return iter(self._tests)
430
Fred Drake02538202001-03-21 18:09:46 +0000431 def countTestCases(self):
432 cases = 0
433 for test in self._tests:
Steve Purcell7e743842003-09-22 11:08:12 +0000434 cases += test.countTestCases()
Fred Drake02538202001-03-21 18:09:46 +0000435 return cases
436
437 def addTest(self, test):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000438 # sanity checks
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000439 if not hasattr(test, '__call__'):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000440 raise TypeError("the test to add must be callable")
Guido van Rossum13257902007-06-07 23:15:56 +0000441 if isinstance(test, type) and issubclass(test, (TestCase, TestSuite)):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000442 raise TypeError("TestCases and TestSuites must be instantiated "
443 "before passing them to addTest()")
Fred Drake02538202001-03-21 18:09:46 +0000444 self._tests.append(test)
445
446 def addTests(self, tests):
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000447 if isinstance(tests, str):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000448 raise TypeError("tests must be an iterable of tests, not a string")
Fred Drake02538202001-03-21 18:09:46 +0000449 for test in tests:
450 self.addTest(test)
451
452 def run(self, result):
Fred Drake02538202001-03-21 18:09:46 +0000453 for test in self._tests:
454 if result.shouldStop:
455 break
456 test(result)
457 return result
458
Raymond Hettinger664347b2004-12-04 21:21:53 +0000459 def __call__(self, *args, **kwds):
460 return self.run(*args, **kwds)
461
Fred Drake02538202001-03-21 18:09:46 +0000462 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000463 """Run the tests without collecting errors in a TestResult"""
Fred Drake02538202001-03-21 18:09:46 +0000464 for test in self._tests: test.debug()
Fred Drake02538202001-03-21 18:09:46 +0000465
466
467class FunctionTestCase(TestCase):
468 """A test case that wraps a test function.
469
470 This is useful for slipping pre-existing test functions into the
Guido van Rossumd8faa362007-04-27 19:54:29 +0000471 unittest framework. Optionally, set-up and tidy-up functions can be
Fred Drake02538202001-03-21 18:09:46 +0000472 supplied. As with TestCase, the tidy-up ('tearDown') function will
473 always be called if the set-up ('setUp') function ran successfully.
474 """
475
476 def __init__(self, testFunc, setUp=None, tearDown=None,
477 description=None):
478 TestCase.__init__(self)
479 self.__setUpFunc = setUp
480 self.__tearDownFunc = tearDown
481 self.__testFunc = testFunc
482 self.__description = description
483
484 def setUp(self):
485 if self.__setUpFunc is not None:
486 self.__setUpFunc()
487
488 def tearDown(self):
489 if self.__tearDownFunc is not None:
490 self.__tearDownFunc()
491
492 def runTest(self):
493 self.__testFunc()
494
495 def id(self):
496 return self.__testFunc.__name__
497
Guido van Rossumd8faa362007-04-27 19:54:29 +0000498 def __eq__(self, other):
499 if type(self) is not type(other):
500 return False
501
502 return self.__setUpFunc == other.__setUpFunc and \
503 self.__tearDownFunc == other.__tearDownFunc and \
504 self.__testFunc == other.__testFunc and \
505 self.__description == other.__description
506
507 def __ne__(self, other):
508 return not self == other
509
510 def __hash__(self):
511 return hash((type(self), self.__setUpFunc, self.__tearDownFunc,
Collin Winterce36ad82007-08-30 01:19:48 +0000512 self.__testFunc, self.__description))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000513
Fred Drake02538202001-03-21 18:09:46 +0000514 def __str__(self):
Collin Winterce36ad82007-08-30 01:19:48 +0000515 return "%s (%s)" % (_strclass(self.__class__),
516 self.__testFunc.__name__)
Fred Drake02538202001-03-21 18:09:46 +0000517
518 def __repr__(self):
Collin Winterce36ad82007-08-30 01:19:48 +0000519 return "<%s testFunc=%s>" % (_strclass(self.__class__),
520 self.__testFunc)
Fred Drake02538202001-03-21 18:09:46 +0000521
522 def shortDescription(self):
523 if self.__description is not None: return self.__description
524 doc = self.__testFunc.__doc__
Steve Purcell7e743842003-09-22 11:08:12 +0000525 return doc and doc.split("\n")[0].strip() or None
Fred Drake02538202001-03-21 18:09:46 +0000526
527
528
529##############################################################################
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000530# Locating and loading tests
Fred Drake02538202001-03-21 18:09:46 +0000531##############################################################################
532
Raymond Hettingerd4cb56d2008-01-30 02:55:10 +0000533def CmpToKey(mycmp):
534 'Convert a cmp= function into a key= function'
535 class K(object):
536 def __init__(self, obj, *args):
537 self.obj = obj
538 def __lt__(self, other):
539 return mycmp(self.obj, other.obj) == -1
540 return K
541
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000542class TestLoader(object):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000543 """This class is responsible for loading tests according to various
Guido van Rossumd8faa362007-04-27 19:54:29 +0000544 criteria and returning them wrapped in a TestSuite
Fred Drake02538202001-03-21 18:09:46 +0000545 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000546 testMethodPrefix = 'test'
547 sortTestMethodsUsing = cmp
548 suiteClass = TestSuite
Fred Drake02538202001-03-21 18:09:46 +0000549
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000550 def loadTestsFromTestCase(self, testCaseClass):
Steve Purcell15d89272001-04-12 09:05:01 +0000551 """Return a suite of all tests cases contained in testCaseClass"""
Johannes Gijsbersd7b6ad42004-11-07 15:46:25 +0000552 if issubclass(testCaseClass, TestSuite):
Collin Winterce36ad82007-08-30 01:19:48 +0000553 raise TypeError("Test cases should not be derived from TestSuite."
554 "Maybe you meant to derive from TestCase?")
Steve Purcell7e743842003-09-22 11:08:12 +0000555 testCaseNames = self.getTestCaseNames(testCaseClass)
556 if not testCaseNames and hasattr(testCaseClass, 'runTest'):
557 testCaseNames = ['runTest']
558 return self.suiteClass(map(testCaseClass, testCaseNames))
Fred Drake02538202001-03-21 18:09:46 +0000559
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000560 def loadTestsFromModule(self, module):
Steve Purcell15d89272001-04-12 09:05:01 +0000561 """Return a suite of all tests cases contained in the given module"""
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000562 tests = []
563 for name in dir(module):
564 obj = getattr(module, name)
Guido van Rossum13257902007-06-07 23:15:56 +0000565 if isinstance(obj, type) and issubclass(obj, TestCase):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000566 tests.append(self.loadTestsFromTestCase(obj))
567 return self.suiteClass(tests)
Fred Drake02538202001-03-21 18:09:46 +0000568
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000569 def loadTestsFromName(self, name, module=None):
Steve Purcell15d89272001-04-12 09:05:01 +0000570 """Return a suite of all tests cases given a string specifier.
571
572 The name may resolve either to a module, a test case class, a
573 test method within a test case class, or a callable object which
574 returns a TestCase or TestSuite instance.
Tim Peters613b2222001-04-13 05:37:27 +0000575
Steve Purcell15d89272001-04-12 09:05:01 +0000576 The method optionally resolves the names relative to a given module.
577 """
Steve Purcell7e743842003-09-22 11:08:12 +0000578 parts = name.split('.')
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000579 if module is None:
Steve Purcell7e743842003-09-22 11:08:12 +0000580 parts_copy = parts[:]
581 while parts_copy:
582 try:
583 module = __import__('.'.join(parts_copy))
584 break
585 except ImportError:
586 del parts_copy[-1]
587 if not parts_copy: raise
Armin Rigo1b3c04b2003-10-24 17:15:29 +0000588 parts = parts[1:]
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000589 obj = module
590 for part in parts:
Steve Purcell7e743842003-09-22 11:08:12 +0000591 parent, obj = obj, getattr(obj, part)
Fred Drake02538202001-03-21 18:09:46 +0000592
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000593 if isinstance(obj, types.ModuleType):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000594 return self.loadTestsFromModule(obj)
Guido van Rossum13257902007-06-07 23:15:56 +0000595 elif isinstance(obj, type) and issubclass(obj, TestCase):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000596 return self.loadTestsFromTestCase(obj)
Christian Heimes4a22b5d2007-11-25 09:39:14 +0000597 elif (isinstance(obj, types.FunctionType) and
Guido van Rossum13257902007-06-07 23:15:56 +0000598 isinstance(parent, type) and
Guido van Rossumd8faa362007-04-27 19:54:29 +0000599 issubclass(parent, TestCase)):
Christian Heimes4a22b5d2007-11-25 09:39:14 +0000600 name = obj.__name__
601 inst = parent(name)
602 # static methods follow a different path
Christian Heimes4975a1f2007-11-26 10:14:51 +0000603 if not isinstance(getattr(inst, name), types.FunctionType):
Christian Heimes4a22b5d2007-11-25 09:39:14 +0000604 return TestSuite([inst])
Steve Purcell397b45d2003-10-26 10:41:03 +0000605 elif isinstance(obj, TestSuite):
Steve Purcell7e743842003-09-22 11:08:12 +0000606 return obj
Christian Heimes4a22b5d2007-11-25 09:39:14 +0000607
608 if hasattr(obj, '__call__'):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000609 test = obj()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000610 if isinstance(test, TestSuite):
611 return test
612 elif isinstance(test, TestCase):
613 return TestSuite([test])
614 else:
615 raise TypeError("calling %s returned %s, not a test" %
616 (obj, test))
Fred Drake02538202001-03-21 18:09:46 +0000617 else:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000618 raise TypeError("don't know how to make test from: %s" % obj)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000619
620 def loadTestsFromNames(self, names, module=None):
Steve Purcell15d89272001-04-12 09:05:01 +0000621 """Return a suite of all tests cases found using the given sequence
622 of string specifiers. See 'loadTestsFromName()'.
623 """
Steve Purcell7e743842003-09-22 11:08:12 +0000624 suites = [self.loadTestsFromName(name, module) for name in names]
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000625 return self.suiteClass(suites)
626
627 def getTestCaseNames(self, testCaseClass):
Steve Purcell15d89272001-04-12 09:05:01 +0000628 """Return a sorted sequence of method names found within testCaseClass
629 """
Collin Winterce36ad82007-08-30 01:19:48 +0000630 def isTestMethod(attrname, testCaseClass=testCaseClass,
631 prefix=self.testMethodPrefix):
632 return attrname.startswith(prefix) \
633 and hasattr(getattr(testCaseClass, attrname), '__call__')
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000634 testFnNames = list(filter(isTestMethod, dir(testCaseClass)))
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000635 if self.sortTestMethodsUsing:
Raymond Hettingerd4cb56d2008-01-30 02:55:10 +0000636 testFnNames.sort(key=CmpToKey(self.sortTestMethodsUsing))
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000637 return testFnNames
638
639
640
641defaultTestLoader = TestLoader()
642
643
644##############################################################################
645# Patches for old functions: these functions should be considered obsolete
646##############################################################################
647
648def _makeLoader(prefix, sortUsing, suiteClass=None):
649 loader = TestLoader()
650 loader.sortTestMethodsUsing = sortUsing
651 loader.testMethodPrefix = prefix
652 if suiteClass: loader.suiteClass = suiteClass
653 return loader
654
655def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp):
656 return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)
657
658def makeSuite(testCaseClass, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
659 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
660
661def findTestCases(module, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
662 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module)
Fred Drake02538202001-03-21 18:09:46 +0000663
664
665##############################################################################
666# Text UI
667##############################################################################
668
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000669class _WritelnDecorator(object):
Fred Drake02538202001-03-21 18:09:46 +0000670 """Used to decorate file-like objects with a handy 'writeln' method"""
671 def __init__(self,stream):
672 self.stream = stream
Fred Drake02538202001-03-21 18:09:46 +0000673
674 def __getattr__(self, attr):
675 return getattr(self.stream,attr)
676
Raymond Hettinger91dd19d2003-09-13 02:58:00 +0000677 def writeln(self, arg=None):
678 if arg: self.write(arg)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000679 self.write('\n') # text-mode streams translate to \r\n if needed
Tim Petersa19a1682001-03-29 04:36:09 +0000680
Fred Drake02538202001-03-21 18:09:46 +0000681
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000682class _TextTestResult(TestResult):
Fred Drake02538202001-03-21 18:09:46 +0000683 """A test result class that can print formatted text results to a stream.
684
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000685 Used by TextTestRunner.
Fred Drake02538202001-03-21 18:09:46 +0000686 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000687 separator1 = '=' * 70
688 separator2 = '-' * 70
Fred Drake02538202001-03-21 18:09:46 +0000689
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000690 def __init__(self, stream, descriptions, verbosity):
Fred Drake02538202001-03-21 18:09:46 +0000691 TestResult.__init__(self)
692 self.stream = stream
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000693 self.showAll = verbosity > 1
694 self.dots = verbosity == 1
Fred Drake02538202001-03-21 18:09:46 +0000695 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000696
697 def getDescription(self, test):
698 if self.descriptions:
699 return test.shortDescription() or str(test)
700 else:
701 return str(test)
702
Fred Drake02538202001-03-21 18:09:46 +0000703 def startTest(self, test):
704 TestResult.startTest(self, test)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000705 if self.showAll:
706 self.stream.write(self.getDescription(test))
707 self.stream.write(" ... ")
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000708 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +0000709
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000710 def addSuccess(self, test):
711 TestResult.addSuccess(self, test)
712 if self.showAll:
Fred Drake02538202001-03-21 18:09:46 +0000713 self.stream.writeln("ok")
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000714 elif self.dots:
715 self.stream.write('.')
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000716 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +0000717
718 def addError(self, test, err):
719 TestResult.addError(self, test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000720 if self.showAll:
721 self.stream.writeln("ERROR")
722 elif self.dots:
723 self.stream.write('E')
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000724 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +0000725
726 def addFailure(self, test, err):
727 TestResult.addFailure(self, test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000728 if self.showAll:
729 self.stream.writeln("FAIL")
730 elif self.dots:
731 self.stream.write('F')
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000732 self.stream.flush()
Fred Drake02538202001-03-21 18:09:46 +0000733
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000734 def printErrors(self):
735 if self.dots or self.showAll:
Fred Drake02538202001-03-21 18:09:46 +0000736 self.stream.writeln()
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000737 self.printErrorList('ERROR', self.errors)
738 self.printErrorList('FAIL', self.failures)
739
740 def printErrorList(self, flavour, errors):
741 for test, err in errors:
742 self.stream.writeln(self.separator1)
743 self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
744 self.stream.writeln(self.separator2)
Steve Purcell7b065702001-09-06 08:24:40 +0000745 self.stream.writeln("%s" % err)
Fred Drake02538202001-03-21 18:09:46 +0000746
747
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000748class TextTestRunner(object):
Fred Drake02538202001-03-21 18:09:46 +0000749 """A test runner class that displays results in textual form.
Tim Petersa19a1682001-03-29 04:36:09 +0000750
Fred Drake02538202001-03-21 18:09:46 +0000751 It prints out the names of tests as they are run, errors as they
752 occur, and a summary of the results at the end of the test run.
753 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000754 def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1):
Fred Drake02538202001-03-21 18:09:46 +0000755 self.stream = _WritelnDecorator(stream)
756 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000757 self.verbosity = verbosity
758
759 def _makeResult(self):
760 return _TextTestResult(self.stream, self.descriptions, self.verbosity)
Fred Drake02538202001-03-21 18:09:46 +0000761
762 def run(self, test):
763 "Run the given test case or test suite."
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000764 result = self._makeResult()
Fred Drake02538202001-03-21 18:09:46 +0000765 startTime = time.time()
766 test(result)
767 stopTime = time.time()
Steve Purcell397b45d2003-10-26 10:41:03 +0000768 timeTaken = stopTime - startTime
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000769 result.printErrors()
770 self.stream.writeln(result.separator2)
Fred Drake02538202001-03-21 18:09:46 +0000771 run = result.testsRun
772 self.stream.writeln("Ran %d test%s in %.3fs" %
Neal Norwitz76165042002-05-31 14:15:11 +0000773 (run, run != 1 and "s" or "", timeTaken))
Fred Drake02538202001-03-21 18:09:46 +0000774 self.stream.writeln()
775 if not result.wasSuccessful():
776 self.stream.write("FAILED (")
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000777 failed, errored = len(result.failures), len(result.errors)
Fred Drake02538202001-03-21 18:09:46 +0000778 if failed:
779 self.stream.write("failures=%d" % failed)
780 if errored:
781 if failed: self.stream.write(", ")
782 self.stream.write("errors=%d" % errored)
783 self.stream.writeln(")")
784 else:
785 self.stream.writeln("OK")
786 return result
Tim Petersa19a1682001-03-29 04:36:09 +0000787
Fred Drake02538202001-03-21 18:09:46 +0000788
Fred Drake02538202001-03-21 18:09:46 +0000789
790##############################################################################
791# Facilities for running tests from the command line
792##############################################################################
793
Benjamin Peterson1467ac82009-01-09 03:42:38 +0000794class TestProgram(object):
Fred Drake02538202001-03-21 18:09:46 +0000795 """A command-line program that runs a set of tests; this is primarily
796 for making test modules conveniently executable.
797 """
798 USAGE = """\
Steve Purcell17a781b2001-04-09 15:37:31 +0000799Usage: %(progName)s [options] [test] [...]
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000800
801Options:
802 -h, --help Show this message
803 -v, --verbose Verbose output
804 -q, --quiet Minimal output
Fred Drake02538202001-03-21 18:09:46 +0000805
806Examples:
807 %(progName)s - run default set of tests
808 %(progName)s MyTestSuite - run suite 'MyTestSuite'
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000809 %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething
810 %(progName)s MyTestCase - run all 'test*' test methods
Fred Drake02538202001-03-21 18:09:46 +0000811 in MyTestCase
812"""
813 def __init__(self, module='__main__', defaultTest=None,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000814 argv=None, testRunner=TextTestRunner,
815 testLoader=defaultTestLoader):
Antoine Pitroue7bd8682009-01-09 19:29:16 +0000816 if isinstance(module, str):
Fred Drake02538202001-03-21 18:09:46 +0000817 self.module = __import__(module)
Steve Purcell7e743842003-09-22 11:08:12 +0000818 for part in module.split('.')[1:]:
Fred Drake02538202001-03-21 18:09:46 +0000819 self.module = getattr(self.module, part)
820 else:
821 self.module = module
822 if argv is None:
823 argv = sys.argv
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000824 self.verbosity = 1
Fred Drake02538202001-03-21 18:09:46 +0000825 self.defaultTest = defaultTest
826 self.testRunner = testRunner
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000827 self.testLoader = testLoader
Fred Drake02538202001-03-21 18:09:46 +0000828 self.progName = os.path.basename(argv[0])
829 self.parseArgs(argv)
Fred Drake02538202001-03-21 18:09:46 +0000830 self.runTests()
831
832 def usageExit(self, msg=None):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000833 if msg: print(msg)
834 print(self.USAGE % self.__dict__)
Fred Drake02538202001-03-21 18:09:46 +0000835 sys.exit(2)
836
837 def parseArgs(self, argv):
838 import getopt
839 try:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000840 options, args = getopt.getopt(argv[1:], 'hHvq',
841 ['help','verbose','quiet'])
Fred Drake02538202001-03-21 18:09:46 +0000842 for opt, value in options:
843 if opt in ('-h','-H','--help'):
844 self.usageExit()
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000845 if opt in ('-q','--quiet'):
846 self.verbosity = 0
847 if opt in ('-v','--verbose'):
848 self.verbosity = 2
Fred Drake02538202001-03-21 18:09:46 +0000849 if len(args) == 0 and self.defaultTest is None:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000850 self.test = self.testLoader.loadTestsFromModule(self.module)
851 return
Fred Drake02538202001-03-21 18:09:46 +0000852 if len(args) > 0:
853 self.testNames = args
854 else:
855 self.testNames = (self.defaultTest,)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000856 self.createTests()
Guido van Rossumb940e112007-01-10 16:19:56 +0000857 except getopt.error as msg:
Fred Drake02538202001-03-21 18:09:46 +0000858 self.usageExit(msg)
859
860 def createTests(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000861 self.test = self.testLoader.loadTestsFromNames(self.testNames,
862 self.module)
Fred Drake02538202001-03-21 18:09:46 +0000863
864 def runTests(self):
Guido van Rossum13257902007-06-07 23:15:56 +0000865 if isinstance(self.testRunner, type):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000866 try:
867 testRunner = self.testRunner(verbosity=self.verbosity)
868 except TypeError:
869 # didn't accept the verbosity argument
870 testRunner = self.testRunner()
871 else:
872 # it is assumed to be a TestRunner instance
873 testRunner = self.testRunner
874 result = testRunner.run(self.test)
Tim Petersa19a1682001-03-29 04:36:09 +0000875 sys.exit(not result.wasSuccessful())
Fred Drake02538202001-03-21 18:09:46 +0000876
877main = TestProgram
878
879
880##############################################################################
881# Executing this module from the command line
882##############################################################################
883
884if __name__ == "__main__":
885 main(module=None)