From 85efd70a715cabd214cbe95523f96bfd236230b6 Mon Sep 17 00:00:00 2001 From: OlegP-andrew Date: Sun, 10 Dec 2023 23:55:28 -0500 Subject: [PATCH] Adding whitespace escaping on difference display --- AUTHORS | 1 + changelog/10704.improvement.rst | 1 + src/_pytest/assertion/util.py | 12 ++++++++++++ testing/test_error_diffs.py | 14 ++++++++++++++ 4 files changed, 28 insertions(+) create mode 100644 changelog/10704.improvement.rst diff --git a/AUTHORS b/AUTHORS index e30131d1a..6f9d75e3b 100644 --- a/AUTHORS +++ b/AUTHORS @@ -284,6 +284,7 @@ Nicolas Delaby Nikolay Kondratyev Nipunn Koorapati Oleg Pidsadnyi +Oleg Plisov Oleg Sushchenko Olga Matoula Oliver Bestwalter diff --git a/changelog/10704.improvement.rst b/changelog/10704.improvement.rst new file mode 100644 index 000000000..4c4ad4454 --- /dev/null +++ b/changelog/10704.improvement.rst @@ -0,0 +1 @@ +Terminal outputting string difference will now escape whitespace characters if those are the difference diff --git a/src/_pytest/assertion/util.py b/src/_pytest/assertion/util.py index 4d9fd114b..d3ff49ccd 100644 --- a/src/_pytest/assertion/util.py +++ b/src/_pytest/assertion/util.py @@ -305,10 +305,22 @@ def _diff_text(left: str, right: str, verbose: int = 0) -> List[str]: left = left[:-i] right = right[:-i] keepends = True + diffspace = False + for i in range(min(len(left), len(right))): + if left[i] != right[i]: + if left[i].isspace() and right[i].isspace(): + diffspace = True # Check if difference in strings is whitespace symbol + break if left.isspace() or right.isspace(): left = repr(str(left)) right = repr(str(right)) explanation += ["Strings contain only whitespace, escaping them using repr()"] + elif diffspace: + left = repr(str(left)) + right = repr(str(right)) + explanation += [ + "Strings are different by whitespaces, escaping them using repr()" + ] # "right" is the expected base against which we compare "left", # see https://github.com/pytest-dev/pytest/issues/3333 explanation += [ diff --git a/testing/test_error_diffs.py b/testing/test_error_diffs.py index eb7812108..723a68e49 100644 --- a/testing/test_error_diffs.py +++ b/testing/test_error_diffs.py @@ -262,6 +262,20 @@ TESTCASES = [ """, id="Compare attrs classes", ), + pytest.param( + """ + def test_this(): + assert "word\t" == "word " + """, + """ + > assert "word\t" == "word " + E AssertionError: assert 'word\\t' == 'word ' + E Strings are different by whitespaces, escaping them using repr() + E - 'word ' + E + 'word\\t' + """, + id="Compare whitespaces", + ), ]