trial.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. # -*- test-case-name: twisted.trial.test.test_script -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. from __future__ import absolute_import, division, print_function
  5. import gc
  6. import inspect
  7. import os
  8. import pdb
  9. import random
  10. import sys
  11. import time
  12. import warnings
  13. from twisted.internet import defer
  14. from twisted.application import app
  15. from twisted.python import usage, reflect, failure
  16. from twisted.python.filepath import FilePath
  17. from twisted.python.reflect import namedModule
  18. from twisted.python.compat import long
  19. from twisted import plugin
  20. from twisted.trial import runner, itrial, reporter
  21. # Yea, this is stupid. Leave it for command-line compatibility for a
  22. # while, though.
  23. TBFORMAT_MAP = {
  24. 'plain': 'default',
  25. 'default': 'default',
  26. 'emacs': 'brief',
  27. 'brief': 'brief',
  28. 'cgitb': 'verbose',
  29. 'verbose': 'verbose'
  30. }
  31. def _parseLocalVariables(line):
  32. """
  33. Accepts a single line in Emacs local variable declaration format and
  34. returns a dict of all the variables {name: value}.
  35. Raises ValueError if 'line' is in the wrong format.
  36. See http://www.gnu.org/software/emacs/manual/html_node/File-Variables.html
  37. """
  38. paren = '-*-'
  39. start = line.find(paren) + len(paren)
  40. end = line.rfind(paren)
  41. if start == -1 or end == -1:
  42. raise ValueError("%r not a valid local variable declaration" % (line,))
  43. items = line[start:end].split(';')
  44. localVars = {}
  45. for item in items:
  46. if len(item.strip()) == 0:
  47. continue
  48. split = item.split(':')
  49. if len(split) != 2:
  50. raise ValueError("%r contains invalid declaration %r"
  51. % (line, item))
  52. localVars[split[0].strip()] = split[1].strip()
  53. return localVars
  54. def loadLocalVariables(filename):
  55. """
  56. Accepts a filename and attempts to load the Emacs variable declarations
  57. from that file, simulating what Emacs does.
  58. See http://www.gnu.org/software/emacs/manual/html_node/File-Variables.html
  59. """
  60. with open(filename, "r") as f:
  61. lines = [f.readline(), f.readline()]
  62. for line in lines:
  63. try:
  64. return _parseLocalVariables(line)
  65. except ValueError:
  66. pass
  67. return {}
  68. def getTestModules(filename):
  69. testCaseVar = loadLocalVariables(filename).get('test-case-name', None)
  70. if testCaseVar is None:
  71. return []
  72. return testCaseVar.split(',')
  73. def isTestFile(filename):
  74. """
  75. Returns true if 'filename' looks like a file containing unit tests.
  76. False otherwise. Doesn't care whether filename exists.
  77. """
  78. basename = os.path.basename(filename)
  79. return (basename.startswith('test_')
  80. and os.path.splitext(basename)[1] == ('.py'))
  81. def _reporterAction():
  82. return usage.CompleteList([p.longOpt for p in
  83. plugin.getPlugins(itrial.IReporter)])
  84. def _maybeFindSourceLine(testThing):
  85. """
  86. Try to find the source line of the given test thing.
  87. @param testThing: the test item to attempt to inspect
  88. @type testThing: an L{TestCase}, test method, or module, though only the
  89. former two have a chance to succeed
  90. @rtype: int
  91. @return: the starting source line, or -1 if one couldn't be found
  92. """
  93. # an instance of L{TestCase} -- locate the test it will run
  94. method = getattr(testThing, "_testMethodName", None)
  95. if method is not None:
  96. testThing = getattr(testThing, method)
  97. # If it's a function, we can get the line number even if the source file no
  98. # longer exists
  99. code = getattr(testThing, "__code__", None)
  100. if code is not None:
  101. return code.co_firstlineno
  102. try:
  103. return inspect.getsourcelines(testThing)[1]
  104. except (IOError, TypeError):
  105. # either testThing is a module, which raised a TypeError, or the file
  106. # couldn't be read
  107. return -1
  108. # orders which can be passed to trial --order
  109. _runOrders = {
  110. "alphabetical" : (
  111. "alphabetical order for test methods, arbitrary order for test cases",
  112. runner.name),
  113. "toptobottom" : (
  114. "attempt to run test cases and methods in the order they were defined",
  115. _maybeFindSourceLine),
  116. }
  117. def _checkKnownRunOrder(order):
  118. """
  119. Check that the given order is a known test running order.
  120. Does nothing else, since looking up the appropriate callable to sort the
  121. tests should be done when it actually will be used, as the default argument
  122. will not be coerced by this function.
  123. @param order: one of the known orders in C{_runOrders}
  124. @return: the order unmodified
  125. """
  126. if order not in _runOrders:
  127. raise usage.UsageError(
  128. "--order must be one of: %s. See --help-orders for details" %
  129. (", ".join(repr(order) for order in _runOrders),))
  130. return order
  131. class _BasicOptions(object):
  132. """
  133. Basic options shared between trial and its local workers.
  134. """
  135. longdesc = ("trial loads and executes a suite of unit tests, obtained "
  136. "from modules, packages and files listed on the command line.")
  137. optFlags = [["help", "h"],
  138. ["no-recurse", "N", "Don't recurse into packages"],
  139. ['help-orders', None, "Help on available test running orders"],
  140. ['help-reporters', None,
  141. "Help on available output plugins (reporters)"],
  142. ["rterrors", "e", "realtime errors, print out tracebacks as "
  143. "soon as they occur"],
  144. ["unclean-warnings", None,
  145. "Turn dirty reactor errors into warnings"],
  146. ["force-gc", None, "Have Trial run gc.collect() before and "
  147. "after each test case."],
  148. ["exitfirst", "x",
  149. "Exit after the first non-successful result (cannot be "
  150. "specified along with --jobs)."],
  151. ]
  152. optParameters = [
  153. ["order", "o", None,
  154. "Specify what order to run test cases and methods. "
  155. "See --help-orders for more info.", _checkKnownRunOrder],
  156. ["random", "z", None,
  157. "Run tests in random order using the specified seed"],
  158. ['temp-directory', None, '_trial_temp',
  159. 'Path to use as working directory for tests.'],
  160. ['reporter', None, 'verbose',
  161. 'The reporter to use for this test run. See --help-reporters for '
  162. 'more info.']]
  163. compData = usage.Completions(
  164. optActions={"order": usage.CompleteList(_runOrders),
  165. "reporter": _reporterAction,
  166. "logfile": usage.CompleteFiles(descr="log file name"),
  167. "random": usage.Completer(descr="random seed")},
  168. extraActions=[usage.CompleteFiles(
  169. "*.py", descr="file | module | package | TestCase | testMethod",
  170. repeat=True)],
  171. )
  172. fallbackReporter = reporter.TreeReporter
  173. tracer = None
  174. def __init__(self):
  175. self['tests'] = []
  176. usage.Options.__init__(self)
  177. def getSynopsis(self):
  178. executableName = reflect.filenameToModuleName(sys.argv[0])
  179. if executableName.endswith('.__main__'):
  180. executableName = '{} -m {}'.format(os.path.basename(sys.executable),
  181. executableName.replace('.__main__', ''))
  182. return """%s [options] [[file|package|module|TestCase|testmethod]...]
  183. """ % (executableName,)
  184. def coverdir(self):
  185. """
  186. Return a L{FilePath} representing the directory into which coverage
  187. results should be written.
  188. """
  189. coverdir = 'coverage'
  190. result = FilePath(self['temp-directory']).child(coverdir)
  191. print("Setting coverage directory to %s." % (result.path,))
  192. return result
  193. # TODO: Some of the opt_* methods on this class have docstrings and some do
  194. # not. This is mostly because usage.Options's currently will replace
  195. # any intended output in optFlags and optParameters with the
  196. # docstring. See #6427. When that is fixed, all methods should be
  197. # given docstrings (and it should be verified that those with
  198. # docstrings already have content suitable for printing as usage
  199. # information).
  200. def opt_coverage(self):
  201. """
  202. Generate coverage information in the coverage file in the
  203. directory specified by the temp-directory option.
  204. """
  205. import trace
  206. self.tracer = trace.Trace(count=1, trace=0)
  207. sys.settrace(self.tracer.globaltrace)
  208. self['coverage'] = True
  209. def opt_testmodule(self, filename):
  210. """
  211. Filename to grep for test cases (-*- test-case-name).
  212. """
  213. # If the filename passed to this parameter looks like a test module
  214. # we just add that to the test suite.
  215. #
  216. # If not, we inspect it for an Emacs buffer local variable called
  217. # 'test-case-name'. If that variable is declared, we try to add its
  218. # value to the test suite as a module.
  219. #
  220. # This parameter allows automated processes (like Buildbot) to pass
  221. # a list of files to Trial with the general expectation of "these files,
  222. # whatever they are, will get tested"
  223. if not os.path.isfile(filename):
  224. sys.stderr.write("File %r doesn't exist\n" % (filename,))
  225. return
  226. filename = os.path.abspath(filename)
  227. if isTestFile(filename):
  228. self['tests'].append(filename)
  229. else:
  230. self['tests'].extend(getTestModules(filename))
  231. def opt_spew(self):
  232. """
  233. Print an insanely verbose log of everything that happens. Useful
  234. when debugging freezes or locks in complex code.
  235. """
  236. from twisted.python.util import spewer
  237. sys.settrace(spewer)
  238. def opt_help_orders(self):
  239. synopsis = ("Trial can attempt to run test cases and their methods in "
  240. "a few different orders. You can select any of the "
  241. "following options using --order=<foo>.\n")
  242. print(synopsis)
  243. for name, (description, _) in sorted(_runOrders.items()):
  244. print(' ', name, '\t', description)
  245. sys.exit(0)
  246. def opt_help_reporters(self):
  247. synopsis = ("Trial's output can be customized using plugins called "
  248. "Reporters. You can\nselect any of the following "
  249. "reporters using --reporter=<foo>\n")
  250. print(synopsis)
  251. for p in plugin.getPlugins(itrial.IReporter):
  252. print(' ', p.longOpt, '\t', p.description)
  253. sys.exit(0)
  254. def opt_disablegc(self):
  255. """
  256. Disable the garbage collector
  257. """
  258. self["disablegc"] = True
  259. gc.disable()
  260. def opt_tbformat(self, opt):
  261. """
  262. Specify the format to display tracebacks with. Valid formats are
  263. 'plain', 'emacs', and 'cgitb' which uses the nicely verbose stdlib
  264. cgitb.text function
  265. """
  266. try:
  267. self['tbformat'] = TBFORMAT_MAP[opt]
  268. except KeyError:
  269. raise usage.UsageError(
  270. "tbformat must be 'plain', 'emacs', or 'cgitb'.")
  271. def opt_recursionlimit(self, arg):
  272. """
  273. see sys.setrecursionlimit()
  274. """
  275. try:
  276. sys.setrecursionlimit(int(arg))
  277. except (TypeError, ValueError):
  278. raise usage.UsageError(
  279. "argument to recursionlimit must be an integer")
  280. else:
  281. self["recursionlimit"] = int(arg)
  282. def opt_random(self, option):
  283. try:
  284. self['random'] = long(option)
  285. except ValueError:
  286. raise usage.UsageError(
  287. "Argument to --random must be a positive integer")
  288. else:
  289. if self['random'] < 0:
  290. raise usage.UsageError(
  291. "Argument to --random must be a positive integer")
  292. elif self['random'] == 0:
  293. self['random'] = long(time.time() * 100)
  294. def opt_without_module(self, option):
  295. """
  296. Fake the lack of the specified modules, separated with commas.
  297. """
  298. self["without-module"] = option
  299. for module in option.split(","):
  300. if module in sys.modules:
  301. warnings.warn("Module '%s' already imported, "
  302. "disabling anyway." % (module,),
  303. category=RuntimeWarning)
  304. sys.modules[module] = None
  305. def parseArgs(self, *args):
  306. self['tests'].extend(args)
  307. def _loadReporterByName(self, name):
  308. for p in plugin.getPlugins(itrial.IReporter):
  309. qual = "%s.%s" % (p.module, p.klass)
  310. if p.longOpt == name:
  311. return reflect.namedAny(qual)
  312. raise usage.UsageError("Only pass names of Reporter plugins to "
  313. "--reporter. See --help-reporters for "
  314. "more info.")
  315. def postOptions(self):
  316. # Only load reporters now, as opposed to any earlier, to avoid letting
  317. # application-defined plugins muck up reactor selecting by importing
  318. # t.i.reactor and causing the default to be installed.
  319. self['reporter'] = self._loadReporterByName(self['reporter'])
  320. if 'tbformat' not in self:
  321. self['tbformat'] = 'default'
  322. if self['order'] is not None and self['random'] is not None:
  323. raise usage.UsageError(
  324. "You can't specify --random when using --order")
  325. class Options(_BasicOptions, usage.Options, app.ReactorSelectionMixin):
  326. """
  327. Options to the trial command line tool.
  328. @ivar _workerFlags: List of flags which are accepted by trial distributed
  329. workers. This is used by C{_getWorkerArguments} to build the command
  330. line arguments.
  331. @type _workerFlags: C{list}
  332. @ivar _workerParameters: List of parameter which are accepted by trial
  333. distributed workers. This is used by C{_getWorkerArguments} to build
  334. the command line arguments.
  335. @type _workerParameters: C{list}
  336. """
  337. optFlags = [
  338. ["debug", "b", "Run tests in a debugger. If that debugger is "
  339. "pdb, will load '.pdbrc' from current directory if it exists."
  340. ],
  341. ["debug-stacktraces", "B", "Report Deferred creation and "
  342. "callback stack traces"],
  343. ["nopm", None, "don't automatically jump into debugger for "
  344. "postmorteming of exceptions"],
  345. ["dry-run", 'n', "do everything but run the tests"],
  346. ["profile", None, "Run tests under the Python profiler"],
  347. ["until-failure", "u", "Repeat test until it fails"],
  348. ]
  349. optParameters = [
  350. ["debugger", None, "pdb", "the fully qualified name of a debugger to "
  351. "use if --debug is passed"],
  352. ["logfile", "l", "test.log", "log file name"],
  353. ["jobs", "j", None, "Number of local workers to run"]
  354. ]
  355. compData = usage.Completions(
  356. optActions = {
  357. "tbformat": usage.CompleteList(["plain", "emacs", "cgitb"]),
  358. "reporter": _reporterAction,
  359. },
  360. )
  361. _workerFlags = ["disablegc", "force-gc", "coverage"]
  362. _workerParameters = ["recursionlimit", "reactor", "without-module"]
  363. fallbackReporter = reporter.TreeReporter
  364. extra = None
  365. tracer = None
  366. def opt_jobs(self, number):
  367. """
  368. Number of local workers to run, a strictly positive integer.
  369. """
  370. try:
  371. number = int(number)
  372. except ValueError:
  373. raise usage.UsageError(
  374. "Expecting integer argument to jobs, got '%s'" % number)
  375. if number <= 0:
  376. raise usage.UsageError(
  377. "Argument to jobs must be a strictly positive integer")
  378. self["jobs"] = number
  379. def _getWorkerArguments(self):
  380. """
  381. Return a list of options to pass to distributed workers.
  382. """
  383. args = []
  384. for option in self._workerFlags:
  385. if self.get(option) is not None:
  386. if self[option]:
  387. args.append("--%s" % (option,))
  388. for option in self._workerParameters:
  389. if self.get(option) is not None:
  390. args.extend(["--%s" % (option,), str(self[option])])
  391. return args
  392. def postOptions(self):
  393. _BasicOptions.postOptions(self)
  394. if self['jobs']:
  395. conflicts = ['debug', 'profile', 'debug-stacktraces', 'exitfirst']
  396. for option in conflicts:
  397. if self[option]:
  398. raise usage.UsageError(
  399. "You can't specify --%s when using --jobs" % option)
  400. if self['nopm']:
  401. if not self['debug']:
  402. raise usage.UsageError("You must specify --debug when using "
  403. "--nopm ")
  404. failure.DO_POST_MORTEM = False
  405. def _initialDebugSetup(config):
  406. # do this part of debug setup first for easy debugging of import failures
  407. if config['debug']:
  408. failure.startDebugMode()
  409. if config['debug'] or config['debug-stacktraces']:
  410. defer.setDebugging(True)
  411. def _getSuite(config):
  412. loader = _getLoader(config)
  413. recurse = not config['no-recurse']
  414. return loader.loadByNames(config['tests'], recurse=recurse)
  415. def _getLoader(config):
  416. loader = runner.TestLoader()
  417. if config['random']:
  418. randomer = random.Random()
  419. randomer.seed(config['random'])
  420. loader.sorter = lambda x : randomer.random()
  421. print('Running tests shuffled with seed %d\n' % config['random'])
  422. elif config['order']:
  423. _, sorter = _runOrders[config['order']]
  424. loader.sorter = sorter
  425. if not config['until-failure']:
  426. loader.suiteFactory = runner.DestructiveTestSuite
  427. return loader
  428. def _wrappedPdb():
  429. """
  430. Wrap an instance of C{pdb.Pdb} with readline support and load any .rcs.
  431. """
  432. dbg = pdb.Pdb()
  433. try:
  434. namedModule('readline')
  435. except ImportError:
  436. print("readline module not available")
  437. for path in ('.pdbrc', 'pdbrc'):
  438. if os.path.exists(path):
  439. try:
  440. rcFile = open(path, 'r')
  441. except IOError:
  442. pass
  443. else:
  444. with rcFile:
  445. dbg.rcLines.extend(rcFile.readlines())
  446. return dbg
  447. class _DebuggerNotFound(Exception):
  448. """
  449. A debugger import failed.
  450. Used to allow translating these errors into usage error messages.
  451. """
  452. def _makeRunner(config):
  453. """
  454. Return a trial runner class set up with the parameters extracted from
  455. C{config}.
  456. @return: A trial runner instance.
  457. @rtype: L{runner.TrialRunner} or C{DistTrialRunner} depending on the
  458. configuration.
  459. """
  460. cls = runner.TrialRunner
  461. args = {'reporterFactory': config['reporter'],
  462. 'tracebackFormat': config['tbformat'],
  463. 'realTimeErrors': config['rterrors'],
  464. 'uncleanWarnings': config['unclean-warnings'],
  465. 'logfile': config['logfile'],
  466. 'workingDirectory': config['temp-directory']}
  467. if config['dry-run']:
  468. args['mode'] = runner.TrialRunner.DRY_RUN
  469. elif config['jobs']:
  470. from twisted.trial._dist.disttrial import DistTrialRunner
  471. cls = DistTrialRunner
  472. args['workerNumber'] = config['jobs']
  473. args['workerArguments'] = config._getWorkerArguments()
  474. else:
  475. if config['debug']:
  476. args['mode'] = runner.TrialRunner.DEBUG
  477. debugger = config['debugger']
  478. if debugger != 'pdb':
  479. try:
  480. args['debugger'] = reflect.namedAny(debugger)
  481. except reflect.ModuleNotFound:
  482. raise _DebuggerNotFound(
  483. '%r debugger could not be found.' % (debugger,))
  484. else:
  485. args['debugger'] = _wrappedPdb()
  486. args['exitFirst'] = config['exitfirst']
  487. args['profile'] = config['profile']
  488. args['forceGarbageCollection'] = config['force-gc']
  489. return cls(**args)
  490. def run():
  491. if len(sys.argv) == 1:
  492. sys.argv.append("--help")
  493. config = Options()
  494. try:
  495. config.parseOptions()
  496. except usage.error as ue:
  497. raise SystemExit("%s: %s" % (sys.argv[0], ue))
  498. _initialDebugSetup(config)
  499. try:
  500. trialRunner = _makeRunner(config)
  501. except _DebuggerNotFound as e:
  502. raise SystemExit('%s: %s' % (sys.argv[0], str(e)))
  503. suite = _getSuite(config)
  504. if config['until-failure']:
  505. test_result = trialRunner.runUntilFailure(suite)
  506. else:
  507. test_result = trialRunner.run(suite)
  508. if config.tracer:
  509. sys.settrace(None)
  510. results = config.tracer.results()
  511. results.write_results(show_missing=1, summary=False,
  512. coverdir=config.coverdir().path)
  513. sys.exit(not test_result.wasSuccessful())