Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Force event to str in ConsoleRenderer #221

Merged
merged 5 commits into from Oct 16, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/structlog/dev.py
Expand Up @@ -8,7 +8,7 @@

from __future__ import absolute_import, division, print_function

from six import StringIO
from six import PY2, StringIO, string_types


try:
Expand Down Expand Up @@ -213,7 +213,11 @@ def __call__(self, _, __, event_dict):
+ "] "
)

# force event to str for compatibility with standard library
event = event_dict.pop("event")
if not PY2 or not isinstance(event, string_types):
event = str(event)

if event_dict:
event = _pad(event, self._pad_event) + self._styles.reset + " "
else:
Expand Down
21 changes: 21 additions & 0 deletions tests/test_dev.py
Expand Up @@ -81,6 +81,27 @@ def test_timestamp(self, cr, styles, unpadded):

assert (styles.timestamp + "42" + styles.reset + " " + unpadded) == rv

def test_event_stringified(self, cr, styles, unpadded):
"""
Event is cast to string.
"""
not_a_string = Exception("test")

rv = cr(None, None, {"event": not_a_string})

assert unpadded == rv

@pytest.mark.skipif(not six.PY2, reason="Problem only exists on Python 2.")
@pytest.mark.parametrize("s", [u"\xc3\xa4".encode("utf-8"), u"ä", "ä"])
def test_event_py2_only_stringify_non_strings(self, cr, s, styles):
"""
If event is a string type already, leave it be on Python 2. Running
str() on unicode strings with non-ascii characters raises an error.
"""
rv = cr(None, None, {"event": s})

assert styles.bright + s + styles.reset == rv

def test_level(self, cr, styles, padded):
"""
Levels are rendered aligned, in square brackets, and color coded.
Expand Down