Skip to content

Commit

Permalink
Fix/improve comparison of byte strings
Browse files Browse the repository at this point in the history
Fixes #5260.
  • Loading branch information
blueyed committed May 15, 2019
1 parent c0e53a6 commit 40b0b80
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 5 deletions.
1 change: 1 addition & 0 deletions changelog/5260.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Improve/fix comparison of byte strings with Python 3.
16 changes: 11 additions & 5 deletions src/_pytest/assertion/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,9 @@ def assertrepr_compare(config, op, left, right):
explanation = None
try:
if op == "==":
if istext(left) and istext(right):
if isinstance(left, bytes) and isinstance(right, bytes):
explanation = _diff_text(left, right, verbose)
elif istext(left) and istext(right):
explanation = _diff_text(left, right, verbose)
else:
if issequence(left) and issequence(right):
Expand Down Expand Up @@ -199,11 +201,15 @@ def _diff_text(left, right, verbose=0):

def escape_for_readable_diff(binary_text):
"""
Ensures that the internal string is always valid unicode, converting any bytes safely to valid unicode.
This is done using repr() which then needs post-processing to fix the encompassing quotes and un-escape
newlines and carriage returns (#429).
Ensure that the internal string is always valid unicode, converting
any bytes safely to valid unicode.
This is done using repr() which then needs post-processing to fix the
encompassing quotes and un-escape newlines and carriage returns (#429).
"""
r = six.text_type(repr(binary_text)[1:-1])
r = repr(binary_text)
if r.startswith("b'"):
r = r[1:]
r = six.text_type(r[1:-1])
r = r.replace(r"\n", "\n")
r = r.replace(r"\r", "\r")
return r
Expand Down
7 changes: 7 additions & 0 deletions testing/test_assertion.py
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,13 @@ def test_multiline_text_diff(self):
assert "- spam" in diff
assert "+ eggs" in diff

def test_bytes_diff(self):
diff = callequal(b"spam", b"eggs")
if PY3:
assert diff == ["b'spam' == b'eggs'", "- spam", "+ eggs"]
else:
assert diff == ["'spam' == 'eggs'", "- spam", "+ eggs"]

def test_list(self):
expl = callequal([0, 1], [0, 2])
assert len(expl) > 1
Expand Down

0 comments on commit 40b0b80

Please sign in to comment.