blob: eac5e78a11589a5e78991d1978894179d944cc17 [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:
192 result.addError(self,self.__exc_info())
193 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:
200 result.addFailure(self,self.__exc_info())
201 except:
202 result.addError(self,self.__exc_info())
203
204 try:
205 self.tearDown()
206 except:
207 result.addError(self,self.__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 def __exc_info(self):
270 """Return a version of sys.exc_info() with the traceback frame
271 minimised; usually the top level of the traceback frame is not
272 needed.
273 """
274 exctype, excvalue, tb = sys.exc_info()
275 newtb = tb.tb_next
276 if newtb is None:
277 return (exctype, excvalue, tb)
278 return (exctype, excvalue, newtb)
279
280
281class TestSuite:
282 """A test suite is a composite test consisting of a number of TestCases.
283
284 For use, create an instance of TestSuite, then add test case instances.
285 When all tests have been added, the suite can be passed to a test
286 runner, such as TextTestRunner. It will run the individual test cases
287 in the order in which they were added, aggregating the results. When
288 subclassing, do not forget to call the base class constructor.
289 """
290 def __init__(self, tests=()):
291 self._tests = []
292 self.addTests(tests)
293
294 def __repr__(self):
295 return "<%s tests=%s>" % (self.__class__, self._tests)
296
297 __str__ = __repr__
298
299 def countTestCases(self):
300 cases = 0
301 for test in self._tests:
302 cases = cases + test.countTestCases()
303 return cases
304
305 def addTest(self, test):
306 self._tests.append(test)
307
308 def addTests(self, tests):
309 for test in tests:
310 self.addTest(test)
311
312 def run(self, result):
313 return self(result)
314
315 def __call__(self, result):
316 for test in self._tests:
317 if result.shouldStop:
318 break
319 test(result)
320 return result
321
322 def debug(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000323 """Run the tests without collecting errors in a TestResult"""
Fred Drake02538202001-03-21 18:09:46 +0000324 for test in self._tests: test.debug()
Fred Drake02538202001-03-21 18:09:46 +0000325
326
327class FunctionTestCase(TestCase):
328 """A test case that wraps a test function.
329
330 This is useful for slipping pre-existing test functions into the
331 PyUnit framework. Optionally, set-up and tidy-up functions can be
332 supplied. As with TestCase, the tidy-up ('tearDown') function will
333 always be called if the set-up ('setUp') function ran successfully.
334 """
335
336 def __init__(self, testFunc, setUp=None, tearDown=None,
337 description=None):
338 TestCase.__init__(self)
339 self.__setUpFunc = setUp
340 self.__tearDownFunc = tearDown
341 self.__testFunc = testFunc
342 self.__description = description
343
344 def setUp(self):
345 if self.__setUpFunc is not None:
346 self.__setUpFunc()
347
348 def tearDown(self):
349 if self.__tearDownFunc is not None:
350 self.__tearDownFunc()
351
352 def runTest(self):
353 self.__testFunc()
354
355 def id(self):
356 return self.__testFunc.__name__
357
358 def __str__(self):
359 return "%s (%s)" % (self.__class__, self.__testFunc.__name__)
360
361 def __repr__(self):
362 return "<%s testFunc=%s>" % (self.__class__, self.__testFunc)
363
364 def shortDescription(self):
365 if self.__description is not None: return self.__description
366 doc = self.__testFunc.__doc__
367 return doc and string.strip(string.split(doc, "\n")[0]) or None
368
369
370
371##############################################################################
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000372# Locating and loading tests
Fred Drake02538202001-03-21 18:09:46 +0000373##############################################################################
374
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000375class TestLoader:
376 """This class is responsible for loading tests according to various
377 criteria and returning them wrapped in a Test
378
379 It can load all tests within a given, module
Fred Drake02538202001-03-21 18:09:46 +0000380 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000381 testMethodPrefix = 'test'
382 sortTestMethodsUsing = cmp
383 suiteClass = TestSuite
Fred Drake02538202001-03-21 18:09:46 +0000384
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000385 def loadTestsFromTestCase(self, testCaseClass):
386 return self.suiteClass(map(testCaseClass,
387 self.getTestCaseNames(testCaseClass)))
Fred Drake02538202001-03-21 18:09:46 +0000388
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000389 def loadTestsFromModule(self, module):
390 tests = []
391 for name in dir(module):
392 obj = getattr(module, name)
393 if type(obj) == types.ClassType and issubclass(obj, TestCase):
394 tests.append(self.loadTestsFromTestCase(obj))
395 return self.suiteClass(tests)
Fred Drake02538202001-03-21 18:09:46 +0000396
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000397 def loadTestsFromName(self, name, module=None):
398 parts = string.split(name, '.')
399 if module is None:
400 if not parts:
401 raise ValueError, "incomplete test name: %s" % name
402 else:
403 module = __import__(parts)
404 parts = parts[1:]
405 obj = module
406 for part in parts:
407 obj = getattr(obj, part)
Fred Drake02538202001-03-21 18:09:46 +0000408
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000409 if type(obj) == types.ModuleType:
410 return self.loadTestsFromModule(obj)
411 elif type(obj) == types.ClassType and issubclass(obj, TestCase):
412 return self.loadTestsFromTestCase(obj)
413 elif type(obj) == types.UnboundMethodType:
414 return obj.im_class(obj.__name__)
415 elif callable(obj):
416 test = obj()
417 if not isinstance(test, TestCase) and \
418 not isinstance(test, TestSuite):
419 raise ValueError, \
420 "calling %s returned %s, not a test" % obj,test
421 return test
Fred Drake02538202001-03-21 18:09:46 +0000422 else:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000423 raise ValueError, "don't know how to make test from: %s" % obj
424
425 def loadTestsFromNames(self, names, module=None):
426 suites = []
427 for name in names:
428 suites.append(self.loadTestsFromName(name, module))
429 return self.suiteClass(suites)
430
431 def getTestCaseNames(self, testCaseClass):
432 testFnNames = filter(lambda n,p=self.testMethodPrefix: n[:len(p)] == p,
433 dir(testCaseClass))
434 for baseclass in testCaseClass.__bases__:
435 for testFnName in self.getTestCaseNames(baseclass):
436 if testFnName not in testFnNames: # handle overridden methods
437 testFnNames.append(testFnName)
438 if self.sortTestMethodsUsing:
439 testFnNames.sort(self.sortTestMethodsUsing)
440 return testFnNames
441
442
443
444defaultTestLoader = TestLoader()
445
446
447##############################################################################
448# Patches for old functions: these functions should be considered obsolete
449##############################################################################
450
451def _makeLoader(prefix, sortUsing, suiteClass=None):
452 loader = TestLoader()
453 loader.sortTestMethodsUsing = sortUsing
454 loader.testMethodPrefix = prefix
455 if suiteClass: loader.suiteClass = suiteClass
456 return loader
457
458def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp):
459 return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)
460
461def makeSuite(testCaseClass, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
462 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
463
464def findTestCases(module, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
465 return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module)
Fred Drake02538202001-03-21 18:09:46 +0000466
467
468##############################################################################
469# Text UI
470##############################################################################
471
472class _WritelnDecorator:
473 """Used to decorate file-like objects with a handy 'writeln' method"""
474 def __init__(self,stream):
475 self.stream = stream
Fred Drake02538202001-03-21 18:09:46 +0000476
477 def __getattr__(self, attr):
478 return getattr(self.stream,attr)
479
480 def writeln(self, *args):
481 if args: apply(self.write, args)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000482 self.write('\n') # text-mode streams translate to \r\n if needed
Tim Petersa19a1682001-03-29 04:36:09 +0000483
Fred Drake02538202001-03-21 18:09:46 +0000484
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000485class _TextTestResult(TestResult):
Fred Drake02538202001-03-21 18:09:46 +0000486 """A test result class that can print formatted text results to a stream.
487
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000488 Used by TextTestRunner.
Fred Drake02538202001-03-21 18:09:46 +0000489 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000490 separator1 = '=' * 70
491 separator2 = '-' * 70
Fred Drake02538202001-03-21 18:09:46 +0000492
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000493 def __init__(self, stream, descriptions, verbosity):
Fred Drake02538202001-03-21 18:09:46 +0000494 TestResult.__init__(self)
495 self.stream = stream
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000496 self.showAll = verbosity > 1
497 self.dots = verbosity == 1
Fred Drake02538202001-03-21 18:09:46 +0000498 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000499
500 def getDescription(self, test):
501 if self.descriptions:
502 return test.shortDescription() or str(test)
503 else:
504 return str(test)
505
Fred Drake02538202001-03-21 18:09:46 +0000506 def startTest(self, test):
507 TestResult.startTest(self, test)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000508 if self.showAll:
509 self.stream.write(self.getDescription(test))
510 self.stream.write(" ... ")
Fred Drake02538202001-03-21 18:09:46 +0000511
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000512 def addSuccess(self, test):
513 TestResult.addSuccess(self, test)
514 if self.showAll:
Fred Drake02538202001-03-21 18:09:46 +0000515 self.stream.writeln("ok")
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000516 elif self.dots:
517 self.stream.write('.')
Fred Drake02538202001-03-21 18:09:46 +0000518
519 def addError(self, test, err):
520 TestResult.addError(self, test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000521 if self.showAll:
522 self.stream.writeln("ERROR")
523 elif self.dots:
524 self.stream.write('E')
Fred Drake02538202001-03-21 18:09:46 +0000525 if err[0] is KeyboardInterrupt:
526 self.shouldStop = 1
527
528 def addFailure(self, test, err):
529 TestResult.addFailure(self, test, err)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000530 if self.showAll:
531 self.stream.writeln("FAIL")
532 elif self.dots:
533 self.stream.write('F')
Fred Drake02538202001-03-21 18:09:46 +0000534
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000535 def printErrors(self):
536 if self.dots or self.showAll:
Fred Drake02538202001-03-21 18:09:46 +0000537 self.stream.writeln()
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000538 self.printErrorList('ERROR', self.errors)
539 self.printErrorList('FAIL', self.failures)
540
541 def printErrorList(self, flavour, errors):
542 for test, err in errors:
543 self.stream.writeln(self.separator1)
544 self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
545 self.stream.writeln(self.separator2)
546 for line in apply(traceback.format_exception, err):
547 for l in string.split(line,"\n")[:-1]:
548 self.stream.writeln("%s" % l)
Fred Drake02538202001-03-21 18:09:46 +0000549
550
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000551class TextTestRunner:
Fred Drake02538202001-03-21 18:09:46 +0000552 """A test runner class that displays results in textual form.
Tim Petersa19a1682001-03-29 04:36:09 +0000553
Fred Drake02538202001-03-21 18:09:46 +0000554 It prints out the names of tests as they are run, errors as they
555 occur, and a summary of the results at the end of the test run.
556 """
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000557 def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1):
Fred Drake02538202001-03-21 18:09:46 +0000558 self.stream = _WritelnDecorator(stream)
559 self.descriptions = descriptions
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000560 self.verbosity = verbosity
561
562 def _makeResult(self):
563 return _TextTestResult(self.stream, self.descriptions, self.verbosity)
Fred Drake02538202001-03-21 18:09:46 +0000564
565 def run(self, test):
566 "Run the given test case or test suite."
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000567 result = self._makeResult()
Fred Drake02538202001-03-21 18:09:46 +0000568 startTime = time.time()
569 test(result)
570 stopTime = time.time()
571 timeTaken = float(stopTime - startTime)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000572 result.printErrors()
573 self.stream.writeln(result.separator2)
Fred Drake02538202001-03-21 18:09:46 +0000574 run = result.testsRun
575 self.stream.writeln("Ran %d test%s in %.3fs" %
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000576 (run, run == 1 and "" or "s", timeTaken))
Fred Drake02538202001-03-21 18:09:46 +0000577 self.stream.writeln()
578 if not result.wasSuccessful():
579 self.stream.write("FAILED (")
580 failed, errored = map(len, (result.failures, result.errors))
581 if failed:
582 self.stream.write("failures=%d" % failed)
583 if errored:
584 if failed: self.stream.write(", ")
585 self.stream.write("errors=%d" % errored)
586 self.stream.writeln(")")
587 else:
588 self.stream.writeln("OK")
589 return result
Tim Petersa19a1682001-03-29 04:36:09 +0000590
Fred Drake02538202001-03-21 18:09:46 +0000591
Fred Drake02538202001-03-21 18:09:46 +0000592
593##############################################################################
594# Facilities for running tests from the command line
595##############################################################################
596
597class TestProgram:
598 """A command-line program that runs a set of tests; this is primarily
599 for making test modules conveniently executable.
600 """
601 USAGE = """\
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000602Usage: %(progName)s [options] [test[:(casename|prefix-)]] [...]
603
604Options:
605 -h, --help Show this message
606 -v, --verbose Verbose output
607 -q, --quiet Minimal output
Fred Drake02538202001-03-21 18:09:46 +0000608
609Examples:
610 %(progName)s - run default set of tests
611 %(progName)s MyTestSuite - run suite 'MyTestSuite'
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000612 %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething
613 %(progName)s MyTestCase - run all 'test*' test methods
Fred Drake02538202001-03-21 18:09:46 +0000614 in MyTestCase
615"""
616 def __init__(self, module='__main__', defaultTest=None,
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000617 argv=None, testRunner=None, testLoader=defaultTestLoader):
Fred Drake02538202001-03-21 18:09:46 +0000618 if type(module) == type(''):
619 self.module = __import__(module)
620 for part in string.split(module,'.')[1:]:
621 self.module = getattr(self.module, part)
622 else:
623 self.module = module
624 if argv is None:
625 argv = sys.argv
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000626 self.verbosity = 1
Fred Drake02538202001-03-21 18:09:46 +0000627 self.defaultTest = defaultTest
628 self.testRunner = testRunner
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000629 self.testLoader = testLoader
Fred Drake02538202001-03-21 18:09:46 +0000630 self.progName = os.path.basename(argv[0])
631 self.parseArgs(argv)
Fred Drake02538202001-03-21 18:09:46 +0000632 self.runTests()
633
634 def usageExit(self, msg=None):
635 if msg: print msg
636 print self.USAGE % self.__dict__
637 sys.exit(2)
638
639 def parseArgs(self, argv):
640 import getopt
641 try:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000642 options, args = getopt.getopt(argv[1:], 'hHvq',
643 ['help','verbose','quiet'])
Fred Drake02538202001-03-21 18:09:46 +0000644 opts = {}
645 for opt, value in options:
646 if opt in ('-h','-H','--help'):
647 self.usageExit()
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000648 if opt in ('-q','--quiet'):
649 self.verbosity = 0
650 if opt in ('-v','--verbose'):
651 self.verbosity = 2
Fred Drake02538202001-03-21 18:09:46 +0000652 if len(args) == 0 and self.defaultTest is None:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000653 self.test = self.testLoader.loadTestsFromModule(self.module)
654 return
Fred Drake02538202001-03-21 18:09:46 +0000655 if len(args) > 0:
656 self.testNames = args
657 else:
658 self.testNames = (self.defaultTest,)
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000659 self.createTests()
Fred Drake02538202001-03-21 18:09:46 +0000660 except getopt.error, msg:
661 self.usageExit(msg)
662
663 def createTests(self):
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000664 self.test = self.testLoader.loadTestsFromNames(self.testNames,
665 self.module)
Fred Drake02538202001-03-21 18:09:46 +0000666
667 def runTests(self):
668 if self.testRunner is None:
Steve Purcell5ddd1a82001-03-22 08:45:36 +0000669 self.testRunner = TextTestRunner(verbosity=self.verbosity)
Fred Drake02538202001-03-21 18:09:46 +0000670 result = self.testRunner.run(self.test)
Tim Petersa19a1682001-03-29 04:36:09 +0000671 sys.exit(not result.wasSuccessful())
Fred Drake02538202001-03-21 18:09:46 +0000672
673main = TestProgram
674
675
676##############################################################################
677# Executing this module from the command line
678##############################################################################
679
680if __name__ == "__main__":
681 main(module=None)