Debian Codegraph @

src/_pytest/reports.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 from collections.abc import Iterable
5 from collections.abc import Iterator
6 from collections.abc import Mapping
7 from collections.abc import Sequence
8 import dataclasses
9 from io import StringIO
10 import os
11 from pprint import pprint
12 import sys
13 from typing import Any
14 from typing import cast
15 from typing import final
16 from typing import Literal
17 from typing import NoReturn
18 from typing import TYPE_CHECKING
19
20 from _pytest._code.code import ExceptionChainRepr
21 from _pytest._code.code import ExceptionInfo
22 from _pytest._code.code import ExceptionRepr
23 from _pytest._code.code import ReprEntry
24 from _pytest._code.code import ReprEntryNative
25 from _pytest._code.code import ReprExceptionInfo
26 from _pytest._code.code import ReprFileLocation
27 from _pytest._code.code import ReprFuncArgs
28 from _pytest._code.code import ReprLocals
29 from _pytest._code.code import ReprTraceback
30 from _pytest._code.code import TerminalRepr
31 from _pytest._io import TerminalWriter
32 from _pytest.config import Config
33 from _pytest.nodes import Collector
34 from _pytest.nodes import Item
35 from _pytest.outcomes import fail
36 from _pytest.outcomes import skip
37
38
39 if sys.version_info < (3, 11):
40 from exceptiongroup import BaseExceptionGroup
41
42
43 if TYPE_CHECKING:
44 from typing_extensions import Self
45
46 from _pytest.runner import CallInfo
47
48
49 def getworkerinfoline(node):
50 try:
51 return node._workerinfocache
52 except AttributeError:
53 d = node.workerinfo
54 ver = "{}.{}.{}".format(*d["version_info"][:3])
55 node._workerinfocache = s = "[{}] {} -- Python {} {}".format(
56 d["id"], d["sysplatform"], ver, d["executable"]
57 )
58 return s
59
60
61 class BaseReport:
62 when: str | None
63 location: tuple[str, int | None, str] | None
64 longrepr: (
65 None | ExceptionInfo[BaseException] | tuple[str, int, str] | str | TerminalRepr
66 )
67 sections: list[tuple[str, str]]
68 nodeid: str
69 outcome: Literal["passed", "failed", "skipped"]
70
71 def __init__(self, **kw: Any) -> None:
72 self.__dict__.update(kw)
73
74 if TYPE_CHECKING:
75 # Can have arbitrary fields given to __init__().
76 def __getattr__(self, key: str) -> Any: ...
77
78 def toterminal(self, out: TerminalWriter) -> None:
79 if hasattr(self, "node"):
80 worker_info = getworkerinfoline(self.node)
81 if worker_info:
82 out.line(worker_info)
83
84 longrepr = self.longrepr
85 if longrepr is None:
86 return
87
88 if hasattr(longrepr, "toterminal"):
89 longrepr_terminal = cast(TerminalRepr, longrepr)
90 longrepr_terminal.toterminal(out)
91 else:
92 try:
93 s = str(longrepr)
94 except UnicodeEncodeError:
95 s = "<unprintable longrepr>"
96 out.line(s)
97
98 def get_sections(self, prefix: str) -> Iterator[tuple[str, str]]:
99 for name, content in self.sections:
100 if name.startswith(prefix):
101 yield prefix, content
102
103 @property
104 def longreprtext(self) -> str:
105 """Read-only property that returns the full string representation of
106 ``longrepr``.
107
108 .. versionadded:: 3.0
109 """
110 file = StringIO()
111 tw = TerminalWriter(file)
112 tw.hasmarkup = False
113 self.toterminal(tw)
114 exc = file.getvalue()
115 return exc.strip()
116
117 @property
118 def caplog(self) -> str:
119 """Return captured log lines, if log capturing is enabled.
120
121 .. versionadded:: 3.5
122 """
123 return "\n".join(
124 content for (prefix, content) in self.get_sections("Captured log")
125 )
126
127 @property
128 def capstdout(self) -> str:
129 """Return captured text from stdout, if capturing is enabled.
130
131 .. versionadded:: 3.0
132 """
133 return "".join(
134 content for (prefix, content) in self.get_sections("Captured stdout")
135 )
136
137 @property
138 def capstderr(self) -> str:
139 """Return captured text from stderr, if capturing is enabled.
140
141 .. versionadded:: 3.0
142 """
143 return "".join(
144 content for (prefix, content) in self.get_sections("Captured stderr")
145 )
146
147 @property
148 def passed(self) -> bool:
149 """Whether the outcome is passed."""
150 return self.outcome == "passed"
151
152 @property
153 def failed(self) -> bool:
154 """Whether the outcome is failed."""
155 return self.outcome == "failed"
156
157 @property
158 def skipped(self) -> bool:
159 """Whether the outcome is skipped."""
160 return self.outcome == "skipped"
161
162 @property
163 def fspath(self) -> str:
164 """The path portion of the reported node, as a string."""
165 return self.nodeid.split("::")[0]
166
167 @property
168 def count_towards_summary(self) -> bool:
169 """**Experimental** Whether this report should be counted towards the
170 totals shown at the end of the test session: "1 passed, 1 failure, etc".
171
172 .. note::
173
174 This function is considered **experimental**, so beware that it is subject to changes
175 even in patch releases.
176 """
177 return True
178
179 @property
180 def head_line(self) -> str | None:
181 """**Experimental** The head line shown with longrepr output for this
182 report, more commonly during traceback representation during
183 failures::
184
185 ________ Test.foo ________
186
187
188 In the example above, the head_line is "Test.foo".
189
190 .. note::
191
192 This function is considered **experimental**, so beware that it is subject to changes
193 even in patch releases.
194 """
195 if self.location is not None:
196 _fspath, _lineno, domain = self.location
197 return domain
198 return None
199
200 def _get_verbose_word_with_markup(
201 self, config: Config, default_markup: Mapping[str, bool]
202 ) -> tuple[str, Mapping[str, bool]]:
203 _category, _short, verbose = config.hook.pytest_report_teststatus(
204 report=self, config=config
205 )
206
207 if isinstance(verbose, str):
208 return verbose, default_markup
209
210 if isinstance(verbose, Sequence) and len(verbose) == 2:
211 word, markup = verbose
212 if isinstance(word, str) and isinstance(markup, Mapping):
213 return word, markup
214
215 fail( # pragma: no cover
216 "pytest_report_teststatus() hook (from a plugin) returned "
217 f"an invalid verbose value: {verbose!r}.\nExpected either a string "
218 "or a tuple of (word, markup)."
219 )
220
221 def _to_json(self) -> dict[str, Any]:
222 """Return the contents of this report as a dict of builtin entries,
223 suitable for serialization.
224
225 This was originally the serialize_report() function from xdist (ca03269).
226
227 Experimental method.
228 """
229 return _report_to_json(self)
230
231 @classmethod
232 def _from_json(cls, reportdict: dict[str, object]) -> Self:
233 """Create either a TestReport or CollectReport, depending on the calling class.
234
235 It is the callers responsibility to know which class to pass here.
236
237 This was originally the serialize_report() function from xdist (ca03269).
238
239 Experimental method.
240 """
241 kwargs = _report_kwargs_from_json(reportdict)
242 return cls(**kwargs)
243
244
245 def _report_unserialization_failure(
246 type_name: str, report_class: type[BaseReport], reportdict
247 ) -> NoReturn:
248 url = "https://github.com/pytest-dev/pytest/issues"
249 stream = StringIO()
250 pprint("-" * 100, stream=stream)
251 pprint(f"INTERNALERROR: Unknown entry type returned: {type_name}", stream=stream)
252 pprint(f"report_name: {report_class}", stream=stream)
253 pprint(reportdict, stream=stream)
254 pprint(f"Please report this bug at {url}", stream=stream)
255 pprint("-" * 100, stream=stream)
256 raise RuntimeError(stream.getvalue())
257
258
259 def _format_failed_longrepr(
260 item: Item, call: CallInfo[None], excinfo: ExceptionInfo[BaseException]
261 ):
262 if call.when == "call":
263 longrepr = item.repr_failure(excinfo)
264 else:
265 # Exception in setup or teardown.
266 longrepr = item._repr_failure_py(
267 excinfo, style=item.config.getoption("tbstyle", "auto")
268 )
269 return longrepr
270
271
272 def _format_exception_group_all_skipped_longrepr(
273 item: Item,
274 excinfo: ExceptionInfo[BaseExceptionGroup[BaseException | BaseExceptionGroup]],
275 ) -> tuple[str, int, str]:
276 r = excinfo._getreprcrash()
277 assert r is not None, (
278 "There should always be a traceback entry for skipping a test."
279 )
280 if all(
281 getattr(skip, "_use_item_location", False) for skip in excinfo.value.exceptions
282 ):
283 path, line = item.reportinfo()[:2]
284 assert line is not None
285 loc = (os.fspath(path), line + 1)
286 default_msg = "skipped"
287 else:
288 loc = (str(r.path), r.lineno)
289 default_msg = r.message
290
291 # Get all unique skip messages.
292 msgs: list[str] = []
293 for exception in excinfo.value.exceptions:
294 m = getattr(exception, "msg", None) or (
295 exception.args[0] if exception.args else None
296 )
297 if m and m not in msgs:
298 msgs.append(m)
299
300 reason = "; ".join(msgs) if msgs else default_msg
301 longrepr = (*loc, reason)
302 return longrepr
303
304
305 class TestReport(BaseReport):
306 """Basic test report object (also used for setup and teardown calls if
307 they fail).
308
309 Reports can contain arbitrary extra attributes.
310 """
311
312 __test__ = False
313
314 # Defined by skipping plugin.
315 # xfail reason if xfailed, otherwise not defined. Use hasattr to distinguish.
316 wasxfail: str
317
318 def __init__(
319 self,
320 nodeid: str,
321 location: tuple[str, int | None, str],
322 keywords: Mapping[str, Any],
323 outcome: Literal["passed", "failed", "skipped"],
324 longrepr: None
325 | ExceptionInfo[BaseException]
326 | tuple[str, int, str]
327 | str
328 | TerminalRepr,
329 when: Literal["setup", "call", "teardown"],
330 sections: Iterable[tuple[str, str]] = (),
331 duration: float = 0,
332 start: float = 0,
333 stop: float = 0,
334 user_properties: Iterable[tuple[str, object]] | None = None,
335 **extra,
336 ) -> None:
337 #: Normalized collection nodeid.
338 self.nodeid = nodeid
339
340 #: A (filesystempath, lineno, domaininfo) tuple indicating the
341 #: actual location of a test item - it might be different from the
342 #: collected one e.g. if a method is inherited from a different module.
343 #: The filesystempath may be relative to ``config.rootdir``.
344 #: The line number is 0-based.
345 self.location: tuple[str, int | None, str] = location
346
347 #: A name -> value dictionary containing all keywords and
348 #: markers associated with a test invocation.
349 self.keywords: Mapping[str, Any] = keywords
350
351 #: Test outcome, always one of "passed", "failed", "skipped".
352 self.outcome = outcome
353
354 #: None or a failure representation.
355 self.longrepr = longrepr
356
357 #: One of 'setup', 'call', 'teardown' to indicate runtest phase.
358 self.when: Literal["setup", "call", "teardown"] = when
359
360 #: User properties is a list of tuples (name, value) that holds user
361 #: defined properties of the test.
362 self.user_properties = list(user_properties or [])
363
364 #: Tuples of str ``(heading, content)`` with extra information
365 #: for the test report. Used by pytest to add text captured
366 #: from ``stdout``, ``stderr``, and intercepted logging events. May
367 #: be used by other plugins to add arbitrary information to reports.
368 self.sections = list(sections)
369
370 #: Time it took to run just the test.
371 self.duration: float = duration
372
373 #: The system time when the call started, in seconds since the epoch.
374 self.start: float = start
375 #: The system time when the call ended, in seconds since the epoch.
376 self.stop: float = stop
377
378 self.__dict__.update(extra)
379
380 def __repr__(self) -> str:
381 return f"<{self.__class__.__name__} {self.nodeid!r} when={self.when!r} outcome={self.outcome!r}>"
382
383 @classmethod
384 def from_item_and_call(cls, item: Item, call: CallInfo[None]) -> TestReport:
385 """Create and fill a TestReport with standard item and call info.
386
387 :param item: The item.
388 :param call: The call info.
389 """
390 when = call.when
391 # Remove "collect" from the Literal type -- only for collection calls.
392 assert when != "collect"
393 duration = call.duration
394 start = call.start
395 stop = call.stop
396 keywords = {x: 1 for x in item.keywords}
397 excinfo = call.excinfo
398 sections = []
399 if not call.excinfo:
400 outcome: Literal["passed", "failed", "skipped"] = "passed"
401 longrepr: (
402 None
403 | ExceptionInfo[BaseException]
404 | tuple[str, int, str]
405 | str
406 | TerminalRepr
407 ) = None
408 else:
409 if not isinstance(excinfo, ExceptionInfo):
410 outcome = "failed"
411 longrepr = excinfo
412 elif isinstance(excinfo.value, skip.Exception):
413 outcome = "skipped"
414 r = excinfo._getreprcrash()
415 assert r is not None, (
416 "There should always be a traceback entry for skipping a test."
417 )
418 if excinfo.value._use_item_location:
419 path, line = item.reportinfo()[:2]
420 assert line is not None
421 longrepr = (os.fspath(path), line + 1, r.message)
422 else:
423 longrepr = (str(r.path), r.lineno, r.message)
424 elif isinstance(excinfo.value, BaseExceptionGroup) and (
425 excinfo.value.split(skip.Exception)[1] is None
426 ):
427 # All exceptions in the group are skip exceptions.
428 outcome = "skipped"
429 excinfo = cast(
430 ExceptionInfo[
431 BaseExceptionGroup[BaseException | BaseExceptionGroup]
432 ],
433 excinfo,
434 )
435 longrepr = _format_exception_group_all_skipped_longrepr(item, excinfo)
436 else:
437 outcome = "failed"
438 longrepr = _format_failed_longrepr(item, call, excinfo)
439 for rwhen, key, content in item._report_sections:
440 sections.append((f"Captured {key} {rwhen}", content))
441 return cls(
442 item.nodeid,
443 item.location,
444 keywords,
445 outcome,
446 longrepr,
447 when,
448 sections,
449 duration,
450 start,
451 stop,
452 user_properties=item.user_properties,
453 )
454
455
456 @final
457 class CollectReport(BaseReport):
458 """Collection report object.
459
460 Reports can contain arbitrary extra attributes.
461 """
462
463 when = "collect"
464
465 def __init__(
466 self,
467 nodeid: str,
468 outcome: Literal["passed", "failed", "skipped"],
469 longrepr: None
470 | ExceptionInfo[BaseException]
471 | tuple[str, int, str]
472 | str
473 | TerminalRepr,
474 result: list[Item | Collector] | None,
475 sections: Iterable[tuple[str, str]] = (),
476 **extra,
477 ) -> None:
478 #: Normalized collection nodeid.
479 self.nodeid = nodeid
480
481 #: Test outcome, always one of "passed", "failed", "skipped".
482 self.outcome = outcome
483
484 #: None or a failure representation.
485 self.longrepr = longrepr
486
487 #: The collected items and collection nodes.
488 self.result = result or []
489
490 #: Tuples of str ``(heading, content)`` with extra information
491 #: for the test report. Used by pytest to add text captured
492 #: from ``stdout``, ``stderr``, and intercepted logging events. May
493 #: be used by other plugins to add arbitrary information to reports.
494 self.sections = list(sections)
495
496 self.__dict__.update(extra)
497
498 @property
499 def location( # type:ignore[override]
500 self,
501 ) -> tuple[str, int | None, str] | None:
502 return (self.fspath, None, self.fspath)
503
504 def __repr__(self) -> str:
505 return f"<CollectReport {self.nodeid!r} lenresult={len(self.result)} outcome={self.outcome!r}>"
506
507
508 class CollectErrorRepr(TerminalRepr):
509 def __init__(self, msg: str) -> None:
510 self.longrepr = msg
511
512 def toterminal(self, out: TerminalWriter) -> None:
513 out.line(self.longrepr, red=True)
514
515
516 def pytest_report_to_serializable(
517 report: CollectReport | TestReport,
518 ) -> dict[str, Any] | None:
519 if isinstance(report, TestReport | CollectReport):
520 data = report._to_json()
521 data["$report_type"] = report.__class__.__name__
522 return data
523 # TODO: Check if this is actually reachable.
524 return None # type: ignore[unreachable]
525
526
527 def pytest_report_from_serializable(
528 data: dict[str, Any],
529 ) -> CollectReport | TestReport | None:
530 if "$report_type" in data:
531 if data["$report_type"] == "TestReport":
532 return TestReport._from_json(data)
533 elif data["$report_type"] == "CollectReport":
534 return CollectReport._from_json(data)
535 assert False, "Unknown report_type unserialize data: {}".format(
536 data["$report_type"]
537 )
538 return None
539
540
541 def _report_to_json(report: BaseReport) -> dict[str, Any]:
542 """Return the contents of this report as a dict of builtin entries,
543 suitable for serialization.
544
545 This was originally the serialize_report() function from xdist (ca03269).
546 """
547
548 def serialize_repr_entry(
549 entry: ReprEntry | ReprEntryNative,
550 ) -> dict[str, Any]:
551 data = dataclasses.asdict(entry)
552 for key, value in data.items():
553 if hasattr(value, "__dict__"):
554 data[key] = dataclasses.asdict(value)
555 entry_data = {"type": type(entry).__name__, "data": data}
556 return entry_data
557
558 def serialize_repr_traceback(reprtraceback: ReprTraceback) -> dict[str, Any]:
559 result = dataclasses.asdict(reprtraceback)
560 result["reprentries"] = [
561 serialize_repr_entry(x) for x in reprtraceback.reprentries
562 ]
563 return result
564
565 def serialize_repr_crash(
566 reprcrash: ReprFileLocation | None,
567 ) -> dict[str, Any] | None:
568 if reprcrash is not None:
569 return dataclasses.asdict(reprcrash)
570 else:
571 return None
572
573 def serialize_exception_longrepr(rep: BaseReport) -> dict[str, Any]:
574 assert rep.longrepr is not None
575 # TODO: Investigate whether the duck typing is really necessary here.
576 longrepr = cast(ExceptionRepr, rep.longrepr)
577 result: dict[str, Any] = {
578 "reprcrash": serialize_repr_crash(longrepr.reprcrash),
579 "reprtraceback": serialize_repr_traceback(longrepr.reprtraceback),
580 "sections": longrepr.sections,
581 }
582 if isinstance(longrepr, ExceptionChainRepr):
583 result["chain"] = []
584 for repr_traceback, repr_crash, description in longrepr.chain:
585 result["chain"].append(
586 (
587 serialize_repr_traceback(repr_traceback),
588 serialize_repr_crash(repr_crash),
589 description,
590 )
591 )
592 else:
593 result["chain"] = None
594 return result
595
596 d = report.__dict__.copy()
597 if hasattr(report.longrepr, "toterminal"):
598 if hasattr(report.longrepr, "reprtraceback") and hasattr(
599 report.longrepr, "reprcrash"
600 ):
601 d["longrepr"] = serialize_exception_longrepr(report)
602 else:
603 d["longrepr"] = str(report.longrepr)
604 else:
605 d["longrepr"] = report.longrepr
606 for name in d:
607 if isinstance(d[name], os.PathLike):
608 d[name] = os.fspath(d[name])
609 elif name == "result":
610 d[name] = None # for now
611 return d
612
613
614 def _report_kwargs_from_json(reportdict: dict[str, Any]) -> dict[str, Any]:
615 """Return **kwargs that can be used to construct a TestReport or
616 CollectReport instance.
617
618 This was originally the serialize_report() function from xdist (ca03269).
619 """
620
621 def deserialize_repr_entry(entry_data):
622 data = entry_data["data"]
623 entry_type = entry_data["type"]
624 if entry_type == "ReprEntry":
625 reprfuncargs = None
626 reprfileloc = None
627 reprlocals = None
628 if data["reprfuncargs"]:
629 reprfuncargs = ReprFuncArgs(**data["reprfuncargs"])
630 if data["reprfileloc"]:
631 reprfileloc = ReprFileLocation(**data["reprfileloc"])
632 if data["reprlocals"]:
633 reprlocals = ReprLocals(data["reprlocals"]["lines"])
634
635 reprentry: ReprEntry | ReprEntryNative = ReprEntry(
636 lines=data["lines"],
637 reprfuncargs=reprfuncargs,
638 reprlocals=reprlocals,
639 reprfileloc=reprfileloc,
640 style=data["style"],
641 )
642 elif entry_type == "ReprEntryNative":
643 reprentry = ReprEntryNative(data["lines"])
644 else:
645 _report_unserialization_failure(entry_type, TestReport, reportdict)
646 return reprentry
647
648 def deserialize_repr_traceback(repr_traceback_dict):
649 repr_traceback_dict["reprentries"] = [
650 deserialize_repr_entry(x) for x in repr_traceback_dict["reprentries"]
651 ]
652 return ReprTraceback(**repr_traceback_dict)
653
654 def deserialize_repr_crash(repr_crash_dict: dict[str, Any] | None):
655 if repr_crash_dict is not None:
656 return ReprFileLocation(**repr_crash_dict)
657 else:
658 return None
659
660 if (
661 reportdict["longrepr"]
662 and "reprcrash" in reportdict["longrepr"]
663 and "reprtraceback" in reportdict["longrepr"]
664 ):
665 reprtraceback = deserialize_repr_traceback(
666 reportdict["longrepr"]["reprtraceback"]
667 )
668 reprcrash = deserialize_repr_crash(reportdict["longrepr"]["reprcrash"])
669 if reportdict["longrepr"]["chain"]:
670 chain = []
671 for repr_traceback_data, repr_crash_data, description in reportdict[
672 "longrepr"
673 ]["chain"]:
674 chain.append(
675 (
676 deserialize_repr_traceback(repr_traceback_data),
677 deserialize_repr_crash(repr_crash_data),
678 description,
679 )
680 )
681 exception_info: ExceptionChainRepr | ReprExceptionInfo = ExceptionChainRepr(
682 chain
683 )
684 else:
685 exception_info = ReprExceptionInfo(
686 reprtraceback=reprtraceback,
687 reprcrash=reprcrash,
688 )
689
690 for section in reportdict["longrepr"]["sections"]:
691 exception_info.addsection(*section)
692 reportdict["longrepr"] = exception_info
693
694 return reportdict