Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Behavior of spy on class attributes #397

Closed
santicardona opened this issue Nov 15, 2023 · 3 comments
Closed

Behavior of spy on class attributes #397

santicardona opened this issue Nov 15, 2023 · 3 comments
Labels

Comments

@santicardona
Copy link

santicardona commented Nov 15, 2023

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.

@santicardona santicardona changed the title Behavior of Spy on class attributes Behavior of spy on class attributes Nov 16, 2023
@nicoddemus
Copy link
Member

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)

@santicardona
Copy link
Author

santicardona commented Nov 16, 2023

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.

@nicoddemus
Copy link
Member

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.

@nicoddemus nicoddemus closed this as not planned Won't fix, can't repro, duplicate, stale Nov 17, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants