Is it possible to add an instance method to a Python "Mock" object?
I would like to create an object mock.Mock()
and then add a named method session
that acts like an instance method that is passed a reference self
to the object's layout, allowing the method to add state to the object's layout. Is this possible (no manual use types.MethodType
, like using the built-in API), or should I just find a way to use it?
Note I found this question which is for Ruby and seems to cover something similar, if not the same. Unfortunately, I don't know Ruby at all.
source to share
If you want to improve the capabilities of a class mock.Mock
, just subclass Mock
and add your own methods.
class MyMock(Mock):
def session(self):
# Save session data here?
The mock documentation explains that when a new mock is created, it will be the same type as the parent. This means that the feature session
will also be available for any other layouts that are created during taunts.
This does not apply if you need to dynamically attach a function session
to an existing layout.
source to share