Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python mock.patch: replace a method

Tags:

python

mocking

I'd like to replace a method in a class with mock:

from unittest.mock import patch

class A(object):
    def method(self, string):
        print(self, "method", string)

def method2(self, string):
    print(self, "method2", string)

with patch.object(A, 'method', side_effect=method2):
    a = A()
    a.method("string")
    a.method.assert_called_with("string")

...but I get insulted by the computer:

TypeError: method2() missing 1 required positional argument: 'string'
like image 224
luc2 Avatar asked May 15 '16 13:05

luc2


1 Answers

The side_effect parameter indicates that a call to method should have a call to method2 as a side effect.

What you probably want is to replace method1 with method2, which you can do by using the new parameter:

with patch.object(A, 'method', new=method2):

Be aware that if you do this, you cannot use assert_called_with, as this is only available on actual Mock objects.

The alternative would be to do away with method2 altogether and just do

with patch.object(A, 'method'):

This will replace method with a Mock instance, which remembers all calls to it and allows you to do assert_called_with.

like image 180
dorian Avatar answered Oct 14 '22 22:10

dorian