Fix stage caplog records not clear

Closes #9877
This commit is contained in:
zx.qiu 2022-06-15 23:11:55 +08:00
parent aa55975c7d
commit c7e784f95d
4 changed files with 27 additions and 0 deletions

View File

@ -363,5 +363,6 @@ Yuval Shimon
Zac Hatfield-Dodds
Zachary Kneupper
Zachary OBrien
Zhouxin Qiu
Zoltán Máté
Zsolt Cserna

View File

@ -0,0 +1 @@
Fixed ``caplog.get_records(when)`` still get the stage records after ``caplog.clear()``

View File

@ -335,6 +335,16 @@ class LogCaptureHandler(logging_StreamHandler):
"""Create a new log handler."""
super().__init__(StringIO())
self.records: List[logging.LogRecord] = []
self.set_when(None)
def set_when(self, when: Optional[str]) -> None:
"""Prepare for the given test phase (setup/call/teardown)."""
self._when = when
def get_when(self) -> Optional[str]:
return self._when
when = property(get_when, set_when)
def emit(self, record: logging.LogRecord) -> None:
"""Keep the log records in a list in addition to the log text."""
@ -441,6 +451,7 @@ class LogCaptureFixture:
def clear(self) -> None:
"""Reset the list of log records and the captured log text."""
self.handler.reset()
self._item.stash[caplog_records_key][self.handler.when] = self.records
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.
@ -695,6 +706,7 @@ class LoggingPlugin:
level=self.log_level,
) as report_handler:
caplog_handler.reset()
caplog_handler.set_when(when)
report_handler.reset()
item.stash[caplog_records_key][when] = caplog_handler.records
item.stash[caplog_handler_key] = caplog_handler

View File

@ -172,6 +172,19 @@ 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"}
def test_ini_controls_global_log_level(pytester: Pytester) -> None:
pytester.makepyfile(
"""