Debian Codegraph @

testing/web-platform/tests/tools/third_party/pytest/src/_pytest/helpconfig.py

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