Behavior of spy on class attributes
santicardona opened this issue · 3 comments
I was playing around with the spy feature and realized it will happily create a spy object when referencing a class attribute:
class MyClass:
attribute: str = "default_value"
def test_my_class(mocker):
my_class = MyClass()
spy = mocker.spy(my_class, "attribute")
assert True
However, if I change the line
spy = mocker.spy(my_class, "attribute)
to something like
spy = mocker.spy(my_class, "not_an_attribute")
It will of course complain that MyClass doesn't have an attribute "not_an_attribute".
It seems a bit odd to me that the case above won't raise an Exception or a Warning, given that spy is supposed to be used for methods and functions. Would like to know what you think.
Hi,
We use mock.patch.object
, which seems to install this happily in attributes too:
pytest-mock/src/pytest_mock/plugin.py
Line 178 in 1ff80b2
Hi,
Thanks for the quick reply. Sure, mock.patch.object
has no problem creating that object but it also has no problem with something like
patch.object(my_class, "not_attribute")
while spy will throw an Error. Just thought the behavior was kind of weird. By the way, the reason it throws an error is because of the first line of the spy method:
method = getattr(obj, name)
Thought maybe you could treat attributes / properties somewhat differently and at the same time solve this issue for example: #35
Let me know what you think, cheers.