Skip to content

Commit

Permalink
Make reprs more accurate
Browse files Browse the repository at this point in the history
  • Loading branch information
pganssle committed Apr 25, 2023
1 parent 9ea754c commit 308b16f
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 12 deletions.
24 changes: 17 additions & 7 deletions Lib/test/support/_hypothesis_stubs/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,28 @@ class StubClass:
def __init__(self, *args, **kwargs):
self.__stub_args = args
self.__stub_kwargs = kwargs
self.__repr = None

def _with_repr(self, new_repr):
new_obj = self.__class__(*self.__stub_args, **self.__stub_kwargs)
new_obj.__repr = new_repr
return new_obj

def __repr__(self):
if self.__repr is not None:
return self.__repr

argstr = ", ".join(self.__stub_args)
kwargstr = ", ".join(
f"{kw}={val}" for kw, val in self.__stub_kwargs.items()
)
kwargstr = ", ".join(f"{kw}={val}" for kw, val in self.__stub_kwargs.items())

in_parens = argstr
if kwargstr:
in_parens += ", " + kwargstr

return f"{self.__qualname__}({in_parens})"
return f"{self.__class__.__qualname__}({in_parens})"


def stub_factory(klass, name, _seen={}):
def stub_factory(klass, name, *, with_repr=None, _seen={}):
if (klass, name) not in _seen:

class Stub(klass):
Expand All @@ -28,6 +35,9 @@ def __init__(self, *args, **kwargs):

Stub.__name__ = name
Stub.__qualname__ = name
_seen.setdefault((klass, name), Stub)
if with_repr is not None:
Stub._repr = None

_seen.setdefault((klass, name, with_repr), Stub)

return _seen[(klass, name)]
return _seen[(klass, name, with_repr)]
16 changes: 11 additions & 5 deletions Lib/test/support/_hypothesis_stubs/strategies.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,22 @@


class StubStrategy(StubClass):
def __make_trailing_repr(self, transformation_name, func):
func_name = func.__name__ or repr(func)
return f"{self!r}.{transformation_name}({func_name})"

def map(self, pack):
return self
return self._with_repr(self.__make_trailing_repr("map", pack))

def flatmap(self, expand):
return self
return self._with_repr(self.__make_trailing_repr("flatmap", expand))

def filter(self, condition):
return self
return self._with_repr(self.__make_trailing_repr("filter", condition))

def __or__(self, other):
return self
new_repr = f"one_of({self!r}, {other!r})"
return self._with_repr(new_repr)


_STRATEGIES = {
Expand All @@ -37,7 +42,8 @@ def __or__(self, other):
"from_regex",
"from_type",
"frozensets",
"functions" "integers",
"functions",
"integers",
"iterables",
"just",
"lists",
Expand Down

0 comments on commit 308b16f

Please sign in to comment.