Skip to content

Commit b67badc

Browse files
committed
Access captures logs in teardown
1 parent 01e37fe commit b67badc

File tree

3 files changed

+26
-0
lines changed

3 files changed

+26
-0
lines changed

_pytest/logging.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -287,11 +287,16 @@ def _runtest_for(self, item, when):
287287
"""Implements the internals of pytest_runtest_xxx() hook."""
288288
with catching_logs(LogCaptureHandler(),
289289
formatter=self.formatter) as log_handler:
290+
if not hasattr(item, 'catch_log_handlers'):
291+
item.catch_log_handlers = {}
292+
item.catch_log_handlers[when] = log_handler
290293
item.catch_log_handler = log_handler
291294
try:
292295
yield # run test
293296
finally:
294297
del item.catch_log_handler
298+
if when == 'teardown':
299+
del item.catch_log_handlers
295300

296301
if self.print_logs:
297302
# Add a captured log section to the report.

changelog/3117.feature

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
New member on the `_item` member of the `caplog` fixture: `catch_log_handlers`. This contains a dict for the logs for the different stages of the test (setup, call, teardown). So to access the logs for the setup phase in your tests you can get to them via `caplog._item.catch_log_handlers`.

testing/logging/test_fixture.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# -*- coding: utf-8 -*-
22
import logging
33

4+
import pytest
45

56
logger = logging.getLogger(__name__)
67
sublogger = logging.getLogger(__name__ + '.baz')
@@ -68,3 +69,22 @@ def test_clear(caplog):
6869
assert len(caplog.records)
6970
caplog.clear()
7071
assert not len(caplog.records)
72+
73+
74+
@pytest.fixture
75+
def logging_during_setup_and_teardown(caplog):
76+
logger.info('a_setup_log')
77+
yield
78+
logger.info('a_teardown_log')
79+
assert [x.message for x in caplog._item.catch_log_handlers['teardown'].records] == ['a_teardown_log']
80+
81+
82+
def test_caplog_captures_for_all_stages(caplog, logging_during_setup_and_teardown):
83+
assert not caplog.records
84+
assert not caplog._item.catch_log_handlers['call'].records
85+
logger.info('a_call_log')
86+
assert [x.message for x in caplog._item.catch_log_handlers['call'].records] == ['a_call_log']
87+
88+
assert [x.message for x in caplog._item.catch_log_handlers['setup'].records] == ['a_setup_log']
89+
90+
assert set(caplog._item.catch_log_handlers.keys()) == {'setup', 'call'}

0 commit comments

Comments
 (0)