trial.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  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. synopsis = """%s [options] [[file|package|module|TestCase|testmethod]...]
  136. """ % (os.path.basename(sys.argv[0]),)
  137. longdesc = ("trial loads and executes a suite of unit tests, obtained "
  138. "from modules, packages and files listed on the command line.")
  139. optFlags = [["help", "h"],
  140. ["no-recurse", "N", "Don't recurse into packages"],
  141. ['help-orders', None, "Help on available test running orders"],
  142. ['help-reporters', None,
  143. "Help on available output plugins (reporters)"],
  144. ["rterrors", "e", "realtime errors, print out tracebacks as "
  145. "soon as they occur"],
  146. ["unclean-warnings", None,
  147. "Turn dirty reactor errors into warnings"],
  148. ["force-gc", None, "Have Trial run gc.collect() before and "
  149. "after each test case."],
  150. ["exitfirst", "x",
  151. "Exit after the first non-successful result (cannot be "
  152. "specified along with --jobs)."],
  153. ]
  154. optParameters = [
  155. ["order", "o", None,
  156. "Specify what order to run test cases and methods. "
  157. "See --help-orders for more info.", _checkKnownRunOrder],
  158. ["random", "z", None,
  159. "Run tests in random order using the specified seed"],
  160. ['temp-directory', None, '_trial_temp',
  161. 'Path to use as working directory for tests.'],
  162. ['reporter', None, 'verbose',
  163. 'The reporter to use for this test run. See --help-reporters for '
  164. 'more info.']]
  165. compData = usage.Completions(
  166. optActions={"order": usage.CompleteList(_runOrders),
  167. "reporter": _reporterAction,
  168. "logfile": usage.CompleteFiles(descr="log file name"),
  169. "random": usage.Completer(descr="random seed")},
  170. extraActions=[usage.CompleteFiles(
  171. "*.py", descr="file | module | package | TestCase | testMethod",
  172. repeat=True)],
  173. )
  174. fallbackReporter = reporter.TreeReporter
  175. tracer = None
  176. def __init__(self):
  177. self['tests'] = []
  178. usage.Options.__init__(self)
  179. def coverdir(self):
  180. """
  181. Return a L{FilePath} representing the directory into which coverage
  182. results should be written.
  183. """
  184. coverdir = 'coverage'
  185. result = FilePath(self['temp-directory']).child(coverdir)
  186. print("Setting coverage directory to %s." % (result.path,))
  187. return result
  188. # TODO: Some of the opt_* methods on this class have docstrings and some do
  189. # not. This is mostly because usage.Options's currently will replace
  190. # any intended output in optFlags and optParameters with the
  191. # docstring. See #6427. When that is fixed, all methods should be
  192. # given docstrings (and it should be verified that those with
  193. # docstrings already have content suitable for printing as usage
  194. # information).
  195. def opt_coverage(self):
  196. """
  197. Generate coverage information in the coverage file in the
  198. directory specified by the temp-directory option.
  199. """
  200. import trace
  201. self.tracer = trace.Trace(count=1, trace=0)
  202. sys.settrace(self.tracer.globaltrace)
  203. self['coverage'] = True
  204. def opt_testmodule(self, filename):
  205. """
  206. Filename to grep for test cases (-*- test-case-name).
  207. """
  208. # If the filename passed to this parameter looks like a test module
  209. # we just add that to the test suite.
  210. #
  211. # If not, we inspect it for an Emacs buffer local variable called
  212. # 'test-case-name'. If that variable is declared, we try to add its
  213. # value to the test suite as a module.
  214. #
  215. # This parameter allows automated processes (like Buildbot) to pass
  216. # a list of files to Trial with the general expectation of "these files,
  217. # whatever they are, will get tested"
  218. if not os.path.isfile(filename):
  219. sys.stderr.write("File %r doesn't exist\n" % (filename,))
  220. return
  221. filename = os.path.abspath(filename)
  222. if isTestFile(filename):
  223. self['tests'].append(filename)
  224. else:
  225. self['tests'].extend(getTestModules(filename))
  226. def opt_spew(self):
  227. """
  228. Print an insanely verbose log of everything that happens. Useful
  229. when debugging freezes or locks in complex code.
  230. """
  231. from twisted.python.util import spewer
  232. sys.settrace(spewer)
  233. def opt_help_orders(self):
  234. synopsis = ("Trial can attempt to run test cases and their methods in "
  235. "a few different orders. You can select any of the "
  236. "following options using --order=<foo>.\n")
  237. print(synopsis)
  238. for name, (description, _) in sorted(_runOrders.items()):
  239. print(' ', name, '\t', description)
  240. sys.exit(0)
  241. def opt_help_reporters(self):
  242. synopsis = ("Trial's output can be customized using plugins called "
  243. "Reporters. You can\nselect any of the following "
  244. "reporters using --reporter=<foo>\n")
  245. print(synopsis)
  246. for p in plugin.getPlugins(itrial.IReporter):
  247. print(' ', p.longOpt, '\t', p.description)
  248. sys.exit(0)
  249. def opt_disablegc(self):
  250. """
  251. Disable the garbage collector
  252. """
  253. self["disablegc"] = True
  254. gc.disable()
  255. def opt_tbformat(self, opt):
  256. """
  257. Specify the format to display tracebacks with. Valid formats are
  258. 'plain', 'emacs', and 'cgitb' which uses the nicely verbose stdlib
  259. cgitb.text function
  260. """
  261. try:
  262. self['tbformat'] = TBFORMAT_MAP[opt]
  263. except KeyError:
  264. raise usage.UsageError(
  265. "tbformat must be 'plain', 'emacs', or 'cgitb'.")
  266. def opt_recursionlimit(self, arg):
  267. """
  268. see sys.setrecursionlimit()
  269. """
  270. try:
  271. sys.setrecursionlimit(int(arg))
  272. except (TypeError, ValueError):
  273. raise usage.UsageError(
  274. "argument to recursionlimit must be an integer")
  275. else:
  276. self["recursionlimit"] = int(arg)
  277. def opt_random(self, option):
  278. try:
  279. self['random'] = long(option)
  280. except ValueError:
  281. raise usage.UsageError(
  282. "Argument to --random must be a positive integer")
  283. else:
  284. if self['random'] < 0:
  285. raise usage.UsageError(
  286. "Argument to --random must be a positive integer")
  287. elif self['random'] == 0:
  288. self['random'] = long(time.time() * 100)
  289. def opt_without_module(self, option):
  290. """
  291. Fake the lack of the specified modules, separated with commas.
  292. """
  293. self["without-module"] = option
  294. for module in option.split(","):
  295. if module in sys.modules:
  296. warnings.warn("Module '%s' already imported, "
  297. "disabling anyway." % (module,),
  298. category=RuntimeWarning)
  299. sys.modules[module] = None
  300. def parseArgs(self, *args):
  301. self['tests'].extend(args)
  302. def _loadReporterByName(self, name):
  303. for p in plugin.getPlugins(itrial.IReporter):
  304. qual = "%s.%s" % (p.module, p.klass)
  305. if p.longOpt == name:
  306. return reflect.namedAny(qual)
  307. raise usage.UsageError("Only pass names of Reporter plugins to "
  308. "--reporter. See --help-reporters for "
  309. "more info.")
  310. def postOptions(self):
  311. # Only load reporters now, as opposed to any earlier, to avoid letting
  312. # application-defined plugins muck up reactor selecting by importing
  313. # t.i.reactor and causing the default to be installed.
  314. self['reporter'] = self._loadReporterByName(self['reporter'])
  315. if 'tbformat' not in self:
  316. self['tbformat'] = 'default'
  317. if self['order'] is not None and self['random'] is not None:
  318. raise usage.UsageError(
  319. "You can't specify --random when using --order")
  320. class Options(_BasicOptions, usage.Options, app.ReactorSelectionMixin):
  321. """
  322. Options to the trial command line tool.
  323. @ivar _workerFlags: List of flags which are accepted by trial distributed
  324. workers. This is used by C{_getWorkerArguments} to build the command
  325. line arguments.
  326. @type _workerFlags: C{list}
  327. @ivar _workerParameters: List of parameter which are accepted by trial
  328. distributed workers. This is used by C{_getWorkerArguments} to build
  329. the command line arguments.
  330. @type _workerParameters: C{list}
  331. """
  332. optFlags = [
  333. ["debug", "b", "Run tests in a debugger. If that debugger is "
  334. "pdb, will load '.pdbrc' from current directory if it exists."
  335. ],
  336. ["debug-stacktraces", "B", "Report Deferred creation and "
  337. "callback stack traces"],
  338. ["nopm", None, "don't automatically jump into debugger for "
  339. "postmorteming of exceptions"],
  340. ["dry-run", 'n', "do everything but run the tests"],
  341. ["profile", None, "Run tests under the Python profiler"],
  342. ["until-failure", "u", "Repeat test until it fails"],
  343. ]
  344. optParameters = [
  345. ["debugger", None, "pdb", "the fully qualified name of a debugger to "
  346. "use if --debug is passed"],
  347. ["logfile", "l", "test.log", "log file name"],
  348. ["jobs", "j", None, "Number of local workers to run"]
  349. ]
  350. compData = usage.Completions(
  351. optActions = {
  352. "tbformat": usage.CompleteList(["plain", "emacs", "cgitb"]),
  353. "reporter": _reporterAction,
  354. },
  355. )
  356. _workerFlags = ["disablegc", "force-gc", "coverage"]
  357. _workerParameters = ["recursionlimit", "reactor", "without-module"]
  358. fallbackReporter = reporter.TreeReporter
  359. extra = None
  360. tracer = None
  361. def opt_jobs(self, number):
  362. """
  363. Number of local workers to run, a strictly positive integer.
  364. """
  365. try:
  366. number = int(number)
  367. except ValueError:
  368. raise usage.UsageError(
  369. "Expecting integer argument to jobs, got '%s'" % number)
  370. if number <= 0:
  371. raise usage.UsageError(
  372. "Argument to jobs must be a strictly positive integer")
  373. self["jobs"] = number
  374. def _getWorkerArguments(self):
  375. """
  376. Return a list of options to pass to distributed workers.
  377. """
  378. args = []
  379. for option in self._workerFlags:
  380. if self.get(option) is not None:
  381. if self[option]:
  382. args.append("--%s" % (option,))
  383. for option in self._workerParameters:
  384. if self.get(option) is not None:
  385. args.extend(["--%s" % (option,), str(self[option])])
  386. return args
  387. def postOptions(self):
  388. _BasicOptions.postOptions(self)
  389. if self['jobs']:
  390. conflicts = ['debug', 'profile', 'debug-stacktraces', 'exitfirst']
  391. for option in conflicts:
  392. if self[option]:
  393. raise usage.UsageError(
  394. "You can't specify --%s when using --jobs" % option)
  395. if self['nopm']:
  396. if not self['debug']:
  397. raise usage.UsageError("You must specify --debug when using "
  398. "--nopm ")
  399. failure.DO_POST_MORTEM = False
  400. def _initialDebugSetup(config):
  401. # do this part of debug setup first for easy debugging of import failures
  402. if config['debug']:
  403. failure.startDebugMode()
  404. if config['debug'] or config['debug-stacktraces']:
  405. defer.setDebugging(True)
  406. def _getSuite(config):
  407. loader = _getLoader(config)
  408. recurse = not config['no-recurse']
  409. return loader.loadByNames(config['tests'], recurse=recurse)
  410. def _getLoader(config):
  411. loader = runner.TestLoader()
  412. if config['random']:
  413. randomer = random.Random()
  414. randomer.seed(config['random'])
  415. loader.sorter = lambda x : randomer.random()
  416. print('Running tests shuffled with seed %d\n' % config['random'])
  417. elif config['order']:
  418. _, sorter = _runOrders[config['order']]
  419. loader.sorter = sorter
  420. if not config['until-failure']:
  421. loader.suiteFactory = runner.DestructiveTestSuite
  422. return loader
  423. def _wrappedPdb():
  424. """
  425. Wrap an instance of C{pdb.Pdb} with readline support and load any .rcs.
  426. """
  427. dbg = pdb.Pdb()
  428. try:
  429. namedModule('readline')
  430. except ImportError:
  431. print("readline module not available")
  432. for path in ('.pdbrc', 'pdbrc'):
  433. if os.path.exists(path):
  434. try:
  435. rcFile = open(path, 'r')
  436. except IOError:
  437. pass
  438. else:
  439. with rcFile:
  440. dbg.rcLines.extend(rcFile.readlines())
  441. return dbg
  442. class _DebuggerNotFound(Exception):
  443. """
  444. A debugger import failed.
  445. Used to allow translating these errors into usage error messages.
  446. """
  447. def _makeRunner(config):
  448. """
  449. Return a trial runner class set up with the parameters extracted from
  450. C{config}.
  451. @return: A trial runner instance.
  452. @rtype: L{runner.TrialRunner} or C{DistTrialRunner} depending on the
  453. configuration.
  454. """
  455. cls = runner.TrialRunner
  456. args = {'reporterFactory': config['reporter'],
  457. 'tracebackFormat': config['tbformat'],
  458. 'realTimeErrors': config['rterrors'],
  459. 'uncleanWarnings': config['unclean-warnings'],
  460. 'logfile': config['logfile'],
  461. 'workingDirectory': config['temp-directory']}
  462. if config['dry-run']:
  463. args['mode'] = runner.TrialRunner.DRY_RUN
  464. elif config['jobs']:
  465. from twisted.trial._dist.disttrial import DistTrialRunner
  466. cls = DistTrialRunner
  467. args['workerNumber'] = config['jobs']
  468. args['workerArguments'] = config._getWorkerArguments()
  469. else:
  470. if config['debug']:
  471. args['mode'] = runner.TrialRunner.DEBUG
  472. debugger = config['debugger']
  473. if debugger != 'pdb':
  474. try:
  475. args['debugger'] = reflect.namedAny(debugger)
  476. except reflect.ModuleNotFound:
  477. raise _DebuggerNotFound(
  478. '%r debugger could not be found.' % (debugger,))
  479. else:
  480. args['debugger'] = _wrappedPdb()
  481. args['exitFirst'] = config['exitfirst']
  482. args['profile'] = config['profile']
  483. args['forceGarbageCollection'] = config['force-gc']
  484. return cls(**args)
  485. def run():
  486. if len(sys.argv) == 1:
  487. sys.argv.append("--help")
  488. config = Options()
  489. try:
  490. config.parseOptions()
  491. except usage.error as ue:
  492. raise SystemExit("%s: %s" % (sys.argv[0], ue))
  493. _initialDebugSetup(config)
  494. try:
  495. trialRunner = _makeRunner(config)
  496. except _DebuggerNotFound as e:
  497. raise SystemExit('%s: %s' % (sys.argv[0], str(e)))
  498. suite = _getSuite(config)
  499. if config['until-failure']:
  500. test_result = trialRunner.runUntilFailure(suite)
  501. else:
  502. test_result = trialRunner.run(suite)
  503. if config.tracer:
  504. sys.settrace(None)
  505. results = config.tracer.results()
  506. results.write_results(show_missing=1, summary=False,
  507. coverdir=config.coverdir().path)
  508. sys.exit(not test_result.wasSuccessful())