helpconfig.py 8.3 KB

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