Join GitHub today
GitHub is home to over 28 million developers working together to host and review code, manage projects, and build software together.Sign up
Spying on properties #35
I've tried to use
I've started looking into adding support for (through
I would appreciate any feedback / help in this regard.
This a nice feature that I didn't even think about because I guess never really mocked a property before.
Below it is a draft I've come up in a hurry that is really buggy but get the basics done:
def spy(self, obj, name): if isinstance(getattr(obj, name), property): prop = getattr(obj, name) class SpyPropertyMock(mock_module.PropertyMock): def __get__(self, obj, obj_type): self() return prop.__get__(obj) def __set__(self, obj, val): self(val) prop.fset(obj, val) result = self.patch.object(obj, name, new_callable=SpyPropertyMock) return result else: method = getattr(obj, name) autospec = inspect.ismethod(method) or inspect.isfunction(method) # Can't use autospec classmethod or staticmethod objects # see: https://bugs.python.org/issue23078 if inspect.isclass(obj): # bypass class descriptor: # http://stackoverflow.com/questions/14187973/python3-check-if-method-is-static value = obj.__getattribute__(obj, name) if isinstance(value, (classmethod, staticmethod)): autospec = False result = self.patch.object(obj, name, side_effect=method, autospec=autospec) return result
A test using it:
def testFoo(mocker): mocked = mocker.spy(Foo, 'foo') foo = Foo() foo.foo = 'b' assert foo.foo == 'b' assert foo.foo != 'c' assert foo.foo != 'd' print mocked.mock_calls # [call(u'b'), call(), call(), call()]
With this, the mock object returned can be used to inspect
Problems I've seen so far:
Anyway I have to get more used to