I would like to create a mock.Mock()
object, then add a method called session
that acts like an instance method, which is passed a self
reference to the mock object, allowing the method to add state to the mock object. Is this possible (without manually using types.MethodType
, e.g., using mock's built-in API), or should I just find a way around it?
Note, I found this question, which is for Ruby and seems to cover something similar, if not the same thing. Unfortunately, I don't know Ruby very well at all.
Mockito allows us to partially mock an object. This means that we can create a mock object and still be able to call a real method on it.
Instance mocking means that a statement like: $obj = new \MyNamespace\Foo; …will actually generate a mock object. This is done by replacing the real class with an instance mock (similar to an alias mock), as with mocking public methods.
Mock allows you to assign functions (or other Mock instances) to magic methods and they will be called appropriately. The MagicMock class is just a Mock variant that has all of the magic methods pre-created for you (well, all the useful ones anyway).
How do we mock in Python? Mocking in Python is done by using patch to hijack an API function or object creation call. When patch intercepts a call, it returns a MagicMock object by default. By setting properties on the MagicMock object, you can mock the API call to return any value you want or raise an Exception .
If you want to enhance the capabilities of the mock.Mock
class, 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 to be created, it will be the same type as the parent. This means that the session
function will also be available on any other mocks which are created during mocking.
This doesn't cover the case where you need to dynamically attach a session
function to an existing mock object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With