python - 访问使用补丁模拟的对象

bow*_*bow 4 python testing unit-testing mocking

我一直在使用该mock库来进行一些测试.到目前为止它一直很棒,但有一些我还没有完全理解的东西.

mock提供了一种使用修补整个方法的好方法patch,我可以像这样的方法访问修补对象:

@patch('package.module')
def test_foo(self, patched_obj):
    # ... call patched_obj here
    self.assertTrue(patched_obj.called)
Run Code Online (Sandbox Code Playgroud)

我的问题是,如果我patch在整个类上使用装饰器,我如何访问修补对象?

例如:

@patch('package.module')
class TestPackage(unittest.TestCase):

    def test_foo(self):
        # how to access the patched object?
Run Code Online (Sandbox Code Playgroud)

ber*_*eal 8

在这种情况下,test_foo将有一个额外的参数,与装饰方法时的方式相同.如果你的方法也被修补了,那么那些args也会被添加:

@patch.object(os, 'listdir')
class TestPackage(unittest.TestCase):
    @patch.object(sys, 'exit')
    def test_foo(self, sys_exit, os_listdir):
        os_listdir.return_value = ['file1', 'file2']
        # ... Test logic
        sys_exit.assert_called_with(1)
Run Code Online (Sandbox Code Playgroud)

参数顺序由装饰器调用的顺序决定.首先调用方法装饰器,因此它附加第一个参数.类装饰器是外部的,因此它将添加第二个参数.将几个补丁修饰符附加到同一个测试方法或类(即外部装饰器最后一个)时,同样适用.