| 1 |
# Stub out only the subset of the interface that we actually use in our tests. |
| 2 |
class StubClass: |
| 3 |
def __init__(self, *args, **kwargs): |
| 4 |
self.__stub_args = args |
| 5 |
self.__stub_kwargs = kwargs |
| 6 |
self.__repr = None |
| 7 |
|
| 8 |
def _with_repr(self, new_repr): |
| 9 |
new_obj = self.__class__(*self.__stub_args, **self.__stub_kwargs) |
| 10 |
new_obj.__repr = new_repr |
| 11 |
return new_obj |
| 12 |
|
| 13 |
def __repr__(self): |
| 14 |
if self.__repr is not None: |
| 15 |
return self.__repr |
| 16 |
|
| 17 |
argstr = ", ".join(self.__stub_args) |
| 18 |
kwargstr = ", ".join(f"{kw}={val}" for kw, val in self.__stub_kwargs.items()) |
| 19 |
|
| 20 |
in_parens = argstr |
| 21 |
if kwargstr: |
| 22 |
in_parens += ", " + kwargstr |
| 23 |
|
| 24 |
return f"{self.__class__.__qualname__}({in_parens})" |
| 25 |
|
| 26 |
|
| 27 |
def stub_factory(klass, name, *, with_repr=None, _seen={}): |
| 28 |
if (klass, name) not in _seen: |
| 29 |
|
| 30 |
class Stub(klass): |
| 31 |
def __init__(self, *args, **kwargs): |
| 32 |
super().__init__() |
| 33 |
self.__stub_args = args |
| 34 |
self.__stub_kwargs = kwargs |
| 35 |
|
| 36 |
Stub.__name__ = name |
| 37 |
Stub.__qualname__ = name |
| 38 |
if with_repr is not None: |
| 39 |
Stub._repr = None |
| 40 |
|
| 41 |
_seen.setdefault((klass, name, with_repr), Stub) |
| 42 |
|
| 43 |
return _seen[(klass, name, with_repr)] |