[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,7 +1,9 @@
# mypy: allow-untyped-defs
from __future__ import annotations
import dataclasses
from io import StringIO
import os
from io import StringIO
from pprint import pprint
from typing import Any
from typing import cast
@ -47,25 +49,25 @@ def getworkerinfoline(node):
return node._workerinfocache
except AttributeError:
d = node.workerinfo
ver = "{}.{}.{}".format(*d["version_info"][:3])
node._workerinfocache = s = "[{}] {} -- Python {} {}".format(
d["id"], d["sysplatform"], ver, d["executable"]
ver = '{}.{}.{}'.format(*d['version_info'][:3])
node._workerinfocache = s = '[{}] {} -- Python {} {}'.format(
d['id'], d['sysplatform'], ver, d['executable'],
)
return s
_R = TypeVar("_R", bound="BaseReport")
_R = TypeVar('_R', bound='BaseReport')
class BaseReport:
when: Optional[str]
location: Optional[Tuple[str, Optional[int], str]]
longrepr: Union[
None, ExceptionInfo[BaseException], Tuple[str, int, str], str, TerminalRepr
]
sections: List[Tuple[str, str]]
when: str | None
location: tuple[str, int | None, str] | None
longrepr: (
None | ExceptionInfo[BaseException] | tuple[str, int, str] | str | TerminalRepr
)
sections: list[tuple[str, str]]
nodeid: str
outcome: Literal["passed", "failed", "skipped"]
outcome: Literal['passed', 'failed', 'skipped']
def __init__(self, **kw: Any) -> None:
self.__dict__.update(kw)
@ -76,7 +78,7 @@ class BaseReport:
...
def toterminal(self, out: TerminalWriter) -> None:
if hasattr(self, "node"):
if hasattr(self, 'node'):
worker_info = getworkerinfoline(self.node)
if worker_info:
out.line(worker_info)
@ -85,17 +87,17 @@ class BaseReport:
if longrepr is None:
return
if hasattr(longrepr, "toterminal"):
if hasattr(longrepr, 'toterminal'):
longrepr_terminal = cast(TerminalRepr, longrepr)
longrepr_terminal.toterminal(out)
else:
try:
s = str(longrepr)
except UnicodeEncodeError:
s = "<unprintable longrepr>"
s = '<unprintable longrepr>'
out.line(s)
def get_sections(self, prefix: str) -> Iterator[Tuple[str, str]]:
def get_sections(self, prefix: str) -> Iterator[tuple[str, str]]:
for name, content in self.sections:
if name.startswith(prefix):
yield prefix, content
@ -120,8 +122,8 @@ class BaseReport:
.. versionadded:: 3.5
"""
return "\n".join(
content for (prefix, content) in self.get_sections("Captured log")
return '\n'.join(
content for (prefix, content) in self.get_sections('Captured log')
)
@property
@ -130,8 +132,8 @@ class BaseReport:
.. versionadded:: 3.0
"""
return "".join(
content for (prefix, content) in self.get_sections("Captured stdout")
return ''.join(
content for (prefix, content) in self.get_sections('Captured stdout')
)
@property
@ -140,29 +142,29 @@ class BaseReport:
.. versionadded:: 3.0
"""
return "".join(
content for (prefix, content) in self.get_sections("Captured stderr")
return ''.join(
content for (prefix, content) in self.get_sections('Captured stderr')
)
@property
def passed(self) -> bool:
"""Whether the outcome is passed."""
return self.outcome == "passed"
return self.outcome == 'passed'
@property
def failed(self) -> bool:
"""Whether the outcome is failed."""
return self.outcome == "failed"
return self.outcome == 'failed'
@property
def skipped(self) -> bool:
"""Whether the outcome is skipped."""
return self.outcome == "skipped"
return self.outcome == 'skipped'
@property
def fspath(self) -> str:
"""The path portion of the reported node, as a string."""
return self.nodeid.split("::")[0]
return self.nodeid.split('::')[0]
@property
def count_towards_summary(self) -> bool:
@ -177,7 +179,7 @@ class BaseReport:
return True
@property
def head_line(self) -> Optional[str]:
def head_line(self) -> str | None:
"""**Experimental** The head line shown with longrepr output for this
report, more commonly during traceback representation during
failures::
@ -199,11 +201,11 @@ class BaseReport:
def _get_verbose_word(self, config: Config):
_category, _short, verbose = config.hook.pytest_report_teststatus(
report=self, config=config
report=self, config=config,
)
return verbose
def _to_json(self) -> Dict[str, Any]:
def _to_json(self) -> dict[str, Any]:
"""Return the contents of this report as a dict of builtin entries,
suitable for serialization.
@ -214,7 +216,7 @@ class BaseReport:
return _report_to_json(self)
@classmethod
def _from_json(cls: Type[_R], reportdict: Dict[str, object]) -> _R:
def _from_json(cls: type[_R], reportdict: dict[str, object]) -> _R:
"""Create either a TestReport or CollectReport, depending on the calling class.
It is the callers responsibility to know which class to pass here.
@ -228,16 +230,16 @@ class BaseReport:
def _report_unserialization_failure(
type_name: str, report_class: Type[BaseReport], reportdict
type_name: str, report_class: type[BaseReport], reportdict,
) -> NoReturn:
url = "https://github.com/pytest-dev/pytest/issues"
url = 'https://github.com/pytest-dev/pytest/issues'
stream = StringIO()
pprint("-" * 100, stream=stream)
pprint("INTERNALERROR: Unknown entry type returned: %s" % type_name, stream=stream)
pprint("report_name: %s" % report_class, stream=stream)
pprint('-' * 100, stream=stream)
pprint('INTERNALERROR: Unknown entry type returned: %s' % type_name, stream=stream)
pprint('report_name: %s' % report_class, stream=stream)
pprint(reportdict, stream=stream)
pprint("Please report this bug at %s" % url, stream=stream)
pprint("-" * 100, stream=stream)
pprint('Please report this bug at %s' % url, stream=stream)
pprint('-' * 100, stream=stream)
raise RuntimeError(stream.getvalue())
@ -257,18 +259,18 @@ class TestReport(BaseReport):
def __init__(
self,
nodeid: str,
location: Tuple[str, Optional[int], str],
location: tuple[str, int | None, str],
keywords: Mapping[str, Any],
outcome: Literal["passed", "failed", "skipped"],
longrepr: Union[
None, ExceptionInfo[BaseException], Tuple[str, int, str], str, TerminalRepr
],
when: Literal["setup", "call", "teardown"],
sections: Iterable[Tuple[str, str]] = (),
outcome: Literal['passed', 'failed', 'skipped'],
longrepr: (
None | ExceptionInfo[BaseException] | tuple[str, int, str] | str | TerminalRepr
),
when: Literal['setup', 'call', 'teardown'],
sections: Iterable[tuple[str, str]] = (),
duration: float = 0,
start: float = 0,
stop: float = 0,
user_properties: Optional[Iterable[Tuple[str, object]]] = None,
user_properties: Iterable[tuple[str, object]] | None = None,
**extra,
) -> None:
#: Normalized collection nodeid.
@ -279,7 +281,7 @@ class TestReport(BaseReport):
#: collected one e.g. if a method is inherited from a different module.
#: The filesystempath may be relative to ``config.rootdir``.
#: The line number is 0-based.
self.location: Tuple[str, Optional[int], str] = location
self.location: tuple[str, int | None, str] = location
#: A name -> value dictionary containing all keywords and
#: markers associated with a test invocation.
@ -315,10 +317,10 @@ class TestReport(BaseReport):
self.__dict__.update(extra)
def __repr__(self) -> str:
return f"<{self.__class__.__name__} {self.nodeid!r} when={self.when!r} outcome={self.outcome!r}>"
return f'<{self.__class__.__name__} {self.nodeid!r} when={self.when!r} outcome={self.outcome!r}>'
@classmethod
def from_item_and_call(cls, item: Item, call: "CallInfo[None]") -> "TestReport":
def from_item_and_call(cls, item: Item, call: CallInfo[None]) -> TestReport:
"""Create and fill a TestReport with standard item and call info.
:param item: The item.
@ -326,7 +328,7 @@ class TestReport(BaseReport):
"""
when = call.when
# Remove "collect" from the Literal type -- only for collection calls.
assert when != "collect"
assert when != 'collect'
duration = call.duration
start = call.start
stop = call.stop
@ -334,24 +336,24 @@ class TestReport(BaseReport):
excinfo = call.excinfo
sections = []
if not call.excinfo:
outcome: Literal["passed", "failed", "skipped"] = "passed"
longrepr: Union[
None,
ExceptionInfo[BaseException],
Tuple[str, int, str],
str,
TerminalRepr,
] = None
outcome: Literal['passed', 'failed', 'skipped'] = 'passed'
longrepr: (
None |
ExceptionInfo[BaseException] |
tuple[str, int, str] |
str |
TerminalRepr
) = None
else:
if not isinstance(excinfo, ExceptionInfo):
outcome = "failed"
outcome = 'failed'
longrepr = excinfo
elif isinstance(excinfo.value, skip.Exception):
outcome = "skipped"
outcome = 'skipped'
r = excinfo._getreprcrash()
assert (
r is not None
), "There should always be a traceback entry for skipping a test."
), 'There should always be a traceback entry for skipping a test.'
if excinfo.value._use_item_location:
path, line = item.reportinfo()[:2]
assert line is not None
@ -359,15 +361,15 @@ class TestReport(BaseReport):
else:
longrepr = (str(r.path), r.lineno, r.message)
else:
outcome = "failed"
if call.when == "call":
outcome = 'failed'
if call.when == 'call':
longrepr = item.repr_failure(excinfo)
else: # exception in setup or teardown
longrepr = item._repr_failure_py(
excinfo, style=item.config.getoption("tbstyle", "auto")
excinfo, style=item.config.getoption('tbstyle', 'auto'),
)
for rwhen, key, content in item._report_sections:
sections.append((f"Captured {key} {rwhen}", content))
sections.append((f'Captured {key} {rwhen}', content))
return cls(
item.nodeid,
item.location,
@ -390,17 +392,17 @@ class CollectReport(BaseReport):
Reports can contain arbitrary extra attributes.
"""
when = "collect"
when = 'collect'
def __init__(
self,
nodeid: str,
outcome: "Literal['passed', 'failed', 'skipped']",
longrepr: Union[
None, ExceptionInfo[BaseException], Tuple[str, int, str], str, TerminalRepr
],
result: Optional[List[Union[Item, Collector]]],
sections: Iterable[Tuple[str, str]] = (),
outcome: Literal['passed', 'failed', 'skipped'],
longrepr: (
None | ExceptionInfo[BaseException] | tuple[str, int, str] | str | TerminalRepr
),
result: list[Item | Collector] | None,
sections: Iterable[tuple[str, str]] = (),
**extra,
) -> None:
#: Normalized collection nodeid.
@ -426,11 +428,11 @@ class CollectReport(BaseReport):
@property
def location( # type:ignore[override]
self,
) -> Optional[Tuple[str, Optional[int], str]]:
) -> tuple[str, int | None, str] | None:
return (self.fspath, None, self.fspath)
def __repr__(self) -> str:
return f"<CollectReport {self.nodeid!r} lenresult={len(self.result)} outcome={self.outcome!r}>"
return f'<CollectReport {self.nodeid!r} lenresult={len(self.result)} outcome={self.outcome!r}>'
class CollectErrorRepr(TerminalRepr):
@ -442,31 +444,31 @@ class CollectErrorRepr(TerminalRepr):
def pytest_report_to_serializable(
report: Union[CollectReport, TestReport],
) -> Optional[Dict[str, Any]]:
report: CollectReport | TestReport,
) -> dict[str, Any] | None:
if isinstance(report, (TestReport, CollectReport)):
data = report._to_json()
data["$report_type"] = report.__class__.__name__
data['$report_type'] = report.__class__.__name__
return data
# TODO: Check if this is actually reachable.
return None # type: ignore[unreachable]
def pytest_report_from_serializable(
data: Dict[str, Any],
) -> Optional[Union[CollectReport, TestReport]]:
if "$report_type" in data:
if data["$report_type"] == "TestReport":
data: dict[str, Any],
) -> CollectReport | TestReport | None:
if '$report_type' in data:
if data['$report_type'] == 'TestReport':
return TestReport._from_json(data)
elif data["$report_type"] == "CollectReport":
elif data['$report_type'] == 'CollectReport':
return CollectReport._from_json(data)
assert False, "Unknown report_type unserialize data: {}".format(
data["$report_type"]
assert False, 'Unknown report_type unserialize data: {}'.format(
data['$report_type'],
)
return None
def _report_to_json(report: BaseReport) -> Dict[str, Any]:
def _report_to_json(report: BaseReport) -> dict[str, Any]:
"""Return the contents of this report as a dict of builtin entries,
suitable for serialization.
@ -474,72 +476,72 @@ def _report_to_json(report: BaseReport) -> Dict[str, Any]:
"""
def serialize_repr_entry(
entry: Union[ReprEntry, ReprEntryNative],
) -> Dict[str, Any]:
entry: ReprEntry | ReprEntryNative,
) -> dict[str, Any]:
data = dataclasses.asdict(entry)
for key, value in data.items():
if hasattr(value, "__dict__"):
if hasattr(value, '__dict__'):
data[key] = dataclasses.asdict(value)
entry_data = {"type": type(entry).__name__, "data": data}
entry_data = {'type': type(entry).__name__, 'data': data}
return entry_data
def serialize_repr_traceback(reprtraceback: ReprTraceback) -> Dict[str, Any]:
def serialize_repr_traceback(reprtraceback: ReprTraceback) -> dict[str, Any]:
result = dataclasses.asdict(reprtraceback)
result["reprentries"] = [
result['reprentries'] = [
serialize_repr_entry(x) for x in reprtraceback.reprentries
]
return result
def serialize_repr_crash(
reprcrash: Optional[ReprFileLocation],
) -> Optional[Dict[str, Any]]:
reprcrash: ReprFileLocation | None,
) -> dict[str, Any] | None:
if reprcrash is not None:
return dataclasses.asdict(reprcrash)
else:
return None
def serialize_exception_longrepr(rep: BaseReport) -> Dict[str, Any]:
def serialize_exception_longrepr(rep: BaseReport) -> dict[str, Any]:
assert rep.longrepr is not None
# TODO: Investigate whether the duck typing is really necessary here.
longrepr = cast(ExceptionRepr, rep.longrepr)
result: Dict[str, Any] = {
"reprcrash": serialize_repr_crash(longrepr.reprcrash),
"reprtraceback": serialize_repr_traceback(longrepr.reprtraceback),
"sections": longrepr.sections,
result: dict[str, Any] = {
'reprcrash': serialize_repr_crash(longrepr.reprcrash),
'reprtraceback': serialize_repr_traceback(longrepr.reprtraceback),
'sections': longrepr.sections,
}
if isinstance(longrepr, ExceptionChainRepr):
result["chain"] = []
result['chain'] = []
for repr_traceback, repr_crash, description in longrepr.chain:
result["chain"].append(
result['chain'].append(
(
serialize_repr_traceback(repr_traceback),
serialize_repr_crash(repr_crash),
description,
)
),
)
else:
result["chain"] = None
result['chain'] = None
return result
d = report.__dict__.copy()
if hasattr(report.longrepr, "toterminal"):
if hasattr(report.longrepr, "reprtraceback") and hasattr(
report.longrepr, "reprcrash"
if hasattr(report.longrepr, 'toterminal'):
if hasattr(report.longrepr, 'reprtraceback') and hasattr(
report.longrepr, 'reprcrash',
):
d["longrepr"] = serialize_exception_longrepr(report)
d['longrepr'] = serialize_exception_longrepr(report)
else:
d["longrepr"] = str(report.longrepr)
d['longrepr'] = str(report.longrepr)
else:
d["longrepr"] = report.longrepr
d['longrepr'] = report.longrepr
for name in d:
if isinstance(d[name], os.PathLike):
d[name] = os.fspath(d[name])
elif name == "result":
elif name == 'result':
d[name] = None # for now
return d
def _report_kwargs_from_json(reportdict: Dict[str, Any]) -> Dict[str, Any]:
def _report_kwargs_from_json(reportdict: dict[str, Any]) -> dict[str, Any]:
"""Return **kwargs that can be used to construct a TestReport or
CollectReport instance.
@ -547,76 +549,76 @@ def _report_kwargs_from_json(reportdict: Dict[str, Any]) -> Dict[str, Any]:
"""
def deserialize_repr_entry(entry_data):
data = entry_data["data"]
entry_type = entry_data["type"]
if entry_type == "ReprEntry":
data = entry_data['data']
entry_type = entry_data['type']
if entry_type == 'ReprEntry':
reprfuncargs = None
reprfileloc = None
reprlocals = None
if data["reprfuncargs"]:
reprfuncargs = ReprFuncArgs(**data["reprfuncargs"])
if data["reprfileloc"]:
reprfileloc = ReprFileLocation(**data["reprfileloc"])
if data["reprlocals"]:
reprlocals = ReprLocals(data["reprlocals"]["lines"])
if data['reprfuncargs']:
reprfuncargs = ReprFuncArgs(**data['reprfuncargs'])
if data['reprfileloc']:
reprfileloc = ReprFileLocation(**data['reprfileloc'])
if data['reprlocals']:
reprlocals = ReprLocals(data['reprlocals']['lines'])
reprentry: Union[ReprEntry, ReprEntryNative] = ReprEntry(
lines=data["lines"],
reprentry: ReprEntry | ReprEntryNative = ReprEntry(
lines=data['lines'],
reprfuncargs=reprfuncargs,
reprlocals=reprlocals,
reprfileloc=reprfileloc,
style=data["style"],
style=data['style'],
)
elif entry_type == "ReprEntryNative":
reprentry = ReprEntryNative(data["lines"])
elif entry_type == 'ReprEntryNative':
reprentry = ReprEntryNative(data['lines'])
else:
_report_unserialization_failure(entry_type, TestReport, reportdict)
return reprentry
def deserialize_repr_traceback(repr_traceback_dict):
repr_traceback_dict["reprentries"] = [
deserialize_repr_entry(x) for x in repr_traceback_dict["reprentries"]
repr_traceback_dict['reprentries'] = [
deserialize_repr_entry(x) for x in repr_traceback_dict['reprentries']
]
return ReprTraceback(**repr_traceback_dict)
def deserialize_repr_crash(repr_crash_dict: Optional[Dict[str, Any]]):
def deserialize_repr_crash(repr_crash_dict: dict[str, Any] | None):
if repr_crash_dict is not None:
return ReprFileLocation(**repr_crash_dict)
else:
return None
if (
reportdict["longrepr"]
and "reprcrash" in reportdict["longrepr"]
and "reprtraceback" in reportdict["longrepr"]
reportdict['longrepr'] and
'reprcrash' in reportdict['longrepr'] and
'reprtraceback' in reportdict['longrepr']
):
reprtraceback = deserialize_repr_traceback(
reportdict["longrepr"]["reprtraceback"]
reportdict['longrepr']['reprtraceback'],
)
reprcrash = deserialize_repr_crash(reportdict["longrepr"]["reprcrash"])
if reportdict["longrepr"]["chain"]:
reprcrash = deserialize_repr_crash(reportdict['longrepr']['reprcrash'])
if reportdict['longrepr']['chain']:
chain = []
for repr_traceback_data, repr_crash_data, description in reportdict[
"longrepr"
]["chain"]:
'longrepr'
]['chain']:
chain.append(
(
deserialize_repr_traceback(repr_traceback_data),
deserialize_repr_crash(repr_crash_data),
description,
)
),
)
exception_info: Union[
ExceptionChainRepr, ReprExceptionInfo
] = ExceptionChainRepr(chain)
exception_info: (
ExceptionChainRepr | ReprExceptionInfo
) = ExceptionChainRepr(chain)
else:
exception_info = ReprExceptionInfo(
reprtraceback=reprtraceback,
reprcrash=reprcrash,
)
for section in reportdict["longrepr"]["sections"]:
for section in reportdict['longrepr']['sections']:
exception_info.addsection(*section)
reportdict["longrepr"] = exception_info
reportdict['longrepr'] = exception_info
return reportdict