Debian Codegraph @

testing/web-platform/tests/tools/third_party/pytest/src/_pytest/terminal.py

raw
1 # mypy: allow-untyped-defs
2 """Terminal reporting of the full testing process.
3
4 This is a good source for looking at the various reporting hooks.
5 """
6
7 import argparse
8 from collections import Counter
9 import dataclasses
10 import datetime
11 from functools import partial
12 import inspect
13 from pathlib import Path
14 import platform
15 import sys
16 import textwrap
17 from typing import Any
18 from typing import Callable
19 from typing import ClassVar
20 from typing import Dict
21 from typing import final
22 from typing import Generator
23 from typing import List
24 from typing import Literal
25 from typing import Mapping
26 from typing import NamedTuple
27 from typing import Optional
28 from typing import Sequence
29 from typing import Set
30 from typing import TextIO
31 from typing import Tuple
32 from typing import TYPE_CHECKING
33 from typing import Union
34 import warnings
35
36 import pluggy
37
38 from _pytest import nodes
39 from _pytest import timing
40 from _pytest._code import ExceptionInfo
41 from _pytest._code.code import ExceptionRepr
42 from _pytest._io import TerminalWriter
43 from _pytest._io.wcwidth import wcswidth
44 import _pytest._version
45 from _pytest.assertion.util import running_on_ci
46 from _pytest.config import _PluggyPlugin
47 from _pytest.config import Config
48 from _pytest.config import ExitCode
49 from _pytest.config import hookimpl
50 from _pytest.config.argparsing import Parser
51 from _pytest.nodes import Item
52 from _pytest.nodes import Node
53 from _pytest.pathlib import absolutepath
54 from _pytest.pathlib import bestrelpath
55 from _pytest.reports import BaseReport
56 from _pytest.reports import CollectReport
57 from _pytest.reports import TestReport
58
59
60 if TYPE_CHECKING:
61 from _pytest.main import Session
62
63
64 REPORT_COLLECTING_RESOLUTION = 0.5
65
66 KNOWN_TYPES = (
67 "failed",
68 "passed",
69 "skipped",
70 "deselected",
71 "xfailed",
72 "xpassed",
73 "warnings",
74 "error",
75 )
76
77 _REPORTCHARS_DEFAULT = "fE"
78
79
80 class MoreQuietAction(argparse.Action):
81 """A modified copy of the argparse count action which counts down and updates
82 the legacy quiet attribute at the same time.
83
84 Used to unify verbosity handling.
85 """
86
87 def __init__(
88 self,
89 option_strings: Sequence[str],
90 dest: str,
91 default: object = None,
92 required: bool = False,
93 help: Optional[str] = None,
94 ) -> None:
95 super().__init__(
96 option_strings=option_strings,
97 dest=dest,
98 nargs=0,
99 default=default,
100 required=required,
101 help=help,
102 )
103
104 def __call__(
105 self,
106 parser: argparse.ArgumentParser,
107 namespace: argparse.Namespace,
108 values: Union[str, Sequence[object], None],
109 option_string: Optional[str] = None,
110 ) -> None:
111 new_count = getattr(namespace, self.dest, 0) - 1
112 setattr(namespace, self.dest, new_count)
113 # todo Deprecate config.quiet
114 namespace.quiet = getattr(namespace, "quiet", 0) + 1
115
116
117 class TestShortLogReport(NamedTuple):
118 """Used to store the test status result category, shortletter and verbose word.
119 For example ``"rerun", "R", ("RERUN", {"yellow": True})``.
120
121 :ivar category:
122 The class of result, for example ``“passed”``, ``“skipped”``, ``“error”``, or the empty string.
123
124 :ivar letter:
125 The short letter shown as testing progresses, for example ``"."``, ``"s"``, ``"E"``, or the empty string.
126
127 :ivar word:
128 Verbose word is shown as testing progresses in verbose mode, for example ``"PASSED"``, ``"SKIPPED"``,
129 ``"ERROR"``, or the empty string.
130 """
131
132 category: str
133 letter: str
134 word: Union[str, Tuple[str, Mapping[str, bool]]]
135
136
137 def pytest_addoption(parser: Parser) -> None:
138 group = parser.getgroup("terminal reporting", "Reporting", after="general")
139 group._addoption(
140 "-v",
141 "--verbose",
142 action="count",
143 default=0,
144 dest="verbose",
145 help="Increase verbosity",
146 )
147 group._addoption(
148 "--no-header",
149 action="store_true",
150 default=False,
151 dest="no_header",
152 help="Disable header",
153 )
154 group._addoption(
155 "--no-summary",
156 action="store_true",
157 default=False,
158 dest="no_summary",
159 help="Disable summary",
160 )
161 group._addoption(
162 "-q",
163 "--quiet",
164 action=MoreQuietAction,
165 default=0,
166 dest="verbose",
167 help="Decrease verbosity",
168 )
169 group._addoption(
170 "--verbosity",
171 dest="verbose",
172 type=int,
173 default=0,
174 help="Set verbosity. Default: 0.",
175 )
176 group._addoption(
177 "-r",
178 action="store",
179 dest="reportchars",
180 default=_REPORTCHARS_DEFAULT,
181 metavar="chars",
182 help="Show extra test summary info as specified by chars: (f)ailed, "
183 "(E)rror, (s)kipped, (x)failed, (X)passed, "
184 "(p)assed, (P)assed with output, (a)ll except passed (p/P), or (A)ll. "
185 "(w)arnings are enabled by default (see --disable-warnings), "
186 "'N' can be used to reset the list. (default: 'fE').",
187 )
188 group._addoption(
189 "--disable-warnings",
190 "--disable-pytest-warnings",
191 default=False,
192 dest="disable_warnings",
193 action="store_true",
194 help="Disable warnings summary",
195 )
196 group._addoption(
197 "-l",
198 "--showlocals",
199 action="store_true",
200 dest="showlocals",
201 default=False,
202 help="Show locals in tracebacks (disabled by default)",
203 )
204 group._addoption(
205 "--no-showlocals",
206 action="store_false",
207 dest="showlocals",
208 help="Hide locals in tracebacks (negate --showlocals passed through addopts)",
209 )
210 group._addoption(
211 "--tb",
212 metavar="style",
213 action="store",
214 dest="tbstyle",
215 default="auto",
216 choices=["auto", "long", "short", "no", "line", "native"],
217 help="Traceback print mode (auto/long/short/line/native/no)",
218 )
219 group._addoption(
220 "--show-capture",
221 action="store",
222 dest="showcapture",
223 choices=["no", "stdout", "stderr", "log", "all"],
224 default="all",
225 help="Controls how captured stdout/stderr/log is shown on failed tests. "
226 "Default: all.",
227 )
228 group._addoption(
229 "--fulltrace",
230 "--full-trace",
231 action="store_true",
232 default=False,
233 help="Don't cut any tracebacks (default is to cut)",
234 )
235 group._addoption(
236 "--color",
237 metavar="color",
238 action="store",
239 dest="color",
240 default="auto",
241 choices=["yes", "no", "auto"],
242 help="Color terminal output (yes/no/auto)",
243 )
244 group._addoption(
245 "--code-highlight",
246 default="yes",
247 choices=["yes", "no"],
248 help="Whether code should be highlighted (only if --color is also enabled). "
249 "Default: yes.",
250 )
251
252 parser.addini(
253 "console_output_style",
254 help='Console output: "classic", or with additional progress information '
255 '("progress" (percentage) | "count" | "progress-even-when-capture-no" (forces '
256 "progress even when capture=no)",
257 default="progress",
258 )
259 Config._add_verbosity_ini(
260 parser,
261 Config.VERBOSITY_TEST_CASES,
262 help=(
263 "Specify a verbosity level for test case execution, overriding the main level. "
264 "Higher levels will provide more detailed information about each test case executed."
265 ),
266 )
267
268
269 def pytest_configure(config: Config) -> None:
270 reporter = TerminalReporter(config, sys.stdout)
271 config.pluginmanager.register(reporter, "terminalreporter")
272 if config.option.debug or config.option.traceconfig:
273
274 def mywriter(tags, args):
275 msg = " ".join(map(str, args))
276 reporter.write_line("[traceconfig] " + msg)
277
278 config.trace.root.setprocessor("pytest:config", mywriter)
279
280
281 def getreportopt(config: Config) -> str:
282 reportchars: str = config.option.reportchars
283
284 old_aliases = {"F", "S"}
285 reportopts = ""
286 for char in reportchars:
287 if char in old_aliases:
288 char = char.lower()
289 if char == "a":
290 reportopts = "sxXEf"
291 elif char == "A":
292 reportopts = "PpsxXEf"
293 elif char == "N":
294 reportopts = ""
295 elif char not in reportopts:
296 reportopts += char
297
298 if not config.option.disable_warnings and "w" not in reportopts:
299 reportopts = "w" + reportopts
300 elif config.option.disable_warnings and "w" in reportopts:
301 reportopts = reportopts.replace("w", "")
302
303 return reportopts
304
305
306 @hookimpl(trylast=True) # after _pytest.runner
307 def pytest_report_teststatus(report: BaseReport) -> Tuple[str, str, str]:
308 letter = "F"
309 if report.passed:
310 letter = "."
311 elif report.skipped:
312 letter = "s"
313
314 outcome: str = report.outcome
315 if report.when in ("collect", "setup", "teardown") and outcome == "failed":
316 outcome = "error"
317 letter = "E"
318
319 return outcome, letter, outcome.upper()
320
321
322 @dataclasses.dataclass
323 class WarningReport:
324 """Simple structure to hold warnings information captured by ``pytest_warning_recorded``.
325
326 :ivar str message:
327 User friendly message about the warning.
328 :ivar str|None nodeid:
329 nodeid that generated the warning (see ``get_location``).
330 :ivar tuple fslocation:
331 File system location of the source of the warning (see ``get_location``).
332 """
333
334 message: str
335 nodeid: Optional[str] = None
336 fslocation: Optional[Tuple[str, int]] = None
337
338 count_towards_summary: ClassVar = True
339
340 def get_location(self, config: Config) -> Optional[str]:
341 """Return the more user-friendly information about the location of a warning, or None."""
342 if self.nodeid:
343 return self.nodeid
344 if self.fslocation:
345 filename, linenum = self.fslocation
346 relpath = bestrelpath(config.invocation_params.dir, absolutepath(filename))
347 return f"{relpath}:{linenum}"
348 return None
349
350
351 @final
352 class TerminalReporter:
353 def __init__(self, config: Config, file: Optional[TextIO] = None) -> None:
354 import _pytest.config
355
356 self.config = config
357 self._numcollected = 0
358 self._session: Optional[Session] = None
359 self._showfspath: Optional[bool] = None
360
361 self.stats: Dict[str, List[Any]] = {}
362 self._main_color: Optional[str] = None
363 self._known_types: Optional[List[str]] = None
364 self.startpath = config.invocation_params.dir
365 if file is None:
366 file = sys.stdout
367 self._tw = _pytest.config.create_terminal_writer(config, file)
368 self._screen_width = self._tw.fullwidth
369 self.currentfspath: Union[None, Path, str, int] = None
370 self.reportchars = getreportopt(config)
371 self.hasmarkup = self._tw.hasmarkup
372 self.isatty = file.isatty()
373 self._progress_nodeids_reported: Set[str] = set()
374 self._show_progress_info = self._determine_show_progress_info()
375 self._collect_report_last_write: Optional[float] = None
376 self._already_displayed_warnings: Optional[int] = None
377 self._keyboardinterrupt_memo: Optional[ExceptionRepr] = None
378
379 def _determine_show_progress_info(self) -> Literal["progress", "count", False]:
380 """Return whether we should display progress information based on the current config."""
381 # do not show progress if we are not capturing output (#3038) unless explicitly
382 # overridden by progress-even-when-capture-no
383 if (
384 self.config.getoption("capture", "no") == "no"
385 and self.config.getini("console_output_style")
386 != "progress-even-when-capture-no"
387 ):
388 return False
389 # do not show progress if we are showing fixture setup/teardown
390 if self.config.getoption("setupshow", False):
391 return False
392 cfg: str = self.config.getini("console_output_style")
393 if cfg in {"progress", "progress-even-when-capture-no"}:
394 return "progress"
395 elif cfg == "count":
396 return "count"
397 else:
398 return False
399
400 @property
401 def verbosity(self) -> int:
402 verbosity: int = self.config.option.verbose
403 return verbosity
404
405 @property
406 def showheader(self) -> bool:
407 return self.verbosity >= 0
408
409 @property
410 def no_header(self) -> bool:
411 return bool(self.config.option.no_header)
412
413 @property
414 def no_summary(self) -> bool:
415 return bool(self.config.option.no_summary)
416
417 @property
418 def showfspath(self) -> bool:
419 if self._showfspath is None:
420 return self.config.get_verbosity(Config.VERBOSITY_TEST_CASES) >= 0
421 return self._showfspath
422
423 @showfspath.setter
424 def showfspath(self, value: Optional[bool]) -> None:
425 self._showfspath = value
426
427 @property
428 def showlongtestinfo(self) -> bool:
429 return self.config.get_verbosity(Config.VERBOSITY_TEST_CASES) > 0
430
431 def hasopt(self, char: str) -> bool:
432 char = {"xfailed": "x", "skipped": "s"}.get(char, char)
433 return char in self.reportchars
434
435 def write_fspath_result(self, nodeid: str, res, **markup: bool) -> None:
436 fspath = self.config.rootpath / nodeid.split("::")[0]
437 if self.currentfspath is None or fspath != self.currentfspath:
438 if self.currentfspath is not None and self._show_progress_info:
439 self._write_progress_information_filling_space()
440 self.currentfspath = fspath
441 relfspath = bestrelpath(self.startpath, fspath)
442 self._tw.line()
443 self._tw.write(relfspath + " ")
444 self._tw.write(res, flush=True, **markup)
445
446 def write_ensure_prefix(self, prefix: str, extra: str = "", **kwargs) -> None:
447 if self.currentfspath != prefix:
448 self._tw.line()
449 self.currentfspath = prefix
450 self._tw.write(prefix)
451 if extra:
452 self._tw.write(extra, **kwargs)
453 self.currentfspath = -2
454
455 def ensure_newline(self) -> None:
456 if self.currentfspath:
457 self._tw.line()
458 self.currentfspath = None
459
460 def wrap_write(
461 self,
462 content: str,
463 *,
464 flush: bool = False,
465 margin: int = 8,
466 line_sep: str = "\n",
467 **markup: bool,
468 ) -> None:
469 """Wrap message with margin for progress info."""
470 width_of_current_line = self._tw.width_of_current_line
471 wrapped = line_sep.join(
472 textwrap.wrap(
473 " " * width_of_current_line + content,
474 width=self._screen_width - margin,
475 drop_whitespace=True,
476 replace_whitespace=False,
477 ),
478 )
479 wrapped = wrapped[width_of_current_line:]
480 self._tw.write(wrapped, flush=flush, **markup)
481
482 def write(self, content: str, *, flush: bool = False, **markup: bool) -> None:
483 self._tw.write(content, flush=flush, **markup)
484
485 def flush(self) -> None:
486 self._tw.flush()
487
488 def write_line(self, line: Union[str, bytes], **markup: bool) -> None:
489 if not isinstance(line, str):
490 line = str(line, errors="replace")
491 self.ensure_newline()
492 self._tw.line(line, **markup)
493
494 def rewrite(self, line: str, **markup: bool) -> None:
495 """Rewinds the terminal cursor to the beginning and writes the given line.
496
497 :param erase:
498 If True, will also add spaces until the full terminal width to ensure
499 previous lines are properly erased.
500
501 The rest of the keyword arguments are markup instructions.
502 """
503 erase = markup.pop("erase", False)
504 if erase:
505 fill_count = self._tw.fullwidth - len(line) - 1
506 fill = " " * fill_count
507 else:
508 fill = ""
509 line = str(line)
510 self._tw.write("\r" + line + fill, **markup)
511
512 def write_sep(
513 self,
514 sep: str,
515 title: Optional[str] = None,
516 fullwidth: Optional[int] = None,
517 **markup: bool,
518 ) -> None:
519 self.ensure_newline()
520 self._tw.sep(sep, title, fullwidth, **markup)
521
522 def section(self, title: str, sep: str = "=", **kw: bool) -> None:
523 self._tw.sep(sep, title, **kw)
524
525 def line(self, msg: str, **kw: bool) -> None:
526 self._tw.line(msg, **kw)
527
528 def _add_stats(self, category: str, items: Sequence[Any]) -> None:
529 set_main_color = category not in self.stats
530 self.stats.setdefault(category, []).extend(items)
531 if set_main_color:
532 self._set_main_color()
533
534 def pytest_internalerror(self, excrepr: ExceptionRepr) -> bool:
535 for line in str(excrepr).split("\n"):
536 self.write_line("INTERNALERROR> " + line)
537 return True
538
539 def pytest_warning_recorded(
540 self,
541 warning_message: warnings.WarningMessage,
542 nodeid: str,
543 ) -> None:
544 from _pytest.warnings import warning_record_to_str
545
546 fslocation = warning_message.filename, warning_message.lineno
547 message = warning_record_to_str(warning_message)
548
549 warning_report = WarningReport(
550 fslocation=fslocation, message=message, nodeid=nodeid
551 )
552 self._add_stats("warnings", [warning_report])
553
554 def pytest_plugin_registered(self, plugin: _PluggyPlugin) -> None:
555 if self.config.option.traceconfig:
556 msg = f"PLUGIN registered: {plugin}"
557 # XXX This event may happen during setup/teardown time
558 # which unfortunately captures our output here
559 # which garbles our output if we use self.write_line.
560 self.write_line(msg)
561
562 def pytest_deselected(self, items: Sequence[Item]) -> None:
563 self._add_stats("deselected", items)
564
565 def pytest_runtest_logstart(
566 self, nodeid: str, location: Tuple[str, Optional[int], str]
567 ) -> None:
568 # Ensure that the path is printed before the
569 # 1st test of a module starts running.
570 if self.showlongtestinfo:
571 line = self._locationline(nodeid, *location)
572 self.write_ensure_prefix(line, "")
573 self.flush()
574 elif self.showfspath:
575 self.write_fspath_result(nodeid, "")
576 self.flush()
577
578 def pytest_runtest_logreport(self, report: TestReport) -> None:
579 self._tests_ran = True
580 rep = report
581
582 res = TestShortLogReport(
583 *self.config.hook.pytest_report_teststatus(report=rep, config=self.config)
584 )
585 category, letter, word = res.category, res.letter, res.word
586 if not isinstance(word, tuple):
587 markup = None
588 else:
589 word, markup = word
590 self._add_stats(category, [rep])
591 if not letter and not word:
592 # Probably passed setup/teardown.
593 return
594 running_xdist = hasattr(rep, "node")
595 if markup is None:
596 was_xfail = hasattr(report, "wasxfail")
597 if rep.passed and not was_xfail:
598 markup = {"green": True}
599 elif rep.passed and was_xfail:
600 markup = {"yellow": True}
601 elif rep.failed:
602 markup = {"red": True}
603 elif rep.skipped:
604 markup = {"yellow": True}
605 else:
606 markup = {}
607 if self.config.get_verbosity(Config.VERBOSITY_TEST_CASES) <= 0:
608 self._tw.write(letter, **markup)
609 else:
610 self._progress_nodeids_reported.add(rep.nodeid)
611 line = self._locationline(rep.nodeid, *rep.location)
612 if not running_xdist:
613 self.write_ensure_prefix(line, word, **markup)
614 if rep.skipped or hasattr(report, "wasxfail"):
615 reason = _get_raw_skip_reason(rep)
616 if self.config.get_verbosity(Config.VERBOSITY_TEST_CASES) < 2:
617 available_width = (
618 (self._tw.fullwidth - self._tw.width_of_current_line)
619 - len(" [100%]")
620 - 1
621 )
622 formatted_reason = _format_trimmed(
623 " ({})", reason, available_width
624 )
625 else:
626 formatted_reason = f" ({reason})"
627
628 if reason and formatted_reason is not None:
629 self.wrap_write(formatted_reason)
630 if self._show_progress_info:
631 self._write_progress_information_filling_space()
632 else:
633 self.ensure_newline()
634 self._tw.write("[%s]" % rep.node.gateway.id)
635 if self._show_progress_info:
636 self._tw.write(
637 self._get_progress_information_message() + " ", cyan=True
638 )
639 else:
640 self._tw.write(" ")
641 self._tw.write(word, **markup)
642 self._tw.write(" " + line)
643 self.currentfspath = -2
644 self.flush()
645
646 @property
647 def _is_last_item(self) -> bool:
648 assert self._session is not None
649 return len(self._progress_nodeids_reported) == self._session.testscollected
650
651 def pytest_runtest_logfinish(self, nodeid: str) -> None:
652 assert self._session
653 if (
654 self.config.get_verbosity(Config.VERBOSITY_TEST_CASES) <= 0
655 and self._show_progress_info
656 ):
657 if self._show_progress_info == "count":
658 num_tests = self._session.testscollected
659 progress_length = len(f" [{num_tests}/{num_tests}]")
660 else:
661 progress_length = len(" [100%]")
662
663 self._progress_nodeids_reported.add(nodeid)
664
665 if self._is_last_item:
666 self._write_progress_information_filling_space()
667 else:
668 main_color, _ = self._get_main_color()
669 w = self._width_of_current_line
670 past_edge = w + progress_length + 1 >= self._screen_width
671 if past_edge:
672 msg = self._get_progress_information_message()
673 self._tw.write(msg + "\n", **{main_color: True})
674
675 def _get_progress_information_message(self) -> str:
676 assert self._session
677 collected = self._session.testscollected
678 if self._show_progress_info == "count":
679 if collected:
680 progress = self._progress_nodeids_reported
681 counter_format = f"{{:{len(str(collected))}d}}"
682 format_string = f" [{counter_format}/{{}}]"
683 return format_string.format(len(progress), collected)
684 return f" [ {collected} / {collected} ]"
685 else:
686 if collected:
687 return (
688 f" [{len(self._progress_nodeids_reported) * 100 // collected:3d}%]"
689 )
690 return " [100%]"
691
692 def _write_progress_information_filling_space(self) -> None:
693 color, _ = self._get_main_color()
694 msg = self._get_progress_information_message()
695 w = self._width_of_current_line
696 fill = self._tw.fullwidth - w - 1
697 self.write(msg.rjust(fill), flush=True, **{color: True})
698
699 @property
700 def _width_of_current_line(self) -> int:
701 """Return the width of the current line."""
702 return self._tw.width_of_current_line
703
704 def pytest_collection(self) -> None:
705 if self.isatty:
706 if self.config.option.verbose >= 0:
707 self.write("collecting ... ", flush=True, bold=True)
708 self._collect_report_last_write = timing.time()
709 elif self.config.option.verbose >= 1:
710 self.write("collecting ... ", flush=True, bold=True)
711
712 def pytest_collectreport(self, report: CollectReport) -> None:
713 if report.failed:
714 self._add_stats("error", [report])
715 elif report.skipped:
716 self._add_stats("skipped", [report])
717 items = [x for x in report.result if isinstance(x, Item)]
718 self._numcollected += len(items)
719 if self.isatty:
720 self.report_collect()
721
722 def report_collect(self, final: bool = False) -> None:
723 if self.config.option.verbose < 0:
724 return
725
726 if not final:
727 # Only write "collecting" report every 0.5s.
728 t = timing.time()
729 if (
730 self._collect_report_last_write is not None
731 and self._collect_report_last_write > t - REPORT_COLLECTING_RESOLUTION
732 ):
733 return
734 self._collect_report_last_write = t
735
736 errors = len(self.stats.get("error", []))
737 skipped = len(self.stats.get("skipped", []))
738 deselected = len(self.stats.get("deselected", []))
739 selected = self._numcollected - deselected
740 line = "collected " if final else "collecting "
741 line += (
742 str(self._numcollected) + " item" + ("" if self._numcollected == 1 else "s")
743 )
744 if errors:
745 line += " / %d error%s" % (errors, "s" if errors != 1 else "")
746 if deselected:
747 line += " / %d deselected" % deselected
748 if skipped:
749 line += " / %d skipped" % skipped
750 if self._numcollected > selected:
751 line += " / %d selected" % selected
752 if self.isatty:
753 self.rewrite(line, bold=True, erase=True)
754 if final:
755 self.write("\n")
756 else:
757 self.write_line(line)
758
759 @hookimpl(trylast=True)
760 def pytest_sessionstart(self, session: "Session") -> None:
761 self._session = session
762 self._sessionstarttime = timing.time()
763 if not self.showheader:
764 return
765 self.write_sep("=", "test session starts", bold=True)
766 verinfo = platform.python_version()
767 if not self.no_header:
768 msg = f"platform {sys.platform} -- Python {verinfo}"
769 pypy_version_info = getattr(sys, "pypy_version_info", None)
770 if pypy_version_info:
771 verinfo = ".".join(map(str, pypy_version_info[:3]))
772 msg += f"[pypy-{verinfo}-{pypy_version_info[3]}]"
773 msg += f", pytest-{_pytest._version.version}, pluggy-{pluggy.__version__}"
774 if (
775 self.verbosity > 0
776 or self.config.option.debug
777 or getattr(self.config.option, "pastebin", None)
778 ):
779 msg += " -- " + str(sys.executable)
780 self.write_line(msg)
781 lines = self.config.hook.pytest_report_header(
782 config=self.config, start_path=self.startpath
783 )
784 self._write_report_lines_from_hooks(lines)
785
786 def _write_report_lines_from_hooks(
787 self, lines: Sequence[Union[str, Sequence[str]]]
788 ) -> None:
789 for line_or_lines in reversed(lines):
790 if isinstance(line_or_lines, str):
791 self.write_line(line_or_lines)
792 else:
793 for line in line_or_lines:
794 self.write_line(line)
795
796 def pytest_report_header(self, config: Config) -> List[str]:
797 result = [f"rootdir: {config.rootpath}"]
798
799 if config.inipath:
800 result.append("configfile: " + bestrelpath(config.rootpath, config.inipath))
801
802 if config.args_source == Config.ArgsSource.TESTPATHS:
803 testpaths: List[str] = config.getini("testpaths")
804 result.append("testpaths: {}".format(", ".join(testpaths)))
805
806 plugininfo = config.pluginmanager.list_plugin_distinfo()
807 if plugininfo:
808 result.append("plugins: %s" % ", ".join(_plugin_nameversions(plugininfo)))
809 return result
810
811 def pytest_collection_finish(self, session: "Session") -> None:
812 self.report_collect(True)
813
814 lines = self.config.hook.pytest_report_collectionfinish(
815 config=self.config,
816 start_path=self.startpath,
817 items=session.items,
818 )
819 self._write_report_lines_from_hooks(lines)
820
821 if self.config.getoption("collectonly"):
822 if session.items:
823 if self.config.option.verbose > -1:
824 self._tw.line("")
825 self._printcollecteditems(session.items)
826
827 failed = self.stats.get("failed")
828 if failed:
829 self._tw.sep("!", "collection failures")
830 for rep in failed:
831 rep.toterminal(self._tw)
832
833 def _printcollecteditems(self, items: Sequence[Item]) -> None:
834 test_cases_verbosity = self.config.get_verbosity(Config.VERBOSITY_TEST_CASES)
835 if test_cases_verbosity < 0:
836 if test_cases_verbosity < -1:
837 counts = Counter(item.nodeid.split("::", 1)[0] for item in items)
838 for name, count in sorted(counts.items()):
839 self._tw.line("%s: %d" % (name, count))
840 else:
841 for item in items:
842 self._tw.line(item.nodeid)
843 return
844 stack: List[Node] = []
845 indent = ""
846 for item in items:
847 needed_collectors = item.listchain()[1:] # strip root node
848 while stack:
849 if stack == needed_collectors[: len(stack)]:
850 break
851 stack.pop()
852 for col in needed_collectors[len(stack) :]:
853 stack.append(col)
854 indent = (len(stack) - 1) * " "
855 self._tw.line(f"{indent}{col}")
856 if test_cases_verbosity >= 1:
857 obj = getattr(col, "obj", None)
858 doc = inspect.getdoc(obj) if obj else None
859 if doc:
860 for line in doc.splitlines():
861 self._tw.line("{}{}".format(indent + " ", line))
862
863 @hookimpl(wrapper=True)
864 def pytest_sessionfinish(
865 self, session: "Session", exitstatus: Union[int, ExitCode]
866 ) -> Generator[None, None, None]:
867 result = yield
868 self._tw.line("")
869 summary_exit_codes = (
870 ExitCode.OK,
871 ExitCode.TESTS_FAILED,
872 ExitCode.INTERRUPTED,
873 ExitCode.USAGE_ERROR,
874 ExitCode.NO_TESTS_COLLECTED,
875 )
876 if exitstatus in summary_exit_codes and not self.no_summary:
877 self.config.hook.pytest_terminal_summary(
878 terminalreporter=self, exitstatus=exitstatus, config=self.config
879 )
880 if session.shouldfail:
881 self.write_sep("!", str(session.shouldfail), red=True)
882 if exitstatus == ExitCode.INTERRUPTED:
883 self._report_keyboardinterrupt()
884 self._keyboardinterrupt_memo = None
885 elif session.shouldstop:
886 self.write_sep("!", str(session.shouldstop), red=True)
887 self.summary_stats()
888 return result
889
890 @hookimpl(wrapper=True)
891 def pytest_terminal_summary(self) -> Generator[None, None, None]:
892 self.summary_errors()
893 self.summary_failures()
894 self.summary_xfailures()
895 self.summary_warnings()
896 self.summary_passes()
897 self.summary_xpasses()
898 try:
899 return (yield)
900 finally:
901 self.short_test_summary()
902 # Display any extra warnings from teardown here (if any).
903 self.summary_warnings()
904
905 def pytest_keyboard_interrupt(self, excinfo: ExceptionInfo[BaseException]) -> None:
906 self._keyboardinterrupt_memo = excinfo.getrepr(funcargs=True)
907
908 def pytest_unconfigure(self) -> None:
909 if self._keyboardinterrupt_memo is not None:
910 self._report_keyboardinterrupt()
911
912 def _report_keyboardinterrupt(self) -> None:
913 excrepr = self._keyboardinterrupt_memo
914 assert excrepr is not None
915 assert excrepr.reprcrash is not None
916 msg = excrepr.reprcrash.message
917 self.write_sep("!", msg)
918 if "KeyboardInterrupt" in msg:
919 if self.config.option.fulltrace:
920 excrepr.toterminal(self._tw)
921 else:
922 excrepr.reprcrash.toterminal(self._tw)
923 self._tw.line(
924 "(to show a full traceback on KeyboardInterrupt use --full-trace)",
925 yellow=True,
926 )
927
928 def _locationline(
929 self, nodeid: str, fspath: str, lineno: Optional[int], domain: str
930 ) -> str:
931 def mkrel(nodeid: str) -> str:
932 line = self.config.cwd_relative_nodeid(nodeid)
933 if domain and line.endswith(domain):
934 line = line[: -len(domain)]
935 values = domain.split("[")
936 values[0] = values[0].replace(".", "::") # don't replace '.' in params
937 line += "[".join(values)
938 return line
939
940 # collect_fspath comes from testid which has a "/"-normalized path.
941 if fspath:
942 res = mkrel(nodeid)
943 if self.verbosity >= 2 and nodeid.split("::")[0] != fspath.replace(
944 "\\", nodes.SEP
945 ):
946 res += " <- " + bestrelpath(self.startpath, Path(fspath))
947 else:
948 res = "[location]"
949 return res + " "
950
951 def _getfailureheadline(self, rep):
952 head_line = rep.head_line
953 if head_line:
954 return head_line
955 return "test session" # XXX?
956
957 def _getcrashline(self, rep):
958 try:
959 return str(rep.longrepr.reprcrash)
960 except AttributeError:
961 try:
962 return str(rep.longrepr)[:50]
963 except AttributeError:
964 return ""
965
966 #
967 # Summaries for sessionfinish.
968 #
969 def getreports(self, name: str):
970 return [x for x in self.stats.get(name, ()) if not hasattr(x, "_pdbshown")]
971
972 def summary_warnings(self) -> None:
973 if self.hasopt("w"):
974 all_warnings: Optional[List[WarningReport]] = self.stats.get("warnings")
975 if not all_warnings:
976 return
977
978 final = self._already_displayed_warnings is not None
979 if final:
980 warning_reports = all_warnings[self._already_displayed_warnings :]
981 else:
982 warning_reports = all_warnings
983 self._already_displayed_warnings = len(warning_reports)
984 if not warning_reports:
985 return
986
987 reports_grouped_by_message: Dict[str, List[WarningReport]] = {}
988 for wr in warning_reports:
989 reports_grouped_by_message.setdefault(wr.message, []).append(wr)
990
991 def collapsed_location_report(reports: List[WarningReport]) -> str:
992 locations = []
993 for w in reports:
994 location = w.get_location(self.config)
995 if location:
996 locations.append(location)
997
998 if len(locations) < 10:
999 return "\n".join(map(str, locations))
1000
1001 counts_by_filename = Counter(
1002 str(loc).split("::", 1)[0] for loc in locations
1003 )
1004 return "\n".join(
1005 "{}: {} warning{}".format(k, v, "s" if v > 1 else "")
1006 for k, v in counts_by_filename.items()
1007 )
1008
1009 title = "warnings summary (final)" if final else "warnings summary"
1010 self.write_sep("=", title, yellow=True, bold=False)
1011 for message, message_reports in reports_grouped_by_message.items():
1012 maybe_location = collapsed_location_report(message_reports)
1013 if maybe_location:
1014 self._tw.line(maybe_location)
1015 lines = message.splitlines()
1016 indented = "\n".join(" " + x for x in lines)
1017 message = indented.rstrip()
1018 else:
1019 message = message.rstrip()
1020 self._tw.line(message)
1021 self._tw.line()
1022 self._tw.line(
1023 "-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html"
1024 )
1025
1026 def summary_passes(self) -> None:
1027 self.summary_passes_combined("passed", "PASSES", "P")
1028
1029 def summary_xpasses(self) -> None:
1030 self.summary_passes_combined("xpassed", "XPASSES", "X")
1031
1032 def summary_passes_combined(
1033 self, which_reports: str, sep_title: str, needed_opt: str
1034 ) -> None:
1035 if self.config.option.tbstyle != "no":
1036 if self.hasopt(needed_opt):
1037 reports: List[TestReport] = self.getreports(which_reports)
1038 if not reports:
1039 return
1040 self.write_sep("=", sep_title)
1041 for rep in reports:
1042 if rep.sections:
1043 msg = self._getfailureheadline(rep)
1044 self.write_sep("_", msg, green=True, bold=True)
1045 self._outrep_summary(rep)
1046 self._handle_teardown_sections(rep.nodeid)
1047
1048 def _get_teardown_reports(self, nodeid: str) -> List[TestReport]:
1049 reports = self.getreports("")
1050 return [
1051 report
1052 for report in reports
1053 if report.when == "teardown" and report.nodeid == nodeid
1054 ]
1055
1056 def _handle_teardown_sections(self, nodeid: str) -> None:
1057 for report in self._get_teardown_reports(nodeid):
1058 self.print_teardown_sections(report)
1059
1060 def print_teardown_sections(self, rep: TestReport) -> None:
1061 showcapture = self.config.option.showcapture
1062 if showcapture == "no":
1063 return
1064 for secname, content in rep.sections:
1065 if showcapture != "all" and showcapture not in secname:
1066 continue
1067 if "teardown" in secname:
1068 self._tw.sep("-", secname)
1069 if content[-1:] == "\n":
1070 content = content[:-1]
1071 self._tw.line(content)
1072
1073 def summary_failures(self) -> None:
1074 self.summary_failures_combined("failed", "FAILURES")
1075
1076 def summary_xfailures(self) -> None:
1077 self.summary_failures_combined("xfailed", "XFAILURES", "x")
1078
1079 def summary_failures_combined(
1080 self, which_reports: str, sep_title: str, needed_opt: Optional[str] = None
1081 ) -> None:
1082 if self.config.option.tbstyle != "no":
1083 if not needed_opt or self.hasopt(needed_opt):
1084 reports: List[BaseReport] = self.getreports(which_reports)
1085 if not reports:
1086 return
1087 self.write_sep("=", sep_title)
1088 if self.config.option.tbstyle == "line":
1089 for rep in reports:
1090 line = self._getcrashline(rep)
1091 self.write_line(line)
1092 else:
1093 for rep in reports:
1094 msg = self._getfailureheadline(rep)
1095 self.write_sep("_", msg, red=True, bold=True)
1096 self._outrep_summary(rep)
1097 self._handle_teardown_sections(rep.nodeid)
1098
1099 def summary_errors(self) -> None:
1100 if self.config.option.tbstyle != "no":
1101 reports: List[BaseReport] = self.getreports("error")
1102 if not reports:
1103 return
1104 self.write_sep("=", "ERRORS")
1105 for rep in self.stats["error"]:
1106 msg = self._getfailureheadline(rep)
1107 if rep.when == "collect":
1108 msg = "ERROR collecting " + msg
1109 else:
1110 msg = f"ERROR at {rep.when} of {msg}"
1111 self.write_sep("_", msg, red=True, bold=True)
1112 self._outrep_summary(rep)
1113
1114 def _outrep_summary(self, rep: BaseReport) -> None:
1115 rep.toterminal(self._tw)
1116 showcapture = self.config.option.showcapture
1117 if showcapture == "no":
1118 return
1119 for secname, content in rep.sections:
1120 if showcapture != "all" and showcapture not in secname:
1121 continue
1122 self._tw.sep("-", secname)
1123 if content[-1:] == "\n":
1124 content = content[:-1]
1125 self._tw.line(content)
1126
1127 def summary_stats(self) -> None:
1128 if self.verbosity < -1:
1129 return
1130
1131 session_duration = timing.time() - self._sessionstarttime
1132 (parts, main_color) = self.build_summary_stats_line()
1133 line_parts = []
1134
1135 display_sep = self.verbosity >= 0
1136 if display_sep:
1137 fullwidth = self._tw.fullwidth
1138 for text, markup in parts:
1139 with_markup = self._tw.markup(text, **markup)
1140 if display_sep:
1141 fullwidth += len(with_markup) - len(text)
1142 line_parts.append(with_markup)
1143 msg = ", ".join(line_parts)
1144
1145 main_markup = {main_color: True}
1146 duration = f" in {format_session_duration(session_duration)}"
1147 duration_with_markup = self._tw.markup(duration, **main_markup)
1148 if display_sep:
1149 fullwidth += len(duration_with_markup) - len(duration)
1150 msg += duration_with_markup
1151
1152 if display_sep:
1153 markup_for_end_sep = self._tw.markup("", **main_markup)
1154 if markup_for_end_sep.endswith("\x1b[0m"):
1155 markup_for_end_sep = markup_for_end_sep[:-4]
1156 fullwidth += len(markup_for_end_sep)
1157 msg += markup_for_end_sep
1158
1159 if display_sep:
1160 self.write_sep("=", msg, fullwidth=fullwidth, **main_markup)
1161 else:
1162 self.write_line(msg, **main_markup)
1163
1164 def short_test_summary(self) -> None:
1165 if not self.reportchars:
1166 return
1167
1168 def show_simple(lines: List[str], *, stat: str) -> None:
1169 failed = self.stats.get(stat, [])
1170 if not failed:
1171 return
1172 config = self.config
1173 for rep in failed:
1174 color = _color_for_type.get(stat, _color_for_type_default)
1175 line = _get_line_with_reprcrash_message(
1176 config, rep, self._tw, {color: True}
1177 )
1178 lines.append(line)
1179
1180 def show_xfailed(lines: List[str]) -> None:
1181 xfailed = self.stats.get("xfailed", [])
1182 for rep in xfailed:
1183 verbose_word = rep._get_verbose_word(self.config)
1184 markup_word = self._tw.markup(
1185 verbose_word, **{_color_for_type["warnings"]: True}
1186 )
1187 nodeid = _get_node_id_with_markup(self._tw, self.config, rep)
1188 line = f"{markup_word} {nodeid}"
1189 reason = rep.wasxfail
1190 if reason:
1191 line += " - " + str(reason)
1192
1193 lines.append(line)
1194
1195 def show_xpassed(lines: List[str]) -> None:
1196 xpassed = self.stats.get("xpassed", [])
1197 for rep in xpassed:
1198 verbose_word = rep._get_verbose_word(self.config)
1199 markup_word = self._tw.markup(
1200 verbose_word, **{_color_for_type["warnings"]: True}
1201 )
1202 nodeid = _get_node_id_with_markup(self._tw, self.config, rep)
1203 line = f"{markup_word} {nodeid}"
1204 reason = rep.wasxfail
1205 if reason:
1206 line += " - " + str(reason)
1207 lines.append(line)
1208
1209 def show_skipped(lines: List[str]) -> None:
1210 skipped: List[CollectReport] = self.stats.get("skipped", [])
1211 fskips = _folded_skips(self.startpath, skipped) if skipped else []
1212 if not fskips:
1213 return
1214 verbose_word = skipped[0]._get_verbose_word(self.config)
1215 markup_word = self._tw.markup(
1216 verbose_word, **{_color_for_type["warnings"]: True}
1217 )
1218 prefix = "Skipped: "
1219 for num, fspath, lineno, reason in fskips:
1220 if reason.startswith(prefix):
1221 reason = reason[len(prefix) :]
1222 if lineno is not None:
1223 lines.append(
1224 "%s [%d] %s:%d: %s" % (markup_word, num, fspath, lineno, reason)
1225 )
1226 else:
1227 lines.append("%s [%d] %s: %s" % (markup_word, num, fspath, reason))
1228
1229 REPORTCHAR_ACTIONS: Mapping[str, Callable[[List[str]], None]] = {
1230 "x": show_xfailed,
1231 "X": show_xpassed,
1232 "f": partial(show_simple, stat="failed"),
1233 "s": show_skipped,
1234 "p": partial(show_simple, stat="passed"),
1235 "E": partial(show_simple, stat="error"),
1236 }
1237
1238 lines: List[str] = []
1239 for char in self.reportchars:
1240 action = REPORTCHAR_ACTIONS.get(char)
1241 if action: # skipping e.g. "P" (passed with output) here.
1242 action(lines)
1243
1244 if lines:
1245 self.write_sep("=", "short test summary info", cyan=True, bold=True)
1246 for line in lines:
1247 self.write_line(line)
1248
1249 def _get_main_color(self) -> Tuple[str, List[str]]:
1250 if self._main_color is None or self._known_types is None or self._is_last_item:
1251 self._set_main_color()
1252 assert self._main_color
1253 assert self._known_types
1254 return self._main_color, self._known_types
1255
1256 def _determine_main_color(self, unknown_type_seen: bool) -> str:
1257 stats = self.stats
1258 if "failed" in stats or "error" in stats:
1259 main_color = "red"
1260 elif "warnings" in stats or "xpassed" in stats or unknown_type_seen:
1261 main_color = "yellow"
1262 elif "passed" in stats or not self._is_last_item:
1263 main_color = "green"
1264 else:
1265 main_color = "yellow"
1266 return main_color
1267
1268 def _set_main_color(self) -> None:
1269 unknown_types: List[str] = []
1270 for found_type in self.stats:
1271 if found_type: # setup/teardown reports have an empty key, ignore them
1272 if found_type not in KNOWN_TYPES and found_type not in unknown_types:
1273 unknown_types.append(found_type)
1274 self._known_types = list(KNOWN_TYPES) + unknown_types
1275 self._main_color = self._determine_main_color(bool(unknown_types))
1276
1277 def build_summary_stats_line(self) -> Tuple[List[Tuple[str, Dict[str, bool]]], str]:
1278 """
1279 Build the parts used in the last summary stats line.
1280
1281 The summary stats line is the line shown at the end, "=== 12 passed, 2 errors in Xs===".
1282
1283 This function builds a list of the "parts" that make up for the text in that line, in
1284 the example above it would be:
1285
1286 [
1287 ("12 passed", {"green": True}),
1288 ("2 errors", {"red": True}
1289 ]
1290
1291 That last dict for each line is a "markup dictionary", used by TerminalWriter to
1292 color output.
1293
1294 The final color of the line is also determined by this function, and is the second
1295 element of the returned tuple.
1296 """
1297 if self.config.getoption("collectonly"):
1298 return self._build_collect_only_summary_stats_line()
1299 else:
1300 return self._build_normal_summary_stats_line()
1301
1302 def _get_reports_to_display(self, key: str) -> List[Any]:
1303 """Get test/collection reports for the given status key, such as `passed` or `error`."""
1304 reports = self.stats.get(key, [])
1305 return [x for x in reports if getattr(x, "count_towards_summary", True)]
1306
1307 def _build_normal_summary_stats_line(
1308 self,
1309 ) -> Tuple[List[Tuple[str, Dict[str, bool]]], str]:
1310 main_color, known_types = self._get_main_color()
1311 parts = []
1312
1313 for key in known_types:
1314 reports = self._get_reports_to_display(key)
1315 if reports:
1316 count = len(reports)
1317 color = _color_for_type.get(key, _color_for_type_default)
1318 markup = {color: True, "bold": color == main_color}
1319 parts.append(("%d %s" % pluralize(count, key), markup))
1320
1321 if not parts:
1322 parts = [("no tests ran", {_color_for_type_default: True})]
1323
1324 return parts, main_color
1325
1326 def _build_collect_only_summary_stats_line(
1327 self,
1328 ) -> Tuple[List[Tuple[str, Dict[str, bool]]], str]:
1329 deselected = len(self._get_reports_to_display("deselected"))
1330 errors = len(self._get_reports_to_display("error"))
1331
1332 if self._numcollected == 0:
1333 parts = [("no tests collected", {"yellow": True})]
1334 main_color = "yellow"
1335
1336 elif deselected == 0:
1337 main_color = "green"
1338 collected_output = "%d %s collected" % pluralize(self._numcollected, "test")
1339 parts = [(collected_output, {main_color: True})]
1340 else:
1341 all_tests_were_deselected = self._numcollected == deselected
1342 if all_tests_were_deselected:
1343 main_color = "yellow"
1344 collected_output = f"no tests collected ({deselected} deselected)"
1345 else:
1346 main_color = "green"
1347 selected = self._numcollected - deselected
1348 collected_output = f"{selected}/{self._numcollected} tests collected ({deselected} deselected)"
1349
1350 parts = [(collected_output, {main_color: True})]
1351
1352 if errors:
1353 main_color = _color_for_type["error"]
1354 parts += [("%d %s" % pluralize(errors, "error"), {main_color: True})]
1355
1356 return parts, main_color
1357
1358
1359 def _get_node_id_with_markup(tw: TerminalWriter, config: Config, rep: BaseReport):
1360 nodeid = config.cwd_relative_nodeid(rep.nodeid)
1361 path, *parts = nodeid.split("::")
1362 if parts:
1363 parts_markup = tw.markup("::".join(parts), bold=True)
1364 return path + "::" + parts_markup
1365 else:
1366 return path
1367
1368
1369 def _format_trimmed(format: str, msg: str, available_width: int) -> Optional[str]:
1370 """Format msg into format, ellipsizing it if doesn't fit in available_width.
1371
1372 Returns None if even the ellipsis can't fit.
1373 """
1374 # Only use the first line.
1375 i = msg.find("\n")
1376 if i != -1:
1377 msg = msg[:i]
1378
1379 ellipsis = "..."
1380 format_width = wcswidth(format.format(""))
1381 if format_width + len(ellipsis) > available_width:
1382 return None
1383
1384 if format_width + wcswidth(msg) > available_width:
1385 available_width -= len(ellipsis)
1386 msg = msg[:available_width]
1387 while format_width + wcswidth(msg) > available_width:
1388 msg = msg[:-1]
1389 msg += ellipsis
1390
1391 return format.format(msg)
1392
1393
1394 def _get_line_with_reprcrash_message(
1395 config: Config, rep: BaseReport, tw: TerminalWriter, word_markup: Dict[str, bool]
1396 ) -> str:
1397 """Get summary line for a report, trying to add reprcrash message."""
1398 verbose_word = rep._get_verbose_word(config)
1399 word = tw.markup(verbose_word, **word_markup)
1400 node = _get_node_id_with_markup(tw, config, rep)
1401
1402 line = f"{word} {node}"
1403 line_width = wcswidth(line)
1404
1405 try:
1406 # Type ignored intentionally -- possible AttributeError expected.
1407 msg = rep.longrepr.reprcrash.message # type: ignore[union-attr]
1408 except AttributeError:
1409 pass
1410 else:
1411 if running_on_ci() or config.option.verbose >= 2:
1412 msg = f" - {msg}"
1413 else:
1414 available_width = tw.fullwidth - line_width
1415 msg = _format_trimmed(" - {}", msg, available_width)
1416 if msg is not None:
1417 line += msg
1418
1419 return line
1420
1421
1422 def _folded_skips(
1423 startpath: Path,
1424 skipped: Sequence[CollectReport],
1425 ) -> List[Tuple[int, str, Optional[int], str]]:
1426 d: Dict[Tuple[str, Optional[int], str], List[CollectReport]] = {}
1427 for event in skipped:
1428 assert event.longrepr is not None
1429 assert isinstance(event.longrepr, tuple), (event, event.longrepr)
1430 assert len(event.longrepr) == 3, (event, event.longrepr)
1431 fspath, lineno, reason = event.longrepr
1432 # For consistency, report all fspaths in relative form.
1433 fspath = bestrelpath(startpath, Path(fspath))
1434 keywords = getattr(event, "keywords", {})
1435 # Folding reports with global pytestmark variable.
1436 # This is a workaround, because for now we cannot identify the scope of a skip marker
1437 # TODO: Revisit after marks scope would be fixed.
1438 if (
1439 event.when == "setup"
1440 and "skip" in keywords
1441 and "pytestmark" not in keywords
1442 ):
1443 key: Tuple[str, Optional[int], str] = (fspath, None, reason)
1444 else:
1445 key = (fspath, lineno, reason)
1446 d.setdefault(key, []).append(event)
1447 values: List[Tuple[int, str, Optional[int], str]] = []
1448 for key, events in d.items():
1449 values.append((len(events), *key))
1450 return values
1451
1452
1453 _color_for_type = {
1454 "failed": "red",
1455 "error": "red",
1456 "warnings": "yellow",
1457 "passed": "green",
1458 }
1459 _color_for_type_default = "yellow"
1460
1461
1462 def pluralize(count: int, noun: str) -> Tuple[int, str]:
1463 # No need to pluralize words such as `failed` or `passed`.
1464 if noun not in ["error", "warnings", "test"]:
1465 return count, noun
1466
1467 # The `warnings` key is plural. To avoid API breakage, we keep it that way but
1468 # set it to singular here so we can determine plurality in the same way as we do
1469 # for `error`.
1470 noun = noun.replace("warnings", "warning")
1471
1472 return count, noun + "s" if count != 1 else noun
1473
1474
1475 def _plugin_nameversions(plugininfo) -> List[str]:
1476 values: List[str] = []
1477 for plugin, dist in plugininfo:
1478 # Gets us name and version!
1479 name = f"{dist.project_name}-{dist.version}"
1480 # Questionable convenience, but it keeps things short.
1481 if name.startswith("pytest-"):
1482 name = name[7:]
1483 # We decided to print python package names they can have more than one plugin.
1484 if name not in values:
1485 values.append(name)
1486 return values
1487
1488
1489 def format_session_duration(seconds: float) -> str:
1490 """Format the given seconds in a human readable manner to show in the final summary."""
1491 if seconds < 60:
1492 return f"{seconds:.2f}s"
1493 else:
1494 dt = datetime.timedelta(seconds=int(seconds))
1495 return f"{seconds:.2f}s ({dt})"
1496
1497
1498 def _get_raw_skip_reason(report: TestReport) -> str:
1499 """Get the reason string of a skip/xfail/xpass test report.
1500
1501 The string is just the part given by the user.
1502 """
1503 if hasattr(report, "wasxfail"):
1504 reason = report.wasxfail
1505 if reason.startswith("reason: "):
1506 reason = reason[len("reason: ") :]
1507 return reason
1508 else:
1509 assert report.skipped
1510 assert isinstance(report.longrepr, tuple)
1511 _, _, reason = report.longrepr
1512 if reason.startswith("Skipped: "):
1513 reason = reason[len("Skipped: ") :]
1514 elif reason == "Skipped":
1515 reason = ""
1516 return reason