gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:13:17 25 4
gpt4 key购买 nike

我一直在使用 mock 库进行一些测试。到目前为止一切都很好,但有些事情我还没有完全理解。

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

@patch('package.module')
def test_foo(self, patched_obj):
# ... call patched_obj here
self.assertTrue(patched_obj.called)

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

例如:

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

def test_foo(self):
# how to access the patched object?

最佳答案

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

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

参数顺序由装饰器调用的顺序决定。方法装饰器首先被调用,因此它附加第一个参数。类装饰器在外部,所以它会添加第二个参数。当您将多个补丁装饰器附加到同一个测试方法或类时,这同样适用(即外部装饰器放在最后)。

关于python - 访问用补丁模拟的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9757965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com