Skip to content

Commit

Permalink
linting
Browse files Browse the repository at this point in the history
  • Loading branch information
Anusha Shekhar authored and Anusha Shekhar committed Dec 14, 2023
1 parent e7f6b98 commit 5fa1164
Show file tree
Hide file tree
Showing 5 changed files with 36 additions and 26 deletions.
5 changes: 4 additions & 1 deletion src/pluggy/_hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -668,7 +668,10 @@ def __init__(
self.trylast: Final = hook_impl_opts["trylast"]

def __repr__(self) -> str:
return f"<HookImpl plugin_name={saferepr(self.plugin_name)}, plugin={saferepr(self.plugin)}>"
return (
f"<HookImpl plugin_name={saferepr(self.plugin_name)}, "
f"plugin={saferepr(self.plugin)}>"
)

Check warning on line 674 in src/pluggy/_hooks.py

View check run for this annotation

Codecov / codecov/patch

src/pluggy/_hooks.py#L674

Added line #L674 was not covered by tests


@final
Expand Down
17 changes: 13 additions & 4 deletions src/pluggy/_tracing.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
"""
from __future__ import annotations

import reprlib
from typing import Any
from typing import Callable
from typing import Sequence
from typing import Tuple
import reprlib


_Writer = Callable[[str], object]
Expand Down Expand Up @@ -60,6 +60,7 @@ def setprocessor(self, tags: str | tuple[str, ...], processor: _Processor) -> No
assert isinstance(tags, tuple)
self._tags2proc[tags] = processor


def _try_repr_or_str(obj: object) -> str:
try:
return repr(obj)
Expand All @@ -68,6 +69,7 @@ def _try_repr_or_str(obj: object) -> str:
except BaseException:
return f'{type(obj).__name__}("{obj}")'


Check warning on line 72 in src/pluggy/_tracing.py

View check run for this annotation

Codecov / codecov/patch

src/pluggy/_tracing.py#L71-L72

Added lines #L71 - L72 were not covered by tests
def _format_repr_exception(exc: BaseException, obj: object) -> str:
try:
exc_info = _try_repr_or_str(exc)
Expand All @@ -79,20 +81,24 @@ def _format_repr_exception(exc: BaseException, obj: object) -> str:
exc_info, type(obj).__name__, id(obj)
)


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

x = len(s) - j
return s[:i] + "..." + s[x:]
return s


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

def __init__(self, maxsize: Optional[int], use_ascii: bool = False) -> None:
def __init__(self, maxsize: int | None, use_ascii: bool = False) -> None:
"""
:param maxsize:
If not None, will truncate the resulting repr to that specific size, using ellipsis
Expand Down Expand Up @@ -136,8 +142,10 @@ def repr_instance(self, x: object, level: int) -> str:

# Maximum size of overall repr of objects to display during assertion errors.
DEFAULT_REPR_MAX_SIZE = 240


def saferepr(
obj: object, maxsize: Optional[int] = DEFAULT_REPR_MAX_SIZE, use_ascii: bool = False
obj: object, maxsize: int | None = DEFAULT_REPR_MAX_SIZE, use_ascii: bool = False
) -> str:
"""Return a size-limited safe repr-string for the given object.
Expand All @@ -151,6 +159,7 @@ def saferepr(

return SafeRepr(maxsize, use_ascii).repr(obj)


class TagTracerSub:
def __init__(self, root: TagTracer, tags: tuple[str, ...]) -> None:
self.root = root
Expand Down
3 changes: 1 addition & 2 deletions testing/benchmark.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,13 @@
"""
import pytest

from ._tracing import saferepr
from pluggy import HookimplMarker
from pluggy import HookspecMarker
from pluggy import PluginManager
from pluggy._callers import _multicall
from pluggy._hooks import HookImpl

from ._tracing import saferepr


hookspec = HookspecMarker("example")
hookimpl = HookimplMarker("example")
Expand Down
13 changes: 4 additions & 9 deletions testing/test_hookcaller.py
Original file line number Diff line number Diff line change
Expand Up @@ -450,20 +450,15 @@ def conflict(self) -> None:
"<class 'test_hookcaller.test_hook_conflict.<locals>.Api1'>"
)

def test_hookcaller_repr_with_saferepr_failure(hc: HookCaller, addmeth: AddMeth) -> None:
@addmeth()
def he_method1() -> None:
pass

def test_hookcaller_repr_with_saferepr_failure(
hc: HookCaller, addmeth: AddMeth
) -> None:
@addmeth()
def he_method2() -> None:
# Intentional error to make the repr fail
raise ValueError("Intentional error in he_method2")

Check warning on line 460 in testing/test_hookcaller.py

View check run for this annotation

Codecov / codecov/patch

testing/test_hookcaller.py#L460

Added line #L460 was not covered by tests

@addmeth()
def he_method3() -> None:
pass

# Verify that HookCaller.repr with saferepr still works despite the error
expected_repr = f"<HookCaller {saferepr(hc.name)}>"
assert repr(hc) == expected_repr
assert repr(hc) == expected_repr
24 changes: 14 additions & 10 deletions testing/test_tracer.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

import pytest

from pluggy._tracing import saferepr, DEFAULT_REPR_MAX_SIZE
from pluggy._tracing import DEFAULT_REPR_MAX_SIZE
from pluggy._tracing import saferepr
from pluggy._tracing import TagTracer


Expand Down Expand Up @@ -79,6 +80,7 @@ def test_setprocessor(rootlogger: TagTracer) -> None:
tags, args = l2[0]
assert args == ("seen",)


def test_saferepr_simple_repr():
assert saferepr(1) == "1"
assert saferepr(None) == "None"
Expand Down Expand Up @@ -110,10 +112,10 @@ def __repr__(self):

def test_saferepr_exceptions() -> None:
class BrokenRepr:
def __init__(self, ex):
def __init__(self, ex) -> None:
self.ex = ex

def __repr__(self):
def __repr__(self) -> str:
raise self.ex

class BrokenReprException(Exception):
Expand Down Expand Up @@ -143,10 +145,10 @@ def test_saferepr_baseexception():
"""Test saferepr() with BaseExceptions, which includes pytest outcomes."""

class RaisingOnStrRepr(BaseException):
def __init__(self, exc_types):
def __init__(self, exc_types) -> None:
self.exc_types = exc_types

def raise_exc(self, *args):
def raise_exc(self, *args) -> None:
try:
self.exc_type = self.exc_types.pop(0)
except IndexError:
Expand All @@ -155,17 +157,19 @@ def raise_exc(self, *args):
raise self.exc_type(*args)
raise self.exc_type

def __str__(self):
def __str__(self) -> str:
self.raise_exc("__str__")
return ""

Check warning on line 162 in testing/test_tracer.py

View check run for this annotation

Codecov / codecov/patch

testing/test_tracer.py#L162

Added line #L162 was not covered by tests

def __repr__(self):
def __repr__(self) -> str:
self.raise_exc("__repr__")
return ""

Check warning on line 166 in testing/test_tracer.py

View check run for this annotation

Codecov / codecov/patch

testing/test_tracer.py#L166

Added line #L166 was not covered by tests

class BrokenObj:
def __init__(self, exc):
def __init__(self, exc) -> None:
self.exc = exc

def __repr__(self):
def __repr__(self) -> str:
raise self.exc

__str__ = __repr__
Expand Down Expand Up @@ -247,4 +251,4 @@ def __repr__(self):

assert saferepr(SomeClass()).startswith(
"<[RuntimeError() raised in repr()] SomeClass object at 0x"
)
)

0 comments on commit 5fa1164

Please sign in to comment.