Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding whitespace escaping on difference display #11696

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

OlegP-andrew
Copy link

@OlegP-andrew OlegP-andrew commented Dec 11, 2023

Solves #10704.

Resolved issue of terminal output showing unhelpful messages if the differentiating symbols are whitespaces.

Solution in util.py/_diff_text:

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()"
        ]

We go through the compared strings, checking if any differentiating symbols are both whitespaces,
after which, unless the strings are already fully escaped due being just whitespace, we escape them using
repr() adding explanation why that's happening.

Testing:

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",
    )

Adding new parameter to test_error_diffs which tests the behaviour of displaying whitespaces correctly.
Output of test in the terminal:
image

@OlegP-andrew
Copy link
Author

There's consideration to add escaping if the difference between the two strings is stuff like trailing spaces. Current solution only works if different symbols exist in both strings and are whitespaces, so something like difference by trailing whitespace might still be not humanly
readable in the difference.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant