helpconfig.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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 pytest
  9. from _pytest.config import Config
  10. from _pytest.config import ExitCode
  11. from _pytest.config import PrintHelp
  12. from _pytest.config.argparsing import Parser
  13. from _pytest.terminal import TerminalReporter
  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). "
  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",
  74. nargs="?",
  75. const="pytestdebug.log",
  76. dest="debug",
  77. metavar="DEBUG_FILE_NAME",
  78. help="Store internal tracing debug information in this log file. "
  79. "This file is opened with 'w' and truncated as a result, care advised. "
  80. "Default: pytestdebug.log.",
  81. )
  82. group._addoption(
  83. "-o",
  84. "--override-ini",
  85. dest="override_ini",
  86. action="append",
  87. help='Override ini option with "option=value" style, '
  88. "e.g. `-o xfail_strict=True -o cache_dir=cache`.",
  89. )
  90. @pytest.hookimpl(hookwrapper=True)
  91. def pytest_cmdline_parse():
  92. outcome = yield
  93. config: Config = outcome.get_result()
  94. if config.option.debug:
  95. # --debug | --debug <file.log> was provided.
  96. path = config.option.debug
  97. debugfile = open(path, "w", encoding="utf-8")
  98. debugfile.write(
  99. "versions pytest-%s, "
  100. "python-%s\ncwd=%s\nargs=%s\n\n"
  101. % (
  102. pytest.__version__,
  103. ".".join(map(str, sys.version_info)),
  104. os.getcwd(),
  105. config.invocation_params.args,
  106. )
  107. )
  108. config.trace.root.setwriter(debugfile.write)
  109. undo_tracing = config.pluginmanager.enable_tracing()
  110. sys.stderr.write("writing pytest debug information to %s\n" % path)
  111. def unset_tracing() -> None:
  112. debugfile.close()
  113. sys.stderr.write("wrote pytest debug information to %s\n" % debugfile.name)
  114. config.trace.root.setwriter(None)
  115. undo_tracing()
  116. config.add_cleanup(unset_tracing)
  117. def showversion(config: Config) -> None:
  118. if config.option.version > 1:
  119. sys.stdout.write(
  120. "This is pytest version {}, imported from {}\n".format(
  121. pytest.__version__, pytest.__file__
  122. )
  123. )
  124. plugininfo = getpluginversioninfo(config)
  125. if plugininfo:
  126. for line in plugininfo:
  127. sys.stdout.write(line + "\n")
  128. else:
  129. sys.stdout.write(f"pytest {pytest.__version__}\n")
  130. def pytest_cmdline_main(config: Config) -> Optional[Union[int, ExitCode]]:
  131. if config.option.version > 0:
  132. showversion(config)
  133. return 0
  134. elif config.option.help:
  135. config._do_configure()
  136. showhelp(config)
  137. config._ensure_unconfigure()
  138. return 0
  139. return None
  140. def showhelp(config: Config) -> None:
  141. import textwrap
  142. reporter: Optional[TerminalReporter] = config.pluginmanager.get_plugin(
  143. "terminalreporter"
  144. )
  145. assert reporter is not None
  146. tw = reporter._tw
  147. tw.write(config._parser.optparser.format_help())
  148. tw.line()
  149. tw.line(
  150. "[pytest] ini-options in the first "
  151. "pytest.ini|tox.ini|setup.cfg|pyproject.toml file found:"
  152. )
  153. tw.line()
  154. columns = tw.fullwidth # costly call
  155. indent_len = 24 # based on argparse's max_help_position=24
  156. indent = " " * indent_len
  157. for name in config._parser._ininames:
  158. help, type, default = config._parser._inidict[name]
  159. if type is None:
  160. type = "string"
  161. if help is None:
  162. raise TypeError(f"help argument cannot be None for {name}")
  163. spec = f"{name} ({type}):"
  164. tw.write(" %s" % spec)
  165. spec_len = len(spec)
  166. if spec_len > (indent_len - 3):
  167. # Display help starting at a new line.
  168. tw.line()
  169. helplines = textwrap.wrap(
  170. help,
  171. columns,
  172. initial_indent=indent,
  173. subsequent_indent=indent,
  174. break_on_hyphens=False,
  175. )
  176. for line in helplines:
  177. tw.line(line)
  178. else:
  179. # Display help starting after the spec, following lines indented.
  180. tw.write(" " * (indent_len - spec_len - 2))
  181. wrapped = textwrap.wrap(help, columns - indent_len, break_on_hyphens=False)
  182. if wrapped:
  183. tw.line(wrapped[0])
  184. for line in wrapped[1:]:
  185. tw.line(indent + line)
  186. tw.line()
  187. tw.line("Environment variables:")
  188. vars = [
  189. ("PYTEST_ADDOPTS", "Extra command line options"),
  190. ("PYTEST_PLUGINS", "Comma-separated plugins to load during startup"),
  191. ("PYTEST_DISABLE_PLUGIN_AUTOLOAD", "Set to disable plugin auto-loading"),
  192. ("PYTEST_DEBUG", "Set to enable debug tracing of pytest's internals"),
  193. ]
  194. for name, help in vars:
  195. tw.line(f" {name:<24} {help}")
  196. tw.line()
  197. tw.line()
  198. tw.line("to see available markers type: pytest --markers")
  199. tw.line("to see available fixtures type: pytest --fixtures")
  200. tw.line(
  201. "(shown according to specified file_or_dir or current dir "
  202. "if not specified; fixtures with leading '_' are only shown "
  203. "with the '-v' option"
  204. )
  205. for warningreport in reporter.stats.get("warnings", []):
  206. tw.line("warning : " + warningreport.message, red=True)
  207. return
  208. conftest_options = [("pytest_plugins", "list of plugin names to load")]
  209. def getpluginversioninfo(config: Config) -> List[str]:
  210. lines = []
  211. plugininfo = config.pluginmanager.list_plugin_distinfo()
  212. if plugininfo:
  213. lines.append("setuptools registered plugins:")
  214. for plugin, dist in plugininfo:
  215. loc = getattr(plugin, "__file__", repr(plugin))
  216. content = f"{dist.project_name}-{dist.version} at {loc}"
  217. lines.append(" " + content)
  218. return lines
  219. def pytest_report_header(config: Config) -> List[str]:
  220. lines = []
  221. if config.option.debug or config.option.traceconfig:
  222. lines.append(f"using: pytest-{pytest.__version__}")
  223. verinfo = getpluginversioninfo(config)
  224. if verinfo:
  225. lines.extend(verinfo)
  226. if config.option.traceconfig:
  227. lines.append("active plugins:")
  228. items = config.pluginmanager.list_name_plugin()
  229. for name, plugin in items:
  230. if hasattr(plugin, "__file__"):
  231. r = plugin.__file__
  232. else:
  233. r = repr(plugin)
  234. lines.append(f" {name:<20}: {r}")
  235. return lines