Python mocking: basic errors mocking a class using patch/MagicMock

37 views Asked by At

Although I've successfully used google test and mock successfully for C++, I'm getting nowhere when it comes to using mocking in Python.

I'm trying to mock a small class in my code so that I can ensure the response from a particular function. I want to mock the whole class since the constructor does things that involve dependencies that I'd like to avoid. This seems like a fairly typical and mundane use case for mocking.

However, when I call the function on the mock, what I get is a MagicMock object, not the result I wanted. Taking a very simple example:

class MyClass:
    def value(self):
        return 10

If I want to mock the MyClass class and change the value function so that it returns a different value, I believed that I could do this as follows:

with patch('__main__.MyClass') as MockMyClass:
    b = MyClass()

If I then attempt to set the value function to something different, it doesn't work the way I expect and calling the function on the mock seems to return a MagicMock object instead:

>>> with patch('__main__.MyClass') as MockMyClass:
...     MockMyClass.value = lambda : 22
...     b = MyClass()
...     print(b.value())
<MagicMock name='MyClass().value()' id='140661276636400'>

I've been through so many references and examples and I still don't get what I'm doing wrong. Feel so clueless - can anyone help me?

1

There are 1 answers

0
Component 10 On

The problem is in fact very similar to the question asked here.

I'm not sure if I'm saying this correctly, but the important bit seems to be that MockMyClass is just a MagicMock, but what I have to change is not on the MagicMock itself but on the returned value of the MagicMock.

When amended to change the attribute on the return_value from MockMyClass, it worked out fine:

>>> with patch('__main__.MyClass') as MockMyClass:
...     MockMyClass.return_value.value = lambda : 22
...     b = MyClass()
...     print(b.value())
...
22