Access to the class instance and original method when using mock.patch

177 views Asked by At

I would like to use mock.patch to intercept a method in a class. Here is my current approach:

class Test( object ):
    def foo( self, *args, **kwargs ):
        print( 'Test.foo: %s %s' % ( repr( self ), repr( ( args, kwargs ) ) ) )

def foo_intercepted( *args, **kwargs ):
    print( 'foo_intercepted: %s' % ( repr( ( args, kwargs ) ) ) )
    # How to access the Test instance, let alone it's original Test.foo method?

if ( __name__ == '__main__' ):
    t1 = Test()
    t1.foo( 'hello 1' )

    with mock.patch( '__main__.Test.foo' ) as mocked:
        mocked.side_effect = foo_intercepted
        t2 = Test()
        t2.foo( 'hello 2' )

How can I access the correct Test instance in foo_intercepted? In the real code Test is from another module, the test instance is a local object in some other function (e.g. no accessing 't2' via globals).

0

There are 0 answers