| 1 |
# mypy: allow-untyped-defs |
| 2 |
"""Access and control log capturing.""" |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
from collections.abc import Generator |
| 7 |
from collections.abc import Mapping |
| 8 |
from collections.abc import Set as AbstractSet |
| 9 |
from contextlib import contextmanager |
| 10 |
from contextlib import nullcontext |
| 11 |
from datetime import datetime |
| 12 |
from datetime import timedelta |
| 13 |
from datetime import timezone |
| 14 |
import io |
| 15 |
from io import StringIO |
| 16 |
import logging |
| 17 |
from logging import LogRecord |
| 18 |
import os |
| 19 |
from pathlib import Path |
| 20 |
import re |
| 21 |
from types import TracebackType |
| 22 |
from typing import final |
| 23 |
from typing import Generic |
| 24 |
from typing import Literal |
| 25 |
from typing import TYPE_CHECKING |
| 26 |
from typing import TypeVar |
| 27 |
|
| 28 |
from _pytest import nodes |
| 29 |
from _pytest._io import TerminalWriter |
| 30 |
from _pytest.capture import CaptureManager |
| 31 |
from _pytest.config import _strtobool |
| 32 |
from _pytest.config import Config |
| 33 |
from _pytest.config import create_terminal_writer |
| 34 |
from _pytest.config import hookimpl |
| 35 |
from _pytest.config import UsageError |
| 36 |
from _pytest.config.argparsing import Parser |
| 37 |
from _pytest.deprecated import check_ispytest |
| 38 |
from _pytest.fixtures import fixture |
| 39 |
from _pytest.fixtures import FixtureRequest |
| 40 |
from _pytest.main import Session |
| 41 |
from _pytest.stash import StashKey |
| 42 |
from _pytest.terminal import TerminalReporter |
| 43 |
|
| 44 |
|
| 45 |
if TYPE_CHECKING: |
| 46 |
logging_StreamHandler = logging.StreamHandler[StringIO] |
| 47 |
else: |
| 48 |
logging_StreamHandler = logging.StreamHandler |
| 49 |
|
| 50 |
DEFAULT_LOG_FORMAT = "%(levelname)-8s %(name)s:%(filename)s:%(lineno)d %(message)s" |
| 51 |
DEFAULT_LOG_DATE_FORMAT = "%H:%M:%S" |
| 52 |
_ANSI_ESCAPE_SEQ = re.compile(r"\x1b\[[\d;]+m") |
| 53 |
caplog_handler_key = StashKey["LogCaptureHandler"]() |
| 54 |
caplog_records_key = StashKey[dict[str, list[logging.LogRecord]]]() |
| 55 |
|
| 56 |
|
| 57 |
def _remove_ansi_escape_sequences(text: str) -> str: |
| 58 |
return _ANSI_ESCAPE_SEQ.sub("", text) |
| 59 |
|
| 60 |
|
| 61 |
class DatetimeFormatter(logging.Formatter): |
| 62 |
"""A logging formatter which formats record with |
| 63 |
:func:`datetime.datetime.strftime` formatter instead of |
| 64 |
:func:`time.strftime` in case of microseconds in format string. |
| 65 |
""" |
| 66 |
|
| 67 |
def formatTime(self, record: LogRecord, datefmt: str | None = None) -> str: |
| 68 |
if datefmt and "%f" in datefmt: |
| 69 |
ct = self.converter(record.created) |
| 70 |
tz = timezone(timedelta(seconds=ct.tm_gmtoff), ct.tm_zone) |
| 71 |
# Construct `datetime.datetime` object from `struct_time` |
| 72 |
# and msecs information from `record` |
| 73 |
# Using int() instead of round() to avoid it exceeding 1_000_000 and causing a ValueError (#11861). |
| 74 |
dt = datetime(*ct[0:6], microsecond=int(record.msecs * 1000), tzinfo=tz) |
| 75 |
return dt.strftime(datefmt) |
| 76 |
# Use `logging.Formatter` for non-microsecond formats |
| 77 |
return super().formatTime(record, datefmt) |
| 78 |
|
| 79 |
|
| 80 |
class ColoredLevelFormatter(DatetimeFormatter): |
| 81 |
"""A logging formatter which colorizes the %(levelname)..s part of the |
| 82 |
log format passed to __init__.""" |
| 83 |
|
| 84 |
LOGLEVEL_COLOROPTS: Mapping[int, AbstractSet[str]] = { |
| 85 |
logging.CRITICAL: {"red"}, |
| 86 |
logging.ERROR: {"red", "bold"}, |
| 87 |
logging.WARNING: {"yellow"}, |
| 88 |
logging.WARN: {"yellow"}, |
| 89 |
logging.INFO: {"green"}, |
| 90 |
logging.DEBUG: {"purple"}, |
| 91 |
logging.NOTSET: set(), |
| 92 |
} |
| 93 |
LEVELNAME_FMT_REGEX = re.compile(r"%\(levelname\)([+-.]?\d*(?:\.\d+)?s)") |
| 94 |
|
| 95 |
def __init__(self, terminalwriter: TerminalWriter, *args, **kwargs) -> None: |
| 96 |
super().__init__(*args, **kwargs) |
| 97 |
self._terminalwriter = terminalwriter |
| 98 |
self._original_fmt = self._style._fmt |
| 99 |
self._level_to_fmt_mapping: dict[int, str] = {} |
| 100 |
|
| 101 |
for level, color_opts in self.LOGLEVEL_COLOROPTS.items(): |
| 102 |
self.add_color_level(level, *color_opts) |
| 103 |
|
| 104 |
def add_color_level(self, level: int, *color_opts: str) -> None: |
| 105 |
"""Add or update color opts for a log level. |
| 106 |
|
| 107 |
:param level: |
| 108 |
Log level to apply a style to, e.g. ``logging.INFO``. |
| 109 |
:param color_opts: |
| 110 |
ANSI escape sequence color options. Capitalized colors indicates |
| 111 |
background color, i.e. ``'green', 'Yellow', 'bold'`` will give bold |
| 112 |
green text on yellow background. |
| 113 |
|
| 114 |
.. warning:: |
| 115 |
This is an experimental API. |
| 116 |
""" |
| 117 |
assert self._fmt is not None |
| 118 |
levelname_fmt_match = self.LEVELNAME_FMT_REGEX.search(self._fmt) |
| 119 |
if not levelname_fmt_match: |
| 120 |
return |
| 121 |
levelname_fmt = levelname_fmt_match.group() |
| 122 |
|
| 123 |
formatted_levelname = levelname_fmt % {"levelname": logging.getLevelName(level)} |
| 124 |
|
| 125 |
# add ANSI escape sequences around the formatted levelname |
| 126 |
color_kwargs = {name: True for name in color_opts} |
| 127 |
colorized_formatted_levelname = self._terminalwriter.markup( |
| 128 |
formatted_levelname, **color_kwargs |
| 129 |
) |
| 130 |
self._level_to_fmt_mapping[level] = self.LEVELNAME_FMT_REGEX.sub( |
| 131 |
colorized_formatted_levelname, self._fmt |
| 132 |
) |
| 133 |
|
| 134 |
def format(self, record: logging.LogRecord) -> str: |
| 135 |
fmt = self._level_to_fmt_mapping.get(record.levelno, self._original_fmt) |
| 136 |
self._style._fmt = fmt |
| 137 |
return super().format(record) |
| 138 |
|
| 139 |
|
| 140 |
class PercentStyleMultiline(logging.PercentStyle): |
| 141 |
"""A logging style with special support for multiline messages. |
| 142 |
|
| 143 |
If the message of a record consists of multiple lines, this style |
| 144 |
formats the message as if each line were logged separately. |
| 145 |
""" |
| 146 |
|
| 147 |
def __init__(self, fmt: str, auto_indent: int | str | bool | None) -> None: |
| 148 |
super().__init__(fmt) |
| 149 |
self._auto_indent = self._get_auto_indent(auto_indent) |
| 150 |
|
| 151 |
@staticmethod |
| 152 |
def _get_auto_indent(auto_indent_option: int | str | bool | None) -> int: |
| 153 |
"""Determine the current auto indentation setting. |
| 154 |
|
| 155 |
Specify auto indent behavior (on/off/fixed) by passing in |
| 156 |
extra={"auto_indent": [value]} to the call to logging.log() or |
| 157 |
using a --log-auto-indent [value] command line or the |
| 158 |
log_auto_indent [value] config option. |
| 159 |
|
| 160 |
Default behavior is auto-indent off. |
| 161 |
|
| 162 |
Using the string "True" or "on" or the boolean True as the value |
| 163 |
turns auto indent on, using the string "False" or "off" or the |
| 164 |
boolean False or the int 0 turns it off, and specifying a |
| 165 |
positive integer fixes the indentation position to the value |
| 166 |
specified. |
| 167 |
|
| 168 |
Any other values for the option are invalid, and will silently be |
| 169 |
converted to the default. |
| 170 |
|
| 171 |
:param None|bool|int|str auto_indent_option: |
| 172 |
User specified option for indentation from command line, config |
| 173 |
or extra kwarg. Accepts int, bool or str. str option accepts the |
| 174 |
same range of values as boolean config options, as well as |
| 175 |
positive integers represented in str form. |
| 176 |
|
| 177 |
:returns: |
| 178 |
Indentation value, which can be |
| 179 |
-1 (automatically determine indentation) or |
| 180 |
0 (auto-indent turned off) or |
| 181 |
>0 (explicitly set indentation position). |
| 182 |
""" |
| 183 |
match auto_indent_option: |
| 184 |
case None | False: |
| 185 |
return 0 |
| 186 |
case True: |
| 187 |
return -1 |
| 188 |
case int(): |
| 189 |
return auto_indent_option |
| 190 |
case str(): |
| 191 |
try: |
| 192 |
return int(auto_indent_option) |
| 193 |
except ValueError: |
| 194 |
pass |
| 195 |
try: |
| 196 |
if _strtobool(auto_indent_option): |
| 197 |
return -1 |
| 198 |
except ValueError: |
| 199 |
return 0 |
| 200 |
return 0 |
| 201 |
|
| 202 |
def format(self, record: logging.LogRecord) -> str: |
| 203 |
if "\n" in record.message: |
| 204 |
if hasattr(record, "auto_indent"): |
| 205 |
# Passed in from the "extra={}" kwarg on the call to logging.log(). |
| 206 |
auto_indent = self._get_auto_indent(record.auto_indent) |
| 207 |
else: |
| 208 |
auto_indent = self._auto_indent |
| 209 |
|
| 210 |
if auto_indent: |
| 211 |
lines = record.message.splitlines() |
| 212 |
formatted = self._fmt % {**record.__dict__, "message": lines[0]} |
| 213 |
|
| 214 |
if auto_indent < 0: |
| 215 |
indentation = _remove_ansi_escape_sequences(formatted).find( |
| 216 |
lines[0] |
| 217 |
) |
| 218 |
else: |
| 219 |
# Optimizes logging by allowing a fixed indentation. |
| 220 |
indentation = auto_indent |
| 221 |
lines[0] = formatted |
| 222 |
return ("\n" + " " * indentation).join(lines) |
| 223 |
return self._fmt % record.__dict__ |
| 224 |
|
| 225 |
|
| 226 |
def get_option_ini(config: Config, *names: str): |
| 227 |
for name in names: |
| 228 |
ret = config.getoption(name) # 'default' arg won't work as expected |
| 229 |
if ret is None: |
| 230 |
ret = config.getini(name) |
| 231 |
if ret: |
| 232 |
return ret |
| 233 |
|
| 234 |
|
| 235 |
def pytest_addoption(parser: Parser) -> None: |
| 236 |
"""Add options to control log capturing.""" |
| 237 |
group = parser.getgroup("logging") |
| 238 |
|
| 239 |
def add_option_ini(option, dest, default=None, type=None, **kwargs): |
| 240 |
parser.addini( |
| 241 |
dest, default=default, type=type, help="Default value for " + option |
| 242 |
) |
| 243 |
group.addoption(option, dest=dest, **kwargs) |
| 244 |
|
| 245 |
add_option_ini( |
| 246 |
"--log-level", |
| 247 |
dest="log_level", |
| 248 |
default=None, |
| 249 |
metavar="LEVEL", |
| 250 |
help=( |
| 251 |
"Level of messages to catch/display." |
| 252 |
" Not set by default, so it depends on the root/parent log handler's" |
| 253 |
' effective level, where it is "WARNING" by default.' |
| 254 |
), |
| 255 |
) |
| 256 |
add_option_ini( |
| 257 |
"--log-format", |
| 258 |
dest="log_format", |
| 259 |
default=DEFAULT_LOG_FORMAT, |
| 260 |
help="Log format used by the logging module", |
| 261 |
) |
| 262 |
add_option_ini( |
| 263 |
"--log-date-format", |
| 264 |
dest="log_date_format", |
| 265 |
default=DEFAULT_LOG_DATE_FORMAT, |
| 266 |
help="Log date format used by the logging module", |
| 267 |
) |
| 268 |
parser.addini( |
| 269 |
"log_cli", |
| 270 |
default=False, |
| 271 |
type="bool", |
| 272 |
help='Enable log display during test run (also known as "live logging")', |
| 273 |
) |
| 274 |
add_option_ini( |
| 275 |
"--log-cli-level", dest="log_cli_level", default=None, help="CLI logging level" |
| 276 |
) |
| 277 |
add_option_ini( |
| 278 |
"--log-cli-format", |
| 279 |
dest="log_cli_format", |
| 280 |
default=None, |
| 281 |
help="Log format used by the logging module", |
| 282 |
) |
| 283 |
add_option_ini( |
| 284 |
"--log-cli-date-format", |
| 285 |
dest="log_cli_date_format", |
| 286 |
default=None, |
| 287 |
help="Log date format used by the logging module", |
| 288 |
) |
| 289 |
add_option_ini( |
| 290 |
"--log-file", |
| 291 |
dest="log_file", |
| 292 |
default=None, |
| 293 |
help="Path to a file when logging will be written to", |
| 294 |
) |
| 295 |
add_option_ini( |
| 296 |
"--log-file-mode", |
| 297 |
dest="log_file_mode", |
| 298 |
default="w", |
| 299 |
choices=["w", "a"], |
| 300 |
help="Log file open mode", |
| 301 |
) |
| 302 |
add_option_ini( |
| 303 |
"--log-file-level", |
| 304 |
dest="log_file_level", |
| 305 |
default=None, |
| 306 |
help="Log file logging level", |
| 307 |
) |
| 308 |
add_option_ini( |
| 309 |
"--log-file-format", |
| 310 |
dest="log_file_format", |
| 311 |
default=None, |
| 312 |
help="Log format used by the logging module", |
| 313 |
) |
| 314 |
add_option_ini( |
| 315 |
"--log-file-date-format", |
| 316 |
dest="log_file_date_format", |
| 317 |
default=None, |
| 318 |
help="Log date format used by the logging module", |
| 319 |
) |
| 320 |
add_option_ini( |
| 321 |
"--log-auto-indent", |
| 322 |
dest="log_auto_indent", |
| 323 |
default=None, |
| 324 |
help="Auto-indent multiline messages passed to the logging module. Accepts true|on, false|off or an integer.", |
| 325 |
) |
| 326 |
group.addoption( |
| 327 |
"--log-disable", |
| 328 |
action="append", |
| 329 |
default=[], |
| 330 |
dest="logger_disable", |
| 331 |
help="Disable a logger by name. Can be passed multiple times.", |
| 332 |
) |
| 333 |
|
| 334 |
|
| 335 |
_HandlerType = TypeVar("_HandlerType", bound=logging.Handler) |
| 336 |
|
| 337 |
|
| 338 |
# Not using @contextmanager for performance reasons. |
| 339 |
class catching_logs(Generic[_HandlerType]): |
| 340 |
"""Context manager that prepares the whole logging machinery properly.""" |
| 341 |
|
| 342 |
__slots__ = ("attached_loggers", "handler", "level", "orig_level") |
| 343 |
|
| 344 |
def __init__(self, handler: _HandlerType, level: int | None = None) -> None: |
| 345 |
self.handler = handler |
| 346 |
self.level = level |
| 347 |
self.attached_loggers: list[logging.Logger] = [] |
| 348 |
|
| 349 |
def __enter__(self) -> _HandlerType: |
| 350 |
root_logger = logging.getLogger() |
| 351 |
if self.level is not None: |
| 352 |
self.handler.setLevel(self.level) |
| 353 |
# Attach to root logger. |
| 354 |
root_logger.addHandler(self.handler) |
| 355 |
self.attached_loggers.append(root_logger) |
| 356 |
# Attach to all non-propagating loggers (won't reach root). |
| 357 |
# Note that will miss loggers that *become* non-propagating |
| 358 |
# after the `__enter__`. Not worth the trouble for now. |
| 359 |
for logger in root_logger.manager.loggerDict.values(): |
| 360 |
if ( |
| 361 |
isinstance(logger, logging.Logger) |
| 362 |
and not logger.propagate |
| 363 |
and logger is not root_logger |
| 364 |
): |
| 365 |
logger.addHandler(self.handler) |
| 366 |
self.attached_loggers.append(logger) |
| 367 |
if self.level is not None: |
| 368 |
# Non-propagating loggers still inherit the level (unless a logger |
| 369 |
# explicitly set level), so only do this on the root logger. |
| 370 |
self.orig_level = root_logger.level |
| 371 |
root_logger.setLevel(min(self.orig_level, self.level)) |
| 372 |
return self.handler |
| 373 |
|
| 374 |
def __exit__( |
| 375 |
self, |
| 376 |
exc_type: type[BaseException] | None, |
| 377 |
exc_val: BaseException | None, |
| 378 |
exc_tb: TracebackType | None, |
| 379 |
) -> None: |
| 380 |
root_logger = logging.getLogger() |
| 381 |
if self.level is not None: |
| 382 |
root_logger.setLevel(self.orig_level) |
| 383 |
for logger in self.attached_loggers: |
| 384 |
logger.removeHandler(self.handler) |
| 385 |
self.attached_loggers.clear() |
| 386 |
|
| 387 |
|
| 388 |
class LogCaptureHandler(logging_StreamHandler): |
| 389 |
"""A logging handler that stores log records and the log text.""" |
| 390 |
|
| 391 |
def __init__(self) -> None: |
| 392 |
"""Create a new log handler.""" |
| 393 |
super().__init__(StringIO()) |
| 394 |
self.records: list[logging.LogRecord] = [] |
| 395 |
|
| 396 |
def emit(self, record: logging.LogRecord) -> None: |
| 397 |
"""Keep the log records in a list in addition to the log text.""" |
| 398 |
self.records.append(record) |
| 399 |
super().emit(record) |
| 400 |
|
| 401 |
def reset(self) -> None: |
| 402 |
self.records = [] |
| 403 |
self.stream = StringIO() |
| 404 |
|
| 405 |
def clear(self) -> None: |
| 406 |
self.records.clear() |
| 407 |
self.stream = StringIO() |
| 408 |
|
| 409 |
def handleError(self, record: logging.LogRecord) -> None: |
| 410 |
if logging.raiseExceptions: |
| 411 |
# Fail the test if the log message is bad (emit failed). |
| 412 |
# The default behavior of logging is to print "Logging error" |
| 413 |
# to stderr with the call stack and some extra details. |
| 414 |
# pytest wants to make such mistakes visible during testing. |
| 415 |
raise # noqa: PLE0704 |
| 416 |
|
| 417 |
|
| 418 |
@final |
| 419 |
class LogCaptureFixture: |
| 420 |
"""Provides access and control of log capturing.""" |
| 421 |
|
| 422 |
def __init__(self, item: nodes.Node, *, _ispytest: bool = False) -> None: |
| 423 |
check_ispytest(_ispytest) |
| 424 |
self._item = item |
| 425 |
self._initial_handler_level: int | None = None |
| 426 |
# Dict of log name -> log level. |
| 427 |
self._initial_logger_levels: dict[str | None, int] = {} |
| 428 |
self._initial_disabled_logging_level: int | None = None |
| 429 |
|
| 430 |
def _finalize(self) -> None: |
| 431 |
"""Finalize the fixture. |
| 432 |
|
| 433 |
This restores the log levels and the disabled logging levels changed by :meth:`set_level`. |
| 434 |
""" |
| 435 |
# Restore log levels. |
| 436 |
if self._initial_handler_level is not None: |
| 437 |
self.handler.setLevel(self._initial_handler_level) |
| 438 |
for logger_name, level in self._initial_logger_levels.items(): |
| 439 |
logger = logging.getLogger(logger_name) |
| 440 |
logger.setLevel(level) |
| 441 |
# Disable logging at the original disabled logging level. |
| 442 |
if self._initial_disabled_logging_level is not None: |
| 443 |
logging.disable(self._initial_disabled_logging_level) |
| 444 |
self._initial_disabled_logging_level = None |
| 445 |
|
| 446 |
@property |
| 447 |
def handler(self) -> LogCaptureHandler: |
| 448 |
"""Get the logging handler used by the fixture.""" |
| 449 |
return self._item.stash[caplog_handler_key] |
| 450 |
|
| 451 |
def get_records( |
| 452 |
self, when: Literal["setup", "call", "teardown"] |
| 453 |
) -> list[logging.LogRecord]: |
| 454 |
"""Get the logging records for one of the possible test phases. |
| 455 |
|
| 456 |
:param when: |
| 457 |
Which test phase to obtain the records from. |
| 458 |
Valid values are: "setup", "call" and "teardown". |
| 459 |
|
| 460 |
:returns: The list of captured records at the given stage. |
| 461 |
|
| 462 |
.. versionadded:: 3.4 |
| 463 |
""" |
| 464 |
return self._item.stash[caplog_records_key].get(when, []) |
| 465 |
|
| 466 |
@property |
| 467 |
def text(self) -> str: |
| 468 |
"""The formatted log text.""" |
| 469 |
return _remove_ansi_escape_sequences(self.handler.stream.getvalue()) |
| 470 |
|
| 471 |
@property |
| 472 |
def records(self) -> list[logging.LogRecord]: |
| 473 |
"""The list of log records.""" |
| 474 |
return self.handler.records |
| 475 |
|
| 476 |
@property |
| 477 |
def record_tuples(self) -> list[tuple[str, int, str]]: |
| 478 |
"""A list of a stripped down version of log records intended |
| 479 |
for use in assertion comparison. |
| 480 |
|
| 481 |
The format of the tuple is: |
| 482 |
|
| 483 |
(logger_name, log_level, message) |
| 484 |
""" |
| 485 |
return [(r.name, r.levelno, r.getMessage()) for r in self.records] |
| 486 |
|
| 487 |
@property |
| 488 |
def messages(self) -> list[str]: |
| 489 |
"""A list of format-interpolated log messages. |
| 490 |
|
| 491 |
Unlike 'records', which contains the format string and parameters for |
| 492 |
interpolation, log messages in this list are all interpolated. |
| 493 |
|
| 494 |
Unlike 'text', which contains the output from the handler, log |
| 495 |
messages in this list are unadorned with levels, timestamps, etc, |
| 496 |
making exact comparisons more reliable. |
| 497 |
|
| 498 |
Note that traceback or stack info (from :func:`logging.exception` or |
| 499 |
the `exc_info` or `stack_info` arguments to the logging functions) is |
| 500 |
not included, as this is added by the formatter in the handler. |
| 501 |
|
| 502 |
.. versionadded:: 3.7 |
| 503 |
""" |
| 504 |
return [r.getMessage() for r in self.records] |
| 505 |
|
| 506 |
def clear(self) -> None: |
| 507 |
"""Reset the list of log records and the captured log text.""" |
| 508 |
self.handler.clear() |
| 509 |
|
| 510 |
def _force_enable_logging( |
| 511 |
self, level: int | str, logger_obj: logging.Logger |
| 512 |
) -> int: |
| 513 |
"""Enable the desired logging level if the global level was disabled via ``logging.disabled``. |
| 514 |
|
| 515 |
Only enables logging levels greater than or equal to the requested ``level``. |
| 516 |
|
| 517 |
Does nothing if the desired ``level`` wasn't disabled. |
| 518 |
|
| 519 |
:param level: |
| 520 |
The logger level caplog should capture. |
| 521 |
All logging is enabled if a non-standard logging level string is supplied. |
| 522 |
Valid level strings are in :data:`logging._nameToLevel`. |
| 523 |
:param logger_obj: The logger object to check. |
| 524 |
|
| 525 |
:return: The original disabled logging level. |
| 526 |
""" |
| 527 |
original_disable_level: int = logger_obj.manager.disable |
| 528 |
|
| 529 |
if isinstance(level, str): |
| 530 |
# Try to translate the level string to an int for `logging.disable()` |
| 531 |
level = logging.getLevelName(level) # type: ignore[deprecated] |
| 532 |
|
| 533 |
if not isinstance(level, int): |
| 534 |
# The level provided was not valid, so just un-disable all logging. |
| 535 |
logging.disable(logging.NOTSET) |
| 536 |
elif not logger_obj.isEnabledFor(level): |
| 537 |
# Each level is `10` away from other levels. |
| 538 |
# https://docs.python.org/3/library/logging.html#logging-levels |
| 539 |
disable_level = max(level - 10, logging.NOTSET) |
| 540 |
logging.disable(disable_level) |
| 541 |
|
| 542 |
return original_disable_level |
| 543 |
|
| 544 |
def set_level(self, level: int | str, logger: str | None = None) -> None: |
| 545 |
"""Set the threshold level of a logger for the duration of a test. |
| 546 |
|
| 547 |
Logging messages which are less severe than this level will not be captured. |
| 548 |
|
| 549 |
.. versionchanged:: 3.4 |
| 550 |
The levels of the loggers changed by this function will be |
| 551 |
restored to their initial values at the end of the test. |
| 552 |
|
| 553 |
Will enable the requested logging level if it was disabled via :func:`logging.disable`. |
| 554 |
|
| 555 |
:param level: The level. |
| 556 |
:param logger: The logger to update. If not given, the root logger. |
| 557 |
""" |
| 558 |
logger_obj = logging.getLogger(logger) |
| 559 |
# Save the original log-level to restore it during teardown. |
| 560 |
self._initial_logger_levels.setdefault(logger, logger_obj.level) |
| 561 |
logger_obj.setLevel(level) |
| 562 |
if self._initial_handler_level is None: |
| 563 |
self._initial_handler_level = self.handler.level |
| 564 |
self.handler.setLevel(level) |
| 565 |
initial_disabled_logging_level = self._force_enable_logging(level, logger_obj) |
| 566 |
if self._initial_disabled_logging_level is None: |
| 567 |
self._initial_disabled_logging_level = initial_disabled_logging_level |
| 568 |
|
| 569 |
@contextmanager |
| 570 |
def at_level(self, level: int | str, logger: str | None = None) -> Generator[None]: |
| 571 |
"""Context manager that sets the level for capturing of logs. After |
| 572 |
the end of the 'with' statement the level is restored to its original |
| 573 |
value. |
| 574 |
|
| 575 |
Will enable the requested logging level if it was disabled via :func:`logging.disable`. |
| 576 |
|
| 577 |
:param level: The level. |
| 578 |
:param logger: The logger to update. If not given, the root logger. |
| 579 |
""" |
| 580 |
logger_obj = logging.getLogger(logger) |
| 581 |
orig_level = logger_obj.level |
| 582 |
logger_obj.setLevel(level) |
| 583 |
handler_orig_level = self.handler.level |
| 584 |
self.handler.setLevel(level) |
| 585 |
original_disable_level = self._force_enable_logging(level, logger_obj) |
| 586 |
try: |
| 587 |
yield |
| 588 |
finally: |
| 589 |
logger_obj.setLevel(orig_level) |
| 590 |
self.handler.setLevel(handler_orig_level) |
| 591 |
logging.disable(original_disable_level) |
| 592 |
|
| 593 |
@contextmanager |
| 594 |
def filtering(self, filter_: logging.Filter) -> Generator[None]: |
| 595 |
"""Context manager that temporarily adds the given filter to the caplog's |
| 596 |
:meth:`handler` for the 'with' statement block, and removes that filter at the |
| 597 |
end of the block. |
| 598 |
|
| 599 |
:param filter_: A custom :class:`logging.Filter` object. |
| 600 |
|
| 601 |
.. versionadded:: 7.5 |
| 602 |
""" |
| 603 |
self.handler.addFilter(filter_) |
| 604 |
try: |
| 605 |
yield |
| 606 |
finally: |
| 607 |
self.handler.removeFilter(filter_) |
| 608 |
|
| 609 |
|
| 610 |
@fixture |
| 611 |
def caplog(request: FixtureRequest) -> Generator[LogCaptureFixture]: |
| 612 |
"""Access and control log capturing. |
| 613 |
|
| 614 |
Captured logs are available through the following properties/methods:: |
| 615 |
|
| 616 |
* caplog.messages -> list of format-interpolated log messages |
| 617 |
* caplog.text -> string containing formatted log output |
| 618 |
* caplog.records -> list of logging.LogRecord instances |
| 619 |
* caplog.record_tuples -> list of (logger_name, level, message) tuples |
| 620 |
* caplog.clear() -> clear captured records and formatted log output string |
| 621 |
""" |
| 622 |
result = LogCaptureFixture(request.node, _ispytest=True) |
| 623 |
yield result |
| 624 |
result._finalize() |
| 625 |
|
| 626 |
|
| 627 |
def get_log_level_for_setting(config: Config, *setting_names: str) -> int | None: |
| 628 |
for setting_name in setting_names: |
| 629 |
log_level = config.getoption(setting_name) |
| 630 |
if log_level is None: |
| 631 |
log_level = config.getini(setting_name) |
| 632 |
if log_level: |
| 633 |
break |
| 634 |
else: |
| 635 |
return None |
| 636 |
|
| 637 |
if isinstance(log_level, str): |
| 638 |
log_level = log_level.upper() |
| 639 |
try: |
| 640 |
return int(getattr(logging, log_level, log_level)) |
| 641 |
except ValueError as e: |
| 642 |
# Python logging does not recognise this as a logging level |
| 643 |
raise UsageError( |
| 644 |
f"'{log_level}' is not recognized as a logging level name for " |
| 645 |
f"'{setting_name}'. Please consider passing the " |
| 646 |
"logging level num instead." |
| 647 |
) from e |
| 648 |
|
| 649 |
|
| 650 |
# run after terminalreporter/capturemanager are configured |
| 651 |
@hookimpl(trylast=True) |
| 652 |
def pytest_configure(config: Config) -> None: |
| 653 |
config.pluginmanager.register(LoggingPlugin(config), "logging-plugin") |
| 654 |
|
| 655 |
|
| 656 |
class LoggingPlugin: |
| 657 |
"""Attaches to the logging module and captures log messages for each test.""" |
| 658 |
|
| 659 |
def __init__(self, config: Config) -> None: |
| 660 |
"""Create a new plugin to capture log messages. |
| 661 |
|
| 662 |
The formatter can be safely shared across all handlers so |
| 663 |
create a single one for the entire test session here. |
| 664 |
""" |
| 665 |
self._config = config |
| 666 |
|
| 667 |
# Report logging. |
| 668 |
self.formatter = self._create_formatter( |
| 669 |
get_option_ini(config, "log_format"), |
| 670 |
get_option_ini(config, "log_date_format"), |
| 671 |
get_option_ini(config, "log_auto_indent"), |
| 672 |
) |
| 673 |
self.log_level = get_log_level_for_setting(config, "log_level") |
| 674 |
self.caplog_handler = LogCaptureHandler() |
| 675 |
self.caplog_handler.setFormatter(self.formatter) |
| 676 |
self.report_handler = LogCaptureHandler() |
| 677 |
self.report_handler.setFormatter(self.formatter) |
| 678 |
|
| 679 |
# File logging. |
| 680 |
self.log_file_level = get_log_level_for_setting( |
| 681 |
config, "log_file_level", "log_level" |
| 682 |
) |
| 683 |
log_file = get_option_ini(config, "log_file") or os.devnull |
| 684 |
if log_file != os.devnull: |
| 685 |
directory = os.path.dirname(os.path.abspath(log_file)) |
| 686 |
if not os.path.isdir(directory): |
| 687 |
os.makedirs(directory) |
| 688 |
|
| 689 |
self.log_file_mode = get_option_ini(config, "log_file_mode") or "w" |
| 690 |
self.log_file_handler = _FileHandler( |
| 691 |
log_file, mode=self.log_file_mode, encoding="UTF-8" |
| 692 |
) |
| 693 |
log_file_format = get_option_ini(config, "log_file_format", "log_format") |
| 694 |
log_file_date_format = get_option_ini( |
| 695 |
config, "log_file_date_format", "log_date_format" |
| 696 |
) |
| 697 |
|
| 698 |
log_file_formatter = DatetimeFormatter( |
| 699 |
log_file_format, datefmt=log_file_date_format |
| 700 |
) |
| 701 |
self.log_file_handler.setFormatter(log_file_formatter) |
| 702 |
|
| 703 |
# CLI/live logging. |
| 704 |
self.log_cli_level = get_log_level_for_setting( |
| 705 |
config, "log_cli_level", "log_level" |
| 706 |
) |
| 707 |
if self._log_cli_enabled(): |
| 708 |
terminal_reporter = config.pluginmanager.get_plugin("terminalreporter") |
| 709 |
# Guaranteed by `_log_cli_enabled()`. |
| 710 |
assert terminal_reporter is not None |
| 711 |
capture_manager = config.pluginmanager.get_plugin("capturemanager") |
| 712 |
# if capturemanager plugin is disabled, live logging still works. |
| 713 |
self.log_cli_handler: ( |
| 714 |
_LiveLoggingStreamHandler | _LiveLoggingNullHandler |
| 715 |
) = _LiveLoggingStreamHandler(terminal_reporter, capture_manager) |
| 716 |
else: |
| 717 |
self.log_cli_handler = _LiveLoggingNullHandler() |
| 718 |
log_cli_formatter = self._create_formatter( |
| 719 |
get_option_ini(config, "log_cli_format", "log_format"), |
| 720 |
get_option_ini(config, "log_cli_date_format", "log_date_format"), |
| 721 |
get_option_ini(config, "log_auto_indent"), |
| 722 |
) |
| 723 |
self.log_cli_handler.setFormatter(log_cli_formatter) |
| 724 |
self._disable_loggers(loggers_to_disable=config.option.logger_disable) |
| 725 |
|
| 726 |
def _disable_loggers(self, loggers_to_disable: list[str]) -> None: |
| 727 |
if not loggers_to_disable: |
| 728 |
return |
| 729 |
|
| 730 |
for name in loggers_to_disable: |
| 731 |
logger = logging.getLogger(name) |
| 732 |
logger.disabled = True |
| 733 |
|
| 734 |
def _create_formatter(self, log_format, log_date_format, auto_indent): |
| 735 |
# Color option doesn't exist if terminal plugin is disabled. |
| 736 |
color = getattr(self._config.option, "color", "no") |
| 737 |
if color != "no" and ColoredLevelFormatter.LEVELNAME_FMT_REGEX.search( |
| 738 |
log_format |
| 739 |
): |
| 740 |
formatter: logging.Formatter = ColoredLevelFormatter( |
| 741 |
create_terminal_writer(self._config), log_format, log_date_format |
| 742 |
) |
| 743 |
else: |
| 744 |
formatter = DatetimeFormatter(log_format, log_date_format) |
| 745 |
|
| 746 |
formatter._style = PercentStyleMultiline( |
| 747 |
formatter._style._fmt, auto_indent=auto_indent |
| 748 |
) |
| 749 |
|
| 750 |
return formatter |
| 751 |
|
| 752 |
def set_log_path(self, fname: str) -> None: |
| 753 |
"""Set the filename parameter for Logging.FileHandler(). |
| 754 |
|
| 755 |
Creates parent directory if it does not exist. |
| 756 |
|
| 757 |
.. warning:: |
| 758 |
This is an experimental API. |
| 759 |
""" |
| 760 |
fpath = Path(fname) |
| 761 |
|
| 762 |
if not fpath.is_absolute(): |
| 763 |
fpath = self._config.rootpath / fpath |
| 764 |
|
| 765 |
if not fpath.parent.exists(): |
| 766 |
fpath.parent.mkdir(exist_ok=True, parents=True) |
| 767 |
|
| 768 |
# https://github.com/python/mypy/issues/11193 |
| 769 |
stream: io.TextIOWrapper = fpath.open(mode=self.log_file_mode, encoding="UTF-8") # type: ignore[assignment] |
| 770 |
old_stream = self.log_file_handler.setStream(stream) |
| 771 |
if old_stream: |
| 772 |
old_stream.close() |
| 773 |
|
| 774 |
def _log_cli_enabled(self) -> bool: |
| 775 |
"""Return whether live logging is enabled.""" |
| 776 |
enabled = self._config.getoption( |
| 777 |
"--log-cli-level" |
| 778 |
) is not None or self._config.getini("log_cli") |
| 779 |
if not enabled: |
| 780 |
return False |
| 781 |
|
| 782 |
terminal_reporter = self._config.pluginmanager.get_plugin("terminalreporter") |
| 783 |
if terminal_reporter is None: |
| 784 |
# terminal reporter is disabled e.g. by pytest-xdist. |
| 785 |
return False |
| 786 |
|
| 787 |
return True |
| 788 |
|
| 789 |
@hookimpl(wrapper=True, tryfirst=True) |
| 790 |
def pytest_sessionstart(self) -> Generator[None]: |
| 791 |
self.log_cli_handler.set_when("sessionstart") |
| 792 |
|
| 793 |
with catching_logs(self.log_cli_handler, level=self.log_cli_level): |
| 794 |
with catching_logs(self.log_file_handler, level=self.log_file_level): |
| 795 |
return (yield) |
| 796 |
|
| 797 |
@hookimpl(wrapper=True, tryfirst=True) |
| 798 |
def pytest_collection(self) -> Generator[None]: |
| 799 |
self.log_cli_handler.set_when("collection") |
| 800 |
|
| 801 |
with catching_logs(self.log_cli_handler, level=self.log_cli_level): |
| 802 |
with catching_logs(self.log_file_handler, level=self.log_file_level): |
| 803 |
return (yield) |
| 804 |
|
| 805 |
@hookimpl(wrapper=True) |
| 806 |
def pytest_runtestloop(self, session: Session) -> Generator[None, object, object]: |
| 807 |
if session.config.option.collectonly: |
| 808 |
return (yield) |
| 809 |
|
| 810 |
if self._log_cli_enabled() and self._config.get_verbosity() < 1: |
| 811 |
# The verbose flag is needed to avoid messy test progress output. |
| 812 |
self._config.option.verbose = 1 |
| 813 |
|
| 814 |
with catching_logs(self.log_cli_handler, level=self.log_cli_level): |
| 815 |
with catching_logs(self.log_file_handler, level=self.log_file_level): |
| 816 |
return (yield) # Run all the tests. |
| 817 |
|
| 818 |
@hookimpl |
| 819 |
def pytest_runtest_logstart(self) -> None: |
| 820 |
self.log_cli_handler.reset() |
| 821 |
self.log_cli_handler.set_when("start") |
| 822 |
|
| 823 |
@hookimpl |
| 824 |
def pytest_runtest_logreport(self) -> None: |
| 825 |
self.log_cli_handler.set_when("logreport") |
| 826 |
|
| 827 |
@contextmanager |
| 828 |
def _runtest_for(self, item: nodes.Item, when: str) -> Generator[None]: |
| 829 |
"""Implement the internals of the pytest_runtest_xxx() hooks.""" |
| 830 |
with ( |
| 831 |
catching_logs( |
| 832 |
self.caplog_handler, |
| 833 |
level=self.log_level, |
| 834 |
) as caplog_handler, |
| 835 |
catching_logs( |
| 836 |
self.report_handler, |
| 837 |
level=self.log_level, |
| 838 |
) as report_handler, |
| 839 |
): |
| 840 |
caplog_handler.reset() |
| 841 |
report_handler.reset() |
| 842 |
item.stash[caplog_records_key][when] = caplog_handler.records |
| 843 |
item.stash[caplog_handler_key] = caplog_handler |
| 844 |
|
| 845 |
try: |
| 846 |
yield |
| 847 |
finally: |
| 848 |
log = report_handler.stream.getvalue().strip() |
| 849 |
item.add_report_section(when, "log", log) |
| 850 |
|
| 851 |
@hookimpl(wrapper=True) |
| 852 |
def pytest_runtest_setup(self, item: nodes.Item) -> Generator[None]: |
| 853 |
self.log_cli_handler.set_when("setup") |
| 854 |
|
| 855 |
empty: dict[str, list[logging.LogRecord]] = {} |
| 856 |
item.stash[caplog_records_key] = empty |
| 857 |
with self._runtest_for(item, "setup"): |
| 858 |
yield |
| 859 |
|
| 860 |
@hookimpl(wrapper=True) |
| 861 |
def pytest_runtest_call(self, item: nodes.Item) -> Generator[None]: |
| 862 |
self.log_cli_handler.set_when("call") |
| 863 |
|
| 864 |
with self._runtest_for(item, "call"): |
| 865 |
yield |
| 866 |
|
| 867 |
@hookimpl(wrapper=True) |
| 868 |
def pytest_runtest_teardown(self, item: nodes.Item) -> Generator[None]: |
| 869 |
self.log_cli_handler.set_when("teardown") |
| 870 |
|
| 871 |
try: |
| 872 |
with self._runtest_for(item, "teardown"): |
| 873 |
yield |
| 874 |
finally: |
| 875 |
del item.stash[caplog_records_key] |
| 876 |
del item.stash[caplog_handler_key] |
| 877 |
|
| 878 |
@hookimpl |
| 879 |
def pytest_runtest_logfinish(self) -> None: |
| 880 |
self.log_cli_handler.set_when("finish") |
| 881 |
|
| 882 |
@hookimpl(wrapper=True, tryfirst=True) |
| 883 |
def pytest_sessionfinish(self) -> Generator[None]: |
| 884 |
self.log_cli_handler.set_when("sessionfinish") |
| 885 |
|
| 886 |
with catching_logs(self.log_cli_handler, level=self.log_cli_level): |
| 887 |
with catching_logs(self.log_file_handler, level=self.log_file_level): |
| 888 |
return (yield) |
| 889 |
|
| 890 |
@hookimpl |
| 891 |
def pytest_unconfigure(self) -> None: |
| 892 |
# Close the FileHandler explicitly. |
| 893 |
# (logging.shutdown might have lost the weakref?!) |
| 894 |
self.log_file_handler.close() |
| 895 |
|
| 896 |
|
| 897 |
class _FileHandler(logging.FileHandler): |
| 898 |
"""A logging FileHandler with pytest tweaks.""" |
| 899 |
|
| 900 |
def handleError(self, record: logging.LogRecord) -> None: |
| 901 |
# Handled by LogCaptureHandler. |
| 902 |
pass |
| 903 |
|
| 904 |
|
| 905 |
class _LiveLoggingStreamHandler(logging_StreamHandler): |
| 906 |
"""A logging StreamHandler used by the live logging feature: it will |
| 907 |
write a newline before the first log message in each test. |
| 908 |
|
| 909 |
During live logging we must also explicitly disable stdout/stderr |
| 910 |
capturing otherwise it will get captured and won't appear in the |
| 911 |
terminal. |
| 912 |
""" |
| 913 |
|
| 914 |
# Officially stream needs to be a IO[str], but TerminalReporter |
| 915 |
# isn't. So force it. |
| 916 |
stream: TerminalReporter = None # type: ignore |
| 917 |
|
| 918 |
def __init__( |
| 919 |
self, |
| 920 |
terminal_reporter: TerminalReporter, |
| 921 |
capture_manager: CaptureManager | None, |
| 922 |
) -> None: |
| 923 |
super().__init__(stream=terminal_reporter) # type: ignore[arg-type] |
| 924 |
self.capture_manager = capture_manager |
| 925 |
self.reset() |
| 926 |
self.set_when(None) |
| 927 |
self._test_outcome_written = False |
| 928 |
|
| 929 |
def reset(self) -> None: |
| 930 |
"""Reset the handler; should be called before the start of each test.""" |
| 931 |
self._first_record_emitted = False |
| 932 |
|
| 933 |
def set_when(self, when: str | None) -> None: |
| 934 |
"""Prepare for the given test phase (setup/call/teardown).""" |
| 935 |
self._when = when |
| 936 |
self._section_name_shown = False |
| 937 |
if when == "start": |
| 938 |
self._test_outcome_written = False |
| 939 |
|
| 940 |
def emit(self, record: logging.LogRecord) -> None: |
| 941 |
ctx_manager = ( |
| 942 |
self.capture_manager.global_and_fixture_disabled() |
| 943 |
if self.capture_manager |
| 944 |
else nullcontext() |
| 945 |
) |
| 946 |
with ctx_manager: |
| 947 |
if not self._first_record_emitted: |
| 948 |
self.stream.write("\n") |
| 949 |
self._first_record_emitted = True |
| 950 |
elif self._when in ("teardown", "finish"): |
| 951 |
if not self._test_outcome_written: |
| 952 |
self._test_outcome_written = True |
| 953 |
self.stream.write("\n") |
| 954 |
if not self._section_name_shown and self._when: |
| 955 |
self.stream.section("live log " + self._when, sep="-", bold=True) |
| 956 |
self._section_name_shown = True |
| 957 |
super().emit(record) |
| 958 |
|
| 959 |
def handleError(self, record: logging.LogRecord) -> None: |
| 960 |
# Handled by LogCaptureHandler. |
| 961 |
pass |
| 962 |
|
| 963 |
|
| 964 |
class _LiveLoggingNullHandler(logging.NullHandler): |
| 965 |
"""A logging handler used when live logging is disabled.""" |
| 966 |
|
| 967 |
def reset(self) -> None: |
| 968 |
pass |
| 969 |
|
| 970 |
def set_when(self, when: str) -> None: |
| 971 |
pass |
| 972 |
|
| 973 |
def handleError(self, record: logging.LogRecord) -> None: |
| 974 |
# Handled by LogCaptureHandler. |
| 975 |
pass |