Skip to content

Commit

Permalink
printable filter should replace non-ascii bytes
Browse files Browse the repository at this point in the history
In Python 2, when repr() returns bytes, replace any non-ascii bytes
with the unicode ? character to ensure that the result is printable.

Fixes #66
  • Loading branch information
mgood committed Feb 2, 2014
1 parent 70488fc commit 82295aa
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
5 changes: 4 additions & 1 deletion flask_debugtoolbar/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,10 @@ def replace_insensitive(string, target, replacement):

def _printable(value):
try:
return repr(value)
value = repr(value)
if isinstance(value, bytes):
value = value.decode('ascii', 'replace')
return value
except Exception as e:
return '<repr(%s) raised %s: %s>' % (
object.__repr__(value), type(e).__name__, e)
Expand Down
30 changes: 30 additions & 0 deletions test/test_toolbar.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
import sys

import pytest

from flask_debugtoolbar import _printable


def load_app(name):
app = __import__(name).app
app.config['TESTING'] = True
Expand All @@ -9,3 +16,26 @@ def test_basic_app():
index = app.get('/')
assert index.status_code == 200
assert b'<div id="flDebug"' in index.data


@pytest.mark.skipif(sys.version_info >= (3,),
reason='test only applies to Python 2')
def test_printable_unicode():
class UnicodeRepr(object):
def __repr__(self):
return u'\uffff'

printable = _printable(UnicodeRepr())
assert "raised UnicodeEncodeError: 'ascii' codec" in printable


@pytest.mark.skipif(sys.version_info >= (3,),
reason='test only applies to Python 2')
def test_printable_non_ascii():
class NonAsciiRepr(object):
def __repr__(self):
return 'a\xffb'

printable = u'%s' % _printable(NonAsciiRepr())
# should replace \xff with the unicode ? character
assert printable == u'a\ufffdb'

0 comments on commit 82295aa

Please sign in to comment.