pytest-dev/pytest-mock

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:

spy_obj = self.patch.object(obj, name, side_effect=wrapped, autospec=autospec)

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.

To be honest I'm not sure how to proceed, particularly I don't have a solution or strong opinion on this.

I suggest we move this discussion over #35, as these two topics are basically the same. 👍

Closing this issue, feel free to follow up on #35 if you have a proposal to move this forward.