main.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. """Unittest main program"""
  2. import sys
  3. import argparse
  4. import os
  5. from . import loader, runner
  6. from .signals import installHandler
  7. __unittest = True
  8. MAIN_EXAMPLES = """\
  9. Examples:
  10. %(prog)s test_module - run tests from test_module
  11. %(prog)s module.TestClass - run tests from module.TestClass
  12. %(prog)s module.Class.test_method - run specified test method
  13. """
  14. MODULE_EXAMPLES = """\
  15. Examples:
  16. %(prog)s - run default set of tests
  17. %(prog)s MyTestSuite - run suite 'MyTestSuite'
  18. %(prog)s MyTestCase.testSomething - run MyTestCase.testSomething
  19. %(prog)s MyTestCase - run all 'test*' test methods
  20. in MyTestCase
  21. """
  22. def _convert_name(name):
  23. # on Linux / Mac OS X 'foo.PY' is not importable, but on
  24. # Windows it is. Simpler to do a case insensitive match
  25. # a better check would be to check that the name is a
  26. # valid Python module name.
  27. if os.path.isfile(name) and name.lower().endswith('.py'):
  28. if os.path.isabs(name):
  29. rel_path = os.path.relpath(name, os.getcwd())
  30. if os.path.isabs(rel_path) or rel_path.startswith(os.pardir):
  31. return name
  32. name = rel_path
  33. # on Windows both '\' and '/' are used as path
  34. # separators. Better to replace both than rely on os.path.sep
  35. return name[:-3].replace('\\', '.').replace('/', '.')
  36. return name
  37. def _convert_names(names):
  38. return [_convert_name(name) for name in names]
  39. class TestProgram(object):
  40. """A command-line program that runs a set of tests; this is primarily
  41. for making test modules conveniently executable.
  42. """
  43. # defaults for testing
  44. module=None
  45. verbosity = 1
  46. failfast = catchbreak = buffer = progName = warnings = None
  47. _discovery_parser = None
  48. def __init__(self, module='__main__', defaultTest=None, argv=None,
  49. testRunner=None, testLoader=loader.defaultTestLoader,
  50. exit=True, verbosity=1, failfast=None, catchbreak=None,
  51. buffer=None, warnings=None, *, tb_locals=False):
  52. if isinstance(module, str):
  53. self.module = __import__(module)
  54. for part in module.split('.')[1:]:
  55. self.module = getattr(self.module, part)
  56. else:
  57. self.module = module
  58. if argv is None:
  59. argv = sys.argv
  60. self.exit = exit
  61. self.failfast = failfast
  62. self.catchbreak = catchbreak
  63. self.verbosity = verbosity
  64. self.buffer = buffer
  65. self.tb_locals = tb_locals
  66. if warnings is None and not sys.warnoptions:
  67. # even if DeprecationWarnings are ignored by default
  68. # print them anyway unless other warnings settings are
  69. # specified by the warnings arg or the -W python flag
  70. self.warnings = 'default'
  71. else:
  72. # here self.warnings is set either to the value passed
  73. # to the warnings args or to None.
  74. # If the user didn't pass a value self.warnings will
  75. # be None. This means that the behavior is unchanged
  76. # and depends on the values passed to -W.
  77. self.warnings = warnings
  78. self.defaultTest = defaultTest
  79. self.testRunner = testRunner
  80. self.testLoader = testLoader
  81. self.progName = os.path.basename(argv[0])
  82. self.parseArgs(argv)
  83. self.runTests()
  84. def usageExit(self, msg=None):
  85. if msg:
  86. print(msg)
  87. if self._discovery_parser is None:
  88. self._initArgParsers()
  89. self._print_help()
  90. sys.exit(2)
  91. def _print_help(self, *args, **kwargs):
  92. if self.module is None:
  93. print(self._main_parser.format_help())
  94. print(MAIN_EXAMPLES % {'prog': self.progName})
  95. self._discovery_parser.print_help()
  96. else:
  97. print(self._main_parser.format_help())
  98. print(MODULE_EXAMPLES % {'prog': self.progName})
  99. def parseArgs(self, argv):
  100. self._initArgParsers()
  101. if self.module is None:
  102. if len(argv) > 1 and argv[1].lower() == 'discover':
  103. self._do_discovery(argv[2:])
  104. return
  105. self._main_parser.parse_args(argv[1:], self)
  106. if not self.tests:
  107. # this allows "python -m unittest -v" to still work for
  108. # test discovery.
  109. self._do_discovery([])
  110. return
  111. else:
  112. self._main_parser.parse_args(argv[1:], self)
  113. if self.tests:
  114. self.testNames = _convert_names(self.tests)
  115. if __name__ == '__main__':
  116. # to support python -m unittest ...
  117. self.module = None
  118. elif self.defaultTest is None:
  119. # createTests will load tests from self.module
  120. self.testNames = None
  121. elif isinstance(self.defaultTest, str):
  122. self.testNames = (self.defaultTest,)
  123. else:
  124. self.testNames = list(self.defaultTest)
  125. self.createTests()
  126. def createTests(self):
  127. if self.testNames is None:
  128. self.test = self.testLoader.loadTestsFromModule(self.module)
  129. else:
  130. self.test = self.testLoader.loadTestsFromNames(self.testNames,
  131. self.module)
  132. def _initArgParsers(self):
  133. parent_parser = self._getParentArgParser()
  134. self._main_parser = self._getMainArgParser(parent_parser)
  135. self._discovery_parser = self._getDiscoveryArgParser(parent_parser)
  136. def _getParentArgParser(self):
  137. parser = argparse.ArgumentParser(add_help=False)
  138. parser.add_argument('-v', '--verbose', dest='verbosity',
  139. action='store_const', const=2,
  140. help='Verbose output')
  141. parser.add_argument('-q', '--quiet', dest='verbosity',
  142. action='store_const', const=0,
  143. help='Quiet output')
  144. parser.add_argument('--locals', dest='tb_locals',
  145. action='store_true',
  146. help='Show local variables in tracebacks')
  147. if self.failfast is None:
  148. parser.add_argument('-f', '--failfast', dest='failfast',
  149. action='store_true',
  150. help='Stop on first fail or error')
  151. self.failfast = False
  152. if self.catchbreak is None:
  153. parser.add_argument('-c', '--catch', dest='catchbreak',
  154. action='store_true',
  155. help='Catch Ctrl-C and display results so far')
  156. self.catchbreak = False
  157. if self.buffer is None:
  158. parser.add_argument('-b', '--buffer', dest='buffer',
  159. action='store_true',
  160. help='Buffer stdout and stderr during tests')
  161. self.buffer = False
  162. return parser
  163. def _getMainArgParser(self, parent):
  164. parser = argparse.ArgumentParser(parents=[parent])
  165. parser.prog = self.progName
  166. parser.print_help = self._print_help
  167. parser.add_argument('tests', nargs='*',
  168. help='a list of any number of test modules, '
  169. 'classes and test methods.')
  170. return parser
  171. def _getDiscoveryArgParser(self, parent):
  172. parser = argparse.ArgumentParser(parents=[parent])
  173. parser.prog = '%s discover' % self.progName
  174. parser.epilog = ('For test discovery all test modules must be '
  175. 'importable from the top level directory of the '
  176. 'project.')
  177. parser.add_argument('-s', '--start-directory', dest='start',
  178. help="Directory to start discovery ('.' default)")
  179. parser.add_argument('-p', '--pattern', dest='pattern',
  180. help="Pattern to match tests ('test*.py' default)")
  181. parser.add_argument('-t', '--top-level-directory', dest='top',
  182. help='Top level directory of project (defaults to '
  183. 'start directory)')
  184. for arg in ('start', 'pattern', 'top'):
  185. parser.add_argument(arg, nargs='?',
  186. default=argparse.SUPPRESS,
  187. help=argparse.SUPPRESS)
  188. return parser
  189. def _do_discovery(self, argv, Loader=None):
  190. self.start = '.'
  191. self.pattern = 'test*.py'
  192. self.top = None
  193. if argv is not None:
  194. # handle command line args for test discovery
  195. if self._discovery_parser is None:
  196. # for testing
  197. self._initArgParsers()
  198. self._discovery_parser.parse_args(argv, self)
  199. loader = self.testLoader if Loader is None else Loader()
  200. self.test = loader.discover(self.start, self.pattern, self.top)
  201. def runTests(self):
  202. if self.catchbreak:
  203. installHandler()
  204. if self.testRunner is None:
  205. self.testRunner = runner.TextTestRunner
  206. if isinstance(self.testRunner, type):
  207. try:
  208. try:
  209. testRunner = self.testRunner(verbosity=self.verbosity,
  210. failfast=self.failfast,
  211. buffer=self.buffer,
  212. warnings=self.warnings,
  213. tb_locals=self.tb_locals)
  214. except TypeError:
  215. # didn't accept the tb_locals argument
  216. testRunner = self.testRunner(verbosity=self.verbosity,
  217. failfast=self.failfast,
  218. buffer=self.buffer,
  219. warnings=self.warnings)
  220. except TypeError:
  221. # didn't accept the verbosity, buffer or failfast arguments
  222. testRunner = self.testRunner()
  223. else:
  224. # it is assumed to be a TestRunner instance
  225. testRunner = self.testRunner
  226. self.result = testRunner.run(self.test)
  227. if self.exit:
  228. sys.exit(not self.result.wasSuccessful())
  229. main = TestProgram