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

Simplify SafeRepr a bit #5603

Merged
merged 4 commits into from
Jul 16, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/5603.trivial.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Simplified internal ``SafeRepr`` class and removed some dead code.
83 changes: 36 additions & 47 deletions src/_pytest/_io/saferepr.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,65 +2,59 @@
import reprlib


def _call_and_format_exception(call, x, *args):
def _format_repr_exception(exc, obj):
exc_name = type(exc).__name__
try:
# Try the vanilla repr and make sure that the result is a string
return call(x, *args)
except Exception as exc:
exc_name = type(exc).__name__
try:
exc_info = str(exc)
except Exception:
exc_info = "unknown"
return '<[{}("{}") raised in repr()] {} object at 0x{:x}>'.format(
exc_name, exc_info, x.__class__.__name__, id(x)
)
exc_info = str(exc)
except Exception:
exc_info = "unknown"
return '<[{}("{}") raised in repr()] {} object at 0x{:x}>'.format(
exc_name, exc_info, obj.__class__.__name__, id(obj)
)


def _ellipsize(s, maxsize):
if len(s) > maxsize:
i = max(0, (maxsize - 3) // 2)
j = max(0, maxsize - 3 - i)
return s[:i] + "..." + s[len(s) - j :]
return s


class SafeRepr(reprlib.Repr):
"""subclass of repr.Repr that limits the resulting size of repr()
and includes information on exceptions raised during the call.
"""

def repr(self, x):
return self._callhelper(reprlib.Repr.repr, self, x)

def repr_unicode(self, x, level):
# Strictly speaking wrong on narrow builds
def repr(u):
if "'" not in u:
return "'%s'" % u
elif '"' not in u:
return '"%s"' % u
else:
return "'%s'" % u.replace("'", r"\'")
def __init__(self, maxsize):
super().__init__()
self.maxstring = maxsize
self.maxsize = maxsize

s = repr(x[: self.maxstring])
if len(s) > self.maxstring:
i = max(0, (self.maxstring - 3) // 2)
j = max(0, self.maxstring - 3 - i)
s = repr(x[:i] + x[len(x) - j :])
s = s[:i] + "..." + s[len(s) - j :]
return s
def repr(self, x):
try:
s = super().repr(x)
except Exception as exc:
bluetech marked this conversation as resolved.
Show resolved Hide resolved
s = _format_repr_exception(exc, x)
return _ellipsize(s, self.maxsize)

def repr_instance(self, x, level):
return self._callhelper(repr, x)

def _callhelper(self, call, x, *args):
s = _call_and_format_exception(call, x, *args)
if len(s) > self.maxsize:
i = max(0, (self.maxsize - 3) // 2)
j = max(0, self.maxsize - 3 - i)
s = s[:i] + "..." + s[len(s) - j :]
return s
try:
s = repr(x)
except Exception as exc:
s = _format_repr_exception(exc, x)
return _ellipsize(s, self.maxsize)


def safeformat(obj):
"""return a pretty printed string for the given object.
Failing __repr__ functions of user instances will be represented
with a short exception info.
"""
return _call_and_format_exception(pprint.pformat, obj)
try:
return pprint.pformat(obj)
except Exception as exc:
return _format_repr_exception(exc, obj)


def saferepr(obj, maxsize=240):
Expand All @@ -70,9 +64,4 @@ def saferepr(obj, maxsize=240):
care to never raise exceptions itself. This function is a wrapper
around the Repr/reprlib functionality of the standard 2.6 lib.
"""
# review exception handling
srepr = SafeRepr()
srepr.maxstring = maxsize
srepr.maxsize = maxsize
srepr.maxother = 160
return srepr.repr(obj)
return SafeRepr(maxsize).repr(obj)
13 changes: 12 additions & 1 deletion testing/io/test_saferepr.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,21 @@ class BrokenReprException(Exception):
assert "unknown" in s2


def test_buggy_builtin_repr():
# Simulate a case where a repr for a builtin raises.
# reprlib dispatches by type name, so use "int".

class int:
def __repr__(self):
raise ValueError("Buggy repr!")

assert "Buggy" in saferepr(int())


def test_big_repr():
from _pytest._io.saferepr import SafeRepr

assert len(saferepr(range(1000))) <= len("[" + SafeRepr().maxlist * "1000" + "]")
assert len(saferepr(range(1000))) <= len("[" + SafeRepr(0).maxlist * "1000" + "]")


def test_repr_on_newstyle():
Expand Down