You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

unittest.py 25KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. #!/usr/bin/env python
  2. '''
  3. Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's
  4. Smalltalk testing framework.
  5. This module contains the core framework classes that form the basis of
  6. specific test cases and suites (TestCase, TestSuite etc.), and also a
  7. text-based utility class for running the tests and reporting the results
  8. (TextTestRunner).
  9. Simple usage:
  10. import unittest
  11. class IntegerArithmenticTestCase(unittest.TestCase):
  12. def testAdd(self): ## test method names begin 'test*'
  13. self.assertEquals((1 + 2), 3)
  14. self.assertEquals(0 + 1, 1)
  15. def testMultiply(self);
  16. self.assertEquals((0 * 10), 0)
  17. self.assertEquals((5 * 8), 40)
  18. if __name__ == '__main__':
  19. unittest.main()
  20. Further information is available in the bundled documentation, and from
  21. http://pyunit.sourceforge.net/
  22. Copyright (c) 1999, 2000, 2001 Steve Purcell
  23. This module is free software, and you may redistribute it and/or modify
  24. it under the same terms as Python itself, so long as this copyright message
  25. and disclaimer are retained in their original form.
  26. IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
  27. SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
  28. THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
  29. DAMAGE.
  30. THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
  31. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
  32. PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
  33. AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
  34. SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
  35. '''
  36. __author__ = "Steve Purcell"
  37. __email__ = "stephen_purcell at yahoo dot com"
  38. __version__ = "$Revision: 1.7 $"[11:-2]
  39. import time
  40. import sys
  41. import traceback
  42. import string
  43. import os
  44. import types
  45. ##############################################################################
  46. # Test framework core
  47. ##############################################################################
  48. class TestResult:
  49. """Holder for test result information.
  50. Test results are automatically managed by the TestCase and TestSuite
  51. classes, and do not need to be explicitly manipulated by writers of tests.
  52. Each instance holds the total number of tests run, and collections of
  53. failures and errors that occurred among those test runs. The collections
  54. contain tuples of (testcase, exceptioninfo), where exceptioninfo is a
  55. tuple of values as returned by sys.exc_info().
  56. """
  57. def __init__(self):
  58. self.failures = []
  59. self.errors = []
  60. self.testsRun = 0
  61. self.shouldStop = 0
  62. def startTest(self, test):
  63. "Called when the given test is about to be run"
  64. self.testsRun = self.testsRun + 1
  65. def stopTest(self, test):
  66. "Called when the given test has been run"
  67. pass
  68. def addError(self, test, err):
  69. "Called when an error has occurred"
  70. self.errors.append((test, err))
  71. def addFailure(self, test, err):
  72. "Called when a failure has occurred"
  73. self.failures.append((test, err))
  74. def addSuccess(self, test):
  75. "Called when a test has completed successfully"
  76. pass
  77. def wasSuccessful(self):
  78. "Tells whether or not this result was a success"
  79. return len(self.failures) == len(self.errors) == 0
  80. def stop(self):
  81. "Indicates that the tests should be aborted"
  82. self.shouldStop = 1
  83. def __repr__(self):
  84. return "<%s run=%i errors=%i failures=%i>" % \
  85. (self.__class__, self.testsRun, len(self.errors),
  86. len(self.failures))
  87. class TestCase:
  88. """A class whose instances are single test cases.
  89. By default, the test code itself should be placed in a method named
  90. 'runTest'.
  91. If the fixture may be used for many test cases, create as
  92. many test methods as are needed. When instantiating such a TestCase
  93. subclass, specify in the constructor arguments the name of the test method
  94. that the instance is to execute.
  95. Test authors should subclass TestCase for their own tests. Construction
  96. and deconstruction of the test's environment ('fixture') can be
  97. implemented by overriding the 'setUp' and 'tearDown' methods respectively.
  98. If it is necessary to override the __init__ method, the base class
  99. __init__ method must always be called. It is important that subclasses
  100. should not change the signature of their __init__ method, since instances
  101. of the classes are instantiated automatically by parts of the framework
  102. in order to be run.
  103. """
  104. # This attribute determines which exception will be raised when
  105. # the instance's assertion methods fail; test methods raising this
  106. # exception will be deemed to have 'failed' rather than 'errored'
  107. failureException = AssertionError
  108. def __init__(self, methodName='runTest'):
  109. """Create an instance of the class that will use the named test
  110. method when executed. Raises a ValueError if the instance does
  111. not have a method with the specified name.
  112. """
  113. try:
  114. self.__testMethodName = methodName
  115. testMethod = getattr(self, methodName)
  116. self.__testMethodDoc = testMethod.__doc__
  117. except AttributeError:
  118. raise ValueError, "no such test method in %s: %s" % \
  119. (self.__class__, methodName)
  120. def setUp(self):
  121. "Hook method for setting up the test fixture before exercising it."
  122. pass
  123. def tearDown(self):
  124. "Hook method for deconstructing the test fixture after testing it."
  125. pass
  126. def countTestCases(self):
  127. return 1
  128. def defaultTestResult(self):
  129. return TestResult()
  130. def shortDescription(self):
  131. """Returns a one-line description of the test, or None if no
  132. description has been provided.
  133. The default implementation of this method returns the first line of
  134. the specified test method's docstring.
  135. """
  136. doc = self.__testMethodDoc
  137. return doc and string.strip(string.split(doc, "\n")[0]) or None
  138. def id(self):
  139. return "%s.%s" % (self.__class__, self.__testMethodName)
  140. def __str__(self):
  141. return "%s (%s)" % (self.__testMethodName, self.__class__)
  142. def __repr__(self):
  143. return "<%s testMethod=%s>" % \
  144. (self.__class__, self.__testMethodName)
  145. def run(self, result=None):
  146. return self(result)
  147. def __call__(self, result=None):
  148. if result is None: result = self.defaultTestResult()
  149. result.startTest(self)
  150. testMethod = getattr(self, self.__testMethodName)
  151. try:
  152. try:
  153. self.setUp()
  154. except:
  155. result.addError(self,self.__exc_info())
  156. return
  157. ok = 0
  158. try:
  159. testMethod()
  160. ok = 1
  161. except self.failureException, e:
  162. result.addFailure(self,self.__exc_info())
  163. except:
  164. result.addError(self,self.__exc_info())
  165. try:
  166. self.tearDown()
  167. except:
  168. result.addError(self,self.__exc_info())
  169. ok = 0
  170. if ok: result.addSuccess(self)
  171. finally:
  172. result.stopTest(self)
  173. def debug(self):
  174. """Run the test without collecting errors in a TestResult"""
  175. self.setUp()
  176. getattr(self, self.__testMethodName)()
  177. self.tearDown()
  178. def __exc_info(self):
  179. """Return a version of sys.exc_info() with the traceback frame
  180. minimised; usually the top level of the traceback frame is not
  181. needed.
  182. """
  183. exctype, excvalue, tb = sys.exc_info()
  184. if sys.platform[:4] == 'java': ## tracebacks look different in Jython
  185. return (exctype, excvalue, tb)
  186. newtb = tb.tb_next
  187. if newtb is None:
  188. return (exctype, excvalue, tb)
  189. return (exctype, excvalue, newtb)
  190. def fail(self, msg=None):
  191. """Fail immediately, with the given message."""
  192. raise self.failureException, msg
  193. def failIf(self, expr, msg=None):
  194. "Fail the test if the expression is true."
  195. if expr: raise self.failureException, msg
  196. def failUnless(self, expr, msg=None):
  197. """Fail the test unless the expression is true."""
  198. if not expr: raise self.failureException, msg
  199. def failUnlessRaises(self, excClass, callableObj, *args, **kwargs):
  200. """Fail unless an exception of class excClass is thrown
  201. by callableObj when invoked with arguments args and keyword
  202. arguments kwargs. If a different type of exception is
  203. thrown, it will not be caught, and the test case will be
  204. deemed to have suffered an error, exactly as for an
  205. unexpected exception.
  206. """
  207. try:
  208. apply(callableObj, args, kwargs)
  209. except excClass:
  210. return
  211. else:
  212. if hasattr(excClass,'__name__'): excName = excClass.__name__
  213. else: excName = str(excClass)
  214. raise self.failureException, excName
  215. def failUnlessEqual(self, first, second, msg=None):
  216. """Fail if the two objects are unequal as determined by the '!='
  217. operator.
  218. """
  219. if first != second:
  220. raise self.failureException, (msg or '%s != %s' % (first, second))
  221. def failIfEqual(self, first, second, msg=None):
  222. """Fail if the two objects are equal as determined by the '=='
  223. operator.
  224. """
  225. if first == second:
  226. raise self.failureException, (msg or '%s == %s' % (first, second))
  227. assertEqual = assertEquals = failUnlessEqual
  228. assertNotEqual = assertNotEquals = failIfEqual
  229. assertRaises = failUnlessRaises
  230. assert_ = failUnless
  231. class TestSuite:
  232. """A test suite is a composite test consisting of a number of TestCases.
  233. For use, create an instance of TestSuite, then add test case instances.
  234. When all tests have been added, the suite can be passed to a test
  235. runner, such as TextTestRunner. It will run the individual test cases
  236. in the order in which they were added, aggregating the results. When
  237. subclassing, do not forget to call the base class constructor.
  238. """
  239. def __init__(self, tests=()):
  240. self._tests = []
  241. self.addTests(tests)
  242. def __repr__(self):
  243. return "<%s tests=%s>" % (self.__class__, self._tests)
  244. __str__ = __repr__
  245. def countTestCases(self):
  246. cases = 0
  247. for test in self._tests:
  248. cases = cases + test.countTestCases()
  249. return cases
  250. def addTest(self, test):
  251. self._tests.append(test)
  252. def addTests(self, tests):
  253. for test in tests:
  254. self.addTest(test)
  255. def run(self, result):
  256. return self(result)
  257. def __call__(self, result):
  258. for test in self._tests:
  259. if result.shouldStop:
  260. break
  261. test(result)
  262. return result
  263. def debug(self):
  264. """Run the tests without collecting errors in a TestResult"""
  265. for test in self._tests: test.debug()
  266. class FunctionTestCase(TestCase):
  267. """A test case that wraps a test function.
  268. This is useful for slipping pre-existing test functions into the
  269. PyUnit framework. Optionally, set-up and tidy-up functions can be
  270. supplied. As with TestCase, the tidy-up ('tearDown') function will
  271. always be called if the set-up ('setUp') function ran successfully.
  272. """
  273. def __init__(self, testFunc, setUp=None, tearDown=None,
  274. description=None):
  275. TestCase.__init__(self)
  276. self.__setUpFunc = setUp
  277. self.__tearDownFunc = tearDown
  278. self.__testFunc = testFunc
  279. self.__description = description
  280. def setUp(self):
  281. if self.__setUpFunc is not None:
  282. self.__setUpFunc()
  283. def tearDown(self):
  284. if self.__tearDownFunc is not None:
  285. self.__tearDownFunc()
  286. def runTest(self):
  287. self.__testFunc()
  288. def id(self):
  289. return self.__testFunc.__name__
  290. def __str__(self):
  291. return "%s (%s)" % (self.__class__, self.__testFunc.__name__)
  292. def __repr__(self):
  293. return "<%s testFunc=%s>" % (self.__class__, self.__testFunc)
  294. def shortDescription(self):
  295. if self.__description is not None: return self.__description
  296. doc = self.__testFunc.__doc__
  297. return doc and string.strip(string.split(doc, "\n")[0]) or None
  298. ##############################################################################
  299. # Locating and loading tests
  300. ##############################################################################
  301. class TestLoader:
  302. """This class is responsible for loading tests according to various
  303. criteria and returning them wrapped in a Test
  304. """
  305. testMethodPrefix = 'test'
  306. sortTestMethodsUsing = cmp
  307. suiteClass = TestSuite
  308. def loadTestsFromTestCase(self, testCaseClass):
  309. """Return a suite of all tests cases contained in testCaseClass"""
  310. return self.suiteClass(map(testCaseClass,
  311. self.getTestCaseNames(testCaseClass)))
  312. def loadTestsFromModule(self, module):
  313. """Return a suite of all tests cases contained in the given module"""
  314. tests = []
  315. for name in dir(module):
  316. obj = getattr(module, name)
  317. if type(obj) == types.ClassType and issubclass(obj, TestCase):
  318. tests.append(self.loadTestsFromTestCase(obj))
  319. return self.suiteClass(tests)
  320. def loadTestsFromName(self, name, module=None):
  321. """Return a suite of all tests cases given a string specifier.
  322. The name may resolve either to a module, a test case class, a
  323. test method within a test case class, or a callable object which
  324. returns a TestCase or TestSuite instance.
  325. The method optionally resolves the names relative to a given module.
  326. """
  327. parts = string.split(name, '.')
  328. if module is None:
  329. if not parts:
  330. raise ValueError, "incomplete test name: %s" % name
  331. else:
  332. parts_copy = parts[:]
  333. while parts_copy:
  334. try:
  335. module = __import__(string.join(parts_copy,'.'))
  336. break
  337. except ImportError:
  338. del parts_copy[-1]
  339. if not parts_copy: raise
  340. parts = parts[1:]
  341. obj = module
  342. for part in parts:
  343. obj = getattr(obj, part)
  344. if type(obj) == types.ModuleType:
  345. return self.loadTestsFromModule(obj)
  346. elif type(obj) == types.ClassType and issubclass(obj, TestCase):
  347. return self.loadTestsFromTestCase(obj)
  348. elif type(obj) == types.UnboundMethodType:
  349. return obj.im_class(obj.__name__)
  350. elif callable(obj):
  351. test = obj()
  352. if not isinstance(test, TestCase) and \
  353. not isinstance(test, TestSuite):
  354. raise ValueError, \
  355. "calling %s returned %s, not a test" % obj,test
  356. return test
  357. else:
  358. raise ValueError, "don't know how to make test from: %s" % obj
  359. def loadTestsFromNames(self, names, module=None):
  360. """Return a suite of all tests cases found using the given sequence
  361. of string specifiers. See 'loadTestsFromName()'.
  362. """
  363. suites = []
  364. for name in names:
  365. suites.append(self.loadTestsFromName(name, module))
  366. return self.suiteClass(suites)
  367. def getTestCaseNames(self, testCaseClass):
  368. """Return a sorted sequence of method names found within testCaseClass
  369. """
  370. testFnNames = filter(lambda n,p=self.testMethodPrefix: n[:len(p)] == p,
  371. dir(testCaseClass))
  372. for baseclass in testCaseClass.__bases__:
  373. for testFnName in self.getTestCaseNames(baseclass):
  374. if testFnName not in testFnNames: # handle overridden methods
  375. testFnNames.append(testFnName)
  376. if self.sortTestMethodsUsing:
  377. testFnNames.sort(self.sortTestMethodsUsing)
  378. return testFnNames
  379. defaultTestLoader = TestLoader()
  380. ##############################################################################
  381. # Patches for old functions: these functions should be considered obsolete
  382. ##############################################################################
  383. def _makeLoader(prefix, sortUsing, suiteClass=None):
  384. loader = TestLoader()
  385. loader.sortTestMethodsUsing = sortUsing
  386. loader.testMethodPrefix = prefix
  387. if suiteClass: loader.suiteClass = suiteClass
  388. return loader
  389. def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp):
  390. return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)
  391. def makeSuite(testCaseClass, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
  392. return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
  393. def findTestCases(module, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
  394. return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module)
  395. ##############################################################################
  396. # Text UI
  397. ##############################################################################
  398. class _WritelnDecorator:
  399. """Used to decorate file-like objects with a handy 'writeln' method"""
  400. def __init__(self,stream):
  401. self.stream = stream
  402. def __getattr__(self, attr):
  403. return getattr(self.stream,attr)
  404. def writeln(self, *args):
  405. if args: apply(self.write, args)
  406. self.write('\n') # text-mode streams translate to \r\n if needed
  407. class _TextTestResult(TestResult):
  408. """A test result class that can print formatted text results to a stream.
  409. Used by TextTestRunner.
  410. """
  411. separator1 = '=' * 70
  412. separator2 = '-' * 70
  413. def __init__(self, stream, descriptions, verbosity):
  414. TestResult.__init__(self)
  415. self.stream = stream
  416. self.showAll = verbosity > 1
  417. self.dots = verbosity == 1
  418. self.descriptions = descriptions
  419. def getDescription(self, test):
  420. if self.descriptions:
  421. return test.shortDescription() or str(test)
  422. else:
  423. return str(test)
  424. def startTest(self, test):
  425. TestResult.startTest(self, test)
  426. if self.showAll:
  427. self.stream.write(self.getDescription(test))
  428. self.stream.write(" ... ")
  429. def addSuccess(self, test):
  430. TestResult.addSuccess(self, test)
  431. if self.showAll:
  432. self.stream.writeln("ok")
  433. elif self.dots:
  434. self.stream.write('.')
  435. def addError(self, test, err):
  436. TestResult.addError(self, test, err)
  437. if self.showAll:
  438. self.stream.writeln("ERROR")
  439. elif self.dots:
  440. self.stream.write('E')
  441. if err[0] is KeyboardInterrupt:
  442. self.shouldStop = 1
  443. def addFailure(self, test, err):
  444. TestResult.addFailure(self, test, err)
  445. if self.showAll:
  446. self.stream.writeln("FAIL")
  447. elif self.dots:
  448. self.stream.write('F')
  449. def printErrors(self):
  450. if self.dots or self.showAll:
  451. self.stream.writeln()
  452. self.printErrorList('ERROR', self.errors)
  453. self.printErrorList('FAIL', self.failures)
  454. def printErrorList(self, flavour, errors):
  455. for test, err in errors:
  456. self.stream.writeln(self.separator1)
  457. self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
  458. self.stream.writeln(self.separator2)
  459. for line in apply(traceback.format_exception, err):
  460. for l in string.split(line,"\n")[:-1]:
  461. self.stream.writeln("%s" % l)
  462. class TextTestRunner:
  463. """A test runner class that displays results in textual form.
  464. It prints out the names of tests as they are run, errors as they
  465. occur, and a summary of the results at the end of the test run.
  466. """
  467. def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1):
  468. self.stream = _WritelnDecorator(stream)
  469. self.descriptions = descriptions
  470. self.verbosity = verbosity
  471. def _makeResult(self):
  472. return _TextTestResult(self.stream, self.descriptions, self.verbosity)
  473. def run(self, test):
  474. "Run the given test case or test suite."
  475. result = self._makeResult()
  476. startTime = time.time()
  477. test(result)
  478. stopTime = time.time()
  479. timeTaken = float(stopTime - startTime)
  480. result.printErrors()
  481. self.stream.writeln(result.separator2)
  482. run = result.testsRun
  483. self.stream.writeln("Ran %d test%s in %.3fs" %
  484. (run, run == 1 and "" or "s", timeTaken))
  485. self.stream.writeln()
  486. if not result.wasSuccessful():
  487. self.stream.write("FAILED (")
  488. failed, errored = map(len, (result.failures, result.errors))
  489. if failed:
  490. self.stream.write("failures=%d" % failed)
  491. if errored:
  492. if failed: self.stream.write(", ")
  493. self.stream.write("errors=%d" % errored)
  494. self.stream.writeln(")")
  495. else:
  496. self.stream.writeln("OK")
  497. return result
  498. ##############################################################################
  499. # Facilities for running tests from the command line
  500. ##############################################################################
  501. class TestProgram:
  502. """A command-line program that runs a set of tests; this is primarily
  503. for making test modules conveniently executable.
  504. """
  505. USAGE = """\
  506. Usage: %(progName)s [options] [test] [...]
  507. Options:
  508. -h, --help Show this message
  509. -v, --verbose Verbose output
  510. -q, --quiet Minimal output
  511. Examples:
  512. %(progName)s - run default set of tests
  513. %(progName)s MyTestSuite - run suite 'MyTestSuite'
  514. %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething
  515. %(progName)s MyTestCase - run all 'test*' test methods
  516. in MyTestCase
  517. """
  518. def __init__(self, module='__main__', defaultTest=None,
  519. argv=None, testRunner=None, testLoader=defaultTestLoader):
  520. if type(module) == type(''):
  521. self.module = __import__(module)
  522. for part in string.split(module,'.')[1:]:
  523. self.module = getattr(self.module, part)
  524. else:
  525. self.module = module
  526. if argv is None:
  527. argv = sys.argv
  528. self.verbosity = 1
  529. self.defaultTest = defaultTest
  530. self.testRunner = testRunner
  531. self.testLoader = testLoader
  532. self.progName = os.path.basename(argv[0])
  533. self.parseArgs(argv)
  534. self.runTests()
  535. def usageExit(self, msg=None):
  536. if msg: print msg
  537. print self.USAGE % self.__dict__
  538. sys.exit(2)
  539. def parseArgs(self, argv):
  540. import getopt
  541. try:
  542. options, args = getopt.getopt(argv[1:], 'hHvq',
  543. ['help','verbose','quiet'])
  544. for opt, value in options:
  545. if opt in ('-h','-H','--help'):
  546. self.usageExit()
  547. if opt in ('-q','--quiet'):
  548. self.verbosity = 0
  549. if opt in ('-v','--verbose'):
  550. self.verbosity = 2
  551. if len(args) == 0 and self.defaultTest is None:
  552. self.test = self.testLoader.loadTestsFromModule(self.module)
  553. return
  554. if len(args) > 0:
  555. self.testNames = args
  556. else:
  557. self.testNames = (self.defaultTest,)
  558. self.createTests()
  559. except getopt.error, msg:
  560. self.usageExit(msg)
  561. def createTests(self):
  562. self.test = self.testLoader.loadTestsFromNames(self.testNames,
  563. self.module)
  564. def runTests(self):
  565. if self.testRunner is None:
  566. self.testRunner = TextTestRunner(verbosity=self.verbosity)
  567. result = self.testRunner.run(self.test)
  568. sys.exit(not result.wasSuccessful())
  569. main = TestProgram
  570. ##############################################################################
  571. # Executing this module from the command line
  572. ##############################################################################
  573. if __name__ == "__main__":
  574. main(module=None)