unittest.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  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-2003 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.63 $"[11:-2]
  39. import time
  40. import sys
  41. import traceback
  42. import os
  43. import types
  44. ##############################################################################
  45. # Exported classes and functions
  46. ##############################################################################
  47. __all__ = ['TestResult', 'TestCase', 'TestSuite', 'TextTestRunner',
  48. 'TestLoader', 'FunctionTestCase', 'main', 'defaultTestLoader']
  49. # Expose obsolete functions for backwards compatibility
  50. __all__.extend(['getTestCaseNames', 'makeSuite', 'findTestCases'])
  51. ##############################################################################
  52. # Backward compatibility
  53. ##############################################################################
  54. if sys.version_info[:2] < (2, 2):
  55. False, True = 0, 1
  56. def isinstance(obj, clsinfo):
  57. import __builtin__
  58. if type(clsinfo) in (types.TupleType, types.ListType):
  59. for cls in clsinfo:
  60. if cls is type: cls = types.ClassType
  61. if __builtin__.isinstance(obj, cls):
  62. return 1
  63. return 0
  64. else: return __builtin__.isinstance(obj, clsinfo)
  65. ##############################################################################
  66. # Test framework core
  67. ##############################################################################
  68. # All classes defined herein are 'new-style' classes, allowing use of 'super()'
  69. __metaclass__ = type
  70. def _strclass(cls):
  71. return "%s.%s" % (cls.__module__, cls.__name__)
  72. __unittest = 1
  73. class TestResult:
  74. """Holder for test result information.
  75. Test results are automatically managed by the TestCase and TestSuite
  76. classes, and do not need to be explicitly manipulated by writers of tests.
  77. Each instance holds the total number of tests run, and collections of
  78. failures and errors that occurred among those test runs. The collections
  79. contain tuples of (testcase, exceptioninfo), where exceptioninfo is the
  80. formatted traceback of the error that occurred.
  81. """
  82. def __init__(self):
  83. self.failures = []
  84. self.errors = []
  85. self.testsRun = 0
  86. self.shouldStop = 0
  87. def startTest(self, test):
  88. "Called when the given test is about to be run"
  89. self.testsRun = self.testsRun + 1
  90. def stopTest(self, test):
  91. "Called when the given test has been run"
  92. pass
  93. def addError(self, test, err):
  94. """Called when an error has occurred. 'err' is a tuple of values as
  95. returned by sys.exc_info().
  96. """
  97. self.errors.append((test, self._exc_info_to_string(err, test)))
  98. def addFailure(self, test, err):
  99. """Called when an error has occurred. 'err' is a tuple of values as
  100. returned by sys.exc_info()."""
  101. self.failures.append((test, self._exc_info_to_string(err, test)))
  102. def addSuccess(self, test):
  103. "Called when a test has completed successfully"
  104. pass
  105. def wasSuccessful(self):
  106. "Tells whether or not this result was a success"
  107. return len(self.failures) == len(self.errors) == 0
  108. def stop(self):
  109. "Indicates that the tests should be aborted"
  110. self.shouldStop = True
  111. def _exc_info_to_string(self, err, test):
  112. """Converts a sys.exc_info()-style tuple of values into a string."""
  113. exctype, value, tb = err
  114. # Skip test runner traceback levels
  115. while tb and self._is_relevant_tb_level(tb):
  116. tb = tb.tb_next
  117. if exctype is test.failureException:
  118. # Skip assert*() traceback levels
  119. length = self._count_relevant_tb_levels(tb)
  120. return ''.join(traceback.format_exception(exctype, value, tb, length))
  121. return ''.join(traceback.format_exception(exctype, value, tb))
  122. def _is_relevant_tb_level(self, tb):
  123. return tb.tb_frame.f_globals.has_key('__unittest')
  124. def _count_relevant_tb_levels(self, tb):
  125. length = 0
  126. while tb and not self._is_relevant_tb_level(tb):
  127. length += 1
  128. tb = tb.tb_next
  129. return length
  130. def __repr__(self):
  131. return "<%s run=%i errors=%i failures=%i>" % \
  132. (_strclass(self.__class__), self.testsRun, len(self.errors),
  133. len(self.failures))
  134. class TestCase:
  135. """A class whose instances are single test cases.
  136. By default, the test code itself should be placed in a method named
  137. 'runTest'.
  138. If the fixture may be used for many test cases, create as
  139. many test methods as are needed. When instantiating such a TestCase
  140. subclass, specify in the constructor arguments the name of the test method
  141. that the instance is to execute.
  142. Test authors should subclass TestCase for their own tests. Construction
  143. and deconstruction of the test's environment ('fixture') can be
  144. implemented by overriding the 'setUp' and 'tearDown' methods respectively.
  145. If it is necessary to override the __init__ method, the base class
  146. __init__ method must always be called. It is important that subclasses
  147. should not change the signature of their __init__ method, since instances
  148. of the classes are instantiated automatically by parts of the framework
  149. in order to be run.
  150. """
  151. # This attribute determines which exception will be raised when
  152. # the instance's assertion methods fail; test methods raising this
  153. # exception will be deemed to have 'failed' rather than 'errored'
  154. failureException = AssertionError
  155. def __init__(self, methodName='runTest'):
  156. """Create an instance of the class that will use the named test
  157. method when executed. Raises a ValueError if the instance does
  158. not have a method with the specified name.
  159. """
  160. try:
  161. self.__testMethodName = methodName
  162. testMethod = getattr(self, methodName)
  163. self.__testMethodDoc = testMethod.__doc__
  164. except AttributeError:
  165. raise ValueError, "no such test method in %s: %s" % \
  166. (self.__class__, methodName)
  167. def setUp(self):
  168. "Hook method for setting up the test fixture before exercising it."
  169. pass
  170. def tearDown(self):
  171. "Hook method for deconstructing the test fixture after testing it."
  172. pass
  173. def countTestCases(self):
  174. return 1
  175. def defaultTestResult(self):
  176. return TestResult()
  177. def shortDescription(self):
  178. """Returns a one-line description of the test, or None if no
  179. description has been provided.
  180. The default implementation of this method returns the first line of
  181. the specified test method's docstring.
  182. """
  183. doc = self.__testMethodDoc
  184. return doc and doc.split("\n")[0].strip() or None
  185. def id(self):
  186. return "%s.%s" % (_strclass(self.__class__), self.__testMethodName)
  187. def __str__(self):
  188. return "%s (%s)" % (self.__testMethodName, _strclass(self.__class__))
  189. def __repr__(self):
  190. return "<%s testMethod=%s>" % \
  191. (_strclass(self.__class__), self.__testMethodName)
  192. def run(self, result=None):
  193. if result is None: result = self.defaultTestResult()
  194. result.startTest(self)
  195. testMethod = getattr(self, self.__testMethodName)
  196. try:
  197. try:
  198. self.setUp()
  199. except KeyboardInterrupt:
  200. raise
  201. except:
  202. result.addError(self, self.__exc_info())
  203. return
  204. ok = False
  205. try:
  206. testMethod()
  207. ok = True
  208. except self.failureException:
  209. result.addFailure(self, self.__exc_info())
  210. except KeyboardInterrupt:
  211. raise
  212. except:
  213. result.addError(self, self.__exc_info())
  214. try:
  215. self.tearDown()
  216. except KeyboardInterrupt:
  217. raise
  218. except:
  219. result.addError(self, self.__exc_info())
  220. ok = False
  221. if ok: result.addSuccess(self)
  222. finally:
  223. result.stopTest(self)
  224. def __call__(self, *args, **kwds):
  225. return self.run(*args, **kwds)
  226. def debug(self):
  227. """Run the test without collecting errors in a TestResult"""
  228. self.setUp()
  229. getattr(self, self.__testMethodName)()
  230. self.tearDown()
  231. def __exc_info(self):
  232. """Return a version of sys.exc_info() with the traceback frame
  233. minimised; usually the top level of the traceback frame is not
  234. needed.
  235. """
  236. exctype, excvalue, tb = sys.exc_info()
  237. if sys.platform[:4] == 'java': ## tracebacks look different in Jython
  238. return (exctype, excvalue, tb)
  239. return (exctype, excvalue, tb)
  240. def fail(self, msg=None):
  241. """Fail immediately, with the given message."""
  242. raise self.failureException, msg
  243. def failIf(self, expr, msg=None):
  244. "Fail the test if the expression is true."
  245. if expr: raise self.failureException, msg
  246. def failUnless(self, expr, msg=None):
  247. """Fail the test unless the expression is true."""
  248. if not expr: raise self.failureException, msg
  249. def failUnlessRaises(self, excClass, callableObj, *args, **kwargs):
  250. """Fail unless an exception of class excClass is thrown
  251. by callableObj when invoked with arguments args and keyword
  252. arguments kwargs. If a different type of exception is
  253. thrown, it will not be caught, and the test case will be
  254. deemed to have suffered an error, exactly as for an
  255. unexpected exception.
  256. """
  257. try:
  258. callableObj(*args, **kwargs)
  259. except excClass:
  260. return
  261. else:
  262. if hasattr(excClass,'__name__'): excName = excClass.__name__
  263. else: excName = str(excClass)
  264. raise self.failureException, "%s not raised" % excName
  265. def failUnlessEqual(self, first, second, msg=None):
  266. """Fail if the two objects are unequal as determined by the '=='
  267. operator.
  268. """
  269. if not first == second:
  270. raise self.failureException, \
  271. (msg or '%r != %r' % (first, second))
  272. def failIfEqual(self, first, second, msg=None):
  273. """Fail if the two objects are equal as determined by the '=='
  274. operator.
  275. """
  276. if first == second:
  277. raise self.failureException, \
  278. (msg or '%r == %r' % (first, second))
  279. def failUnlessAlmostEqual(self, first, second, places=7, msg=None):
  280. """Fail if the two objects are unequal as determined by their
  281. difference rounded to the given number of decimal places
  282. (default 7) and comparing to zero.
  283. Note that decimal places (from zero) are usually not the same
  284. as significant digits (measured from the most signficant digit).
  285. """
  286. if round(second-first, places) != 0:
  287. raise self.failureException, \
  288. (msg or '%r != %r within %r places' % (first, second, places))
  289. def failIfAlmostEqual(self, first, second, places=7, msg=None):
  290. """Fail if the two objects are equal as determined by their
  291. difference rounded to the given number of decimal places
  292. (default 7) and comparing to zero.
  293. Note that decimal places (from zero) are usually not the same
  294. as significant digits (measured from the most signficant digit).
  295. """
  296. if round(second-first, places) == 0:
  297. raise self.failureException, \
  298. (msg or '%r == %r within %r places' % (first, second, places))
  299. # Synonyms for assertion methods
  300. assertEqual = assertEquals = failUnlessEqual
  301. assertNotEqual = assertNotEquals = failIfEqual
  302. assertAlmostEqual = assertAlmostEquals = failUnlessAlmostEqual
  303. assertNotAlmostEqual = assertNotAlmostEquals = failIfAlmostEqual
  304. assertRaises = failUnlessRaises
  305. assert_ = assertTrue = failUnless
  306. assertFalse = failIf
  307. class TestSuite:
  308. """A test suite is a composite test consisting of a number of TestCases.
  309. For use, create an instance of TestSuite, then add test case instances.
  310. When all tests have been added, the suite can be passed to a test
  311. runner, such as TextTestRunner. It will run the individual test cases
  312. in the order in which they were added, aggregating the results. When
  313. subclassing, do not forget to call the base class constructor.
  314. """
  315. def __init__(self, tests=()):
  316. self._tests = []
  317. self.addTests(tests)
  318. def __repr__(self):
  319. return "<%s tests=%s>" % (_strclass(self.__class__), self._tests)
  320. __str__ = __repr__
  321. def __iter__(self):
  322. return iter(self._tests)
  323. def countTestCases(self):
  324. cases = 0
  325. for test in self._tests:
  326. cases += test.countTestCases()
  327. return cases
  328. def addTest(self, test):
  329. self._tests.append(test)
  330. def addTests(self, tests):
  331. for test in tests:
  332. self.addTest(test)
  333. def run(self, result):
  334. for test in self._tests:
  335. if result.shouldStop:
  336. break
  337. test(result)
  338. return result
  339. def __call__(self, *args, **kwds):
  340. return self.run(*args, **kwds)
  341. def debug(self):
  342. """Run the tests without collecting errors in a TestResult"""
  343. for test in self._tests: test.debug()
  344. class FunctionTestCase(TestCase):
  345. """A test case that wraps a test function.
  346. This is useful for slipping pre-existing test functions into the
  347. PyUnit framework. Optionally, set-up and tidy-up functions can be
  348. supplied. As with TestCase, the tidy-up ('tearDown') function will
  349. always be called if the set-up ('setUp') function ran successfully.
  350. """
  351. def __init__(self, testFunc, setUp=None, tearDown=None,
  352. description=None):
  353. TestCase.__init__(self)
  354. self.__setUpFunc = setUp
  355. self.__tearDownFunc = tearDown
  356. self.__testFunc = testFunc
  357. self.__description = description
  358. def setUp(self):
  359. if self.__setUpFunc is not None:
  360. self.__setUpFunc()
  361. def tearDown(self):
  362. if self.__tearDownFunc is not None:
  363. self.__tearDownFunc()
  364. def runTest(self):
  365. self.__testFunc()
  366. def id(self):
  367. return self.__testFunc.__name__
  368. def __str__(self):
  369. return "%s (%s)" % (_strclass(self.__class__), self.__testFunc.__name__)
  370. def __repr__(self):
  371. return "<%s testFunc=%s>" % (_strclass(self.__class__), self.__testFunc)
  372. def shortDescription(self):
  373. if self.__description is not None: return self.__description
  374. doc = self.__testFunc.__doc__
  375. return doc and doc.split("\n")[0].strip() or None
  376. ##############################################################################
  377. # Locating and loading tests
  378. ##############################################################################
  379. class TestLoader:
  380. """This class is responsible for loading tests according to various
  381. criteria and returning them wrapped in a Test
  382. """
  383. testMethodPrefix = 'test'
  384. sortTestMethodsUsing = cmp
  385. suiteClass = TestSuite
  386. def loadTestsFromTestCase(self, testCaseClass):
  387. """Return a suite of all tests cases contained in testCaseClass"""
  388. if issubclass(testCaseClass, TestSuite):
  389. raise TypeError("Test cases should not be derived from TestSuite. Maybe you meant to derive from TestCase?")
  390. testCaseNames = self.getTestCaseNames(testCaseClass)
  391. if not testCaseNames and hasattr(testCaseClass, 'runTest'):
  392. testCaseNames = ['runTest']
  393. return self.suiteClass(map(testCaseClass, testCaseNames))
  394. def loadTestsFromModule(self, module):
  395. """Return a suite of all tests cases contained in the given module"""
  396. tests = []
  397. for name in dir(module):
  398. obj = getattr(module, name)
  399. if (isinstance(obj, (type, types.ClassType)) and
  400. issubclass(obj, TestCase)):
  401. tests.append(self.loadTestsFromTestCase(obj))
  402. return self.suiteClass(tests)
  403. def loadTestsFromName(self, name, module=None):
  404. """Return a suite of all tests cases given a string specifier.
  405. The name may resolve either to a module, a test case class, a
  406. test method within a test case class, or a callable object which
  407. returns a TestCase or TestSuite instance.
  408. The method optionally resolves the names relative to a given module.
  409. """
  410. parts = name.split('.')
  411. if module is None:
  412. parts_copy = parts[:]
  413. while parts_copy:
  414. try:
  415. module = __import__('.'.join(parts_copy))
  416. break
  417. except ImportError:
  418. del parts_copy[-1]
  419. if not parts_copy: raise
  420. parts = parts[1:]
  421. obj = module
  422. for part in parts:
  423. parent, obj = obj, getattr(obj, part)
  424. if type(obj) == types.ModuleType:
  425. return self.loadTestsFromModule(obj)
  426. elif (isinstance(obj, (type, types.ClassType)) and
  427. issubclass(obj, TestCase)):
  428. return self.loadTestsFromTestCase(obj)
  429. elif type(obj) == types.UnboundMethodType:
  430. return parent(obj.__name__)
  431. elif isinstance(obj, TestSuite):
  432. return obj
  433. elif callable(obj):
  434. test = obj()
  435. if not isinstance(test, (TestCase, TestSuite)):
  436. raise ValueError, \
  437. "calling %s returned %s, not a test" % (obj,test)
  438. return test
  439. else:
  440. raise ValueError, "don't know how to make test from: %s" % obj
  441. def loadTestsFromNames(self, names, module=None):
  442. """Return a suite of all tests cases found using the given sequence
  443. of string specifiers. See 'loadTestsFromName()'.
  444. """
  445. suites = [self.loadTestsFromName(name, module) for name in names]
  446. return self.suiteClass(suites)
  447. def getTestCaseNames(self, testCaseClass):
  448. """Return a sorted sequence of method names found within testCaseClass
  449. """
  450. def isTestMethod(attrname, testCaseClass=testCaseClass, prefix=self.testMethodPrefix):
  451. return attrname.startswith(prefix) and callable(getattr(testCaseClass, attrname))
  452. testFnNames = filter(isTestMethod, dir(testCaseClass))
  453. for baseclass in testCaseClass.__bases__:
  454. for testFnName in self.getTestCaseNames(baseclass):
  455. if testFnName not in testFnNames: # handle overridden methods
  456. testFnNames.append(testFnName)
  457. if self.sortTestMethodsUsing:
  458. testFnNames.sort(self.sortTestMethodsUsing)
  459. return testFnNames
  460. defaultTestLoader = TestLoader()
  461. ##############################################################################
  462. # Patches for old functions: these functions should be considered obsolete
  463. ##############################################################################
  464. def _makeLoader(prefix, sortUsing, suiteClass=None):
  465. loader = TestLoader()
  466. loader.sortTestMethodsUsing = sortUsing
  467. loader.testMethodPrefix = prefix
  468. if suiteClass: loader.suiteClass = suiteClass
  469. return loader
  470. def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp):
  471. return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)
  472. def makeSuite(testCaseClass, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
  473. return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
  474. def findTestCases(module, prefix='test', sortUsing=cmp, suiteClass=TestSuite):
  475. return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module)
  476. ##############################################################################
  477. # Text UI
  478. ##############################################################################
  479. class _WritelnDecorator:
  480. """Used to decorate file-like objects with a handy 'writeln' method"""
  481. def __init__(self,stream):
  482. self.stream = stream
  483. def __getattr__(self, attr):
  484. return getattr(self.stream,attr)
  485. def writeln(self, arg=None):
  486. if arg: self.write(arg)
  487. self.write('\n') # text-mode streams translate to \r\n if needed
  488. class _TextTestResult(TestResult):
  489. """A test result class that can print formatted text results to a stream.
  490. Used by TextTestRunner.
  491. """
  492. separator1 = '=' * 70
  493. separator2 = '-' * 70
  494. def __init__(self, stream, descriptions, verbosity):
  495. TestResult.__init__(self)
  496. self.stream = stream
  497. self.showAll = verbosity > 1
  498. self.dots = verbosity == 1
  499. self.descriptions = descriptions
  500. def getDescription(self, test):
  501. if self.descriptions:
  502. return test.shortDescription() or str(test)
  503. else:
  504. return str(test)
  505. def startTest(self, test):
  506. TestResult.startTest(self, test)
  507. if self.showAll:
  508. self.stream.write(self.getDescription(test))
  509. self.stream.write(" ... ")
  510. def addSuccess(self, test):
  511. TestResult.addSuccess(self, test)
  512. if self.showAll:
  513. self.stream.writeln("ok")
  514. elif self.dots:
  515. self.stream.write('.')
  516. def addError(self, test, err):
  517. TestResult.addError(self, test, err)
  518. if self.showAll:
  519. self.stream.writeln("ERROR")
  520. elif self.dots:
  521. self.stream.write('E')
  522. def addFailure(self, test, err):
  523. TestResult.addFailure(self, test, err)
  524. if self.showAll:
  525. self.stream.writeln("FAIL")
  526. elif self.dots:
  527. self.stream.write('F')
  528. def printErrors(self):
  529. if self.dots or self.showAll:
  530. self.stream.writeln()
  531. self.printErrorList('ERROR', self.errors)
  532. self.printErrorList('FAIL', self.failures)
  533. def printErrorList(self, flavour, errors):
  534. for test, err in errors:
  535. self.stream.writeln(self.separator1)
  536. self.stream.writeln("%s: %s" % (flavour,self.getDescription(test)))
  537. self.stream.writeln(self.separator2)
  538. self.stream.writeln("%s" % err)
  539. class TextTestRunner:
  540. """A test runner class that displays results in textual form.
  541. It prints out the names of tests as they are run, errors as they
  542. occur, and a summary of the results at the end of the test run.
  543. """
  544. def __init__(self, stream=sys.stderr, descriptions=1, verbosity=1):
  545. self.stream = _WritelnDecorator(stream)
  546. self.descriptions = descriptions
  547. self.verbosity = verbosity
  548. def _makeResult(self):
  549. return _TextTestResult(self.stream, self.descriptions, self.verbosity)
  550. def run(self, test):
  551. "Run the given test case or test suite."
  552. result = self._makeResult()
  553. startTime = time.time()
  554. test(result)
  555. stopTime = time.time()
  556. timeTaken = stopTime - startTime
  557. result.printErrors()
  558. self.stream.writeln(result.separator2)
  559. run = result.testsRun
  560. self.stream.writeln("Ran %d test%s in %.3fs" %
  561. (run, run != 1 and "s" or "", timeTaken))
  562. self.stream.writeln()
  563. if not result.wasSuccessful():
  564. self.stream.write("FAILED (")
  565. failed, errored = map(len, (result.failures, result.errors))
  566. if failed:
  567. self.stream.write("failures=%d" % failed)
  568. if errored:
  569. if failed: self.stream.write(", ")
  570. self.stream.write("errors=%d" % errored)
  571. self.stream.writeln(")")
  572. else:
  573. self.stream.writeln("OK")
  574. return result
  575. ##############################################################################
  576. # Facilities for running tests from the command line
  577. ##############################################################################
  578. class TestProgram:
  579. """A command-line program that runs a set of tests; this is primarily
  580. for making test modules conveniently executable.
  581. """
  582. USAGE = """\
  583. Usage: %(progName)s [options] [test] [...]
  584. Options:
  585. -h, --help Show this message
  586. -v, --verbose Verbose output
  587. -q, --quiet Minimal output
  588. Examples:
  589. %(progName)s - run default set of tests
  590. %(progName)s MyTestSuite - run suite 'MyTestSuite'
  591. %(progName)s MyTestCase.testSomething - run MyTestCase.testSomething
  592. %(progName)s MyTestCase - run all 'test*' test methods
  593. in MyTestCase
  594. """
  595. def __init__(self, module='__main__', defaultTest=None,
  596. argv=None, testRunner=None, testLoader=defaultTestLoader):
  597. if type(module) == type(''):
  598. self.module = __import__(module)
  599. for part in module.split('.')[1:]:
  600. self.module = getattr(self.module, part)
  601. else:
  602. self.module = module
  603. if argv is None:
  604. argv = sys.argv
  605. self.verbosity = 1
  606. self.defaultTest = defaultTest
  607. self.testRunner = testRunner
  608. self.testLoader = testLoader
  609. self.progName = os.path.basename(argv[0])
  610. self.parseArgs(argv)
  611. self.runTests()
  612. def usageExit(self, msg=None):
  613. if msg: print msg
  614. print self.USAGE % self.__dict__
  615. sys.exit(2)
  616. def parseArgs(self, argv):
  617. import getopt
  618. try:
  619. options, args = getopt.getopt(argv[1:], 'hHvq',
  620. ['help','verbose','quiet'])
  621. for opt, value in options:
  622. if opt in ('-h','-H','--help'):
  623. self.usageExit()
  624. if opt in ('-q','--quiet'):
  625. self.verbosity = 0
  626. if opt in ('-v','--verbose'):
  627. self.verbosity = 2
  628. if len(args) == 0 and self.defaultTest is None:
  629. self.test = self.testLoader.loadTestsFromModule(self.module)
  630. return
  631. if len(args) > 0:
  632. self.testNames = args
  633. else:
  634. self.testNames = (self.defaultTest,)
  635. self.createTests()
  636. except getopt.error, msg:
  637. self.usageExit(msg)
  638. def createTests(self):
  639. self.test = self.testLoader.loadTestsFromNames(self.testNames,
  640. self.module)
  641. def runTests(self):
  642. if self.testRunner is None:
  643. self.testRunner = TextTestRunner(verbosity=self.verbosity)
  644. result = self.testRunner.run(self.test)
  645. sys.exit(not result.wasSuccessful())
  646. main = TestProgram
  647. ##############################################################################
  648. # Executing this module from the command line
  649. ##############################################################################
  650. if __name__ == "__main__":
  651. main(module=None)