Skip to content

Commit

Permalink
Use record.message field instead of getMessage() method
Browse files Browse the repository at this point in the history
In case when a log record has mutable objects attached as arguments,
the getMessage() method may return different results each time it is
called. Instead, use the 'message' field initialized by a formatter
upon a record reaches a handler.
  • Loading branch information
abusalimov committed Apr 19, 2016
1 parent 1570124 commit e51ddfd
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 1 deletion.
2 changes: 1 addition & 1 deletion pytest_catchlog/fixture.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def record_tuples(self):
(logger_name, log_level, message)
"""
return [(r.name, r.levelno, r.getMessage()) for r in self.records]
return [(r.name, r.levelno, r.message) for r in self.records]

def set_level(self, level, logger=None):
"""Sets the level for capturing of logs.
Expand Down
19 changes: 19 additions & 0 deletions tests/test_fixture.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
import sys
import logging
from fnmatch import fnmatch

import pytest

Expand Down Expand Up @@ -65,3 +66,21 @@ def test_unicode(caplog):
assert caplog.records[0].levelname == 'INFO'
assert caplog.records[0].msg == u('bū')
assert u('bū') in caplog.text


def test_mutable_arg(caplog):
mutable = {}
logger.info("Mutable dict %r empty", mutable)
mutable['foo'] = 'bar'
logger.info("Mutable dict %r bar", mutable)
mutable['foo'] = 'baz'
logger.info("Mutable dict %r baz", mutable)

assert caplog.record_tuples == [
(__name__, logging.INFO, "Mutable dict {} empty"),
(__name__, logging.INFO, "Mutable dict {'foo': 'bar'} bar"),
(__name__, logging.INFO, "Mutable dict {'foo': 'baz'} baz"),
]
assert fnmatch(caplog.text, ("*Mutable dict {} empty\n"
"*Mutable dict {'foo': 'bar'} bar\n"
"*Mutable dict {'foo': 'baz'} baz\n"))
23 changes: 23 additions & 0 deletions tests/test_reporting.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,3 +138,26 @@ def test_foo():
'text going to stderr'])
with pytest.raises(pytest.fail.Exception):
result.stdout.fnmatch_lines(['*- Captured *log call -*'])


def test_mutable_arg(testdir):
testdir.makepyfile('''
import logging
logger = logging.getLogger(__name__)
def test_it():
mutable = {}
logger.info("Mutable dict %r empty", mutable)
mutable['foo'] = 'bar'
logger.info("Mutable dict %r bar", mutable)
mutable['foo'] = 'baz'
logger.info("Mutable dict %r baz", mutable)
assert False
''')
result = testdir.runpytest()
assert result.ret == 1
result.stdout.fnmatch_lines(['*- Captured *log call -*',
"*Mutable dict {} empty",
"*Mutable dict {'foo': 'bar'} bar",
"*Mutable dict {'foo': 'baz'} baz"])

0 comments on commit e51ddfd

Please sign in to comment.