From f9302f1ca15136d2ad9d0e5dfd0aa31d1c471da4 Mon Sep 17 00:00:00 2001 From: Itxaso Aizpurua Date: Sat, 8 Oct 2022 08:48:23 +0200 Subject: [PATCH] Return ascii(obj) or repr(obj) + tests --- src/_pytest/_io/saferepr.py | 13 +++++++------ src/_pytest/assertion/util.py | 2 ++ testing/test_assertion.py | 4 ++-- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/src/_pytest/_io/saferepr.py b/src/_pytest/_io/saferepr.py index c1bb3ae8f..9b4378e06 100644 --- a/src/_pytest/_io/saferepr.py +++ b/src/_pytest/_io/saferepr.py @@ -41,7 +41,7 @@ class SafeRepr(reprlib.Repr): information on exceptions raised during the call. """ - def __init__(self, maxsize: Optional[int]) -> None: + def __init__(self, maxsize: Optional[int], use_ascii: bool = False) -> None: """ :param maxsize: If not None, will truncate the resulting repr to that specific size, using ellipsis @@ -54,9 +54,13 @@ class SafeRepr(reprlib.Repr): # truncation. self.maxstring = maxsize if maxsize is not None else 1_000_000_000 self.maxsize = maxsize + self.use_ascii = use_ascii def repr(self, x: object) -> str: try: + if self.use_ascii: + return ascii(x) + s = super().repr(x) except (KeyboardInterrupt, SystemExit): raise @@ -107,10 +111,7 @@ def saferepr( stdlib. """ - if use_ascii: - obj = ascii(obj) - - return SafeRepr(maxsize).repr(obj) + return SafeRepr(maxsize, use_ascii).repr(obj) def saferepr_unlimited(obj: object, use_ascii: bool = True) -> str: @@ -126,7 +127,7 @@ def saferepr_unlimited(obj: object, use_ascii: bool = True) -> str: """ try: if use_ascii: - obj = ascii(obj) + return ascii(obj) return repr(obj) except Exception as exc: return _format_repr_exception(exc, obj) diff --git a/src/_pytest/assertion/util.py b/src/_pytest/assertion/util.py index 32ad03e78..fc5dfdbd5 100644 --- a/src/_pytest/assertion/util.py +++ b/src/_pytest/assertion/util.py @@ -163,6 +163,8 @@ def assertrepr_compare( """Return specialised explanations for some operators/operands.""" verbose = config.getoption("verbose") + # Strings which normalize equal are often hard to distinguish when printed; use ascii() to make this easier. + # See issue #3246. use_ascii = ( isinstance(left, str) and isinstance(right, str) diff --git a/testing/test_assertion.py b/testing/test_assertion.py index 27bb69269..d8844f2e4 100644 --- a/testing/test_assertion.py +++ b/testing/test_assertion.py @@ -782,14 +782,14 @@ class TestAssert_reprcompare: right = "hyva\u0308" expl = callequal(left, right) assert expl == [ - "\"'hyv\\\\xe4'\" == \"'hyva\\\\u0308'\"", + r"'hyv\xe4' == 'hyva\u0308'", f"- {str(right)}", f"+ {str(left)}", ] expl = callequal(left, right, verbose=2) assert expl == [ - "\"'hyv\\\\xe4'\" == \"'hyva\\\\u0308'\"", + r"'hyv\xe4' == 'hyva\u0308'", f"- {str(right)}", f"+ {str(left)}", ]