Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
repos:
- repo: https://github.com/psf/black
rev: 19.10b0
rev: 22.1.0
hooks:
- id: black
args: [--safe, --quiet]
- repo: https://github.com/asottile/blacken-docs
rev: v1.8.0
rev: v1.12.1
hooks:
- id: blacken-docs
additional_dependencies: [black==19.10b0]
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.2.0
rev: v4.1.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
Expand All @@ -20,36 +20,36 @@ repos:
- id: debug-statements
exclude: _pytest/(debugging|hookspec).py
language_version: python3
- repo: https://gitlab.com/pycqa/flake8
rev: 3.8.3
- repo: https://github.com/PyCQA/flake8
rev: 4.0.1
hooks:
- id: flake8
language_version: python3
additional_dependencies:
- flake8-typing-imports==1.9.0
- flake8-docstrings==1.5.0
- repo: https://github.com/asottile/reorder_python_imports
rev: v2.3.5
rev: v3.0.1
hooks:
- id: reorder-python-imports
args: ['--application-directories=.:src', --py36-plus]
- repo: https://github.com/asottile/pyupgrade
rev: v2.7.2
rev: v2.31.1
hooks:
- id: pyupgrade
args: [--py36-plus]
- repo: https://github.com/asottile/setup-cfg-fmt
rev: v1.11.0
rev: v1.20.0
hooks:
- id: setup-cfg-fmt
# TODO: when upgrading setup-cfg-fmt this can be removed
args: [--max-py-version=3.9]
- repo: https://github.com/pre-commit/pygrep-hooks
rev: v1.6.0
rev: v1.9.0
hooks:
- id: python-use-type-annotations
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v0.790
rev: v0.941
hooks:
- id: mypy
files: ^(src/|testing/)
Expand Down
1 change: 1 addition & 0 deletions extra/setup-py.test/setup.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import sys

from distutils.core import setup

if __name__ == "__main__":
Expand Down
10 changes: 8 additions & 2 deletions scripts/prepare-release-pr.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,10 @@ def prepare_release_pr(base_branch: str, is_major: bool, token: str) -> None:
cmdline = ["tox", "-e", "release", "--", version, "--skip-check-links"]
print("Running", " ".join(cmdline))
run(
cmdline, text=True, check=True, capture_output=True,
cmdline,
text=True,
check=True,
capture_output=True,
)

oauth_url = f"https://{token}:[email protected]/{SLUG}.git"
Expand All @@ -105,7 +108,10 @@ def prepare_release_pr(base_branch: str, is_major: bool, token: str) -> None:
body = PR_BODY.format(version=version)
repo = login(token)
pr = repo.create_pull(
f"Prepare release {version}", base=base_branch, head=release_branch, body=body,
f"Prepare release {version}",
base=base_branch,
head=release_branch,
body=body,
)
print(f"Pull request {Fore.CYAN}{pr.url}{Fore.RESET} created.")

Expand Down
5 changes: 4 additions & 1 deletion scripts/release-on-comment.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,10 @@ def trigger_release(payload_path: Path, token: str) -> None:
cmdline = ["tox", "-e", "release", "--", version, "--skip-check-links"]
print("Running", " ".join(cmdline))
run(
cmdline, text=True, check=True, capture_output=True,
cmdline,
text=True,
check=True,
capture_output=True,
)

oauth_url = f"https://{token}:[email protected]/{SLUG}.git"
Expand Down
1 change: 0 additions & 1 deletion src/_pytest/_argcomplete.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,6 @@ def __call__(self, prefix: str, **kwargs: Any) -> List[str]:
def try_argcomplete(parser: argparse.ArgumentParser) -> None:
argcomplete.autocomplete(parser, always_complete_options=False)


else:

def try_argcomplete(parser: argparse.ArgumentParser) -> None:
Expand Down
8 changes: 4 additions & 4 deletions src/_pytest/_code/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,9 +270,9 @@ def ishidden(self) -> bool:
Mostly for internal use.
"""
tbh: Union[bool, Callable[[Optional[ExceptionInfo[BaseException]]], bool]] = (
False
)
tbh: Union[
bool, Callable[[Optional[ExceptionInfo[BaseException]]], bool]
] = False
for maybe_ns_dct in (self.frame.f_locals, self.frame.f_globals):
# in normal cases, f_locals and f_globals are dictionaries
# however via `exec(...)` / `eval(...)` they can be other types
Expand Down Expand Up @@ -950,7 +950,7 @@ def __str__(self) -> str:
return io.getvalue().strip()

def __repr__(self) -> str:
return "<{} instance at {:0x}>".format(self.__class__, id(self))
return f"<{self.__class__} instance at {id(self):0x}>"

def toterminal(self, tw: TerminalWriter) -> None:
raise NotImplementedError()
Expand Down
11 changes: 8 additions & 3 deletions src/_pytest/_io/saferepr.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def _try_repr_or_str(obj: object) -> str:
except (KeyboardInterrupt, SystemExit):
raise
except BaseException:
return '{}("{}")'.format(type(obj).__name__, obj)
return f'{type(obj).__name__}("{obj}")'


def _format_repr_exception(exc: BaseException, obj: object) -> str:
Expand All @@ -21,7 +21,7 @@ def _format_repr_exception(exc: BaseException, obj: object) -> str:
except (KeyboardInterrupt, SystemExit):
raise
except BaseException as exc:
exc_info = "unpresentable exception ({})".format(_try_repr_or_str(exc))
exc_info = f"unpresentable exception ({_try_repr_or_str(exc)})"
return "<[{} raised in repr()] {} object at 0x{:x}>".format(
exc_info, type(obj).__name__, id(obj)
)
Expand Down Expand Up @@ -107,7 +107,12 @@ def _format(
if objid in context or p is None:
# Type ignored because _format is private.
super()._format( # type: ignore[misc]
object, stream, indent, allowance, context, level,
object,
stream,
indent,
allowance,
context,
level,
)
return

Expand Down
1 change: 0 additions & 1 deletion src/_pytest/assertion/rewrite.py
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,6 @@ def _write_pyc(
return False
return True


else:

def _write_pyc(
Expand Down
3 changes: 2 additions & 1 deletion src/_pytest/cacheprovider.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,8 @@ def pytest_make_collect_report(self, collector: nodes.Collector):
# Sort any lf-paths to the beginning.
lf_paths = self.lfplugin._last_failed_paths
res.result = sorted(
res.result, key=lambda x: 0 if Path(str(x.fspath)) in lf_paths else 1,
res.result,
key=lambda x: 0 if Path(str(x.fspath)) in lf_paths else 1,
)
return

Expand Down
10 changes: 8 additions & 2 deletions src/_pytest/capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -556,7 +556,11 @@ def __init__(self, in_, out, err) -> None:

def __repr__(self) -> str:
return "<MultiCapture out={!r} err={!r} in_={!r} _state={!r} _in_suspended={!r}>".format(
self.out, self.err, self.in_, self._state, self._in_suspended,
self.out,
self.err,
self.in_,
self._state,
self._in_suspended,
)

def start_capturing(self) -> None:
Expand Down Expand Up @@ -843,7 +847,9 @@ def __init__(
def _start(self) -> None:
if self._capture is None:
self._capture = MultiCapture(
in_=None, out=self.captureclass(1), err=self.captureclass(2),
in_=None,
out=self.captureclass(1),
err=self.captureclass(2),
)
self._capture.start_capturing()

Expand Down
6 changes: 3 additions & 3 deletions src/_pytest/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,8 @@ def getfuncargnames(
parameters = signature(function).parameters
except (ValueError, TypeError) as e:
fail(
f"Could not determine arguments of {function!r}: {e}", pytrace=False,
f"Could not determine arguments of {function!r}: {e}",
pytrace=False,
)

arg_names = tuple(
Expand Down Expand Up @@ -177,7 +178,6 @@ def getfuncargnames(
def nullcontext():
yield


else:
from contextlib import nullcontext as nullcontext # noqa: F401

Expand Down Expand Up @@ -397,4 +397,4 @@ def __get__(self, instance, owner=None):
#
# This also work for Enums (if you use `is` to compare) and Literals.
def assert_never(value: "NoReturn") -> "NoReturn":
assert False, "Unhandled value: {} ({})".format(value, type(value).__name__)
assert False, f"Unhandled value: {value} ({type(value).__name__})"
43 changes: 32 additions & 11 deletions src/_pytest/config/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,9 @@ class ExitCode(enum.IntEnum):

class ConftestImportFailure(Exception):
def __init__(
self, path: Path, excinfo: Tuple[Type[Exception], Exception, TracebackType],
self,
path: Path,
excinfo: Tuple[Type[Exception], Exception, TracebackType],
) -> None:
super().__init__(path, excinfo)
self.path = path
Expand Down Expand Up @@ -269,7 +271,9 @@ def get_config(
config = Config(
pluginmanager,
invocation_params=Config.InvocationParams(
args=args or (), plugins=plugins, dir=Path.cwd(),
args=args or (),
plugins=plugins,
dir=Path.cwd(),
),
)

Expand Down Expand Up @@ -362,7 +366,10 @@ def __init__(self) -> None:
encoding: str = getattr(err, "encoding", "utf8")
try:
err = open(
os.dup(err.fileno()), mode=err.mode, buffering=1, encoding=encoding,
os.dup(err.fileno()),
mode=err.mode,
buffering=1,
encoding=encoding,
)
except Exception:
pass
Expand Down Expand Up @@ -514,7 +521,9 @@ def _try_load_conftest(

@lru_cache(maxsize=128)
def _getconftestmodules(
self, path: Path, importmode: Union[str, ImportMode],
self,
path: Path,
importmode: Union[str, ImportMode],
) -> List[types.ModuleType]:
if self._noconftest:
return []
Expand All @@ -539,7 +548,10 @@ def _getconftestmodules(
return clist

def _rget_with_confmod(
self, name: str, path: Path, importmode: Union[str, ImportMode],
self,
name: str,
path: Path,
importmode: Union[str, ImportMode],
) -> Tuple[types.ModuleType, Any]:
modules = self._getconftestmodules(path, importmode)
for mod in reversed(modules):
Expand All @@ -550,7 +562,9 @@ def _rget_with_confmod(
raise KeyError(name)

def _importconftest(
self, conftestpath: Path, importmode: Union[str, ImportMode],
self,
conftestpath: Path,
importmode: Union[str, ImportMode],
) -> types.ModuleType:
# Use a resolved Path object as key to avoid loading the same conftest
# twice with build systems that create build directories containing
Expand Down Expand Up @@ -588,7 +602,9 @@ def _importconftest(
return mod

def _check_non_top_pytest_plugins(
self, mod: types.ModuleType, conftestpath: Path,
self,
mod: types.ModuleType,
conftestpath: Path,
) -> None:
if (
hasattr(mod, "pytest_plugins")
Expand Down Expand Up @@ -703,7 +719,7 @@ def import_plugin(self, modname: str, consider_entry_points: bool = False) -> No
__import__(importspec)
except ImportError as e:
raise ImportError(
'Error importing plugin "{}": {}'.format(modname, str(e.args[0]))
f'Error importing plugin "{modname}": {str(e.args[0])}'
).with_traceback(e.__traceback__) from e

except Skipped as e:
Expand Down Expand Up @@ -1225,7 +1241,11 @@ def _checkversion(self) -> None:
if Version(minver) > Version(pytest.__version__):
raise pytest.UsageError(
"%s: 'minversion' requires pytest-%s, actual pytest-%s'"
% (self.inipath, minver, pytest.__version__,)
% (
self.inipath,
minver,
pytest.__version__,
)
)

def _validate_config_options(self) -> None:
Expand Down Expand Up @@ -1500,7 +1520,8 @@ def _warn_about_missing_assertion(self, mode: str) -> None:
"(are you using python -O?)\n"
)
self.issue_config_time_warning(
PytestConfigWarning(warning_text), stacklevel=3,
PytestConfigWarning(warning_text),
stacklevel=3,
)

def _warn_about_skipped_plugins(self) -> None:
Expand Down Expand Up @@ -1576,7 +1597,7 @@ def parse_warning_filter(
raise warnings._OptionError(f"too many fields (max 5): {arg!r}")
while len(parts) < 5:
parts.append("")
action_, message, category_, module, lineno_ = [s.strip() for s in parts]
action_, message, category_, module, lineno_ = (s.strip() for s in parts)
action: str = warnings._getaction(action_) # type: ignore[attr-defined]
category: Type[Warning] = warnings._getcategory(category_) # type: ignore[attr-defined]
if message and escape:
Expand Down
4 changes: 1 addition & 3 deletions src/_pytest/config/findpaths.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,7 @@ def make_scalar(v: object) -> Union[str, List[str]]:

def locate_config(
args: Iterable[Path],
) -> Tuple[
Optional[Path], Optional[Path], Dict[str, Union[str, List[str]]],
]:
) -> Tuple[Optional[Path], Optional[Path], Dict[str, Union[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 = [
Expand Down
Loading