Skip to content

Commit

Permalink
Merge pull request #1107 from dbowd/patch-1
Browse files Browse the repository at this point in the history
Fix unicode error when trying to escape binary data
  • Loading branch information
matthiask committed Nov 28, 2018
2 parents 52f9ac8 + efc9180 commit e78ac8c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
7 changes: 5 additions & 2 deletions debug_toolbar/panels/sql/tracking.py
Expand Up @@ -6,7 +6,7 @@
from time import time

from django.utils import six
from django.utils.encoding import force_text
from django.utils.encoding import DjangoUnicodeDecodeError, force_text

from debug_toolbar import settings as dt_settings
from debug_toolbar.utils import get_stack, get_template_info, tidy_stacktrace
Expand Down Expand Up @@ -88,7 +88,10 @@ def __init__(self, cursor, db, logger):

def _quote_expr(self, element):
if isinstance(element, six.string_types):
return "'%s'" % force_text(element).replace("'", "''")
try:
return "'%s'" % force_text(element).replace("'", "''")
except DjangoUnicodeDecodeError:
return repr(element)
else:
return repr(element)

Expand Down
19 changes: 19 additions & 0 deletions tests/panels/test_sql.py
Expand Up @@ -113,6 +113,25 @@ def test_param_conversion(self):
('["Foo", true, false]', "[10, 1]", '["2017-12-22 16:07:01"]'),
)

@unittest.skipIf(
connection.vendor in ("sqlite", "postgresql"),
"Mixing bytestrings and text is not allowed on PostgreSQL and SQLite",
)
def test_binary_param_force_text(self):
self.assertEqual(len(self.panel._queries), 0)

with connection.cursor() as cursor:
cursor.execute("SELECT * FROM auth_user WHERE username = %s", [b"\xff"])

self.panel.process_response(self.request, self.response)
self.panel.generate_stats(self.request, self.response)

self.assertEqual(len(self.panel._queries), 1)
self.assertEqual(
self.panel._queries[0][1]["sql"],
"SELECT * FROM auth_user WHERE username = '\ufffd'",
)

@unittest.skipUnless(connection.vendor != "sqlite", "Test invalid for SQLite")
def test_raw_query_param_conversion(self):
self.assertEqual(len(self.panel._queries), 0)
Expand Down

0 comments on commit e78ac8c

Please sign in to comment.