| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from collections.abc import Iterable |
| 4 |
from collections.abc import Sequence |
| 5 |
from dataclasses import dataclass |
| 6 |
from dataclasses import KW_ONLY |
| 7 |
import os |
| 8 |
from pathlib import Path |
| 9 |
import sys |
| 10 |
from typing import Literal |
| 11 |
from typing import TypeAlias |
| 12 |
|
| 13 |
import iniconfig |
| 14 |
|
| 15 |
from .exceptions import UsageError |
| 16 |
from _pytest.outcomes import fail |
| 17 |
from _pytest.pathlib import absolutepath |
| 18 |
from _pytest.pathlib import commonpath |
| 19 |
from _pytest.pathlib import safe_exists |
| 20 |
|
| 21 |
|
| 22 |
@dataclass(frozen=True) |
| 23 |
class ConfigValue: |
| 24 |
"""Represents a configuration value with its origin and parsing mode. |
| 25 |
|
| 26 |
This allows tracking whether a value came from a configuration file |
| 27 |
or from a CLI override (--override-ini), which is important for |
| 28 |
determining precedence when dealing with ini option aliases. |
| 29 |
|
| 30 |
The mode tracks the parsing mode/data model used for the value: |
| 31 |
- "ini": from INI files or [tool.pytest.ini_options], where the only |
| 32 |
supported value types are `str` or `list[str]`. |
| 33 |
- "toml": from TOML files (not in INI mode), where native TOML types |
| 34 |
are preserved. |
| 35 |
""" |
| 36 |
|
| 37 |
value: object |
| 38 |
_: KW_ONLY |
| 39 |
origin: Literal["file", "override"] |
| 40 |
mode: Literal["ini", "toml"] |
| 41 |
|
| 42 |
|
| 43 |
ConfigDict: TypeAlias = dict[str, ConfigValue] |
| 44 |
|
| 45 |
|
| 46 |
def _parse_ini_config(path: Path) -> iniconfig.IniConfig: |
| 47 |
"""Parse the given generic '.ini' file using legacy IniConfig parser, returning |
| 48 |
the parsed object. |
| 49 |
|
| 50 |
Raise UsageError if the file cannot be parsed. |
| 51 |
""" |
| 52 |
try: |
| 53 |
return iniconfig.IniConfig(str(path)) |
| 54 |
except iniconfig.ParseError as exc: |
| 55 |
raise UsageError(str(exc)) from exc |
| 56 |
|
| 57 |
|
| 58 |
def load_config_dict_from_file( |
| 59 |
filepath: Path, |
| 60 |
) -> ConfigDict | None: |
| 61 |
"""Load pytest configuration from the given file path, if supported. |
| 62 |
|
| 63 |
Return None if the file does not contain valid pytest configuration. |
| 64 |
""" |
| 65 |
# Configuration from ini files are obtained from the [pytest] section, if present. |
| 66 |
if filepath.suffix == ".ini": |
| 67 |
iniconfig = _parse_ini_config(filepath) |
| 68 |
|
| 69 |
if "pytest" in iniconfig: |
| 70 |
return { |
| 71 |
k: ConfigValue(v, origin="file", mode="ini") |
| 72 |
for k, v in iniconfig["pytest"].items() |
| 73 |
} |
| 74 |
else: |
| 75 |
# "pytest.ini" files are always the source of configuration, even if empty. |
| 76 |
if filepath.name in {"pytest.ini", ".pytest.ini"}: |
| 77 |
return {} |
| 78 |
|
| 79 |
# '.cfg' files are considered if they contain a "[tool:pytest]" section. |
| 80 |
elif filepath.suffix == ".cfg": |
| 81 |
iniconfig = _parse_ini_config(filepath) |
| 82 |
|
| 83 |
if "tool:pytest" in iniconfig.sections: |
| 84 |
return { |
| 85 |
k: ConfigValue(v, origin="file", mode="ini") |
| 86 |
for k, v in iniconfig["tool:pytest"].items() |
| 87 |
} |
| 88 |
elif "pytest" in iniconfig.sections: |
| 89 |
# If a setup.cfg contains a "[pytest]" section, we raise a failure to indicate users that |
| 90 |
# plain "[pytest]" sections in setup.cfg files is no longer supported (#3086). |
| 91 |
fail(CFG_PYTEST_SECTION.format(filename="setup.cfg"), pytrace=False) |
| 92 |
|
| 93 |
# '.toml' files are considered if they contain a [tool.pytest] table (toml mode) |
| 94 |
# or [tool.pytest.ini_options] table (ini mode) for pyproject.toml, |
| 95 |
# or [pytest] table (toml mode) for pytest.toml/.pytest.toml. |
| 96 |
elif filepath.suffix == ".toml": |
| 97 |
if sys.version_info >= (3, 11): |
| 98 |
import tomllib |
| 99 |
else: |
| 100 |
import tomli as tomllib |
| 101 |
|
| 102 |
toml_text = filepath.read_text(encoding="utf-8") |
| 103 |
try: |
| 104 |
config = tomllib.loads(toml_text) |
| 105 |
except tomllib.TOMLDecodeError as exc: |
| 106 |
raise UsageError(f"{filepath}: {exc}") from exc |
| 107 |
|
| 108 |
# pytest.toml and .pytest.toml use [pytest] table directly. |
| 109 |
if filepath.name in ("pytest.toml", ".pytest.toml"): |
| 110 |
pytest_config = config.get("pytest", {}) |
| 111 |
if pytest_config: |
| 112 |
# TOML mode - preserve native TOML types. |
| 113 |
return { |
| 114 |
k: ConfigValue(v, origin="file", mode="toml") |
| 115 |
for k, v in pytest_config.items() |
| 116 |
} |
| 117 |
# "pytest.toml" files are always the source of configuration, even if empty. |
| 118 |
return {} |
| 119 |
|
| 120 |
# pyproject.toml uses [tool.pytest] or [tool.pytest.ini_options]. |
| 121 |
else: |
| 122 |
tool_pytest = config.get("tool", {}).get("pytest", {}) |
| 123 |
|
| 124 |
# Check for toml mode config: [tool.pytest] with content outside of ini_options. |
| 125 |
toml_config = {k: v for k, v in tool_pytest.items() if k != "ini_options"} |
| 126 |
# Check for ini mode config: [tool.pytest.ini_options]. |
| 127 |
ini_config = tool_pytest.get("ini_options", None) |
| 128 |
|
| 129 |
if toml_config and ini_config: |
| 130 |
raise UsageError( |
| 131 |
f"{filepath}: Cannot use both [tool.pytest] (native TOML types) and " |
| 132 |
"[tool.pytest.ini_options] (string-based INI format) simultaneously. " |
| 133 |
"Please use [tool.pytest] with native TOML types (recommended) " |
| 134 |
"or [tool.pytest.ini_options] for backwards compatibility." |
| 135 |
) |
| 136 |
|
| 137 |
if toml_config: |
| 138 |
# TOML mode - preserve native TOML types. |
| 139 |
return { |
| 140 |
k: ConfigValue(v, origin="file", mode="toml") |
| 141 |
for k, v in toml_config.items() |
| 142 |
} |
| 143 |
|
| 144 |
elif ini_config is not None: |
| 145 |
# INI mode - TOML supports richer data types than INI files, but we need to |
| 146 |
# convert all scalar values to str for compatibility with the INI system. |
| 147 |
def make_scalar(v: object) -> str | list[str]: |
| 148 |
return v if isinstance(v, list) else str(v) |
| 149 |
|
| 150 |
return { |
| 151 |
k: ConfigValue(make_scalar(v), origin="file", mode="ini") |
| 152 |
for k, v in ini_config.items() |
| 153 |
} |
| 154 |
|
| 155 |
return None |
| 156 |
|
| 157 |
|
| 158 |
def locate_config( |
| 159 |
invocation_dir: Path, |
| 160 |
args: Iterable[Path], |
| 161 |
) -> tuple[Path | None, Path | None, ConfigDict, Sequence[str]]: |
| 162 |
"""Search in the list of arguments for a valid ini-file for pytest, |
| 163 |
and return a tuple of (rootdir, inifile, cfg-dict, ignored-config-files), where |
| 164 |
ignored-config-files is a list of config basenames found that contain |
| 165 |
pytest configuration but were ignored.""" |
| 166 |
config_names = [ |
| 167 |
"pytest.toml", |
| 168 |
".pytest.toml", |
| 169 |
"pytest.ini", |
| 170 |
".pytest.ini", |
| 171 |
"pyproject.toml", |
| 172 |
"tox.ini", |
| 173 |
"setup.cfg", |
| 174 |
] |
| 175 |
args = [x for x in args if not str(x).startswith("-")] |
| 176 |
if not args: |
| 177 |
args = [invocation_dir] |
| 178 |
found_pyproject_toml: Path | None = None |
| 179 |
ignored_config_files: list[str] = [] |
| 180 |
|
| 181 |
for arg in args: |
| 182 |
argpath = absolutepath(arg) |
| 183 |
for base in (argpath, *argpath.parents): |
| 184 |
for config_name in config_names: |
| 185 |
p = base / config_name |
| 186 |
if p.is_file(): |
| 187 |
if p.name == "pyproject.toml" and found_pyproject_toml is None: |
| 188 |
found_pyproject_toml = p |
| 189 |
ini_config = load_config_dict_from_file(p) |
| 190 |
if ini_config is not None: |
| 191 |
index = config_names.index(config_name) |
| 192 |
for remainder in config_names[index + 1 :]: |
| 193 |
p2 = base / remainder |
| 194 |
if ( |
| 195 |
p2.is_file() |
| 196 |
and load_config_dict_from_file(p2) is not None |
| 197 |
): |
| 198 |
ignored_config_files.append(remainder) |
| 199 |
return base, p, ini_config, ignored_config_files |
| 200 |
if found_pyproject_toml is not None: |
| 201 |
return found_pyproject_toml.parent, found_pyproject_toml, {}, [] |
| 202 |
return None, None, {}, [] |
| 203 |
|
| 204 |
|
| 205 |
def get_common_ancestor( |
| 206 |
invocation_dir: Path, |
| 207 |
paths: Iterable[Path], |
| 208 |
) -> Path: |
| 209 |
common_ancestor: Path | None = None |
| 210 |
for path in paths: |
| 211 |
if not path.exists(): |
| 212 |
continue |
| 213 |
if common_ancestor is None: |
| 214 |
common_ancestor = path |
| 215 |
else: |
| 216 |
if common_ancestor in path.parents or path == common_ancestor: |
| 217 |
continue |
| 218 |
elif path in common_ancestor.parents: |
| 219 |
common_ancestor = path |
| 220 |
else: |
| 221 |
shared = commonpath(path, common_ancestor) |
| 222 |
if shared is not None: |
| 223 |
common_ancestor = shared |
| 224 |
if common_ancestor is None: |
| 225 |
common_ancestor = invocation_dir |
| 226 |
elif common_ancestor.is_file(): |
| 227 |
common_ancestor = common_ancestor.parent |
| 228 |
return common_ancestor |
| 229 |
|
| 230 |
|
| 231 |
def get_dirs_from_args(args: Iterable[str]) -> list[Path]: |
| 232 |
def is_option(x: str) -> bool: |
| 233 |
return x.startswith("-") |
| 234 |
|
| 235 |
def get_file_part_from_node_id(x: str) -> str: |
| 236 |
return x.split("::", maxsplit=1)[0] |
| 237 |
|
| 238 |
def get_dir_from_path(path: Path) -> Path: |
| 239 |
if path.is_dir(): |
| 240 |
return path |
| 241 |
return path.parent |
| 242 |
|
| 243 |
# These look like paths but may not exist |
| 244 |
possible_paths = ( |
| 245 |
absolutepath(get_file_part_from_node_id(arg)) |
| 246 |
for arg in args |
| 247 |
if not is_option(arg) |
| 248 |
) |
| 249 |
|
| 250 |
return [get_dir_from_path(path) for path in possible_paths if safe_exists(path)] |
| 251 |
|
| 252 |
|
| 253 |
def parse_override_ini(override_ini: Sequence[str] | None) -> ConfigDict: |
| 254 |
"""Parse the -o/--override-ini command line arguments and return the overrides. |
| 255 |
|
| 256 |
:raises UsageError: |
| 257 |
If one of the values is malformed. |
| 258 |
""" |
| 259 |
overrides = {} |
| 260 |
# override_ini is a list of "ini=value" options. |
| 261 |
# Always use the last item if multiple values are set for same ini-name, |
| 262 |
# e.g. -o foo=bar1 -o foo=bar2 will set foo to bar2. |
| 263 |
for ini_config in override_ini or (): |
| 264 |
try: |
| 265 |
key, user_ini_value = ini_config.split("=", 1) |
| 266 |
except ValueError as e: |
| 267 |
raise UsageError( |
| 268 |
f"-o/--override-ini expects option=value style (got: {ini_config!r})." |
| 269 |
) from e |
| 270 |
else: |
| 271 |
overrides[key] = ConfigValue(user_ini_value, origin="override", mode="ini") |
| 272 |
return overrides |
| 273 |
|
| 274 |
|
| 275 |
CFG_PYTEST_SECTION = "[pytest] section in {filename} files is no longer supported, change to [tool:pytest] instead." |
| 276 |
|
| 277 |
|
| 278 |
def determine_setup( |
| 279 |
*, |
| 280 |
inifile: str | None, |
| 281 |
override_ini: Sequence[str] | None, |
| 282 |
args: Sequence[str], |
| 283 |
rootdir_cmd_arg: str | None, |
| 284 |
invocation_dir: Path, |
| 285 |
) -> tuple[Path, Path | None, ConfigDict, Sequence[str]]: |
| 286 |
"""Determine the rootdir, inifile and ini configuration values from the |
| 287 |
command line arguments. |
| 288 |
|
| 289 |
:param inifile: |
| 290 |
The `--inifile` command line argument, if given. |
| 291 |
:param override_ini: |
| 292 |
The -o/--override-ini command line arguments, if given. |
| 293 |
:param args: |
| 294 |
The free command line arguments. |
| 295 |
:param rootdir_cmd_arg: |
| 296 |
The `--rootdir` command line argument, if given. |
| 297 |
:param invocation_dir: |
| 298 |
The working directory when pytest was invoked. |
| 299 |
|
| 300 |
:raises UsageError: |
| 301 |
""" |
| 302 |
rootdir = None |
| 303 |
dirs = get_dirs_from_args(args) |
| 304 |
ignored_config_files: Sequence[str] = [] |
| 305 |
|
| 306 |
if inifile: |
| 307 |
inipath_ = absolutepath(inifile) |
| 308 |
inipath: Path | None = inipath_ |
| 309 |
inicfg = load_config_dict_from_file(inipath_) or {} |
| 310 |
if rootdir_cmd_arg is None: |
| 311 |
rootdir = inipath_.parent |
| 312 |
else: |
| 313 |
ancestor = get_common_ancestor(invocation_dir, dirs) |
| 314 |
rootdir, inipath, inicfg, ignored_config_files = locate_config( |
| 315 |
invocation_dir, [ancestor] |
| 316 |
) |
| 317 |
if rootdir is None and rootdir_cmd_arg is None: |
| 318 |
for possible_rootdir in (ancestor, *ancestor.parents): |
| 319 |
if (possible_rootdir / "setup.py").is_file(): |
| 320 |
rootdir = possible_rootdir |
| 321 |
break |
| 322 |
else: |
| 323 |
if dirs != [ancestor]: |
| 324 |
rootdir, inipath, inicfg, _ = locate_config(invocation_dir, dirs) |
| 325 |
if rootdir is None: |
| 326 |
rootdir = get_common_ancestor( |
| 327 |
invocation_dir, [invocation_dir, ancestor] |
| 328 |
) |
| 329 |
if is_fs_root(rootdir): |
| 330 |
rootdir = ancestor |
| 331 |
if rootdir_cmd_arg: |
| 332 |
rootdir = absolutepath(os.path.expandvars(rootdir_cmd_arg)) |
| 333 |
if not rootdir.is_dir(): |
| 334 |
raise UsageError( |
| 335 |
f"Directory '{rootdir}' not found. Check your '--rootdir' option." |
| 336 |
) |
| 337 |
|
| 338 |
ini_overrides = parse_override_ini(override_ini) |
| 339 |
inicfg.update(ini_overrides) |
| 340 |
|
| 341 |
assert rootdir is not None |
| 342 |
return rootdir, inipath, inicfg, ignored_config_files |
| 343 |
|
| 344 |
|
| 345 |
def is_fs_root(p: Path) -> bool: |
| 346 |
r""" |
| 347 |
Return True if the given path is pointing to the root of the |
| 348 |
file system ("/" on Unix and "C:\\" on Windows for example). |
| 349 |
""" |
| 350 |
return os.path.splitdrive(str(p))[1] == os.sep |