Skip to content

Commit

Permalink
Merge pull request pytest-dev#10051 from EmptyRabbit/dev_main
Browse files Browse the repository at this point in the history
Fix stage caplog records not clear
  • Loading branch information
RonnyPfannschmidt committed Jul 8, 2022
2 parents 4449bdc + 8726597 commit 966d4fb
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 2 deletions.
1 change: 1 addition & 0 deletions AUTHORS
Expand Up @@ -366,5 +366,6 @@ Yuval Shimon
Zac Hatfield-Dodds
Zachary Kneupper
Zachary OBrien
Zhouxin Qiu
Zoltán Máté
Zsolt Cserna
1 change: 1 addition & 0 deletions changelog/9877.bugfix.rst
@@ -0,0 +1 @@
Ensure ``caplog.get_records(when)`` returns current/correct data after invoking ``caplog.clear()``.
7 changes: 5 additions & 2 deletions src/_pytest/logging.py
Expand Up @@ -40,7 +40,6 @@
else:
logging_StreamHandler = logging.StreamHandler


DEFAULT_LOG_FORMAT = "%(levelname)-8s %(name)s:%(filename)s:%(lineno)d %(message)s"
DEFAULT_LOG_DATE_FORMAT = "%H:%M:%S"
_ANSI_ESCAPE_SEQ = re.compile(r"\x1b\[[\d;]+m")
Expand Down Expand Up @@ -345,6 +344,10 @@ def reset(self) -> None:
self.records = []
self.stream = StringIO()

def clear(self) -> None:
self.records.clear()
self.stream = StringIO()

def handleError(self, record: logging.LogRecord) -> None:
if logging.raiseExceptions:
# Fail the test if the log message is bad (emit failed).
Expand Down Expand Up @@ -440,7 +443,7 @@ def messages(self) -> List[str]:

def clear(self) -> None:
"""Reset the list of log records and the captured log text."""
self.handler.reset()
self.handler.clear()

def set_level(self, level: Union[int, str], logger: Optional[str] = None) -> None:
"""Set the level of a logger for the duration of a test.
Expand Down
18 changes: 18 additions & 0 deletions testing/logging/test_fixture.py
Expand Up @@ -172,6 +172,24 @@ def test_caplog_captures_for_all_stages(caplog, logging_during_setup_and_teardow
assert set(caplog._item.stash[caplog_records_key]) == {"setup", "call"}


def test_clear_for_call_stage(caplog, logging_during_setup_and_teardown):
logger.info("a_call_log")
assert [x.message for x in caplog.get_records("call")] == ["a_call_log"]
assert [x.message for x in caplog.get_records("setup")] == ["a_setup_log"]
assert set(caplog._item.stash[caplog_records_key]) == {"setup", "call"}

caplog.clear()

assert caplog.get_records("call") == []
assert [x.message for x in caplog.get_records("setup")] == ["a_setup_log"]
assert set(caplog._item.stash[caplog_records_key]) == {"setup", "call"}

logging.info("a_call_log_after_clear")
assert [x.message for x in caplog.get_records("call")] == ["a_call_log_after_clear"]
assert [x.message for x in caplog.get_records("setup")] == ["a_setup_log"]
assert set(caplog._item.stash[caplog_records_key]) == {"setup", "call"}


def test_ini_controls_global_log_level(pytester: Pytester) -> None:
pytester.makepyfile(
"""
Expand Down

0 comments on commit 966d4fb

Please sign in to comment.