studioj
studioj

Reputation: 1400

is there a simple way of adding __name__ to MagicMock attributes recursively

Statement

when I ask a __name__ of a MagicMock object I get an AttributeError => which is just how MagicMock works I think.

from mock import MagicMock
a = MagicMock()
a.__name__

-------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
----> 1 a.__name__

this is easily solved by :

a.__name__ = "some_name"

BUT

a.some_attr.__name__
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
----> 1 a.some_attr.__name__

any deeper attribute I ask of course still returns an AttributeError

Question

is there an easy way to add the __name__ to the "not yet" requested attrs of a MagicMock ??

Upvotes: 5

Views: 978

Answers (1)

studioj
studioj

Reputation: 1400

ok solution is easier than expected

>>> from unittest.mock import MagicMock

>>> class MySpecialMagicMock(MagicMock):
>>>     __name__ = "some value"

>>> a = MySpecialMagicMock()

>>> a.__name__
some value

>>> a.another_attribute.__name__    
some value

Upvotes: 1

Related Questions