Return ascii(obj) or repr(obj) + tests

This commit is contained in:
Itxaso Aizpurua 2022-10-08 08:48:23 +02:00
parent 50d75b3822
commit f9302f1ca1
3 changed files with 11 additions and 8 deletions

View File

@ -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)

View File

@ -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)

View File

@ -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)}",
]