trial.py 21 KB

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