[pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci
This commit is contained in:
pre-commit-ci[bot] 2024-04-13 00:00:18 +00:00
parent 72ad6dc953
commit f4cd1ba0d6
813 changed files with 66015 additions and 58839 deletions

View file

@ -1,6 +1,8 @@
from __future__ import annotations
import os
from pathlib import Path
import sys
from pathlib import Path
from typing import Dict
from typing import Iterable
from typing import List
@ -10,13 +12,13 @@ from typing import Tuple
from typing import Union
import iniconfig
from .exceptions import UsageError
from _pytest.outcomes import fail
from _pytest.pathlib import absolutepath
from _pytest.pathlib import commonpath
from _pytest.pathlib import safe_exists
from .exceptions import UsageError
def _parse_ini_config(path: Path) -> iniconfig.IniConfig:
"""Parse the given generic '.ini' file using legacy IniConfig parser, returning
@ -32,52 +34,52 @@ def _parse_ini_config(path: Path) -> iniconfig.IniConfig:
def load_config_dict_from_file(
filepath: Path,
) -> Optional[Dict[str, Union[str, List[str]]]]:
) -> dict[str, str | list[str]] | None:
"""Load pytest configuration from the given file path, if supported.
Return None if the file does not contain valid pytest configuration.
"""
# Configuration from ini files are obtained from the [pytest] section, if present.
if filepath.suffix == ".ini":
if filepath.suffix == '.ini':
iniconfig = _parse_ini_config(filepath)
if "pytest" in iniconfig:
return dict(iniconfig["pytest"].items())
if 'pytest' in iniconfig:
return dict(iniconfig['pytest'].items())
else:
# "pytest.ini" files are always the source of configuration, even if empty.
if filepath.name == "pytest.ini":
if filepath.name == 'pytest.ini':
return {}
# '.cfg' files are considered if they contain a "[tool:pytest]" section.
elif filepath.suffix == ".cfg":
elif filepath.suffix == '.cfg':
iniconfig = _parse_ini_config(filepath)
if "tool:pytest" in iniconfig.sections:
return dict(iniconfig["tool:pytest"].items())
elif "pytest" in iniconfig.sections:
if 'tool:pytest' in iniconfig.sections:
return dict(iniconfig['tool:pytest'].items())
elif 'pytest' in iniconfig.sections:
# If a setup.cfg contains a "[pytest]" section, we raise a failure to indicate users that
# plain "[pytest]" sections in setup.cfg files is no longer supported (#3086).
fail(CFG_PYTEST_SECTION.format(filename="setup.cfg"), pytrace=False)
fail(CFG_PYTEST_SECTION.format(filename='setup.cfg'), pytrace=False)
# '.toml' files are considered if they contain a [tool.pytest.ini_options] table.
elif filepath.suffix == ".toml":
elif filepath.suffix == '.toml':
if sys.version_info >= (3, 11):
import tomllib
else:
import tomli as tomllib
toml_text = filepath.read_text(encoding="utf-8")
toml_text = filepath.read_text(encoding='utf-8')
try:
config = tomllib.loads(toml_text)
except tomllib.TOMLDecodeError as exc:
raise UsageError(f"{filepath}: {exc}") from exc
raise UsageError(f'{filepath}: {exc}') from exc
result = config.get("tool", {}).get("pytest", {}).get("ini_options", None)
result = config.get('tool', {}).get('pytest', {}).get('ini_options', None)
if result is not None:
# TOML supports richer data types than ini files (strings, arrays, floats, ints, etc),
# however we need to convert all scalar values to str for compatibility with the rest
# of the configuration system, which expects strings only.
def make_scalar(v: object) -> Union[str, List[str]]:
def make_scalar(v: object) -> str | list[str]:
return v if isinstance(v, list) else str(v)
return {k: make_scalar(v) for k, v in result.items()}
@ -88,27 +90,27 @@ def load_config_dict_from_file(
def locate_config(
invocation_dir: Path,
args: Iterable[Path],
) -> Tuple[Optional[Path], Optional[Path], Dict[str, Union[str, List[str]]]]:
) -> tuple[Path | None, Path | None, dict[str, str | list[str]]]:
"""Search in the list of arguments for a valid ini-file for pytest,
and return a tuple of (rootdir, inifile, cfg-dict)."""
config_names = [
"pytest.ini",
".pytest.ini",
"pyproject.toml",
"tox.ini",
"setup.cfg",
'pytest.ini',
'.pytest.ini',
'pyproject.toml',
'tox.ini',
'setup.cfg',
]
args = [x for x in args if not str(x).startswith("-")]
args = [x for x in args if not str(x).startswith('-')]
if not args:
args = [invocation_dir]
found_pyproject_toml: Optional[Path] = None
found_pyproject_toml: Path | None = None
for arg in args:
argpath = absolutepath(arg)
for base in (argpath, *argpath.parents):
for config_name in config_names:
p = base / config_name
if p.is_file():
if p.name == "pyproject.toml" and found_pyproject_toml is None:
if p.name == 'pyproject.toml' and found_pyproject_toml is None:
found_pyproject_toml = p
ini_config = load_config_dict_from_file(p)
if ini_config is not None:
@ -122,7 +124,7 @@ def get_common_ancestor(
invocation_dir: Path,
paths: Iterable[Path],
) -> Path:
common_ancestor: Optional[Path] = None
common_ancestor: Path | None = None
for path in paths:
if not path.exists():
continue
@ -144,12 +146,12 @@ def get_common_ancestor(
return common_ancestor
def get_dirs_from_args(args: Iterable[str]) -> List[Path]:
def get_dirs_from_args(args: Iterable[str]) -> list[Path]:
def is_option(x: str) -> bool:
return x.startswith("-")
return x.startswith('-')
def get_file_part_from_node_id(x: str) -> str:
return x.split("::")[0]
return x.split('::')[0]
def get_dir_from_path(path: Path) -> Path:
if path.is_dir():
@ -166,16 +168,16 @@ def get_dirs_from_args(args: Iterable[str]) -> List[Path]:
return [get_dir_from_path(path) for path in possible_paths if safe_exists(path)]
CFG_PYTEST_SECTION = "[pytest] section in {filename} files is no longer supported, change to [tool:pytest] instead."
CFG_PYTEST_SECTION = '[pytest] section in {filename} files is no longer supported, change to [tool:pytest] instead.'
def determine_setup(
*,
inifile: Optional[str],
inifile: str | None,
args: Sequence[str],
rootdir_cmd_arg: Optional[str],
rootdir_cmd_arg: str | None,
invocation_dir: Path,
) -> Tuple[Path, Optional[Path], Dict[str, Union[str, List[str]]]]:
) -> tuple[Path, Path | None, dict[str, str | list[str]]]:
"""Determine the rootdir, inifile and ini configuration values from the
command line arguments.
@ -192,7 +194,7 @@ def determine_setup(
dirs = get_dirs_from_args(args)
if inifile:
inipath_ = absolutepath(inifile)
inipath: Optional[Path] = inipath_
inipath: Path | None = inipath_
inicfg = load_config_dict_from_file(inipath_) or {}
if rootdir_cmd_arg is None:
rootdir = inipath_.parent
@ -201,7 +203,7 @@ def determine_setup(
rootdir, inipath, inicfg = locate_config(invocation_dir, [ancestor])
if rootdir is None and rootdir_cmd_arg is None:
for possible_rootdir in (ancestor, *ancestor.parents):
if (possible_rootdir / "setup.py").is_file():
if (possible_rootdir / 'setup.py').is_file():
rootdir = possible_rootdir
break
else:
@ -209,7 +211,7 @@ def determine_setup(
rootdir, inipath, inicfg = locate_config(invocation_dir, dirs)
if rootdir is None:
rootdir = get_common_ancestor(
invocation_dir, [invocation_dir, ancestor]
invocation_dir, [invocation_dir, ancestor],
)
if is_fs_root(rootdir):
rootdir = ancestor
@ -217,7 +219,7 @@ def determine_setup(
rootdir = absolutepath(os.path.expandvars(rootdir_cmd_arg))
if not rootdir.is_dir():
raise UsageError(
f"Directory '{rootdir}' not found. Check your '--rootdir' option."
f"Directory '{rootdir}' not found. Check your '--rootdir' option.",
)
assert rootdir is not None
return rootdir, inipath, inicfg or {}