【问题标题】:Mock function call inside init method Python在init方法Python中模拟函数调用
【发布时间】:2017-10-26 19:40:06
【问题描述】:

我正在编写一个单元测试以确保我的类对象被正确创建,并且这个对象依赖于从 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?

【问题讨论】:

    标签: python unit-testing mocking init


    【解决方案1】:

    当您进行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')

    没有办法修补指向特定值的每个名称。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-18
      • 1970-01-01
      • 2015-08-23
      • 2017-10-24
      • 1970-01-01
      • 1970-01-01
      • 2011-03-30
      • 1970-01-01
      相关资源
      最近更新 更多