| 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 |
from __future__ import annotations |
| 8 |
|
| 9 |
import argparse |
| 10 |
from collections import Counter |
| 11 |
from collections.abc import Callable |
| 12 |
from collections.abc import Generator |
| 13 |
from collections.abc import Mapping |
| 14 |
from collections.abc import Sequence |
| 15 |
import dataclasses |
| 16 |
import datetime |
| 17 |
from functools import partial |
| 18 |
import inspect |
| 19 |
from pathlib import Path |
| 20 |
import platform |
| 21 |
import sys |
| 22 |
import textwrap |
| 23 |
from typing import Any |
| 24 |
from typing import ClassVar |
| 25 |
from typing import final |
| 26 |
from typing import Literal |
| 27 |
from typing import NamedTuple |
| 28 |
from typing import TextIO |
| 29 |
from typing import TYPE_CHECKING |
| 30 |
import warnings |
| 31 |
|
| 32 |
import pluggy |
| 33 |
|
| 34 |
from _pytest import compat |
| 35 |
from _pytest import nodes |
| 36 |
from _pytest import timing |
| 37 |
from _pytest._code import ExceptionInfo |
| 38 |
from _pytest._code.code import ExceptionRepr |
| 39 |
from _pytest._io import TerminalWriter |
| 40 |
from _pytest._io.wcwidth import wcswidth |
| 41 |
import _pytest._version |
| 42 |
from _pytest.compat import running_on_ci |
| 43 |
from _pytest.config import _PluggyPlugin |
| 44 |
from _pytest.config import Config |
| 45 |
from _pytest.config import ExitCode |
| 46 |
from _pytest.config import hookimpl |
| 47 |
from _pytest.config.argparsing import Parser |
| 48 |
from _pytest.nodes import Item |
| 49 |
from _pytest.nodes import Node |
| 50 |
from _pytest.pathlib import absolutepath |
| 51 |
from _pytest.pathlib import bestrelpath |
| 52 |
from _pytest.reports import BaseReport |
| 53 |
from _pytest.reports import CollectReport |
| 54 |
from _pytest.reports import TestReport |
| 55 |
|
| 56 |
|
| 57 |
if TYPE_CHECKING: |
| 58 |
from _pytest.main import Session |
| 59 |
|
| 60 |
|
| 61 |
REPORT_COLLECTING_RESOLUTION = 0.5 |
| 62 |
|
| 63 |
KNOWN_TYPES = ( |
| 64 |
"failed", |
| 65 |
"passed", |
| 66 |
"skipped", |
| 67 |
"deselected", |
| 68 |
"xfailed", |
| 69 |
"xpassed", |
| 70 |
"warnings", |
| 71 |
"error", |
| 72 |
"subtests passed", |
| 73 |
"subtests failed", |
| 74 |
"subtests skipped", |
| 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: str | None = 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: str | Sequence[object] | None, |
| 109 |
option_string: str | None = 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: 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( # private to use reserved lower-case short option |
| 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 |
"--no-fold-skipped", |
| 163 |
action="store_false", |
| 164 |
dest="fold_skipped", |
| 165 |
default=True, |
| 166 |
help="Do not fold skipped tests in short summary.", |
| 167 |
) |
| 168 |
group.addoption( |
| 169 |
"--force-short-summary", |
| 170 |
action="store_true", |
| 171 |
dest="force_short_summary", |
| 172 |
default=False, |
| 173 |
help="Force condensed summary output regardless of verbosity level.", |
| 174 |
) |
| 175 |
group._addoption( # private to use reserved lower-case short option |
| 176 |
"-q", |
| 177 |
"--quiet", |
| 178 |
action=MoreQuietAction, |
| 179 |
default=0, |
| 180 |
dest="verbose", |
| 181 |
help="Decrease verbosity", |
| 182 |
) |
| 183 |
group.addoption( |
| 184 |
"--verbosity", |
| 185 |
dest="verbose", |
| 186 |
type=int, |
| 187 |
default=0, |
| 188 |
help="Set verbosity. Default: 0.", |
| 189 |
) |
| 190 |
group._addoption( # private to use reserved lower-case short option |
| 191 |
"-r", |
| 192 |
"--report-chars", |
| 193 |
action="store", |
| 194 |
dest="reportchars", |
| 195 |
default=_REPORTCHARS_DEFAULT, |
| 196 |
metavar="chars", |
| 197 |
help="Show extra test summary info as specified by chars: (f)ailed, " |
| 198 |
"(E)rror, (s)kipped, (x)failed, (X)passed, " |
| 199 |
"(p)assed, (P)assed with output, (a)ll except passed (p/P), or (A)ll. " |
| 200 |
"(w)arnings are enabled by default (see --disable-warnings), " |
| 201 |
"'N' can be used to reset the list. (default: 'fE').", |
| 202 |
) |
| 203 |
group.addoption( |
| 204 |
"--disable-warnings", |
| 205 |
"--disable-pytest-warnings", |
| 206 |
default=False, |
| 207 |
dest="disable_warnings", |
| 208 |
action="store_true", |
| 209 |
help="Disable warnings summary", |
| 210 |
) |
| 211 |
group._addoption( # private to use reserved lower-case short option |
| 212 |
"-l", |
| 213 |
"--showlocals", |
| 214 |
action="store_true", |
| 215 |
dest="showlocals", |
| 216 |
default=False, |
| 217 |
help="Show locals in tracebacks (disabled by default)", |
| 218 |
) |
| 219 |
group.addoption( |
| 220 |
"--no-showlocals", |
| 221 |
action="store_false", |
| 222 |
dest="showlocals", |
| 223 |
help="Hide locals in tracebacks (negate --showlocals passed through addopts)", |
| 224 |
) |
| 225 |
group.addoption( |
| 226 |
"--tb", |
| 227 |
metavar="style", |
| 228 |
action="store", |
| 229 |
dest="tbstyle", |
| 230 |
default="auto", |
| 231 |
choices=["auto", "long", "short", "no", "line", "native"], |
| 232 |
help="Traceback print mode (auto/long/short/line/native/no)", |
| 233 |
) |
| 234 |
group.addoption( |
| 235 |
"--xfail-tb", |
| 236 |
action="store_true", |
| 237 |
dest="xfail_tb", |
| 238 |
default=False, |
| 239 |
help="Show tracebacks for xfail (as long as --tb != no)", |
| 240 |
) |
| 241 |
group.addoption( |
| 242 |
"--show-capture", |
| 243 |
action="store", |
| 244 |
dest="showcapture", |
| 245 |
choices=["no", "stdout", "stderr", "log", "all"], |
| 246 |
default="all", |
| 247 |
help="Controls how captured stdout/stderr/log is shown on failed tests. " |
| 248 |
"Default: all.", |
| 249 |
) |
| 250 |
group.addoption( |
| 251 |
"--fulltrace", |
| 252 |
"--full-trace", |
| 253 |
action="store_true", |
| 254 |
default=False, |
| 255 |
help="Don't cut any tracebacks (default is to cut)", |
| 256 |
) |
| 257 |
group.addoption( |
| 258 |
"--color", |
| 259 |
metavar="color", |
| 260 |
action="store", |
| 261 |
dest="color", |
| 262 |
default="auto", |
| 263 |
choices=["yes", "no", "auto"], |
| 264 |
help="Color terminal output (yes/no/auto)", |
| 265 |
) |
| 266 |
group.addoption( |
| 267 |
"--code-highlight", |
| 268 |
default="yes", |
| 269 |
choices=["yes", "no"], |
| 270 |
help="Whether code should be highlighted (only if --color is also enabled). " |
| 271 |
"Default: yes.", |
| 272 |
) |
| 273 |
|
| 274 |
parser.addini( |
| 275 |
"console_output_style", |
| 276 |
help='Console output: "classic", or with additional progress information ' |
| 277 |
'("progress" (percentage) | "count" | "progress-even-when-capture-no" (forces ' |
| 278 |
"progress even when capture=no)", |
| 279 |
default="progress", |
| 280 |
) |
| 281 |
Config._add_verbosity_ini( |
| 282 |
parser, |
| 283 |
Config.VERBOSITY_TEST_CASES, |
| 284 |
help=( |
| 285 |
"Specify a verbosity level for test case execution, overriding the main level. " |
| 286 |
"Higher levels will provide more detailed information about each test case executed." |
| 287 |
), |
| 288 |
) |
| 289 |
|
| 290 |
|
| 291 |
def pytest_configure(config: Config) -> None: |
| 292 |
reporter = TerminalReporter(config, sys.stdout) |
| 293 |
config.pluginmanager.register(reporter, "terminalreporter") |
| 294 |
if config.option.debug or config.option.traceconfig: |
| 295 |
|
| 296 |
def mywriter(tags, args): |
| 297 |
msg = " ".join(map(str, args)) |
| 298 |
reporter.write_line("[traceconfig] " + msg) |
| 299 |
|
| 300 |
config.trace.root.setprocessor("pytest:config", mywriter) |
| 301 |
|
| 302 |
# See terminalprogress.py. |
| 303 |
# On Windows it's safe to load by default. |
| 304 |
if sys.platform == "win32": |
| 305 |
config.pluginmanager.import_plugin("terminalprogress") |
| 306 |
|
| 307 |
|
| 308 |
def getreportopt(config: Config) -> str: |
| 309 |
reportchars: str = config.option.reportchars |
| 310 |
|
| 311 |
old_aliases = {"F", "S"} |
| 312 |
reportopts = "" |
| 313 |
for char in reportchars: |
| 314 |
if char in old_aliases: |
| 315 |
char = char.lower() |
| 316 |
if char == "a": |
| 317 |
reportopts = "sxXEf" |
| 318 |
elif char == "A": |
| 319 |
reportopts = "PpsxXEf" |
| 320 |
elif char == "N": |
| 321 |
reportopts = "" |
| 322 |
elif char not in reportopts: |
| 323 |
reportopts += char |
| 324 |
|
| 325 |
if not config.option.disable_warnings and "w" not in reportopts: |
| 326 |
reportopts = "w" + reportopts |
| 327 |
elif config.option.disable_warnings and "w" in reportopts: |
| 328 |
reportopts = reportopts.replace("w", "") |
| 329 |
|
| 330 |
return reportopts |
| 331 |
|
| 332 |
|
| 333 |
@hookimpl(trylast=True) # after _pytest.runner |
| 334 |
def pytest_report_teststatus(report: BaseReport) -> tuple[str, str, str]: |
| 335 |
letter = "F" |
| 336 |
if report.passed: |
| 337 |
letter = "." |
| 338 |
elif report.skipped: |
| 339 |
letter = "s" |
| 340 |
|
| 341 |
outcome: str = report.outcome |
| 342 |
if report.when in ("collect", "setup", "teardown") and outcome == "failed": |
| 343 |
outcome = "error" |
| 344 |
letter = "E" |
| 345 |
|
| 346 |
return outcome, letter, outcome.upper() |
| 347 |
|
| 348 |
|
| 349 |
@dataclasses.dataclass |
| 350 |
class WarningReport: |
| 351 |
"""Simple structure to hold warnings information captured by ``pytest_warning_recorded``. |
| 352 |
|
| 353 |
:ivar str message: |
| 354 |
User friendly message about the warning. |
| 355 |
:ivar str|None nodeid: |
| 356 |
nodeid that generated the warning (see ``get_location``). |
| 357 |
:ivar tuple fslocation: |
| 358 |
File system location of the source of the warning (see ``get_location``). |
| 359 |
""" |
| 360 |
|
| 361 |
message: str |
| 362 |
nodeid: str | None = None |
| 363 |
fslocation: tuple[str, int] | None = None |
| 364 |
|
| 365 |
count_towards_summary: ClassVar = True |
| 366 |
|
| 367 |
def get_location(self, config: Config) -> str | None: |
| 368 |
"""Return the more user-friendly information about the location of a warning, or None.""" |
| 369 |
if self.nodeid: |
| 370 |
return self.nodeid |
| 371 |
if self.fslocation: |
| 372 |
filename, linenum = self.fslocation |
| 373 |
relpath = bestrelpath(config.invocation_params.dir, absolutepath(filename)) |
| 374 |
return f"{relpath}:{linenum}" |
| 375 |
return None |
| 376 |
|
| 377 |
|
| 378 |
@final |
| 379 |
class TerminalReporter: |
| 380 |
def __init__(self, config: Config, file: TextIO | None = None) -> None: |
| 381 |
import _pytest.config |
| 382 |
|
| 383 |
self.config = config |
| 384 |
self._numcollected = 0 |
| 385 |
self._session: Session | None = None |
| 386 |
self._showfspath: bool | None = None |
| 387 |
|
| 388 |
self.stats: dict[str, list[Any]] = {} |
| 389 |
self._main_color: str | None = None |
| 390 |
self._known_types: list[str] | None = None |
| 391 |
self.startpath = config.invocation_params.dir |
| 392 |
if file is None: |
| 393 |
file = sys.stdout |
| 394 |
self._tw = _pytest.config.create_terminal_writer(config, file) |
| 395 |
self._screen_width = self._tw.fullwidth |
| 396 |
self.currentfspath: None | Path | str | int = None |
| 397 |
self.reportchars = getreportopt(config) |
| 398 |
self.foldskipped = config.option.fold_skipped |
| 399 |
self.hasmarkup = self._tw.hasmarkup |
| 400 |
# isatty should be a method but was wrongly implemented as a boolean. |
| 401 |
# We use CallableBool here to support both. |
| 402 |
self.isatty = compat.CallableBool(file.isatty()) |
| 403 |
self._progress_nodeids_reported: set[str] = set() |
| 404 |
self._timing_nodeids_reported: set[str] = set() |
| 405 |
self._show_progress_info = self._determine_show_progress_info() |
| 406 |
self._collect_report_last_write = timing.Instant() |
| 407 |
self._already_displayed_warnings: int | None = None |
| 408 |
self._keyboardinterrupt_memo: ExceptionRepr | None = None |
| 409 |
|
| 410 |
def _determine_show_progress_info( |
| 411 |
self, |
| 412 |
) -> Literal["progress", "count", "times", False]: |
| 413 |
"""Return whether we should display progress information based on the current config.""" |
| 414 |
# do not show progress if we are not capturing output (#3038) unless explicitly |
| 415 |
# overridden by progress-even-when-capture-no |
| 416 |
if ( |
| 417 |
self.config.getoption("capture", "no") == "no" |
| 418 |
and self.config.getini("console_output_style") |
| 419 |
!= "progress-even-when-capture-no" |
| 420 |
): |
| 421 |
return False |
| 422 |
# do not show progress if we are showing fixture setup/teardown |
| 423 |
if self.config.getoption("setupshow", False): |
| 424 |
return False |
| 425 |
cfg: str = self.config.getini("console_output_style") |
| 426 |
if cfg in {"progress", "progress-even-when-capture-no"}: |
| 427 |
return "progress" |
| 428 |
elif cfg == "count": |
| 429 |
return "count" |
| 430 |
elif cfg == "times": |
| 431 |
return "times" |
| 432 |
else: |
| 433 |
return False |
| 434 |
|
| 435 |
@property |
| 436 |
def verbosity(self) -> int: |
| 437 |
verbosity: int = self.config.option.verbose |
| 438 |
return verbosity |
| 439 |
|
| 440 |
@property |
| 441 |
def showheader(self) -> bool: |
| 442 |
return self.verbosity >= 0 |
| 443 |
|
| 444 |
@property |
| 445 |
def no_header(self) -> bool: |
| 446 |
return bool(self.config.option.no_header) |
| 447 |
|
| 448 |
@property |
| 449 |
def no_summary(self) -> bool: |
| 450 |
return bool(self.config.option.no_summary) |
| 451 |
|
| 452 |
@property |
| 453 |
def showfspath(self) -> bool: |
| 454 |
if self._showfspath is None: |
| 455 |
return self.config.get_verbosity(Config.VERBOSITY_TEST_CASES) >= 0 |
| 456 |
return self._showfspath |
| 457 |
|
| 458 |
@showfspath.setter |
| 459 |
def showfspath(self, value: bool | None) -> None: |
| 460 |
self._showfspath = value |
| 461 |
|
| 462 |
@property |
| 463 |
def showlongtestinfo(self) -> bool: |
| 464 |
return self.config.get_verbosity(Config.VERBOSITY_TEST_CASES) > 0 |
| 465 |
|
| 466 |
@property |
| 467 |
def reported_progress(self) -> int: |
| 468 |
"""The amount of items reported in the progress so far. |
| 469 |
|
| 470 |
:meta private: |
| 471 |
""" |
| 472 |
return len(self._progress_nodeids_reported) |
| 473 |
|
| 474 |
def hasopt(self, char: str) -> bool: |
| 475 |
char = {"xfailed": "x", "skipped": "s"}.get(char, char) |
| 476 |
return char in self.reportchars |
| 477 |
|
| 478 |
def write_fspath_result(self, nodeid: str, res: str, **markup: bool) -> None: |
| 479 |
fspath = self.config.rootpath / nodeid.split("::", maxsplit=1)[0] |
| 480 |
if self.currentfspath is None or fspath != self.currentfspath: |
| 481 |
if self.currentfspath is not None and self._show_progress_info: |
| 482 |
self._write_progress_information_filling_space() |
| 483 |
self.currentfspath = fspath |
| 484 |
relfspath = bestrelpath(self.startpath, fspath) |
| 485 |
self._tw.line() |
| 486 |
self._tw.write(relfspath + " ") |
| 487 |
self._tw.write(res, flush=True, **markup) |
| 488 |
|
| 489 |
def write_ensure_prefix(self, prefix: str, extra: str = "", **kwargs) -> None: |
| 490 |
if self.currentfspath != prefix: |
| 491 |
self._tw.line() |
| 492 |
self.currentfspath = prefix |
| 493 |
self._tw.write(prefix) |
| 494 |
if extra: |
| 495 |
self._tw.write(extra, **kwargs) |
| 496 |
self.currentfspath = -2 |
| 497 |
|
| 498 |
def ensure_newline(self) -> None: |
| 499 |
if self.currentfspath: |
| 500 |
self._tw.line() |
| 501 |
self.currentfspath = None |
| 502 |
|
| 503 |
def wrap_write( |
| 504 |
self, |
| 505 |
content: str, |
| 506 |
*, |
| 507 |
flush: bool = False, |
| 508 |
margin: int = 8, |
| 509 |
line_sep: str = "\n", |
| 510 |
**markup: bool, |
| 511 |
) -> None: |
| 512 |
"""Wrap message with margin for progress info.""" |
| 513 |
width_of_current_line = self._tw.width_of_current_line |
| 514 |
wrapped = line_sep.join( |
| 515 |
textwrap.wrap( |
| 516 |
" " * width_of_current_line + content, |
| 517 |
width=self._screen_width - margin, |
| 518 |
drop_whitespace=True, |
| 519 |
replace_whitespace=False, |
| 520 |
), |
| 521 |
) |
| 522 |
wrapped = wrapped[width_of_current_line:] |
| 523 |
self._tw.write(wrapped, flush=flush, **markup) |
| 524 |
|
| 525 |
def write(self, content: str, *, flush: bool = False, **markup: bool) -> None: |
| 526 |
self._tw.write(content, flush=flush, **markup) |
| 527 |
|
| 528 |
def write_raw(self, content: str, *, flush: bool = False) -> None: |
| 529 |
self._tw.write_raw(content, flush=flush) |
| 530 |
|
| 531 |
def flush(self) -> None: |
| 532 |
self._tw.flush() |
| 533 |
|
| 534 |
def write_line(self, line: str | bytes, **markup: bool) -> None: |
| 535 |
if not isinstance(line, str): |
| 536 |
line = str(line, errors="replace") |
| 537 |
self.ensure_newline() |
| 538 |
self._tw.line(line, **markup) |
| 539 |
|
| 540 |
def rewrite(self, line: str, **markup: bool) -> None: |
| 541 |
"""Rewinds the terminal cursor to the beginning and writes the given line. |
| 542 |
|
| 543 |
:param erase: |
| 544 |
If True, will also add spaces until the full terminal width to ensure |
| 545 |
previous lines are properly erased. |
| 546 |
|
| 547 |
The rest of the keyword arguments are markup instructions. |
| 548 |
""" |
| 549 |
erase = markup.pop("erase", False) |
| 550 |
if erase: |
| 551 |
fill_count = self._tw.fullwidth - len(line) - 1 |
| 552 |
fill = " " * fill_count |
| 553 |
else: |
| 554 |
fill = "" |
| 555 |
line = str(line) |
| 556 |
self._tw.write("\r" + line + fill, **markup) |
| 557 |
|
| 558 |
def write_sep( |
| 559 |
self, |
| 560 |
sep: str, |
| 561 |
title: str | None = None, |
| 562 |
fullwidth: int | None = None, |
| 563 |
**markup: bool, |
| 564 |
) -> None: |
| 565 |
self.ensure_newline() |
| 566 |
self._tw.sep(sep, title, fullwidth, **markup) |
| 567 |
|
| 568 |
def section(self, title: str, sep: str = "=", **kw: bool) -> None: |
| 569 |
self._tw.sep(sep, title, **kw) |
| 570 |
|
| 571 |
def line(self, msg: str, **kw: bool) -> None: |
| 572 |
self._tw.line(msg, **kw) |
| 573 |
|
| 574 |
def _add_stats(self, category: str, items: Sequence[Any]) -> None: |
| 575 |
set_main_color = category not in self.stats |
| 576 |
self.stats.setdefault(category, []).extend(items) |
| 577 |
if set_main_color: |
| 578 |
self._set_main_color() |
| 579 |
|
| 580 |
def pytest_internalerror(self, excrepr: ExceptionRepr) -> bool: |
| 581 |
for line in str(excrepr).split("\n"): |
| 582 |
self.write_line("INTERNALERROR> " + line) |
| 583 |
return True |
| 584 |
|
| 585 |
def pytest_warning_recorded( |
| 586 |
self, |
| 587 |
warning_message: warnings.WarningMessage, |
| 588 |
nodeid: str, |
| 589 |
) -> None: |
| 590 |
from _pytest.warnings import warning_record_to_str |
| 591 |
|
| 592 |
fslocation = warning_message.filename, warning_message.lineno |
| 593 |
message = warning_record_to_str(warning_message) |
| 594 |
|
| 595 |
warning_report = WarningReport( |
| 596 |
fslocation=fslocation, message=message, nodeid=nodeid |
| 597 |
) |
| 598 |
self._add_stats("warnings", [warning_report]) |
| 599 |
|
| 600 |
def pytest_plugin_registered(self, plugin: _PluggyPlugin) -> None: |
| 601 |
if self.config.option.traceconfig: |
| 602 |
msg = f"PLUGIN registered: {plugin}" |
| 603 |
# XXX This event may happen during setup/teardown time |
| 604 |
# which unfortunately captures our output here |
| 605 |
# which garbles our output if we use self.write_line. |
| 606 |
self.write_line(msg) |
| 607 |
|
| 608 |
def pytest_deselected(self, items: Sequence[Item]) -> None: |
| 609 |
self._add_stats("deselected", items) |
| 610 |
|
| 611 |
def pytest_runtest_logstart( |
| 612 |
self, nodeid: str, location: tuple[str, int | None, str] |
| 613 |
) -> None: |
| 614 |
fspath, lineno, domain = location |
| 615 |
# Ensure that the path is printed before the |
| 616 |
# 1st test of a module starts running. |
| 617 |
if self.showlongtestinfo: |
| 618 |
line = self._locationline(nodeid, fspath, lineno, domain) |
| 619 |
self.write_ensure_prefix(line, "") |
| 620 |
self.flush() |
| 621 |
elif self.showfspath: |
| 622 |
self.write_fspath_result(nodeid, "") |
| 623 |
self.flush() |
| 624 |
|
| 625 |
def pytest_runtest_logreport(self, report: TestReport) -> None: |
| 626 |
self._tests_ran = True |
| 627 |
rep = report |
| 628 |
|
| 629 |
res = TestShortLogReport( |
| 630 |
*self.config.hook.pytest_report_teststatus(report=rep, config=self.config) |
| 631 |
) |
| 632 |
category, letter, word = res.category, res.letter, res.word |
| 633 |
if not isinstance(word, tuple): |
| 634 |
markup = None |
| 635 |
else: |
| 636 |
word, markup = word |
| 637 |
self._add_stats(category, [rep]) |
| 638 |
if not letter and not word: |
| 639 |
# Probably passed setup/teardown. |
| 640 |
return |
| 641 |
if markup is None: |
| 642 |
was_xfail = hasattr(report, "wasxfail") |
| 643 |
if rep.passed and not was_xfail: |
| 644 |
markup = {"green": True} |
| 645 |
elif rep.passed and was_xfail: |
| 646 |
markup = {"yellow": True} |
| 647 |
elif rep.failed: |
| 648 |
markup = {"red": True} |
| 649 |
elif rep.skipped: |
| 650 |
markup = {"yellow": True} |
| 651 |
else: |
| 652 |
markup = {} |
| 653 |
self._progress_nodeids_reported.add(rep.nodeid) |
| 654 |
if self.config.get_verbosity(Config.VERBOSITY_TEST_CASES) <= 0: |
| 655 |
self._tw.write(letter, **markup) |
| 656 |
# When running in xdist, the logreport and logfinish of multiple |
| 657 |
# items are interspersed, e.g. `logreport`, `logreport`, |
| 658 |
# `logfinish`, `logfinish`. To avoid the "past edge" calculation |
| 659 |
# from getting confused and overflowing (#7166), do the past edge |
| 660 |
# printing here and not in logfinish, except for the 100% which |
| 661 |
# should only be printed after all teardowns are finished. |
| 662 |
if self._show_progress_info and not self._is_last_item: |
| 663 |
self._write_progress_information_if_past_edge() |
| 664 |
else: |
| 665 |
line = self._locationline(rep.nodeid, *rep.location) |
| 666 |
running_xdist = hasattr(rep, "node") |
| 667 |
if not running_xdist: |
| 668 |
self.write_ensure_prefix(line, word, **markup) |
| 669 |
if rep.skipped or hasattr(report, "wasxfail"): |
| 670 |
reason = _get_raw_skip_reason(rep) |
| 671 |
if self.config.get_verbosity(Config.VERBOSITY_TEST_CASES) < 2: |
| 672 |
available_width = ( |
| 673 |
(self._tw.fullwidth - self._tw.width_of_current_line) |
| 674 |
- len(" [100%]") |
| 675 |
- 1 |
| 676 |
) |
| 677 |
formatted_reason = _format_trimmed( |
| 678 |
" ({})", reason, available_width |
| 679 |
) |
| 680 |
else: |
| 681 |
formatted_reason = f" ({reason})" |
| 682 |
|
| 683 |
if reason and formatted_reason is not None: |
| 684 |
self.wrap_write(formatted_reason) |
| 685 |
if self._show_progress_info: |
| 686 |
self._write_progress_information_filling_space() |
| 687 |
else: |
| 688 |
self.ensure_newline() |
| 689 |
self._tw.write(f"[{rep.node.gateway.id}]") |
| 690 |
if self._show_progress_info: |
| 691 |
self._tw.write( |
| 692 |
self._get_progress_information_message() + " ", cyan=True |
| 693 |
) |
| 694 |
else: |
| 695 |
self._tw.write(" ") |
| 696 |
self._tw.write(word, **markup) |
| 697 |
self._tw.write(" " + line) |
| 698 |
self.currentfspath = -2 |
| 699 |
self.flush() |
| 700 |
|
| 701 |
@property |
| 702 |
def _is_last_item(self) -> bool: |
| 703 |
assert self._session is not None |
| 704 |
return self.reported_progress == self._session.testscollected |
| 705 |
|
| 706 |
@hookimpl(wrapper=True) |
| 707 |
def pytest_runtestloop(self) -> Generator[None, object, object]: |
| 708 |
result = yield |
| 709 |
|
| 710 |
# Write the final/100% progress -- deferred until the loop is complete. |
| 711 |
if ( |
| 712 |
self.config.get_verbosity(Config.VERBOSITY_TEST_CASES) <= 0 |
| 713 |
and self._show_progress_info |
| 714 |
and self.reported_progress |
| 715 |
): |
| 716 |
self._write_progress_information_filling_space() |
| 717 |
|
| 718 |
return result |
| 719 |
|
| 720 |
def _get_progress_information_message(self) -> str: |
| 721 |
assert self._session |
| 722 |
collected = self._session.testscollected |
| 723 |
if self._show_progress_info == "count": |
| 724 |
if collected: |
| 725 |
progress = self.reported_progress |
| 726 |
counter_format = f"{{:{len(str(collected))}d}}" |
| 727 |
format_string = f" [{counter_format}/{{}}]" |
| 728 |
return format_string.format(progress, collected) |
| 729 |
return f" [ {collected} / {collected} ]" |
| 730 |
if self._show_progress_info == "times": |
| 731 |
if not collected: |
| 732 |
return "" |
| 733 |
all_reports = ( |
| 734 |
self._get_reports_to_display("passed") |
| 735 |
+ self._get_reports_to_display("xpassed") |
| 736 |
+ self._get_reports_to_display("failed") |
| 737 |
+ self._get_reports_to_display("xfailed") |
| 738 |
+ self._get_reports_to_display("skipped") |
| 739 |
+ self._get_reports_to_display("error") |
| 740 |
+ self._get_reports_to_display("") |
| 741 |
) |
| 742 |
current_location = all_reports[-1].location[0] |
| 743 |
not_reported = [ |
| 744 |
r for r in all_reports if r.nodeid not in self._timing_nodeids_reported |
| 745 |
] |
| 746 |
tests_in_module = sum( |
| 747 |
i.location[0] == current_location for i in self._session.items |
| 748 |
) |
| 749 |
tests_completed = sum( |
| 750 |
r.when == "setup" |
| 751 |
for r in not_reported |
| 752 |
if r.location[0] == current_location |
| 753 |
) |
| 754 |
last_in_module = tests_completed == tests_in_module |
| 755 |
if self.showlongtestinfo or last_in_module: |
| 756 |
self._timing_nodeids_reported.update(r.nodeid for r in not_reported) |
| 757 |
return format_node_duration( |
| 758 |
sum(r.duration for r in not_reported if isinstance(r, TestReport)) |
| 759 |
) |
| 760 |
return "" |
| 761 |
if collected: |
| 762 |
return f" [{self.reported_progress * 100 // collected:3d}%]" |
| 763 |
return " [100%]" |
| 764 |
|
| 765 |
def _write_progress_information_if_past_edge(self) -> None: |
| 766 |
w = self._width_of_current_line |
| 767 |
if self._show_progress_info == "count": |
| 768 |
assert self._session |
| 769 |
num_tests = self._session.testscollected |
| 770 |
progress_length = len(f" [{num_tests}/{num_tests}]") |
| 771 |
elif self._show_progress_info == "times": |
| 772 |
progress_length = len(" 99h 59m") |
| 773 |
else: |
| 774 |
progress_length = len(" [100%]") |
| 775 |
past_edge = w + progress_length + 1 >= self._screen_width |
| 776 |
if past_edge: |
| 777 |
main_color, _ = self._get_main_color() |
| 778 |
msg = self._get_progress_information_message() |
| 779 |
self._tw.write(msg + "\n", **{main_color: True}) |
| 780 |
|
| 781 |
def _write_progress_information_filling_space(self) -> None: |
| 782 |
color, _ = self._get_main_color() |
| 783 |
msg = self._get_progress_information_message() |
| 784 |
w = self._width_of_current_line |
| 785 |
fill = self._tw.fullwidth - w - 1 |
| 786 |
self.write(msg.rjust(fill), flush=True, **{color: True}) |
| 787 |
|
| 788 |
@property |
| 789 |
def _width_of_current_line(self) -> int: |
| 790 |
"""Return the width of the current line.""" |
| 791 |
return self._tw.width_of_current_line |
| 792 |
|
| 793 |
def pytest_collection(self) -> None: |
| 794 |
if self.isatty(): |
| 795 |
if self.config.option.verbose >= 0: |
| 796 |
self.write("collecting ... ", flush=True, bold=True) |
| 797 |
elif self.config.option.verbose >= 1: |
| 798 |
self.write("collecting ... ", flush=True, bold=True) |
| 799 |
|
| 800 |
def pytest_collectreport(self, report: CollectReport) -> None: |
| 801 |
if report.failed: |
| 802 |
self._add_stats("error", [report]) |
| 803 |
elif report.skipped: |
| 804 |
self._add_stats("skipped", [report]) |
| 805 |
items = [x for x in report.result if isinstance(x, Item)] |
| 806 |
self._numcollected += len(items) |
| 807 |
if self.isatty(): |
| 808 |
self.report_collect() |
| 809 |
|
| 810 |
def report_collect(self, final: bool = False) -> None: |
| 811 |
if self.config.option.verbose < 0: |
| 812 |
return |
| 813 |
|
| 814 |
if not final: |
| 815 |
# Only write the "collecting" report every `REPORT_COLLECTING_RESOLUTION`. |
| 816 |
if ( |
| 817 |
self._collect_report_last_write.elapsed().seconds |
| 818 |
< REPORT_COLLECTING_RESOLUTION |
| 819 |
): |
| 820 |
return |
| 821 |
self._collect_report_last_write = timing.Instant() |
| 822 |
|
| 823 |
errors = len(self.stats.get("error", [])) |
| 824 |
skipped = len(self.stats.get("skipped", [])) |
| 825 |
deselected = len(self.stats.get("deselected", [])) |
| 826 |
selected = self._numcollected - deselected |
| 827 |
line = "collected " if final else "collecting " |
| 828 |
line += ( |
| 829 |
str(self._numcollected) + " item" + ("" if self._numcollected == 1 else "s") |
| 830 |
) |
| 831 |
if errors: |
| 832 |
line += f" / {errors} error{'s' if errors != 1 else ''}" |
| 833 |
if deselected: |
| 834 |
line += f" / {deselected} deselected" |
| 835 |
if skipped: |
| 836 |
line += f" / {skipped} skipped" |
| 837 |
if self._numcollected > selected: |
| 838 |
line += f" / {selected} selected" |
| 839 |
if self.isatty(): |
| 840 |
self.rewrite(line, bold=True, erase=True) |
| 841 |
if final: |
| 842 |
self.write("\n") |
| 843 |
else: |
| 844 |
self.write_line(line) |
| 845 |
|
| 846 |
@hookimpl(trylast=True) |
| 847 |
def pytest_sessionstart(self, session: Session) -> None: |
| 848 |
self._session = session |
| 849 |
self._session_start = timing.Instant() |
| 850 |
if not self.showheader: |
| 851 |
return |
| 852 |
self.write_sep("=", "test session starts", bold=True) |
| 853 |
verinfo = platform.python_version() |
| 854 |
if not self.no_header: |
| 855 |
msg = f"platform {sys.platform} -- Python {verinfo}" |
| 856 |
pypy_version_info = getattr(sys, "pypy_version_info", None) |
| 857 |
if pypy_version_info: |
| 858 |
verinfo = ".".join(map(str, pypy_version_info[:3])) |
| 859 |
msg += f"[pypy-{verinfo}-{pypy_version_info[3]}]" |
| 860 |
msg += f", pytest-{_pytest._version.version}, pluggy-{pluggy.__version__}" |
| 861 |
if ( |
| 862 |
self.verbosity > 0 |
| 863 |
or self.config.option.debug |
| 864 |
or getattr(self.config.option, "pastebin", None) |
| 865 |
): |
| 866 |
msg += " -- " + str(sys.executable) |
| 867 |
self.write_line(msg) |
| 868 |
lines = self.config.hook.pytest_report_header( |
| 869 |
config=self.config, start_path=self.startpath |
| 870 |
) |
| 871 |
self._write_report_lines_from_hooks(lines) |
| 872 |
|
| 873 |
def _write_report_lines_from_hooks( |
| 874 |
self, lines: Sequence[str | Sequence[str]] |
| 875 |
) -> None: |
| 876 |
for line_or_lines in reversed(lines): |
| 877 |
if isinstance(line_or_lines, str): |
| 878 |
self.write_line(line_or_lines) |
| 879 |
else: |
| 880 |
for line in line_or_lines: |
| 881 |
self.write_line(line) |
| 882 |
|
| 883 |
def pytest_report_header(self, config: Config) -> list[str]: |
| 884 |
result = [f"rootdir: {config.rootpath}"] |
| 885 |
|
| 886 |
if config.inipath: |
| 887 |
warning = "" |
| 888 |
if config._ignored_config_files: |
| 889 |
warning = f" (WARNING: ignoring pytest config in {', '.join(config._ignored_config_files)}!)" |
| 890 |
result.append( |
| 891 |
"configfile: " + bestrelpath(config.rootpath, config.inipath) + warning |
| 892 |
) |
| 893 |
|
| 894 |
if config.args_source == Config.ArgsSource.TESTPATHS: |
| 895 |
testpaths: list[str] = config.getini("testpaths") |
| 896 |
result.append("testpaths: {}".format(", ".join(testpaths))) |
| 897 |
|
| 898 |
plugininfo = config.pluginmanager.list_plugin_distinfo() |
| 899 |
if plugininfo: |
| 900 |
result.append( |
| 901 |
"plugins: {}".format(", ".join(_plugin_nameversions(plugininfo))) |
| 902 |
) |
| 903 |
return result |
| 904 |
|
| 905 |
def pytest_collection_finish(self, session: Session) -> None: |
| 906 |
self.report_collect(True) |
| 907 |
|
| 908 |
lines = self.config.hook.pytest_report_collectionfinish( |
| 909 |
config=self.config, |
| 910 |
start_path=self.startpath, |
| 911 |
items=session.items, |
| 912 |
) |
| 913 |
self._write_report_lines_from_hooks(lines) |
| 914 |
|
| 915 |
if self.config.getoption("collectonly"): |
| 916 |
if session.items: |
| 917 |
if self.config.option.verbose > -1: |
| 918 |
self._tw.line("") |
| 919 |
self._printcollecteditems(session.items) |
| 920 |
|
| 921 |
failed = self.stats.get("failed") |
| 922 |
if failed: |
| 923 |
self._tw.sep("!", "collection failures") |
| 924 |
for rep in failed: |
| 925 |
rep.toterminal(self._tw) |
| 926 |
|
| 927 |
def _printcollecteditems(self, items: Sequence[Item]) -> None: |
| 928 |
test_cases_verbosity = self.config.get_verbosity(Config.VERBOSITY_TEST_CASES) |
| 929 |
if test_cases_verbosity < 0: |
| 930 |
if test_cases_verbosity < -1: |
| 931 |
counts = Counter(item.nodeid.split("::", 1)[0] for item in items) |
| 932 |
for name, count in sorted(counts.items()): |
| 933 |
self._tw.line(f"{name}: {count}") |
| 934 |
else: |
| 935 |
for item in items: |
| 936 |
self._tw.line(item.nodeid) |
| 937 |
return |
| 938 |
stack: list[Node] = [] |
| 939 |
indent = "" |
| 940 |
for item in items: |
| 941 |
needed_collectors = item.listchain()[1:] # strip root node |
| 942 |
while stack: |
| 943 |
if stack == needed_collectors[: len(stack)]: |
| 944 |
break |
| 945 |
stack.pop() |
| 946 |
for col in needed_collectors[len(stack) :]: |
| 947 |
stack.append(col) |
| 948 |
indent = (len(stack) - 1) * " " |
| 949 |
self._tw.line(f"{indent}{col}") |
| 950 |
if test_cases_verbosity >= 1: |
| 951 |
obj = getattr(col, "obj", None) |
| 952 |
doc = inspect.getdoc(obj) if obj else None |
| 953 |
if doc: |
| 954 |
for line in doc.splitlines(): |
| 955 |
self._tw.line("{}{}".format(indent + " ", line)) |
| 956 |
|
| 957 |
@hookimpl(wrapper=True) |
| 958 |
def pytest_sessionfinish( |
| 959 |
self, session: Session, exitstatus: int | ExitCode |
| 960 |
) -> Generator[None]: |
| 961 |
result = yield |
| 962 |
self._tw.line("") |
| 963 |
summary_exit_codes = ( |
| 964 |
ExitCode.OK, |
| 965 |
ExitCode.TESTS_FAILED, |
| 966 |
ExitCode.INTERRUPTED, |
| 967 |
ExitCode.USAGE_ERROR, |
| 968 |
ExitCode.NO_TESTS_COLLECTED, |
| 969 |
ExitCode.MAX_WARNINGS_ERROR, |
| 970 |
) |
| 971 |
if exitstatus in summary_exit_codes and not self.no_summary: |
| 972 |
self.config.hook.pytest_terminal_summary( |
| 973 |
terminalreporter=self, exitstatus=exitstatus, config=self.config |
| 974 |
) |
| 975 |
# Check --max-warnings threshold after all warnings have been collected. |
| 976 |
max_warnings = self._get_max_warnings() |
| 977 |
if max_warnings is not None and session.exitstatus == ExitCode.OK: |
| 978 |
warning_count = len(self.stats.get("warnings", [])) |
| 979 |
if warning_count > max_warnings: |
| 980 |
session.exitstatus = ExitCode.MAX_WARNINGS_ERROR |
| 981 |
self.write_line( |
| 982 |
"Tests pass, but maximum allowed warnings exceeded: " |
| 983 |
f"{warning_count} > {max_warnings}", |
| 984 |
red=True, |
| 985 |
) |
| 986 |
if session.shouldfail: |
| 987 |
self.write_sep("!", str(session.shouldfail), red=True) |
| 988 |
if exitstatus == ExitCode.INTERRUPTED: |
| 989 |
self._report_keyboardinterrupt() |
| 990 |
self._keyboardinterrupt_memo = None |
| 991 |
elif session.shouldstop: |
| 992 |
self.write_sep("!", str(session.shouldstop), red=True) |
| 993 |
self.summary_stats() |
| 994 |
return result |
| 995 |
|
| 996 |
@hookimpl(wrapper=True) |
| 997 |
def pytest_terminal_summary(self) -> Generator[None]: |
| 998 |
self.summary_errors() |
| 999 |
self.summary_failures() |
| 1000 |
self.summary_xfailures() |
| 1001 |
self.summary_warnings() |
| 1002 |
self.summary_passes() |
| 1003 |
self.summary_xpasses() |
| 1004 |
try: |
| 1005 |
return (yield) |
| 1006 |
finally: |
| 1007 |
self.short_test_summary() |
| 1008 |
# Display any extra warnings from teardown here (if any). |
| 1009 |
self.summary_warnings() |
| 1010 |
|
| 1011 |
def pytest_keyboard_interrupt(self, excinfo: ExceptionInfo[BaseException]) -> None: |
| 1012 |
self._keyboardinterrupt_memo = excinfo.getrepr(funcargs=True) |
| 1013 |
|
| 1014 |
def pytest_unconfigure(self) -> None: |
| 1015 |
if self._keyboardinterrupt_memo is not None: |
| 1016 |
self._report_keyboardinterrupt() |
| 1017 |
|
| 1018 |
def _report_keyboardinterrupt(self) -> None: |
| 1019 |
excrepr = self._keyboardinterrupt_memo |
| 1020 |
assert excrepr is not None |
| 1021 |
assert excrepr.reprcrash is not None |
| 1022 |
msg = excrepr.reprcrash.message |
| 1023 |
self.write_sep("!", msg) |
| 1024 |
if "KeyboardInterrupt" in msg: |
| 1025 |
if self.config.option.fulltrace: |
| 1026 |
excrepr.toterminal(self._tw) |
| 1027 |
else: |
| 1028 |
excrepr.reprcrash.toterminal(self._tw) |
| 1029 |
self._tw.line( |
| 1030 |
"(to show a full traceback on KeyboardInterrupt use --full-trace)", |
| 1031 |
yellow=True, |
| 1032 |
) |
| 1033 |
|
| 1034 |
def _locationline( |
| 1035 |
self, nodeid: str, fspath: str, lineno: int | None, domain: str |
| 1036 |
) -> str: |
| 1037 |
def mkrel(nodeid: str) -> str: |
| 1038 |
line = self.config.cwd_relative_nodeid(nodeid) |
| 1039 |
if domain and line.endswith(domain): |
| 1040 |
line = line[: -len(domain)] |
| 1041 |
values = domain.split("[") |
| 1042 |
values[0] = values[0].replace(".", "::") # don't replace '.' in params |
| 1043 |
line += "[".join(values) |
| 1044 |
return line |
| 1045 |
|
| 1046 |
# fspath comes from testid which has a "/"-normalized path. |
| 1047 |
if fspath: |
| 1048 |
res = mkrel(nodeid) |
| 1049 |
if self.verbosity >= 2 and ( |
| 1050 |
nodeid.split("::", maxsplit=1)[0] != nodes.norm_sep(fspath) |
| 1051 |
): |
| 1052 |
res += " <- " + bestrelpath(self.startpath, Path(fspath)) |
| 1053 |
else: |
| 1054 |
res = "[location]" |
| 1055 |
return res + " " |
| 1056 |
|
| 1057 |
def _getfailureheadline(self, rep): |
| 1058 |
head_line = rep.head_line |
| 1059 |
if head_line: |
| 1060 |
return head_line |
| 1061 |
return "test session" # XXX? |
| 1062 |
|
| 1063 |
def _getcrashline(self, rep): |
| 1064 |
try: |
| 1065 |
return str(rep.longrepr.reprcrash) |
| 1066 |
except AttributeError: |
| 1067 |
try: |
| 1068 |
return str(rep.longrepr)[:50] |
| 1069 |
except AttributeError: |
| 1070 |
return "" |
| 1071 |
|
| 1072 |
def _get_max_warnings(self) -> int | None: |
| 1073 |
"""Return the max_warnings threshold, from CLI or INI, or None if unset.""" |
| 1074 |
value = self.config.option.max_warnings |
| 1075 |
if value is not None: |
| 1076 |
return int(value) |
| 1077 |
ini_value = self.config.getini("max_warnings") |
| 1078 |
if ini_value: |
| 1079 |
return int(ini_value) |
| 1080 |
return None |
| 1081 |
|
| 1082 |
# |
| 1083 |
# Summaries for sessionfinish. |
| 1084 |
# |
| 1085 |
def getreports(self, name: str): |
| 1086 |
return [x for x in self.stats.get(name, ()) if not hasattr(x, "_pdbshown")] |
| 1087 |
|
| 1088 |
def summary_warnings(self) -> None: |
| 1089 |
if self.hasopt("w"): |
| 1090 |
all_warnings: list[WarningReport] | None = self.stats.get("warnings") |
| 1091 |
if not all_warnings: |
| 1092 |
return |
| 1093 |
|
| 1094 |
final = self._already_displayed_warnings is not None |
| 1095 |
if final: |
| 1096 |
warning_reports = all_warnings[self._already_displayed_warnings :] |
| 1097 |
else: |
| 1098 |
warning_reports = all_warnings |
| 1099 |
self._already_displayed_warnings = len(warning_reports) |
| 1100 |
if not warning_reports: |
| 1101 |
return |
| 1102 |
|
| 1103 |
reports_grouped_by_message: dict[str, list[WarningReport]] = {} |
| 1104 |
for wr in warning_reports: |
| 1105 |
reports_grouped_by_message.setdefault(wr.message, []).append(wr) |
| 1106 |
|
| 1107 |
def collapsed_location_report(reports: list[WarningReport]) -> str: |
| 1108 |
locations = [] |
| 1109 |
for w in reports: |
| 1110 |
location = w.get_location(self.config) |
| 1111 |
if location: |
| 1112 |
locations.append(location) |
| 1113 |
|
| 1114 |
if len(locations) < 10: |
| 1115 |
return "\n".join(map(str, locations)) |
| 1116 |
|
| 1117 |
counts_by_filename = Counter( |
| 1118 |
str(loc).split("::", 1)[0] for loc in locations |
| 1119 |
) |
| 1120 |
return "\n".join( |
| 1121 |
"{}: {} warning{}".format(k, v, "s" if v > 1 else "") |
| 1122 |
for k, v in counts_by_filename.items() |
| 1123 |
) |
| 1124 |
|
| 1125 |
title = "warnings summary (final)" if final else "warnings summary" |
| 1126 |
self.write_sep("=", title, yellow=True, bold=False) |
| 1127 |
for message, message_reports in reports_grouped_by_message.items(): |
| 1128 |
maybe_location = collapsed_location_report(message_reports) |
| 1129 |
if maybe_location: |
| 1130 |
self._tw.line(maybe_location) |
| 1131 |
lines = message.splitlines() |
| 1132 |
indented = "\n".join(" " + x for x in lines) |
| 1133 |
message = indented.rstrip() |
| 1134 |
else: |
| 1135 |
message = message.rstrip() |
| 1136 |
self._tw.line(message) |
| 1137 |
self._tw.line() |
| 1138 |
self._tw.line( |
| 1139 |
"-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html" |
| 1140 |
) |
| 1141 |
|
| 1142 |
def summary_passes(self) -> None: |
| 1143 |
self.summary_passes_combined("passed", "PASSES", "P") |
| 1144 |
|
| 1145 |
def summary_xpasses(self) -> None: |
| 1146 |
self.summary_passes_combined("xpassed", "XPASSES", "X") |
| 1147 |
|
| 1148 |
def summary_passes_combined( |
| 1149 |
self, which_reports: str, sep_title: str, needed_opt: str |
| 1150 |
) -> None: |
| 1151 |
if self.config.option.tbstyle != "no": |
| 1152 |
if self.hasopt(needed_opt): |
| 1153 |
reports: list[TestReport] = self.getreports(which_reports) |
| 1154 |
if not reports: |
| 1155 |
return |
| 1156 |
self.write_sep("=", sep_title) |
| 1157 |
for rep in reports: |
| 1158 |
if rep.sections: |
| 1159 |
msg = self._getfailureheadline(rep) |
| 1160 |
self.write_sep("_", msg, green=True, bold=True) |
| 1161 |
self._outrep_summary(rep) |
| 1162 |
self._handle_teardown_sections(rep.nodeid) |
| 1163 |
|
| 1164 |
def _get_teardown_reports(self, nodeid: str) -> list[TestReport]: |
| 1165 |
reports = self.getreports("") |
| 1166 |
return [ |
| 1167 |
report |
| 1168 |
for report in reports |
| 1169 |
if report.when == "teardown" and report.nodeid == nodeid |
| 1170 |
] |
| 1171 |
|
| 1172 |
def _handle_teardown_sections(self, nodeid: str) -> None: |
| 1173 |
for report in self._get_teardown_reports(nodeid): |
| 1174 |
self.print_teardown_sections(report) |
| 1175 |
|
| 1176 |
def print_teardown_sections(self, rep: TestReport) -> None: |
| 1177 |
showcapture = self.config.option.showcapture |
| 1178 |
if showcapture == "no": |
| 1179 |
return |
| 1180 |
for secname, content in rep.sections: |
| 1181 |
if showcapture != "all" and showcapture not in secname: |
| 1182 |
continue |
| 1183 |
if "teardown" in secname: |
| 1184 |
self._tw.sep("-", secname) |
| 1185 |
if content[-1:] == "\n": |
| 1186 |
content = content[:-1] |
| 1187 |
self._tw.line(content) |
| 1188 |
|
| 1189 |
def summary_failures(self) -> None: |
| 1190 |
style = self.config.option.tbstyle |
| 1191 |
self.summary_failures_combined("failed", "FAILURES", style=style) |
| 1192 |
|
| 1193 |
def summary_xfailures(self) -> None: |
| 1194 |
show_tb = self.config.option.xfail_tb |
| 1195 |
style = self.config.option.tbstyle if show_tb else "no" |
| 1196 |
self.summary_failures_combined("xfailed", "XFAILURES", style=style) |
| 1197 |
|
| 1198 |
def summary_failures_combined( |
| 1199 |
self, |
| 1200 |
which_reports: str, |
| 1201 |
sep_title: str, |
| 1202 |
*, |
| 1203 |
style: str, |
| 1204 |
needed_opt: str | None = None, |
| 1205 |
) -> None: |
| 1206 |
if style != "no": |
| 1207 |
if not needed_opt or self.hasopt(needed_opt): |
| 1208 |
reports: list[BaseReport] = self.getreports(which_reports) |
| 1209 |
if not reports: |
| 1210 |
return |
| 1211 |
self.write_sep("=", sep_title) |
| 1212 |
if style == "line": |
| 1213 |
for rep in reports: |
| 1214 |
line = self._getcrashline(rep) |
| 1215 |
self._outrep_summary(rep) |
| 1216 |
self.write_line(line) |
| 1217 |
else: |
| 1218 |
for rep in reports: |
| 1219 |
msg = self._getfailureheadline(rep) |
| 1220 |
self.write_sep("_", msg, red=True, bold=True) |
| 1221 |
self._outrep_summary(rep) |
| 1222 |
self._handle_teardown_sections(rep.nodeid) |
| 1223 |
|
| 1224 |
def summary_errors(self) -> None: |
| 1225 |
if self.config.option.tbstyle != "no": |
| 1226 |
reports: list[BaseReport] = self.getreports("error") |
| 1227 |
if not reports: |
| 1228 |
return |
| 1229 |
self.write_sep("=", "ERRORS") |
| 1230 |
for rep in self.stats["error"]: |
| 1231 |
msg = self._getfailureheadline(rep) |
| 1232 |
if rep.when == "collect": |
| 1233 |
msg = "ERROR collecting " + msg |
| 1234 |
else: |
| 1235 |
msg = f"ERROR at {rep.when} of {msg}" |
| 1236 |
self.write_sep("_", msg, red=True, bold=True) |
| 1237 |
self._outrep_summary(rep) |
| 1238 |
|
| 1239 |
def _outrep_summary(self, rep: BaseReport) -> None: |
| 1240 |
rep.toterminal(self._tw) |
| 1241 |
showcapture = self.config.option.showcapture |
| 1242 |
if showcapture == "no": |
| 1243 |
return |
| 1244 |
for secname, content in rep.sections: |
| 1245 |
if showcapture != "all" and showcapture not in secname: |
| 1246 |
continue |
| 1247 |
self._tw.sep("-", secname) |
| 1248 |
if content[-1:] == "\n": |
| 1249 |
content = content[:-1] |
| 1250 |
self._tw.line(content) |
| 1251 |
|
| 1252 |
def summary_stats(self) -> None: |
| 1253 |
if self.verbosity < -1: |
| 1254 |
return |
| 1255 |
|
| 1256 |
session_duration = self._session_start.elapsed() |
| 1257 |
(parts, main_color) = self.build_summary_stats_line() |
| 1258 |
line_parts = [] |
| 1259 |
|
| 1260 |
display_sep = self.verbosity >= 0 |
| 1261 |
if display_sep: |
| 1262 |
fullwidth = self._tw.fullwidth |
| 1263 |
for text, markup in parts: |
| 1264 |
with_markup = self._tw.markup(text, **markup) |
| 1265 |
if display_sep: |
| 1266 |
fullwidth += len(with_markup) - len(text) |
| 1267 |
line_parts.append(with_markup) |
| 1268 |
msg = ", ".join(line_parts) |
| 1269 |
|
| 1270 |
main_markup = {main_color: True} |
| 1271 |
duration = f" in {format_session_duration(session_duration.seconds)}" |
| 1272 |
duration_with_markup = self._tw.markup(duration, **main_markup) |
| 1273 |
if display_sep: |
| 1274 |
fullwidth += len(duration_with_markup) - len(duration) |
| 1275 |
msg += duration_with_markup |
| 1276 |
|
| 1277 |
if display_sep: |
| 1278 |
markup_for_end_sep = self._tw.markup("", **main_markup) |
| 1279 |
if markup_for_end_sep.endswith("\x1b[0m"): |
| 1280 |
markup_for_end_sep = markup_for_end_sep[:-4] |
| 1281 |
fullwidth += len(markup_for_end_sep) |
| 1282 |
msg += markup_for_end_sep |
| 1283 |
|
| 1284 |
if display_sep: |
| 1285 |
self.write_sep("=", msg, fullwidth=fullwidth, **main_markup) |
| 1286 |
else: |
| 1287 |
self.write_line(msg, **main_markup) |
| 1288 |
|
| 1289 |
def short_test_summary(self) -> None: |
| 1290 |
if not self.reportchars: |
| 1291 |
return |
| 1292 |
|
| 1293 |
def show_simple(lines: list[str], *, stat: str) -> None: |
| 1294 |
failed = self.stats.get(stat, []) |
| 1295 |
if not failed: |
| 1296 |
return |
| 1297 |
config = self.config |
| 1298 |
for rep in failed: |
| 1299 |
color = _color_for_type.get(stat, _color_for_type_default) |
| 1300 |
line = _get_line_with_reprcrash_message( |
| 1301 |
config, rep, self._tw, {color: True} |
| 1302 |
) |
| 1303 |
lines.append(line) |
| 1304 |
|
| 1305 |
def show_xfailed(lines: list[str]) -> None: |
| 1306 |
xfailed = self.stats.get("xfailed", []) |
| 1307 |
for rep in xfailed: |
| 1308 |
verbose_word, verbose_markup = rep._get_verbose_word_with_markup( |
| 1309 |
self.config, {_color_for_type["warnings"]: True} |
| 1310 |
) |
| 1311 |
markup_word = self._tw.markup(verbose_word, **verbose_markup) |
| 1312 |
nodeid = _get_node_id_with_markup(self._tw, self.config, rep) |
| 1313 |
line = f"{markup_word} {nodeid}" |
| 1314 |
reason = rep.wasxfail |
| 1315 |
if reason: |
| 1316 |
line += " - " + str(reason) |
| 1317 |
|
| 1318 |
lines.append(line) |
| 1319 |
|
| 1320 |
def show_xpassed(lines: list[str]) -> None: |
| 1321 |
xpassed = self.stats.get("xpassed", []) |
| 1322 |
for rep in xpassed: |
| 1323 |
verbose_word, verbose_markup = rep._get_verbose_word_with_markup( |
| 1324 |
self.config, {_color_for_type["warnings"]: True} |
| 1325 |
) |
| 1326 |
markup_word = self._tw.markup(verbose_word, **verbose_markup) |
| 1327 |
nodeid = _get_node_id_with_markup(self._tw, self.config, rep) |
| 1328 |
line = f"{markup_word} {nodeid}" |
| 1329 |
reason = rep.wasxfail |
| 1330 |
if reason: |
| 1331 |
line += " - " + str(reason) |
| 1332 |
lines.append(line) |
| 1333 |
|
| 1334 |
def show_skipped_folded(lines: list[str]) -> None: |
| 1335 |
skipped: list[CollectReport] = self.stats.get("skipped", []) |
| 1336 |
fskips = _folded_skips(self.startpath, skipped) if skipped else [] |
| 1337 |
if not fskips: |
| 1338 |
return |
| 1339 |
verbose_word, verbose_markup = skipped[0]._get_verbose_word_with_markup( |
| 1340 |
self.config, {_color_for_type["warnings"]: True} |
| 1341 |
) |
| 1342 |
markup_word = self._tw.markup(verbose_word, **verbose_markup) |
| 1343 |
prefix = "Skipped: " |
| 1344 |
for num, fspath, lineno, reason in fskips: |
| 1345 |
if reason.startswith(prefix): |
| 1346 |
reason = reason[len(prefix) :] |
| 1347 |
if lineno is not None: |
| 1348 |
lines.append(f"{markup_word} [{num}] {fspath}:{lineno}: {reason}") |
| 1349 |
else: |
| 1350 |
lines.append(f"{markup_word} [{num}] {fspath}: {reason}") |
| 1351 |
|
| 1352 |
def show_skipped_unfolded(lines: list[str]) -> None: |
| 1353 |
skipped: list[CollectReport] = self.stats.get("skipped", []) |
| 1354 |
|
| 1355 |
for rep in skipped: |
| 1356 |
assert rep.longrepr is not None |
| 1357 |
assert isinstance(rep.longrepr, tuple), (rep, rep.longrepr) |
| 1358 |
assert len(rep.longrepr) == 3, (rep, rep.longrepr) |
| 1359 |
|
| 1360 |
verbose_word, verbose_markup = rep._get_verbose_word_with_markup( |
| 1361 |
self.config, {_color_for_type["warnings"]: True} |
| 1362 |
) |
| 1363 |
markup_word = self._tw.markup(verbose_word, **verbose_markup) |
| 1364 |
nodeid = _get_node_id_with_markup(self._tw, self.config, rep) |
| 1365 |
line = f"{markup_word} {nodeid}" |
| 1366 |
reason = rep.longrepr[2] |
| 1367 |
if reason: |
| 1368 |
line += " - " + str(reason) |
| 1369 |
lines.append(line) |
| 1370 |
|
| 1371 |
def show_skipped(lines: list[str]) -> None: |
| 1372 |
if self.foldskipped: |
| 1373 |
show_skipped_folded(lines) |
| 1374 |
else: |
| 1375 |
show_skipped_unfolded(lines) |
| 1376 |
|
| 1377 |
REPORTCHAR_ACTIONS: Mapping[str, Callable[[list[str]], None]] = { |
| 1378 |
"x": show_xfailed, |
| 1379 |
"X": show_xpassed, |
| 1380 |
"f": partial(show_simple, stat="failed"), |
| 1381 |
"s": show_skipped, |
| 1382 |
"p": partial(show_simple, stat="passed"), |
| 1383 |
"E": partial(show_simple, stat="error"), |
| 1384 |
} |
| 1385 |
|
| 1386 |
lines: list[str] = [] |
| 1387 |
for char in self.reportchars: |
| 1388 |
action = REPORTCHAR_ACTIONS.get(char) |
| 1389 |
if action: # skipping e.g. "P" (passed with output) here. |
| 1390 |
action(lines) |
| 1391 |
|
| 1392 |
if lines: |
| 1393 |
self.write_sep("=", "short test summary info", cyan=True, bold=True) |
| 1394 |
for line in lines: |
| 1395 |
self.write_line(line) |
| 1396 |
|
| 1397 |
def _get_main_color(self) -> tuple[str, list[str]]: |
| 1398 |
if self._main_color is None or self._known_types is None or self._is_last_item: |
| 1399 |
self._set_main_color() |
| 1400 |
assert self._main_color |
| 1401 |
assert self._known_types |
| 1402 |
return self._main_color, self._known_types |
| 1403 |
|
| 1404 |
def _determine_main_color(self, unknown_type_seen: bool) -> str: |
| 1405 |
stats = self.stats |
| 1406 |
if "failed" in stats or "error" in stats: |
| 1407 |
main_color = "red" |
| 1408 |
elif "warnings" in stats or "xpassed" in stats or unknown_type_seen: |
| 1409 |
main_color = "yellow" |
| 1410 |
elif "passed" in stats or not self._is_last_item: |
| 1411 |
main_color = "green" |
| 1412 |
else: |
| 1413 |
main_color = "yellow" |
| 1414 |
return main_color |
| 1415 |
|
| 1416 |
def _set_main_color(self) -> None: |
| 1417 |
unknown_types: list[str] = [] |
| 1418 |
for found_type in self.stats: |
| 1419 |
if found_type: # setup/teardown reports have an empty key, ignore them |
| 1420 |
if found_type not in KNOWN_TYPES and found_type not in unknown_types: |
| 1421 |
unknown_types.append(found_type) |
| 1422 |
self._known_types = list(KNOWN_TYPES) + unknown_types |
| 1423 |
self._main_color = self._determine_main_color(bool(unknown_types)) |
| 1424 |
|
| 1425 |
def build_summary_stats_line(self) -> tuple[list[tuple[str, dict[str, bool]]], str]: |
| 1426 |
""" |
| 1427 |
Build the parts used in the last summary stats line. |
| 1428 |
|
| 1429 |
The summary stats line is the line shown at the end, "=== 12 passed, 2 errors in Xs===". |
| 1430 |
|
| 1431 |
This function builds a list of the "parts" that make up for the text in that line, in |
| 1432 |
the example above it would be:: |
| 1433 |
|
| 1434 |
[ |
| 1435 |
("12 passed", {"green": True}), |
| 1436 |
("2 errors", {"red": True} |
| 1437 |
] |
| 1438 |
|
| 1439 |
That last dict for each line is a "markup dictionary", used by TerminalWriter to |
| 1440 |
color output. |
| 1441 |
|
| 1442 |
The final color of the line is also determined by this function, and is the second |
| 1443 |
element of the returned tuple. |
| 1444 |
""" |
| 1445 |
if self.config.getoption("collectonly"): |
| 1446 |
return self._build_collect_only_summary_stats_line() |
| 1447 |
else: |
| 1448 |
return self._build_normal_summary_stats_line() |
| 1449 |
|
| 1450 |
def _get_reports_to_display(self, key: str) -> list[Any]: |
| 1451 |
"""Get test/collection reports for the given status key, such as `passed` or `error`.""" |
| 1452 |
reports = self.stats.get(key, []) |
| 1453 |
return [x for x in reports if getattr(x, "count_towards_summary", True)] |
| 1454 |
|
| 1455 |
def _build_normal_summary_stats_line( |
| 1456 |
self, |
| 1457 |
) -> tuple[list[tuple[str, dict[str, bool]]], str]: |
| 1458 |
main_color, known_types = self._get_main_color() |
| 1459 |
parts = [] |
| 1460 |
|
| 1461 |
for key in known_types: |
| 1462 |
reports = self._get_reports_to_display(key) |
| 1463 |
if reports: |
| 1464 |
count = len(reports) |
| 1465 |
color = _color_for_type.get(key, _color_for_type_default) |
| 1466 |
markup = {color: True, "bold": color == main_color} |
| 1467 |
parts.append(("%d %s" % pluralize(count, key), markup)) # noqa: UP031 |
| 1468 |
|
| 1469 |
if not parts: |
| 1470 |
parts = [("no tests ran", {_color_for_type_default: True})] |
| 1471 |
|
| 1472 |
return parts, main_color |
| 1473 |
|
| 1474 |
def _build_collect_only_summary_stats_line( |
| 1475 |
self, |
| 1476 |
) -> tuple[list[tuple[str, dict[str, bool]]], str]: |
| 1477 |
deselected = len(self._get_reports_to_display("deselected")) |
| 1478 |
errors = len(self._get_reports_to_display("error")) |
| 1479 |
|
| 1480 |
if self._numcollected == 0: |
| 1481 |
parts = [("no tests collected", {"yellow": True})] |
| 1482 |
main_color = "yellow" |
| 1483 |
|
| 1484 |
elif deselected == 0: |
| 1485 |
main_color = "green" |
| 1486 |
collected_output = "%d %s collected" % pluralize(self._numcollected, "test") # noqa: UP031 |
| 1487 |
parts = [(collected_output, {main_color: True})] |
| 1488 |
else: |
| 1489 |
all_tests_were_deselected = self._numcollected == deselected |
| 1490 |
if all_tests_were_deselected: |
| 1491 |
main_color = "yellow" |
| 1492 |
collected_output = f"no tests collected ({deselected} deselected)" |
| 1493 |
else: |
| 1494 |
main_color = "green" |
| 1495 |
selected = self._numcollected - deselected |
| 1496 |
collected_output = f"{selected}/{self._numcollected} tests collected ({deselected} deselected)" |
| 1497 |
|
| 1498 |
parts = [(collected_output, {main_color: True})] |
| 1499 |
|
| 1500 |
if errors: |
| 1501 |
main_color = _color_for_type["error"] |
| 1502 |
parts += [("%d %s" % pluralize(errors, "error"), {main_color: True})] # noqa: UP031 |
| 1503 |
|
| 1504 |
return parts, main_color |
| 1505 |
|
| 1506 |
|
| 1507 |
def _get_node_id_with_markup(tw: TerminalWriter, config: Config, rep: BaseReport): |
| 1508 |
nodeid = config.cwd_relative_nodeid(rep.nodeid) |
| 1509 |
path, *parts = nodeid.split("::") |
| 1510 |
if parts: |
| 1511 |
parts_markup = tw.markup("::".join(parts), bold=True) |
| 1512 |
return path + "::" + parts_markup |
| 1513 |
else: |
| 1514 |
return path |
| 1515 |
|
| 1516 |
|
| 1517 |
def _format_trimmed(format: str, msg: str, available_width: int) -> str | None: |
| 1518 |
"""Format msg into format, ellipsizing it if doesn't fit in available_width. |
| 1519 |
|
| 1520 |
Returns None if even the ellipsis can't fit. |
| 1521 |
""" |
| 1522 |
# Only use the first line. |
| 1523 |
i = msg.find("\n") |
| 1524 |
if i != -1: |
| 1525 |
msg = msg[:i] |
| 1526 |
|
| 1527 |
ellipsis = "..." |
| 1528 |
format_width = wcswidth(format.format("")) |
| 1529 |
if format_width + len(ellipsis) > available_width: |
| 1530 |
return None |
| 1531 |
|
| 1532 |
if format_width + wcswidth(msg) > available_width: |
| 1533 |
available_width -= len(ellipsis) |
| 1534 |
msg = msg[:available_width] |
| 1535 |
while format_width + wcswidth(msg) > available_width: |
| 1536 |
msg = msg[:-1] |
| 1537 |
msg += ellipsis |
| 1538 |
|
| 1539 |
return format.format(msg) |
| 1540 |
|
| 1541 |
|
| 1542 |
def _get_line_with_reprcrash_message( |
| 1543 |
config: Config, rep: BaseReport, tw: TerminalWriter, word_markup: dict[str, bool] |
| 1544 |
) -> str: |
| 1545 |
"""Get summary line for a report, trying to add reprcrash message.""" |
| 1546 |
verbose_word, verbose_markup = rep._get_verbose_word_with_markup( |
| 1547 |
config, word_markup |
| 1548 |
) |
| 1549 |
word = tw.markup(verbose_word, **verbose_markup) |
| 1550 |
node = _get_node_id_with_markup(tw, config, rep) |
| 1551 |
|
| 1552 |
line = f"{word} {node}" |
| 1553 |
line_width = wcswidth(line) |
| 1554 |
|
| 1555 |
msg: str | None |
| 1556 |
try: |
| 1557 |
if isinstance(rep.longrepr, str): |
| 1558 |
msg = rep.longrepr |
| 1559 |
else: |
| 1560 |
# Type ignored intentionally -- possible AttributeError expected. |
| 1561 |
msg = rep.longrepr.reprcrash.message # type: ignore[union-attr] |
| 1562 |
except AttributeError: |
| 1563 |
pass |
| 1564 |
else: |
| 1565 |
if ( |
| 1566 |
running_on_ci() or config.option.verbose >= 2 |
| 1567 |
) and not config.option.force_short_summary: |
| 1568 |
msg = f" - {msg}" |
| 1569 |
else: |
| 1570 |
available_width = tw.fullwidth - line_width |
| 1571 |
msg = _format_trimmed(" - {}", msg, available_width) |
| 1572 |
if msg is not None: |
| 1573 |
line += msg |
| 1574 |
|
| 1575 |
return line |
| 1576 |
|
| 1577 |
|
| 1578 |
def _folded_skips( |
| 1579 |
startpath: Path, |
| 1580 |
skipped: Sequence[CollectReport], |
| 1581 |
) -> list[tuple[int, str, int | None, str]]: |
| 1582 |
d: dict[tuple[str, int | None, str], list[CollectReport]] = {} |
| 1583 |
for event in skipped: |
| 1584 |
assert event.longrepr is not None |
| 1585 |
assert isinstance(event.longrepr, tuple), (event, event.longrepr) |
| 1586 |
assert len(event.longrepr) == 3, (event, event.longrepr) |
| 1587 |
fspath, lineno, reason = event.longrepr |
| 1588 |
# For consistency, report all fspaths in relative form. |
| 1589 |
fspath = bestrelpath(startpath, Path(fspath)) |
| 1590 |
keywords = getattr(event, "keywords", {}) |
| 1591 |
# Folding reports with global pytestmark variable. |
| 1592 |
# This is a workaround, because for now we cannot identify the scope of a skip marker |
| 1593 |
# TODO: Revisit after marks scope would be fixed. |
| 1594 |
if ( |
| 1595 |
event.when == "setup" |
| 1596 |
and "skip" in keywords |
| 1597 |
and "pytestmark" not in keywords |
| 1598 |
): |
| 1599 |
key: tuple[str, int | None, str] = (fspath, None, reason) |
| 1600 |
else: |
| 1601 |
key = (fspath, lineno, reason) |
| 1602 |
d.setdefault(key, []).append(event) |
| 1603 |
values: list[tuple[int, str, int | None, str]] = [] |
| 1604 |
for key, events in d.items(): |
| 1605 |
values.append((len(events), *key)) |
| 1606 |
return values |
| 1607 |
|
| 1608 |
|
| 1609 |
_color_for_type = { |
| 1610 |
"failed": "red", |
| 1611 |
"error": "red", |
| 1612 |
"warnings": "yellow", |
| 1613 |
"passed": "green", |
| 1614 |
"subtests passed": "green", |
| 1615 |
"subtests failed": "red", |
| 1616 |
} |
| 1617 |
_color_for_type_default = "yellow" |
| 1618 |
|
| 1619 |
|
| 1620 |
def pluralize(count: int, noun: str) -> tuple[int, str]: |
| 1621 |
# No need to pluralize words such as `failed` or `passed`. |
| 1622 |
if noun not in ["error", "warnings", "test"]: |
| 1623 |
return count, noun |
| 1624 |
|
| 1625 |
# The `warnings` key is plural. To avoid API breakage, we keep it that way but |
| 1626 |
# set it to singular here so we can determine plurality in the same way as we do |
| 1627 |
# for `error`. |
| 1628 |
noun = noun.replace("warnings", "warning") |
| 1629 |
|
| 1630 |
return count, noun + "s" if count != 1 else noun |
| 1631 |
|
| 1632 |
|
| 1633 |
def _plugin_nameversions(plugininfo) -> list[str]: |
| 1634 |
values: list[str] = [] |
| 1635 |
for plugin, dist in plugininfo: |
| 1636 |
# Gets us name and version! |
| 1637 |
name = f"{dist.project_name}-{dist.version}" |
| 1638 |
# Questionable convenience, but it keeps things short. |
| 1639 |
if name.startswith("pytest-"): |
| 1640 |
name = name[7:] |
| 1641 |
# We decided to print python package names they can have more than one plugin. |
| 1642 |
if name not in values: |
| 1643 |
values.append(name) |
| 1644 |
return values |
| 1645 |
|
| 1646 |
|
| 1647 |
def format_session_duration(seconds: float) -> str: |
| 1648 |
"""Format the given seconds in a human readable manner to show in the final summary.""" |
| 1649 |
if seconds < 60: |
| 1650 |
return f"{seconds:.2f}s" |
| 1651 |
else: |
| 1652 |
dt = datetime.timedelta(seconds=int(seconds)) |
| 1653 |
return f"{seconds:.2f}s ({dt})" |
| 1654 |
|
| 1655 |
|
| 1656 |
def format_node_duration(seconds: float) -> str: |
| 1657 |
"""Format the given seconds in a human readable manner to show in the test progress.""" |
| 1658 |
# The formatting is designed to be compact and readable, with at most 7 characters |
| 1659 |
# for durations below 100 hours. |
| 1660 |
if seconds < 0.00001: |
| 1661 |
return f" {seconds * 1000000:.3f}us" |
| 1662 |
if seconds < 0.0001: |
| 1663 |
return f" {seconds * 1000000:.2f}us" |
| 1664 |
if seconds < 0.001: |
| 1665 |
return f" {seconds * 1000000:.1f}us" |
| 1666 |
if seconds < 0.01: |
| 1667 |
return f" {seconds * 1000:.3f}ms" |
| 1668 |
if seconds < 0.1: |
| 1669 |
return f" {seconds * 1000:.2f}ms" |
| 1670 |
if seconds < 1: |
| 1671 |
return f" {seconds * 1000:.1f}ms" |
| 1672 |
if seconds < 60: |
| 1673 |
return f" {seconds:.3f}s" |
| 1674 |
if seconds < 3600: |
| 1675 |
return f" {seconds // 60:.0f}m {seconds % 60:.0f}s" |
| 1676 |
return f" {seconds // 3600:.0f}h {(seconds % 3600) // 60:.0f}m" |
| 1677 |
|
| 1678 |
|
| 1679 |
def _get_raw_skip_reason(report: TestReport) -> str: |
| 1680 |
"""Get the reason string of a skip/xfail/xpass test report. |
| 1681 |
|
| 1682 |
The string is just the part given by the user. |
| 1683 |
""" |
| 1684 |
if hasattr(report, "wasxfail"): |
| 1685 |
reason = report.wasxfail |
| 1686 |
if reason.startswith("reason: "): |
| 1687 |
reason = reason[len("reason: ") :] |
| 1688 |
return reason |
| 1689 |
else: |
| 1690 |
assert report.skipped |
| 1691 |
assert isinstance(report.longrepr, tuple) |
| 1692 |
_, _, reason = report.longrepr |
| 1693 |
if reason.startswith("Skipped: "): |
| 1694 |
reason = reason[len("Skipped: ") :] |
| 1695 |
elif reason == "Skipped": |
| 1696 |
reason = "" |
| 1697 |
return reason |
| 1698 |
|
| 1699 |
|
| 1700 |
class TerminalProgressPlugin: |
| 1701 |
"""Terminal progress reporting plugin using OSC 9;4 ANSI sequences. |
| 1702 |
|
| 1703 |
Emits OSC 9;4 sequences to indicate test progress to terminal |
| 1704 |
tabs/windows/etc. |
| 1705 |
|
| 1706 |
Not all terminal emulators support this feature. |
| 1707 |
|
| 1708 |
Ref: https://conemu.github.io/en/AnsiEscapeCodes.html#ConEmu_specific_OSC |
| 1709 |
""" |
| 1710 |
|
| 1711 |
def __init__(self, tr: TerminalReporter) -> None: |
| 1712 |
self._tr = tr |
| 1713 |
self._session: Session | None = None |
| 1714 |
self._has_failures = False |
| 1715 |
|
| 1716 |
def _emit_progress( |
| 1717 |
self, |
| 1718 |
state: Literal["remove", "normal", "error", "indeterminate", "paused"], |
| 1719 |
progress: int | None = None, |
| 1720 |
) -> None: |
| 1721 |
"""Emit OSC 9;4 sequence for indicating progress to the terminal. |
| 1722 |
|
| 1723 |
:param state: |
| 1724 |
Progress state to set. |
| 1725 |
:param progress: |
| 1726 |
Progress value 0-100. Required for "normal", optional for "error" |
| 1727 |
and "paused", otherwise ignored. |
| 1728 |
""" |
| 1729 |
assert progress is None or 0 <= progress <= 100 |
| 1730 |
|
| 1731 |
# OSC 9;4 sequence: ESC ] 9 ; 4 ; state ; progress ST |
| 1732 |
# ST can be ESC \ or BEL. ESC \ seems better supported. |
| 1733 |
match state: |
| 1734 |
case "remove": |
| 1735 |
sequence = "\x1b]9;4;0;\x1b\\" |
| 1736 |
case "normal": |
| 1737 |
assert progress is not None |
| 1738 |
sequence = f"\x1b]9;4;1;{progress}\x1b\\" |
| 1739 |
case "error": |
| 1740 |
if progress is not None: |
| 1741 |
sequence = f"\x1b]9;4;2;{progress}\x1b\\" |
| 1742 |
else: |
| 1743 |
sequence = "\x1b]9;4;2;\x1b\\" |
| 1744 |
case "indeterminate": |
| 1745 |
sequence = "\x1b]9;4;3;\x1b\\" |
| 1746 |
case "paused": |
| 1747 |
if progress is not None: |
| 1748 |
sequence = f"\x1b]9;4;4;{progress}\x1b\\" |
| 1749 |
else: |
| 1750 |
sequence = "\x1b]9;4;4;\x1b\\" |
| 1751 |
|
| 1752 |
self._tr.write_raw(sequence, flush=True) |
| 1753 |
|
| 1754 |
@hookimpl |
| 1755 |
def pytest_sessionstart(self, session: Session) -> None: |
| 1756 |
self._session = session |
| 1757 |
# Show indeterminate progress during collection. |
| 1758 |
self._emit_progress("indeterminate") |
| 1759 |
|
| 1760 |
@hookimpl |
| 1761 |
def pytest_collection_finish(self) -> None: |
| 1762 |
assert self._session is not None |
| 1763 |
if self._session.testscollected > 0: |
| 1764 |
# Switch from indeterminate to 0% progress. |
| 1765 |
self._emit_progress("normal", 0) |
| 1766 |
|
| 1767 |
@hookimpl |
| 1768 |
def pytest_runtest_logreport(self, report: TestReport) -> None: |
| 1769 |
if report.failed: |
| 1770 |
self._has_failures = True |
| 1771 |
|
| 1772 |
# Let's consider the "call" phase for progress. |
| 1773 |
if report.when != "call": |
| 1774 |
return |
| 1775 |
|
| 1776 |
# Calculate and emit progress. |
| 1777 |
assert self._session is not None |
| 1778 |
collected = self._session.testscollected |
| 1779 |
if collected > 0: |
| 1780 |
reported = self._tr.reported_progress |
| 1781 |
progress = min(reported * 100 // collected, 100) |
| 1782 |
self._emit_progress("error" if self._has_failures else "normal", progress) |
| 1783 |
|
| 1784 |
@hookimpl |
| 1785 |
def pytest_sessionfinish(self) -> None: |
| 1786 |
self._emit_progress("remove") |