blob: 1c2163f689fb0f0299390f76cc382fd2c0893cfb [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
9(TextTestRunner).
10
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)
19 def testMultiply(self);
20 self.assertEquals((0 * 10), 0)
21 self.assertEquals((5 * 8), 40)
22
23 if __name__ == '__main__':
24 unittest.main()
25
26Further information is available in the bundled documentation, and from
27
28 http://pyunit.sourceforge.net/
29
Fred Drake02538202001-03-21 18:09:46 +000030Copyright (c) 1999, 2000, 2001 Steve Purcell
31This 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"
Fred Drake02538202001-03-21 18:09:46 +000049__version__ = "$Revision$"[11:-2]
50
51import time
52import sys
53import traceback
54import string
55import os
Steve Purcell5ddd1a82001-03-22 08:45:36 +000056import types
Fred Drake02538202001-03-21 18:09:46 +000057
58##############################################################################
59# Test framework core
60##############################################################################
61
62class TestResult:
63 """Holder for test result information.
64
65 Test results are automatically managed by the TestCase and TestSuite
66 classes, and do not need to be explicitly manipulated by writers of tests.
67
68 Each instance holds the total number of tests run, and collections of
69 failures and errors that occurred among those test runs. The collections
70 contain tuples of (testcase, exceptioninfo), where exceptioninfo is a
71 tuple of values as returned by sys.exc_info().
72 """
73 def __init__(self):
74 self.failures = []
75 self.errors = []
76 self.testsRun = 0
77 self.shouldStop = 0
78
79 def startTest(self, test):
80 "Called when the given test is about to be run"
81 self.testsRun = self.testsRun + 1
82
83 def stopTest(self, test):
84 "Called when the given test has been run"
85 pass
86
87 def addError(self, test, err):
88 "Called when an error has occurred"
89 self.errors.append((test, err))
90
91 def addFailure(self, test, err):
92 "Called when a failure has occurred"
93 self.failures.append((test, err))
94
Steve Purcell5ddd1a82001-03-22 08:45:36 +000095 def addSuccess(self, test):
96 "Called when a test has completed successfully"
97 pass
98
Fred Drake02538202001-03-21 18:09:46 +000099 def wasSuccessful(self):
100 "Tells whether or not this result was a success"
101 return len(self.failures) == len(self.errors) == 0
102
103 def stop(self):
104 "Indicates that the tests should be aborted"
105 self.shouldStop = 1
Tim Petersa19a1682001-03-29 04:36:09 +0000106
Fred Drake02538202001-03-21 18:09:46 +0000107 def __repr__(self):
108 return "<%s run=%i errors=%i failures=%i>" % \
109 (self.__class__, self.testsRun, len(self.errors),
110 len(self.failures))
111
112
113class TestCase:
114 """A class whose instances are single test cases.
115
Fred Drake02538202001-03-21 18:09:46 +0000116 By default, the test code itself should be placed in a method named
117 'runTest'.
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000118
Tim Petersa19a1682001-03-29 04:36:09 +0000119 If the fixture may be used for many test cases, create as
Fred Drake02538202001-03-21 18:09:46 +0000120 many test methods as are needed. When instantiating such a TestCase
121 subclass, specify in the constructor arguments the name of the test method
122 that the instance is to execute.
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000123
Tim Petersa19a1682001-03-29 04:36:09 +0000124 Test authors should subclass TestCase for their own tests. Construction
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000125 and deconstruction of the test's environment ('fixture') can be
126 implemented by overriding the 'setUp' and 'tearDown' methods respectively.
127
128 If it is necessary to override the __init__ method, the base class
129 __init__ method must always be called. It is important that subclasses
130 should not change the signature of their __init__ method, since instances
131 of the classes are instantiated automatically by parts of the framework
132 in order to be run.
Fred Drake02538202001-03-21 18:09:46 +0000133 """
134 def __init__(self, methodName='runTest'):
135 """Create an instance of the class that will use the named test
136 method when executed. Raises a ValueError if the instance does
137 not have a method with the specified name.
138 """
139 try:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000140 self.__testMethodName = methodName
141 testMethod = getattr(self, methodName)
142 self.__testMethodDoc = testMethod.__doc__
Fred Drake02538202001-03-21 18:09:46 +0000143 except AttributeError:
144 raise ValueError, "no such test method in %s: %s" % \
145 (self.__class__, methodName)
146
147 def setUp(self):
148 "Hook method for setting up the test fixture before exercising it."
149 pass
150
151 def tearDown(self):
152 "Hook method for deconstructing the test fixture after testing it."
153 pass
154
155 def countTestCases(self):
156 return 1
157
158 def defaultTestResult(self):
159 return TestResult()
160
161 def shortDescription(self):
162 """Returns a one-line description of the test, or None if no
163 description has been provided.
164
165 The default implementation of this method returns the first line of
166 the specified test method's docstring.
167 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000168 doc = self.__testMethodDoc
Fred Drake02538202001-03-21 18:09:46 +0000169 return doc and string.strip(string.split(doc, "\n")[0]) or None
170
171 def id(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000172 return "%s.%s" % (self.__class__, self.__testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000173
174 def __str__(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000175 return "%s (%s)" % (self.__testMethodName, self.__class__)
Fred Drake02538202001-03-21 18:09:46 +0000176
177 def __repr__(self):
178 return "<%s testMethod=%s>" % \
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000179 (self.__class__, self.__testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000180
181 def run(self, result=None):
182 return self(result)
183
184 def __call__(self, result=None):
185 if result is None: result = self.defaultTestResult()
186 result.startTest(self)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000187 testMethod = getattr(self, self.__testMethodName)
Fred Drake02538202001-03-21 18:09:46 +0000188 try:
189 try:
190 self.setUp()
191 except:
Steve Purcell17a781b2001-04-09 15:37:31 +0000192 result.addError(self,sys.exc_info())
Fred Drake02538202001-03-21 18:09:46 +0000193 return
194
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000195 ok = 0
Fred Drake02538202001-03-21 18:09:46 +0000196 try:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000197 testMethod()
198 ok = 1
Fred Drake02538202001-03-21 18:09:46 +0000199 except AssertionError, e:
Steve Purcell17a781b2001-04-09 15:37:31 +0000200 result.addFailure(self,sys.exc_info())
Fred Drake02538202001-03-21 18:09:46 +0000201 except:
Steve Purcell17a781b2001-04-09 15:37:31 +0000202 result.addError(self,sys.exc_info())
Fred Drake02538202001-03-21 18:09:46 +0000203
204 try:
205 self.tearDown()
206 except:
Steve Purcell17a781b2001-04-09 15:37:31 +0000207 result.addError(self,sys.exc_info())
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000208 ok = 0
209 if ok: result.addSuccess(self)
Fred Drake02538202001-03-21 18:09:46 +0000210 finally:
211 result.stopTest(self)
212
213 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000214 """Run the test without collecting errors in a TestResult"""
Fred Drake02538202001-03-21 18:09:46 +0000215 self.setUp()
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000216 getattr(self, self.__testMethodName)()
Fred Drake02538202001-03-21 18:09:46 +0000217 self.tearDown()
218
219 def assert_(self, expr, msg=None):
220 """Equivalent of built-in 'assert', but is not optimised out when
221 __debug__ is false.
222 """
223 if not expr:
224 raise AssertionError, msg
225
226 failUnless = assert_
227
228 def failIf(self, expr, msg=None):
229 "Fail the test if the expression is true."
230 apply(self.assert_,(not expr,msg))
231
232 def assertRaises(self, excClass, callableObj, *args, **kwargs):
233 """Assert that an exception of class excClass is thrown
234 by callableObj when invoked with arguments args and keyword
235 arguments kwargs. If a different type of exception is
236 thrown, it will not be caught, and the test case will be
237 deemed to have suffered an error, exactly as for an
238 unexpected exception.
239 """
240 try:
241 apply(callableObj, args, kwargs)
242 except excClass:
243 return
244 else:
245 if hasattr(excClass,'__name__'): excName = excClass.__name__
246 else: excName = str(excClass)
247 raise AssertionError, excName
248
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000249 def assertEquals(self, first, second, msg=None):
250 """Assert that the two objects are equal as determined by the '=='
251 operator.
252 """
253 self.assert_((first == second), msg or '%s != %s' % (first, second))
254
255 def assertNotEquals(self, first, second, msg=None):
256 """Assert that the two objects are unequal as determined by the '!='
257 operator.
258 """
259 self.assert_((first != second), msg or '%s == %s' % (first, second))
260
261 assertEqual = assertEquals
262
263 assertNotEqual = assertNotEquals
264
Fred Drake02538202001-03-21 18:09:46 +0000265 def fail(self, msg=None):
266 """Fail immediately, with the given message."""
267 raise AssertionError, msg
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000268
Fred Drake02538202001-03-21 18:09:46 +0000269
270class TestSuite:
271 """A test suite is a composite test consisting of a number of TestCases.
272
273 For use, create an instance of TestSuite, then add test case instances.
274 When all tests have been added, the suite can be passed to a test
275 runner, such as TextTestRunner. It will run the individual test cases
276 in the order in which they were added, aggregating the results. When
277 subclassing, do not forget to call the base class constructor.
278 """
279 def __init__(self, tests=()):
280 self._tests = []
281 self.addTests(tests)
282
283 def __repr__(self):
284 return "<%s tests=%s>" % (self.__class__, self._tests)
285
286 __str__ = __repr__
287
288 def countTestCases(self):
289 cases = 0
290 for test in self._tests:
291 cases = cases + test.countTestCases()
292 return cases
293
294 def addTest(self, test):
295 self._tests.append(test)
296
297 def addTests(self, tests):
298 for test in tests:
299 self.addTest(test)
300
301 def run(self, result):
302 return self(result)
303
304 def __call__(self, result):
305 for test in self._tests:
306 if result.shouldStop:
307 break
308 test(result)
309 return result
310
311 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000312 """Run the tests without collecting errors in a TestResult"""
Fred Drake02538202001-03-21 18:09:46 +0000313 for test in self._tests: test.debug()
Fred Drake02538202001-03-21 18:09:46 +0000314
315
316class FunctionTestCase(TestCase):
317 """A test case that wraps a test function.
318
319 This is useful for slipping pre-existing test functions into the
320 PyUnit framework. Optionally, set-up and tidy-up functions can be
321 supplied. As with TestCase, the tidy-up ('tearDown') function will
322 always be called if the set-up ('setUp') function ran successfully.
323 """
324
325 def __init__(self, testFunc, setUp=None, tearDown=None,
326 description=None):
327 TestCase.__init__(self)
328 self.__setUpFunc = setUp
329 self.__tearDownFunc = tearDown
330 self.__testFunc = testFunc
331 self.__description = description
332
333 def setUp(self):
334 if self.__setUpFunc is not None:
335 self.__setUpFunc()
336
337 def tearDown(self):
338 if self.__tearDownFunc is not None:
339 self.__tearDownFunc()
340
341 def runTest(self):
342 self.__testFunc()
343
344 def id(self):
345 return self.__testFunc.__name__
346
347 def __str__(self):
348 return "%s (%s)" % (self.__class__, self.__testFunc.__name__)
349
350 def __repr__(self):
351 return "<%s testFunc=%s>" % (self.__class__, self.__testFunc)
352
353 def shortDescription(self):
354 if self.__description is not None: return self.__description
355 doc = self.__testFunc.__doc__
356 return doc and string.strip(string.split(doc, "\n")[0]) or None
357
358
359
360##############################################################################
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000361# Locating and loading tests
Fred Drake02538202001-03-21 18:09:46 +0000362##############################################################################
363
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000364class TestLoader:
365 """This class is responsible for loading tests according to various
366 criteria and returning them wrapped in a Test
367
368 It can load all tests within a given, module
Fred Drake02538202001-03-21 18:09:46 +0000369 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000370 testMethodPrefix = 'test'
371 sortTestMethodsUsing = cmp
372 suiteClass = TestSuite
Fred Drake02538202001-03-21 18:09:46 +0000373
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000374 def loadTestsFromTestCase(self, testCaseClass):
375 return self.suiteClass(map(testCaseClass,
376 self.getTestCaseNames(testCaseClass)))
Fred Drake02538202001-03-21 18:09:46 +0000377
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000378 def loadTestsFromModule(self, module):
379 tests = []
380 for name in dir(module):
381 obj = getattr(module, name)
382 if type(obj) == types.ClassType and issubclass(obj, TestCase):
383 tests.append(self.loadTestsFromTestCase(obj))
384 return self.suiteClass(tests)
Fred Drake02538202001-03-21 18:09:46 +0000385
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000386 def loadTestsFromName(self, name, module=None):
387 parts = string.split(name, '.')
388 if module is None:
389 if not parts:
390 raise ValueError, "incomplete test name: %s" % name
391 else:
Steve Purcell17a781b2001-04-09 15:37:31 +0000392 parts_copy = parts[:]
393 while parts_copy:
394 try:
395 module = __import__(string.join(parts_copy,'.'))
396 break
397 except ImportError:
398 del parts_copy[-1]
399 if not parts_copy: raise
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000400 parts = parts[1:]
401 obj = module
402 for part in parts:
403 obj = getattr(obj, part)
Fred Drake02538202001-03-21 18:09:46 +0000404
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000405 if type(obj) == types.ModuleType:
406 return self.loadTestsFromModule(obj)
407 elif type(obj) == types.ClassType and issubclass(obj, TestCase):
408 return self.loadTestsFromTestCase(obj)
409 elif type(obj) == types.UnboundMethodType:
410 return obj.im_class(obj.__name__)
411 elif callable(obj):
412 test = obj()
413 if not isinstance(test, TestCase) and \
414 not isinstance(test, TestSuite):
415 raise ValueError, \
416 "calling %s returned %s, not a test" % obj,test
417 return test
Fred Drake02538202001-03-21 18:09:46 +0000418 else:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000419 raise ValueError, "don't know how to make test from: %s" % obj
420
421 def loadTestsFromNames(self, names, module=None):
422 suites = []
423 for name in names:
424 suites.append(self.loadTestsFromName(name, module))
425 return self.suiteClass(suites)
426
427 def getTestCaseNames(self, testCaseClass):
428 testFnNames = filter(lambda n,p=self.testMethodPrefix: n[:len(p)] == p,
429 dir(testCaseClass))
430 for baseclass in testCaseClass.__bases__:
431 for testFnName in self.getTestCaseNames(baseclass):
432 if testFnName not in testFnNames: # handle overridden methods
433 testFnNames.append(testFnName)
434 if self.sortTestMethodsUsing:
435 testFnNames.sort(self.sortTestMethodsUsing)
436 return testFnNames
437
438
439
440defaultTestLoader = TestLoader()
441
442
443##############################################################################
444# Patches for old functions: these functions should be considered obsolete
445##############################################################################
446
447def _makeLoader(prefix, sortUsing, suiteClass=None):
448 loader = TestLoader()
449 loader.sortTestMethodsUsing = sortUsing
450 loader.testMethodPrefix = prefix
451 if suiteClass: loader.suiteClass = suiteClass
452 return loader
453
454def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp):
455 return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)
456
457def makeSuite(testCaseClass, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
458 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
459
460def findTestCases(module, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
461 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module)
Fred Drake02538202001-03-21 18:09:46 +0000462
463
464##############################################################################
465# Text UI
466##############################################################################
467
468class _WritelnDecorator:
469 """Used to decorate file-like objects with a handy 'writeln' method"""
470 def __init__(self,stream):
471 self.stream = stream
Fred Drake02538202001-03-21 18:09:46 +0000472
473 def __getattr__(self, attr):
474 return getattr(self.stream,attr)
475
476 def writeln(self, *args):
477 if args: apply(self.write, args)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000478 self.write('\n') # text-mode streams translate to \r\n if needed
Tim Petersa19a1682001-03-29 04:36:09 +0000479
Fred Drake02538202001-03-21 18:09:46 +0000480
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000481class _TextTestResult(TestResult):
Fred Drake02538202001-03-21 18:09:46 +0000482 """A test result class that can print formatted text results to a stream.
483
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000484 Used by TextTestRunner.
Fred Drake02538202001-03-21 18:09:46 +0000485 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000486 separator1 = '=' * 70
487 separator2 = '-' * 70
Fred Drake02538202001-03-21 18:09:46 +0000488
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000489 def __init__(self, stream, descriptions, verbosity):
Fred Drake02538202001-03-21 18:09:46 +0000490 TestResult.__init__(self)
491 self.stream = stream
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000492 self.showAll = verbosity > 1
493 self.dots = verbosity == 1
Fred Drake02538202001-03-21 18:09:46 +0000494 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000495
496 def getDescription(self, test):
497 if self.descriptions:
498 return test.shortDescription() or str(test)
499 else:
500 return str(test)
501
Fred Drake02538202001-03-21 18:09:46 +0000502 def startTest(self, test):
503 TestResult.startTest(self, test)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000504 if self.showAll:
505 self.stream.write(self.getDescription(test))
506 self.stream.write(" ... ")
Fred Drake02538202001-03-21 18:09:46 +0000507
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000508 def addSuccess(self, test):
509 TestResult.addSuccess(self, test)
510 if self.showAll:
Fred Drake02538202001-03-21 18:09:46 +0000511 self.stream.writeln("ok")
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000512 elif self.dots:
513 self.stream.write('.')
Fred Drake02538202001-03-21 18:09:46 +0000514
515 def addError(self, test, err):
516 TestResult.addError(self, test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000517 if self.showAll:
518 self.stream.writeln("ERROR")
519 elif self.dots:
520 self.stream.write('E')
Fred Drake02538202001-03-21 18:09:46 +0000521 if err[0] is KeyboardInterrupt:
522 self.shouldStop = 1
523
524 def addFailure(self, test, err):
525 TestResult.addFailure(self, test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000526 if self.showAll:
527 self.stream.writeln("FAIL")
528 elif self.dots:
529 self.stream.write('F')
Fred Drake02538202001-03-21 18:09:46 +0000530
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000531 def printErrors(self):
532 if self.dots or self.showAll:
Fred Drake02538202001-03-21 18:09:46 +0000533 self.stream.writeln()
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000534 self.printErrorList('ERROR', self.errors)
535 self.printErrorList('FAIL', self.failures)
536
537 def printErrorList(self, flavour, errors):
538 for test, err in errors:
539 self.stream.writeln(self.separator1)
540 self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
541 self.stream.writeln(self.separator2)
542 for line in apply(traceback.format_exception, err):
543 for l in string.split(line,"\n")[:-1]:
544 self.stream.writeln("%s" % l)
Fred Drake02538202001-03-21 18:09:46 +0000545
546
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000547class TextTestRunner:
Fred Drake02538202001-03-21 18:09:46 +0000548 """A test runner class that displays results in textual form.
Tim Petersa19a1682001-03-29 04:36:09 +0000549
Fred Drake02538202001-03-21 18:09:46 +0000550 It prints out the names of tests as they are run, errors as they
551 occur, and a summary of the results at the end of the test run.
552 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000553 def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1):
Fred Drake02538202001-03-21 18:09:46 +0000554 self.stream = _WritelnDecorator(stream)
555 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000556 self.verbosity = verbosity
557
558 def _makeResult(self):
559 return _TextTestResult(self.stream, self.descriptions, self.verbosity)
Fred Drake02538202001-03-21 18:09:46 +0000560
561 def run(self, test):
562 "Run the given test case or test suite."
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000563 result = self._makeResult()
Fred Drake02538202001-03-21 18:09:46 +0000564 startTime = time.time()
565 test(result)
566 stopTime = time.time()
567 timeTaken = float(stopTime - startTime)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000568 result.printErrors()
569 self.stream.writeln(result.separator2)
Fred Drake02538202001-03-21 18:09:46 +0000570 run = result.testsRun
571 self.stream.writeln("Ran %d test%s in %.3fs" %
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000572 (run, run == 1 and "" or "s", timeTaken))
Fred Drake02538202001-03-21 18:09:46 +0000573 self.stream.writeln()
574 if not result.wasSuccessful():
575 self.stream.write("FAILED (")
576 failed, errored = map(len, (result.failures, result.errors))
577 if failed:
578 self.stream.write("failures=%d" % failed)
579 if errored:
580 if failed: self.stream.write(", ")
581 self.stream.write("errors=%d" % errored)
582 self.stream.writeln(")")
583 else:
584 self.stream.writeln("OK")
585 return result
Tim Petersa19a1682001-03-29 04:36:09 +0000586
Fred Drake02538202001-03-21 18:09:46 +0000587
Fred Drake02538202001-03-21 18:09:46 +0000588
589##############################################################################
590# Facilities for running tests from the command line
591##############################################################################
592
593class TestProgram:
594 """A command-line program that runs a set of tests; this is primarily
595 for making test modules conveniently executable.
596 """
597 USAGE = """\
Steve Purcell17a781b2001-04-09 15:37:31 +0000598Usage: %(progName)s [options] [test] [...]
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000599
600Options:
601 -h, --help Show this message
602 -v, --verbose Verbose output
603 -q, --quiet Minimal output
Fred Drake02538202001-03-21 18:09:46 +0000604
605Examples:
606 %(progName)s - run default set of tests
607 %(progName)s MyTestSuite - run suite 'MyTestSuite'
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000608 %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething
609 %(progName)s MyTestCase - run all 'test*' test methods
Fred Drake02538202001-03-21 18:09:46 +0000610 in MyTestCase
611"""
612 def __init__(self, module='__main__', defaultTest=None,
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000613 argv=None, testRunner=None, testLoader=defaultTestLoader):
Fred Drake02538202001-03-21 18:09:46 +0000614 if type(module) == type(''):
615 self.module = __import__(module)
616 for part in string.split(module,'.')[1:]:
617 self.module = getattr(self.module, part)
618 else:
619 self.module = module
620 if argv is None:
621 argv = sys.argv
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000622 self.verbosity = 1
Fred Drake02538202001-03-21 18:09:46 +0000623 self.defaultTest = defaultTest
624 self.testRunner = testRunner
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000625 self.testLoader = testLoader
Fred Drake02538202001-03-21 18:09:46 +0000626 self.progName = os.path.basename(argv[0])
627 self.parseArgs(argv)
Fred Drake02538202001-03-21 18:09:46 +0000628 self.runTests()
629
630 def usageExit(self, msg=None):
631 if msg: print msg
632 print self.USAGE % self.__dict__
633 sys.exit(2)
634
635 def parseArgs(self, argv):
636 import getopt
637 try:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000638 options, args = getopt.getopt(argv[1:], 'hHvq',
639 ['help','verbose','quiet'])
Fred Drake02538202001-03-21 18:09:46 +0000640 opts = {}
641 for opt, value in options:
642 if opt in ('-h','-H','--help'):
643 self.usageExit()
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000644 if opt in ('-q','--quiet'):
645 self.verbosity = 0
646 if opt in ('-v','--verbose'):
647 self.verbosity = 2
Fred Drake02538202001-03-21 18:09:46 +0000648 if len(args) == 0 and self.defaultTest is None:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000649 self.test = self.testLoader.loadTestsFromModule(self.module)
650 return
Fred Drake02538202001-03-21 18:09:46 +0000651 if len(args) > 0:
652 self.testNames = args
653 else:
654 self.testNames = (self.defaultTest,)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000655 self.createTests()
Fred Drake02538202001-03-21 18:09:46 +0000656 except getopt.error, msg:
657 self.usageExit(msg)
658
659 def createTests(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000660 self.test = self.testLoader.loadTestsFromNames(self.testNames,
661 self.module)
Fred Drake02538202001-03-21 18:09:46 +0000662
663 def runTests(self):
664 if self.testRunner is None:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000665 self.testRunner = TextTestRunner(verbosity=self.verbosity)
Fred Drake02538202001-03-21 18:09:46 +0000666 result = self.testRunner.run(self.test)
Tim Petersa19a1682001-03-29 04:36:09 +0000667 sys.exit(not result.wasSuccessful())
Fred Drake02538202001-03-21 18:09:46 +0000668
669main = TestProgram
670
671
672##############################################################################
673# Executing this module from the command line
674##############################################################################
675
676if __name__ == "__main__":
677 main(module=None)