Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I add an instance method to a Python "Mock" object?

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.

like image 925
orokusaki Avatar asked Jan 20 '13 23:01

orokusaki


People also ask

Can you call method on mocked object?

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.

What is a mock instance?

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.

What is the difference between mock and MagicMock?

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 you mock a method in Python?

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 .


1 Answers

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.

like image 53
Austin Phillips Avatar answered Sep 30 '22 03:09

Austin Phillips