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