Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call mocked method in Python mock

I want to create a mock method that calls the underlying method being mocked.

I'm imagining something like the following, but I can't find any documentation about the mock object holding a reference to the object being mocked, which I've denoted as [[wrapped_method_foo]] below:

from mock import patch

class Foo(object):
    def __init__(self, state):
        self.state = state
    def foo(self, a):
        print "real foo", a
        return a + self.state

f = Foo(2000)
f.foo(1)

with patch.object(Foo, 'foo', autospec=True) as mock_foo:
    def side_effect(self, a):
        print "mock foo", a
        return mock_foo.[[wrapped_method_foo]](self, a*2)
    mock_foo.side_effect = side_effect

    f.foo(2)
like image 826
cbare Avatar asked Sep 03 '26 13:09

cbare


1 Answers

The simplest way is to grab your own reference to the original function before patching. Patching can be done on an individual instance of the class:

original_foo = f.foo
with patch.object(f, 'foo') as mock_foo:
    def side_effect(a):
        print "mock foo", a
        return original_foo(a*2)
    mock_foo.side_effect = side_effect

    f.foo(2)

...or by patching the unbound method on the class:

original_foo = Foo.foo
with patch.object(Foo, 'foo', autospec=True) as mock_foo:
    def side_effect(self, a):
        print "mock foo", a
        return original_foo(self, a*2)
    mock_foo.side_effect = side_effect

    f.foo(3)
like image 172
Erin Call Avatar answered Sep 05 '26 02:09

Erin Call



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!