init 方法中的模拟函数调用 Python

Mock function call inside init method Python

我正在编写单元测试以确保正确创建了我的 class 对象,并且此对象依赖于从 s3 获取内容。我想完全模拟其中调用 s3 的函数,:

class SomeClassTest(unittest.TestCase):

    @patch('someDir.util._call_to_s3')
    def test_someclass_load(self, magic_mock):
        magic_mock.return_value = {"host": "bogus.com"}
        some_class = SomeClass()

        self.assertGreater(len(some_class), 0)

class SomeClass():

    def __init__():
        try:
            content = _call_to_s3(bucket_name, file_name)
        except:
            rest of code ...

如何模拟另一个库文件中定义的函数_call_to_s3?

当您使用 monkeypatch 时,您是在更改名称以使其指向不同的值。你没有改变价值本身。关键是要修补您正在测试的单元正在使用的名称。

每次 "from foo import bar",您都在创建名称的新本地副本。在这种情况下,看起来 SomeClass 不在 someDir.util 模块中。假设它在 someDir.other_mod

someDir.other_mod 会做类似 "from someDir.util import _call_to_s3" 的事情。这将创建一个新名称 someDir.other_mod._call_to_s3。这是 SomeClass 使用的名称,所以这是您需要修补的名称。

例如@patch('someDir.other_mod._call_to_s3')

无法修补指向特定值的每个名称。