You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

262 lines
8.1KB

  1. """Version info, help messages, tracing configuration."""
  2. import os
  3. import sys
  4. from argparse import Action
  5. from typing import List
  6. from typing import Optional
  7. from typing import Union
  8. import py
  9. import pytest
  10. from _pytest.config import Config
  11. from _pytest.config import ExitCode
  12. from _pytest.config import PrintHelp
  13. from _pytest.config.argparsing import Parser
  14. class HelpAction(Action):
  15. """An argparse Action that will raise an exception in order to skip the
  16. rest of the argument parsing when --help is passed.
  17. This prevents argparse from quitting due to missing required arguments
  18. when any are defined, for example by ``pytest_addoption``.
  19. This is similar to the way that the builtin argparse --help option is
  20. implemented by raising SystemExit.
  21. """
  22. def __init__(self, option_strings, dest=None, default=False, help=None):
  23. super().__init__(
  24. option_strings=option_strings,
  25. dest=dest,
  26. const=True,
  27. default=default,
  28. nargs=0,
  29. help=help,
  30. )
  31. def __call__(self, parser, namespace, values, option_string=None):
  32. setattr(namespace, self.dest, self.const)
  33. # We should only skip the rest of the parsing after preparse is done.
  34. if getattr(parser._parser, "after_preparse", False):
  35. raise PrintHelp
  36. def pytest_addoption(parser: Parser) -> None:
  37. group = parser.getgroup("debugconfig")
  38. group.addoption(
  39. "--version",
  40. "-V",
  41. action="count",
  42. default=0,
  43. dest="version",
  44. help="display pytest version and information about plugins."
  45. "When given twice, also display information about plugins.",
  46. )
  47. group._addoption(
  48. "-h",
  49. "--help",
  50. action=HelpAction,
  51. dest="help",
  52. help="show help message and configuration info",
  53. )
  54. group._addoption(
  55. "-p",
  56. action="append",
  57. dest="plugins",
  58. default=[],
  59. metavar="name",
  60. help="early-load given plugin module name or entry point (multi-allowed).\n"
  61. "To avoid loading of plugins, use the `no:` prefix, e.g. "
  62. "`no:doctest`.",
  63. )
  64. group.addoption(
  65. "--traceconfig",
  66. "--trace-config",
  67. action="store_true",
  68. default=False,
  69. help="trace considerations of conftest.py files.",
  70. )
  71. group.addoption(
  72. "--debug",
  73. action="store_true",
  74. dest="debug",
  75. default=False,
  76. help="store internal tracing debug information in 'pytestdebug.log'.",
  77. )
  78. group._addoption(
  79. "-o",
  80. "--override-ini",
  81. dest="override_ini",
  82. action="append",
  83. help='override ini option with "option=value" style, e.g. `-o xfail_strict=True -o cache_dir=cache`.',
  84. )
  85. @pytest.hookimpl(hookwrapper=True)
  86. def pytest_cmdline_parse():
  87. outcome = yield
  88. config: Config = outcome.get_result()
  89. if config.option.debug:
  90. path = os.path.abspath("pytestdebug.log")
  91. debugfile = open(path, "w")
  92. debugfile.write(
  93. "versions pytest-%s, py-%s, "
  94. "python-%s\ncwd=%s\nargs=%s\n\n"
  95. % (
  96. pytest.__version__,
  97. py.__version__,
  98. ".".join(map(str, sys.version_info)),
  99. os.getcwd(),
  100. config.invocation_params.args,
  101. )
  102. )
  103. config.trace.root.setwriter(debugfile.write)
  104. undo_tracing = config.pluginmanager.enable_tracing()
  105. sys.stderr.write("writing pytestdebug information to %s\n" % path)
  106. def unset_tracing() -> None:
  107. debugfile.close()
  108. sys.stderr.write("wrote pytestdebug information to %s\n" % debugfile.name)
  109. config.trace.root.setwriter(None)
  110. undo_tracing()
  111. config.add_cleanup(unset_tracing)
  112. def showversion(config: Config) -> None:
  113. if config.option.version > 1:
  114. sys.stderr.write(
  115. "This is pytest version {}, imported from {}\n".format(
  116. pytest.__version__, pytest.__file__
  117. )
  118. )
  119. plugininfo = getpluginversioninfo(config)
  120. if plugininfo:
  121. for line in plugininfo:
  122. sys.stderr.write(line + "\n")
  123. else:
  124. sys.stderr.write(f"pytest {pytest.__version__}\n")
  125. def pytest_cmdline_main(config: Config) -> Optional[Union[int, ExitCode]]:
  126. if config.option.version > 0:
  127. showversion(config)
  128. return 0
  129. elif config.option.help:
  130. config._do_configure()
  131. showhelp(config)
  132. config._ensure_unconfigure()
  133. return 0
  134. return None
  135. def showhelp(config: Config) -> None:
  136. import textwrap
  137. reporter = config.pluginmanager.get_plugin("terminalreporter")
  138. tw = reporter._tw
  139. tw.write(config._parser.optparser.format_help())
  140. tw.line()
  141. tw.line(
  142. "[pytest] ini-options in the first pytest.ini|tox.ini|setup.cfg file found:"
  143. )
  144. tw.line()
  145. columns = tw.fullwidth # costly call
  146. indent_len = 24 # based on argparse's max_help_position=24
  147. indent = " " * indent_len
  148. for name in config._parser._ininames:
  149. help, type, default = config._parser._inidict[name]
  150. if type is None:
  151. type = "string"
  152. if help is None:
  153. raise TypeError(f"help argument cannot be None for {name}")
  154. spec = f"{name} ({type}):"
  155. tw.write(" %s" % spec)
  156. spec_len = len(spec)
  157. if spec_len > (indent_len - 3):
  158. # Display help starting at a new line.
  159. tw.line()
  160. helplines = textwrap.wrap(
  161. help,
  162. columns,
  163. initial_indent=indent,
  164. subsequent_indent=indent,
  165. break_on_hyphens=False,
  166. )
  167. for line in helplines:
  168. tw.line(line)
  169. else:
  170. # Display help starting after the spec, following lines indented.
  171. tw.write(" " * (indent_len - spec_len - 2))
  172. wrapped = textwrap.wrap(help, columns - indent_len, break_on_hyphens=False)
  173. if wrapped:
  174. tw.line(wrapped[0])
  175. for line in wrapped[1:]:
  176. tw.line(indent + line)
  177. tw.line()
  178. tw.line("environment variables:")
  179. vars = [
  180. ("PYTEST_ADDOPTS", "extra command line options"),
  181. ("PYTEST_PLUGINS", "comma-separated plugins to load during startup"),
  182. ("PYTEST_DISABLE_PLUGIN_AUTOLOAD", "set to disable plugin auto-loading"),
  183. ("PYTEST_DEBUG", "set to enable debug tracing of pytest's internals"),
  184. ]
  185. for name, help in vars:
  186. tw.line(f" {name:<24} {help}")
  187. tw.line()
  188. tw.line()
  189. tw.line("to see available markers type: pytest --markers")
  190. tw.line("to see available fixtures type: pytest --fixtures")
  191. tw.line(
  192. "(shown according to specified file_or_dir or current dir "
  193. "if not specified; fixtures with leading '_' are only shown "
  194. "with the '-v' option"
  195. )
  196. for warningreport in reporter.stats.get("warnings", []):
  197. tw.line("warning : " + warningreport.message, red=True)
  198. return
  199. conftest_options = [("pytest_plugins", "list of plugin names to load")]
  200. def getpluginversioninfo(config: Config) -> List[str]:
  201. lines = []
  202. plugininfo = config.pluginmanager.list_plugin_distinfo()
  203. if plugininfo:
  204. lines.append("setuptools registered plugins:")
  205. for plugin, dist in plugininfo:
  206. loc = getattr(plugin, "__file__", repr(plugin))
  207. content = f"{dist.project_name}-{dist.version} at {loc}"
  208. lines.append(" " + content)
  209. return lines
  210. def pytest_report_header(config: Config) -> List[str]:
  211. lines = []
  212. if config.option.debug or config.option.traceconfig:
  213. lines.append(f"using: pytest-{pytest.__version__} pylib-{py.__version__}")
  214. verinfo = getpluginversioninfo(config)
  215. if verinfo:
  216. lines.extend(verinfo)
  217. if config.option.traceconfig:
  218. lines.append("active plugins:")
  219. items = config.pluginmanager.list_name_plugin()
  220. for name, plugin in items:
  221. if hasattr(plugin, "__file__"):
  222. r = plugin.__file__
  223. else:
  224. r = repr(plugin)
  225. lines.append(f" {name:<20}: {r}")
  226. return lines