Provides access and control of log capturing.
| 352 | |
| 353 | @final |
| 354 | class LogCaptureFixture: |
| 355 | """Provides access and control of log capturing.""" |
| 356 | |
| 357 | def __init__(self, item: nodes.Node, *, _ispytest: bool = False) -> None: |
| 358 | check_ispytest(_ispytest) |
| 359 | self._item = item |
| 360 | self._initial_handler_level: Optional[int] = None |
| 361 | # Dict of log name -> log level. |
| 362 | self._initial_logger_levels: Dict[Optional[str], int] = {} |
| 363 | |
| 364 | def _finalize(self) -> None: |
| 365 | """Finalize the fixture. |
| 366 | |
| 367 | This restores the log levels changed by :meth:`set_level`. |
| 368 | """ |
| 369 | # Restore log levels. |
| 370 | if self._initial_handler_level is not None: |
| 371 | self.handler.setLevel(self._initial_handler_level) |
| 372 | for logger_name, level in self._initial_logger_levels.items(): |
| 373 | logger = logging.getLogger(logger_name) |
| 374 | logger.setLevel(level) |
| 375 | |
| 376 | @property |
| 377 | def handler(self) -> LogCaptureHandler: |
| 378 | """Get the logging handler used by the fixture. |
| 379 | |
| 380 | :rtype: LogCaptureHandler |
| 381 | """ |
| 382 | return self._item.stash[caplog_handler_key] |
| 383 | |
| 384 | def get_records(self, when: str) -> List[logging.LogRecord]: |
| 385 | """Get the logging records for one of the possible test phases. |
| 386 | |
| 387 | :param str when: |
| 388 | Which test phase to obtain the records from. Valid values are: "setup", "call" and "teardown". |
| 389 | |
| 390 | :returns: The list of captured records at the given stage. |
| 391 | :rtype: List[logging.LogRecord] |
| 392 | |
| 393 | .. versionadded:: 3.4 |
| 394 | """ |
| 395 | return self._item.stash[caplog_records_key].get(when, []) |
| 396 | |
| 397 | @property |
| 398 | def text(self) -> str: |
| 399 | """The formatted log text.""" |
| 400 | return _remove_ansi_escape_sequences(self.handler.stream.getvalue()) |
| 401 | |
| 402 | @property |
| 403 | def records(self) -> List[logging.LogRecord]: |
| 404 | """The list of log records.""" |
| 405 | return self.handler.records |
| 406 | |
| 407 | @property |
| 408 | def record_tuples(self) -> List[Tuple[str, int, str]]: |
| 409 | """A list of a stripped down version of log records intended |
| 410 | for use in assertion comparison. |
| 411 |