8

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.

Community
  • 1
  • 1
orokusaki
  • 55,146
  • 59
  • 179
  • 257

2 Answers2

6
mock_answer = Mock()

def session():
    mock_answer.b = 1

mock_answer.session = session
mock_answer.session()
print(mock_answer.b)  # 1

You don't need self actually.

laike9m
  • 18,344
  • 20
  • 107
  • 140
  • 1
    but if you need to use self you could use partial: `from functools import partial` and then `mock_answer.session = partial(session, mock_answer)` – Matt Jan 08 '16 at 03:02
4

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.

Austin Phillips
  • 15,228
  • 2
  • 51
  • 50
  • Thanks, that actually works fine. Although the subclass mimicking the parent part doesn't prove useful in my case, it won't hurt anything. – orokusaki Jan 21 '13 at 03:57