Somebody
Somebody

Reputation: 236

Mock class returning same value for all attributes

I want to mock a class and for any attribute it should return the same string.

c = SomeMocking(all_attributes="abc")
c.foo == "abc"
True
c.bar == "abc"
True

Should https://docs.python.org/3/library/unittest.mock.html do the trick? I only find return_value which can be used for function calls and not for arbitrary attributes.

Upvotes: 1

Views: 159

Answers (1)

Markus
Markus

Reputation: 316

Don't know if this is too simple. But this would always return the same value for every attribute:

class A:
    def __getattribute__(self, name):
        return 'abc'

print(A().foo)

If you also want to have your own attributes in the class and only have this used for undefined ones, you should use __getattr__. You can read about the difference in this post.

These special methods simply mimic the access to an attribute with the name give in the name parameter.

Upvotes: 1

Related Questions