3 Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's
4 Smalltalk testing framework.
6 This module contains the core framework classes that form the basis of
7 specific test cases and suites (TestCase, TestSuite etc.), and also a
8 text-based utility class for running the tests and reporting the results
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)
23 if __name__ == '__main__':
26 Further information is available in the bundled documentation, and from
28 http://docs.python.org/lib/module-unittest.html
30 Copyright (c) 1999-2003 Steve Purcell
31 This module is free software, and you may redistribute it and/or modify
32 it under the same terms as Python itself, so long as this copyright message
33 and disclaimer are retained in their original form.
35 IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
36 SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
37 THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
40 THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
41 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
42 PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
43 AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
44 SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
47 __author__
= "Steve Purcell"
48 __email__
= "stephen_purcell at yahoo dot com"
49 __version__
= "#Revision: 1.63 $"[11:-2]
57 ##############################################################################
58 # Exported classes and functions
59 ##############################################################################
60 __all__
= ['TestResult', 'TestCase', 'TestSuite', 'TextTestRunner',
61 'TestLoader', 'FunctionTestCase', 'main', 'defaultTestLoader']
63 # Expose obsolete functions for backwards compatibility
64 __all__
.extend(['getTestCaseNames', 'makeSuite', 'findTestCases'])
67 ##############################################################################
68 # Backward compatibility
69 ##############################################################################
72 'Convert a cmp= function into a key= function'
74 def __init__(self
, obj
):
76 def __lt__(self
, other
):
77 return mycmp(self
.obj
, other
.obj
) == -1
80 ##############################################################################
82 ##############################################################################
85 return "%s.%s" % (cls
.__module
__, cls
.__name
__)
89 class TestResult(object):
90 """Holder for test result information.
92 Test results are automatically managed by the TestCase and TestSuite
93 classes, and do not need to be explicitly manipulated by writers of tests.
95 Each instance holds the total number of tests run, and collections of
96 failures and errors that occurred among those test runs. The collections
97 contain tuples of (testcase, exceptioninfo), where exceptioninfo is the
98 formatted traceback of the error that occurred.
104 self
.shouldStop
= False
106 def startTest(self
, test
):
107 "Called when the given test is about to be run"
108 self
.testsRun
= self
.testsRun
+ 1
110 def stopTest(self
, test
):
111 "Called when the given test has been run"
114 def addError(self
, test
, err
):
115 """Called when an error has occurred. 'err' is a tuple of values as
116 returned by sys.exc_info().
118 self
.errors
.append((test
, self
._exc
_info
_to
_string
(err
, test
)))
120 def addFailure(self
, test
, err
):
121 """Called when an error has occurred. 'err' is a tuple of values as
122 returned by sys.exc_info()."""
123 self
.failures
.append((test
, self
._exc
_info
_to
_string
(err
, test
)))
125 def addSuccess(self
, test
):
126 "Called when a test has completed successfully"
129 def wasSuccessful(self
):
130 "Tells whether or not this result was a success"
131 return len(self
.failures
) == len(self
.errors
) == 0
134 "Indicates that the tests should be aborted"
135 self
.shouldStop
= True
137 def _exc_info_to_string(self
, err
, test
):
138 """Converts a sys.exc_info()-style tuple of values into a string."""
139 exctype
, value
, tb
= err
140 # Skip test runner traceback levels
141 while tb
and self
._is
_relevant
_tb
_level
(tb
):
143 if exctype
is test
.failureException
:
144 # Skip assert*() traceback levels
145 length
= self
._count
_relevant
_tb
_levels
(tb
)
146 return ''.join(traceback
.format_exception(exctype
, value
, tb
, length
))
147 return ''.join(traceback
.format_exception(exctype
, value
, tb
))
149 def _is_relevant_tb_level(self
, tb
):
150 return '__unittest' in tb
.tb_frame
.f_globals
152 def _count_relevant_tb_levels(self
, tb
):
154 while tb
and not self
._is
_relevant
_tb
_level
(tb
):
160 return "<%s run=%i errors=%i failures=%i>" % \
161 (_strclass(self
.__class
__), self
.testsRun
, len(self
.errors
),
164 class AssertRaisesContext(object):
165 def __init__(self
, expected
, test_case
):
166 self
.expected
= expected
167 self
.failureException
= test_case
.failureException
170 def __exit__(self
, exc_type
, exc_value
, traceback
):
173 exc_name
= self
.expected
.__name
__
174 except AttributeError:
175 exc_name
= str(self
.expected
)
176 raise self
.failureException(
177 "{0} not raised".format(exc_name
))
178 if issubclass(exc_type
, self
.expected
):
180 # Let unexpected exceptions skip through
183 class TestCase(object):
184 """A class whose instances are single test cases.
186 By default, the test code itself should be placed in a method named
189 If the fixture may be used for many test cases, create as
190 many test methods as are needed. When instantiating such a TestCase
191 subclass, specify in the constructor arguments the name of the test method
192 that the instance is to execute.
194 Test authors should subclass TestCase for their own tests. Construction
195 and deconstruction of the test's environment ('fixture') can be
196 implemented by overriding the 'setUp' and 'tearDown' methods respectively.
198 If it is necessary to override the __init__ method, the base class
199 __init__ method must always be called. It is important that subclasses
200 should not change the signature of their __init__ method, since instances
201 of the classes are instantiated automatically by parts of the framework
205 # This attribute determines which exception will be raised when
206 # the instance's assertion methods fail; test methods raising this
207 # exception will be deemed to have 'failed' rather than 'errored'
209 failureException
= AssertionError
211 def __init__(self
, methodName
='runTest'):
212 """Create an instance of the class that will use the named test
213 method when executed. Raises a ValueError if the instance does
214 not have a method with the specified name.
217 self
._testMethodName
= methodName
218 testMethod
= getattr(self
, methodName
)
219 self
._testMethodDoc
= testMethod
.__doc
__
220 except AttributeError:
221 raise ValueError("no such test method in %s: %s" % \
222 (self
.__class
__, methodName
))
225 "Hook method for setting up the test fixture before exercising it."
229 "Hook method for deconstructing the test fixture after testing it."
232 def countTestCases(self
):
235 def defaultTestResult(self
):
238 def shortDescription(self
):
239 """Returns a one-line description of the test, or None if no
240 description has been provided.
242 The default implementation of this method returns the first line of
243 the specified test method's docstring.
245 doc
= self
._testMethodDoc
246 return doc
and doc
.split("\n")[0].strip() or None
249 return "%s.%s" % (_strclass(self
.__class
__), self
._testMethodName
)
251 def __eq__(self
, other
):
252 if type(self
) is not type(other
):
255 return self
._testMethodName
== other
._testMethodName
257 def __ne__(self
, other
):
258 return not self
== other
261 return hash((type(self
), self
._testMethodName
))
264 return "%s (%s)" % (self
._testMethodName
, _strclass(self
.__class
__))
267 return "<%s testMethod=%s>" % \
268 (_strclass(self
.__class
__), self
._testMethodName
)
270 def run(self
, result
=None):
271 if result
is None: result
= self
.defaultTestResult()
272 result
.startTest(self
)
273 testMethod
= getattr(self
, self
._testMethodName
)
278 result
.addError(self
, self
._exc
_info
())
285 except self
.failureException
:
286 result
.addFailure(self
, self
._exc
_info
())
288 result
.addError(self
, self
._exc
_info
())
293 result
.addError(self
, self
._exc
_info
())
295 if ok
: result
.addSuccess(self
)
297 result
.stopTest(self
)
299 def __call__(self
, *args
, **kwds
):
300 return self
.run(*args
, **kwds
)
303 """Run the test without collecting errors in a TestResult"""
305 getattr(self
, self
._testMethodName
)()
309 """Return a version of sys.exc_info() with the traceback frame
310 minimised; usually the top level of the traceback frame is not
313 return sys
.exc_info()
315 def fail(self
, msg
=None):
316 """Fail immediately, with the given message."""
317 raise self
.failureException(msg
)
319 def failIf(self
, expr
, msg
=None):
320 "Fail the test if the expression is true."
321 if expr
: raise self
.failureException(msg
)
323 def failUnless(self
, expr
, msg
=None):
324 """Fail the test unless the expression is true."""
325 if not expr
: raise self
.failureException(msg
)
327 def failUnlessRaises(self
, excClass
, callableObj
=None, *args
, **kwargs
):
328 """Fail unless an exception of class excClass is thrown
329 by callableObj when invoked with arguments args and keyword
330 arguments kwargs. If a different type of exception is
331 thrown, it will not be caught, and the test case will be
332 deemed to have suffered an error, exactly as for an
333 unexpected exception.
335 If called with callableObj omitted or None, will return a
336 context object used like this::
338 with self.failUnlessRaises(some_error_class):
341 context
= AssertRaisesContext(excClass
, self
)
342 if callableObj
is None:
345 callableObj(*args
, **kwargs
)
347 def failUnlessEqual(self
, first
, second
, msg
=None):
348 """Fail if the two objects are unequal as determined by the '=='
351 if not first
== second
:
352 raise self
.failureException(msg
or '%r != %r' % (first
, second
))
354 def failIfEqual(self
, first
, second
, msg
=None):
355 """Fail if the two objects are equal as determined by the '=='
359 raise self
.failureException(msg
or '%r == %r' % (first
, second
))
361 def failUnlessAlmostEqual(self
, first
, second
, places
=7, msg
=None):
362 """Fail if the two objects are unequal as determined by their
363 difference rounded to the given number of decimal places
364 (default 7) and comparing to zero.
366 Note that decimal places (from zero) are usually not the same
367 as significant digits (measured from the most signficant digit).
369 if round(abs(second
-first
), places
) != 0:
370 raise self
.failureException(
371 msg
or '%r != %r within %r places' % (first
, second
, places
))
373 def failIfAlmostEqual(self
, first
, second
, places
=7, msg
=None):
374 """Fail if the two objects are equal as determined by their
375 difference rounded to the given number of decimal places
376 (default 7) and comparing to zero.
378 Note that decimal places (from zero) are usually not the same
379 as significant digits (measured from the most signficant digit).
381 if round(abs(second
-first
), places
) == 0:
382 raise self
.failureException(
383 msg
or '%r == %r within %r places' % (first
, second
, places
))
385 # Synonyms for assertion methods
387 assertEqual
= assertEquals
= failUnlessEqual
389 assertNotEqual
= assertNotEquals
= failIfEqual
391 assertAlmostEqual
= assertAlmostEquals
= failUnlessAlmostEqual
393 assertNotAlmostEqual
= assertNotAlmostEquals
= failIfAlmostEqual
395 assertRaises
= failUnlessRaises
397 assert_
= assertTrue
= failUnless
403 class TestSuite(object):
404 """A test suite is a composite test consisting of a number of TestCases.
406 For use, create an instance of TestSuite, then add test case instances.
407 When all tests have been added, the suite can be passed to a test
408 runner, such as TextTestRunner. It will run the individual test cases
409 in the order in which they were added, aggregating the results. When
410 subclassing, do not forget to call the base class constructor.
412 def __init__(self
, tests
=()):
417 return "<%s tests=%s>" % (_strclass(self
.__class
__), self
._tests
)
421 def __eq__(self
, other
):
422 if type(self
) is not type(other
):
424 return self
._tests
== other
._tests
426 def __ne__(self
, other
):
427 return not self
== other
429 # Can't guarantee hash invariant, so flag as unhashable
433 return iter(self
._tests
)
435 def countTestCases(self
):
437 for test
in self
._tests
:
438 cases
+= test
.countTestCases()
441 def addTest(self
, test
):
443 if not hasattr(test
, '__call__'):
444 raise TypeError("the test to add must be callable")
445 if (isinstance(test
, (type, types
.ClassType
)) and
446 issubclass(test
, (TestCase
, TestSuite
))):
447 raise TypeError("TestCases and TestSuites must be instantiated "
448 "before passing them to addTest()")
449 self
._tests
.append(test
)
451 def addTests(self
, tests
):
452 if isinstance(tests
, basestring
):
453 raise TypeError("tests must be an iterable of tests, not a string")
457 def run(self
, result
):
458 for test
in self
._tests
:
459 if result
.shouldStop
:
464 def __call__(self
, *args
, **kwds
):
465 return self
.run(*args
, **kwds
)
468 """Run the tests without collecting errors in a TestResult"""
469 for test
in self
._tests
: test
.debug()
472 class FunctionTestCase(TestCase
):
473 """A test case that wraps a test function.
475 This is useful for slipping pre-existing test functions into the
476 unittest framework. Optionally, set-up and tidy-up functions can be
477 supplied. As with TestCase, the tidy-up ('tearDown') function will
478 always be called if the set-up ('setUp') function ran successfully.
481 def __init__(self
, testFunc
, setUp
=None, tearDown
=None,
483 TestCase
.__init
__(self
)
484 self
.__setUpFunc
= setUp
485 self
.__tearDownFunc
= tearDown
486 self
.__testFunc
= testFunc
487 self
.__description
= description
490 if self
.__setUpFunc
is not None:
494 if self
.__tearDownFunc
is not None:
495 self
.__tearDownFunc
()
501 return self
.__testFunc
.__name
__
503 def __eq__(self
, other
):
504 if type(self
) is not type(other
):
507 return self
.__setUpFunc
== other
.__setUpFunc
and \
508 self
.__tearDownFunc
== other
.__tearDownFunc
and \
509 self
.__testFunc
== other
.__testFunc
and \
510 self
.__description
== other
.__description
512 def __ne__(self
, other
):
513 return not self
== other
516 return hash((type(self
), self
.__setUpFunc
, self
.__tearDownFunc
,
517 self
.__testFunc
, self
.__description
))
520 return "%s (%s)" % (_strclass(self
.__class
__), self
.__testFunc
.__name
__)
523 return "<%s testFunc=%s>" % (_strclass(self
.__class
__), self
.__testFunc
)
525 def shortDescription(self
):
526 if self
.__description
is not None: return self
.__description
527 doc
= self
.__testFunc
.__doc
__
528 return doc
and doc
.split("\n")[0].strip() or None
532 ##############################################################################
533 # Locating and loading tests
534 ##############################################################################
536 class TestLoader(object):
537 """This class is responsible for loading tests according to various
538 criteria and returning them wrapped in a TestSuite
540 testMethodPrefix
= 'test'
541 sortTestMethodsUsing
= cmp
542 suiteClass
= TestSuite
544 def loadTestsFromTestCase(self
, testCaseClass
):
545 """Return a suite of all tests cases contained in testCaseClass"""
546 if issubclass(testCaseClass
, TestSuite
):
547 raise TypeError("Test cases should not be derived from TestSuite. Maybe you meant to derive from TestCase?")
548 testCaseNames
= self
.getTestCaseNames(testCaseClass
)
549 if not testCaseNames
and hasattr(testCaseClass
, 'runTest'):
550 testCaseNames
= ['runTest']
551 return self
.suiteClass(map(testCaseClass
, testCaseNames
))
553 def loadTestsFromModule(self
, module
):
554 """Return a suite of all tests cases contained in the given module"""
556 for name
in dir(module
):
557 obj
= getattr(module
, name
)
558 if (isinstance(obj
, (type, types
.ClassType
)) and
559 issubclass(obj
, TestCase
)):
560 tests
.append(self
.loadTestsFromTestCase(obj
))
561 return self
.suiteClass(tests
)
563 def loadTestsFromName(self
, name
, module
=None):
564 """Return a suite of all tests cases given a string specifier.
566 The name may resolve either to a module, a test case class, a
567 test method within a test case class, or a callable object which
568 returns a TestCase or TestSuite instance.
570 The method optionally resolves the names relative to a given module.
572 parts
= name
.split('.')
574 parts_copy
= parts
[:]
577 module
= __import__('.'.join(parts_copy
))
581 if not parts_copy
: raise
585 parent
, obj
= obj
, getattr(obj
, part
)
587 if isinstance(obj
, types
.ModuleType
):
588 return self
.loadTestsFromModule(obj
)
589 elif (isinstance(obj
, (type, types
.ClassType
)) and
590 issubclass(obj
, TestCase
)):
591 return self
.loadTestsFromTestCase(obj
)
592 elif (isinstance(obj
, types
.UnboundMethodType
) and
593 isinstance(parent
, (type, types
.ClassType
)) and
594 issubclass(parent
, TestCase
)):
595 return TestSuite([parent(obj
.__name
__)])
596 elif isinstance(obj
, TestSuite
):
598 elif hasattr(obj
, '__call__'):
600 if isinstance(test
, TestSuite
):
602 elif isinstance(test
, TestCase
):
603 return TestSuite([test
])
605 raise TypeError("calling %s returned %s, not a test" %
608 raise TypeError("don't know how to make test from: %s" % obj
)
610 def loadTestsFromNames(self
, names
, module
=None):
611 """Return a suite of all tests cases found using the given sequence
612 of string specifiers. See 'loadTestsFromName()'.
614 suites
= [self
.loadTestsFromName(name
, module
) for name
in names
]
615 return self
.suiteClass(suites
)
617 def getTestCaseNames(self
, testCaseClass
):
618 """Return a sorted sequence of method names found within testCaseClass
620 def isTestMethod(attrname
, testCaseClass
=testCaseClass
, prefix
=self
.testMethodPrefix
):
621 return attrname
.startswith(prefix
) and hasattr(getattr(testCaseClass
, attrname
), '__call__')
622 testFnNames
= filter(isTestMethod
, dir(testCaseClass
))
623 if self
.sortTestMethodsUsing
:
624 testFnNames
.sort(key
=_CmpToKey(self
.sortTestMethodsUsing
))
629 defaultTestLoader
= TestLoader()
632 ##############################################################################
633 # Patches for old functions: these functions should be considered obsolete
634 ##############################################################################
636 def _makeLoader(prefix
, sortUsing
, suiteClass
=None):
637 loader
= TestLoader()
638 loader
.sortTestMethodsUsing
= sortUsing
639 loader
.testMethodPrefix
= prefix
640 if suiteClass
: loader
.suiteClass
= suiteClass
643 def getTestCaseNames(testCaseClass
, prefix
, sortUsing
=cmp):
644 return _makeLoader(prefix
, sortUsing
).getTestCaseNames(testCaseClass
)
646 def makeSuite(testCaseClass
, prefix
='test', sortUsing
=cmp, suiteClass
=TestSuite
):
647 return _makeLoader(prefix
, sortUsing
, suiteClass
).loadTestsFromTestCase(testCaseClass
)
649 def findTestCases(module
, prefix
='test', sortUsing
=cmp, suiteClass
=TestSuite
):
650 return _makeLoader(prefix
, sortUsing
, suiteClass
).loadTestsFromModule(module
)
653 ##############################################################################
655 ##############################################################################
657 class _WritelnDecorator(object):
658 """Used to decorate file-like objects with a handy 'writeln' method"""
659 def __init__(self
,stream
):
662 def __getattr__(self
, attr
):
663 return getattr(self
.stream
,attr
)
665 def writeln(self
, arg
=None):
666 if arg
: self
.write(arg
)
667 self
.write('\n') # text-mode streams translate to \r\n if needed
670 class _TextTestResult(TestResult
):
671 """A test result class that can print formatted text results to a stream.
673 Used by TextTestRunner.
675 separator1
= '=' * 70
676 separator2
= '-' * 70
678 def __init__(self
, stream
, descriptions
, verbosity
):
679 TestResult
.__init
__(self
)
681 self
.showAll
= verbosity
> 1
682 self
.dots
= verbosity
== 1
683 self
.descriptions
= descriptions
685 def getDescription(self
, test
):
686 if self
.descriptions
:
687 return test
.shortDescription() or str(test
)
691 def startTest(self
, test
):
692 TestResult
.startTest(self
, test
)
694 self
.stream
.write(self
.getDescription(test
))
695 self
.stream
.write(" ... ")
698 def addSuccess(self
, test
):
699 TestResult
.addSuccess(self
, test
)
701 self
.stream
.writeln("ok")
703 self
.stream
.write('.')
706 def addError(self
, test
, err
):
707 TestResult
.addError(self
, test
, err
)
709 self
.stream
.writeln("ERROR")
711 self
.stream
.write('E')
714 def addFailure(self
, test
, err
):
715 TestResult
.addFailure(self
, test
, err
)
717 self
.stream
.writeln("FAIL")
719 self
.stream
.write('F')
722 def printErrors(self
):
723 if self
.dots
or self
.showAll
:
724 self
.stream
.writeln()
725 self
.printErrorList('ERROR', self
.errors
)
726 self
.printErrorList('FAIL', self
.failures
)
728 def printErrorList(self
, flavour
, errors
):
729 for test
, err
in errors
:
730 self
.stream
.writeln(self
.separator1
)
731 self
.stream
.writeln("%s: %s" % (flavour
,self
.getDescription(test
)))
732 self
.stream
.writeln(self
.separator2
)
733 self
.stream
.writeln("%s" % err
)
736 class TextTestRunner(object):
737 """A test runner class that displays results in textual form.
739 It prints out the names of tests as they are run, errors as they
740 occur, and a summary of the results at the end of the test run.
742 def __init__(self
, stream
=sys
.stderr
, descriptions
=1, verbosity
=1):
743 self
.stream
= _WritelnDecorator(stream
)
744 self
.descriptions
= descriptions
745 self
.verbosity
= verbosity
747 def _makeResult(self
):
748 return _TextTestResult(self
.stream
, self
.descriptions
, self
.verbosity
)
751 "Run the given test case or test suite."
752 result
= self
._makeResult
()
753 startTime
= time
.time()
755 stopTime
= time
.time()
756 timeTaken
= stopTime
- startTime
758 self
.stream
.writeln(result
.separator2
)
759 run
= result
.testsRun
760 self
.stream
.writeln("Ran %d test%s in %.3fs" %
761 (run
, run
!= 1 and "s" or "", timeTaken
))
762 self
.stream
.writeln()
763 if not result
.wasSuccessful():
764 self
.stream
.write("FAILED (")
765 failed
, errored
= map(len, (result
.failures
, result
.errors
))
767 self
.stream
.write("failures=%d" % failed
)
769 if failed
: self
.stream
.write(", ")
770 self
.stream
.write("errors=%d" % errored
)
771 self
.stream
.writeln(")")
773 self
.stream
.writeln("OK")
778 ##############################################################################
779 # Facilities for running tests from the command line
780 ##############################################################################
782 class TestProgram(object):
783 """A command-line program that runs a set of tests; this is primarily
784 for making test modules conveniently executable.
787 Usage: %(progName)s [options] [test] [...]
790 -h, --help Show this message
791 -v, --verbose Verbose output
792 -q, --quiet Minimal output
795 %(progName)s - run default set of tests
796 %(progName)s MyTestSuite - run suite 'MyTestSuite'
797 %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething
798 %(progName)s MyTestCase - run all 'test*' test methods
801 def __init__(self
, module
='__main__', defaultTest
=None,
802 argv
=None, testRunner
=TextTestRunner
,
803 testLoader
=defaultTestLoader
):
804 if isinstance(module
, basestring
):
805 self
.module
= __import__(module
)
806 for part
in module
.split('.')[1:]:
807 self
.module
= getattr(self
.module
, part
)
813 self
.defaultTest
= defaultTest
814 self
.testRunner
= testRunner
815 self
.testLoader
= testLoader
816 self
.progName
= os
.path
.basename(argv
[0])
820 def usageExit(self
, msg
=None):
822 print self
.USAGE
% self
.__dict
__
825 def parseArgs(self
, argv
):
828 options
, args
= getopt
.getopt(argv
[1:], 'hHvq',
829 ['help','verbose','quiet'])
830 for opt
, value
in options
:
831 if opt
in ('-h','-H','--help'):
833 if opt
in ('-q','--quiet'):
835 if opt
in ('-v','--verbose'):
837 if len(args
) == 0 and self
.defaultTest
is None:
838 self
.test
= self
.testLoader
.loadTestsFromModule(self
.module
)
841 self
.testNames
= args
843 self
.testNames
= (self
.defaultTest
,)
845 except getopt
.error
, msg
:
848 def createTests(self
):
849 self
.test
= self
.testLoader
.loadTestsFromNames(self
.testNames
,
853 if isinstance(self
.testRunner
, (type, types
.ClassType
)):
855 testRunner
= self
.testRunner(verbosity
=self
.verbosity
)
857 # didn't accept the verbosity argument
858 testRunner
= self
.testRunner()
860 # it is assumed to be a TestRunner instance
861 testRunner
= self
.testRunner
862 result
= testRunner
.run(self
.test
)
863 sys
.exit(not result
.wasSuccessful())
868 ##############################################################################
869 # Executing this module from the command line
870 ##############################################################################
872 if __name__
== "__main__":