Skip to content

Commit

Permalink
Access captures logs in teardown
Browse files Browse the repository at this point in the history
  • Loading branch information
boxed committed Jan 18, 2018
1 parent 01e37fe commit b67badc
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
5 changes: 5 additions & 0 deletions _pytest/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -287,11 +287,16 @@ def _runtest_for(self, item, when):
"""Implements the internals of pytest_runtest_xxx() hook."""
with catching_logs(LogCaptureHandler(),
formatter=self.formatter) as log_handler:
if not hasattr(item, 'catch_log_handlers'):
item.catch_log_handlers = {}
item.catch_log_handlers[when] = log_handler
item.catch_log_handler = log_handler
try:
yield # run test
finally:
del item.catch_log_handler
if when == 'teardown':
del item.catch_log_handlers

if self.print_logs:
# Add a captured log section to the report.
Expand Down
1 change: 1 addition & 0 deletions changelog/3117.feature
Original file line number Diff line number Diff line change
@@ -0,0 +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`.
20 changes: 20 additions & 0 deletions testing/logging/test_fixture.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
import logging

import pytest

logger = logging.getLogger(__name__)
sublogger = logging.getLogger(__name__ + '.baz')
Expand Down Expand Up @@ -68,3 +69,22 @@ def test_clear(caplog):
assert len(caplog.records)
caplog.clear()
assert not len(caplog.records)


@pytest.fixture
def logging_during_setup_and_teardown(caplog):
logger.info('a_setup_log')
yield
logger.info('a_teardown_log')
assert [x.message for x in caplog._item.catch_log_handlers['teardown'].records] == ['a_teardown_log']


def test_caplog_captures_for_all_stages(caplog, logging_during_setup_and_teardown):
assert not caplog.records
assert not caplog._item.catch_log_handlers['call'].records
logger.info('a_call_log')
assert [x.message for x in caplog._item.catch_log_handlers['call'].records] == ['a_call_log']

assert [x.message for x in caplog._item.catch_log_handlers['setup'].records] == ['a_setup_log']

assert set(caplog._item.catch_log_handlers.keys()) == {'setup', 'call'}

0 comments on commit b67badc

Please sign in to comment.