使用mock.patch

时间:2016-12-18 16:28:01

标签: python python-mock

我想使用mock.patch来拦截类中的方法。这是我目前的做法:

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' )

如何在foo_intercepted中访问正确的Test实例?在实际代码中Test来自另一个模块,测试实例是其他函数中的本地对象(例如,没有通过全局变量访问't2')。

0 个答案:

没有答案