From 8c7eb8236348c8fb8db43a6a9c02ba442a09f6b8 Mon Sep 17 00:00:00 2001 From: Daniel Hahler Date: Wed, 15 May 2019 12:03:00 +0200 Subject: [PATCH] Fix/improve comparison of byte strings Fixes https://github.com/pytest-dev/pytest/issues/5260. --- changelog/5260.bugfix.rst | 1 + src/_pytest/assertion/util.py | 5 ++++- testing/test_assertion.py | 12 ++++++++++++ 3 files changed, 17 insertions(+), 1 deletion(-) create mode 100644 changelog/5260.bugfix.rst diff --git a/changelog/5260.bugfix.rst b/changelog/5260.bugfix.rst new file mode 100644 index 000000000..ab521d163 --- /dev/null +++ b/changelog/5260.bugfix.rst @@ -0,0 +1 @@ +Improve/fix comparison of byte strings with Python 3. diff --git a/src/_pytest/assertion/util.py b/src/_pytest/assertion/util.py index 762e5761d..493c630f6 100644 --- a/src/_pytest/assertion/util.py +++ b/src/_pytest/assertion/util.py @@ -263,8 +263,11 @@ def _compare_eq_sequence(left, right, verbose=0): "At index {} diff: {!r} != {!r}".format(i, left[i], right[i]) ] break - len_diff = len_left - len_right + if isinstance(left, bytes): + return explanation + + len_diff = len_left - len_right if len_diff: if len_diff > 0: dir_with_more = "Left" diff --git a/testing/test_assertion.py b/testing/test_assertion.py index 0fcfd9f27..f9c67d703 100644 --- a/testing/test_assertion.py +++ b/testing/test_assertion.py @@ -331,6 +331,18 @@ class TestAssert_reprcompare: 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'", + "At index 0 diff: 115 != 101", + "Use -v to get the full diff", + ] + else: + # Handled as text on Python 2. + assert diff == ["'spam' == 'eggs'", "- spam", "+ eggs"] + def test_list(self): expl = callequal([0, 1], [0, 2]) assert len(expl) > 1