python mock:配置模拟对象的规范

Jay*_*shi 5 python unit-testing mocking

我有一个实例方法,它启动另一个类的对象。对于前,

import module_two
class One:
    def start(self):
        self.two = module_two.Two()
Run Code Online (Sandbox Code Playgroud)

我正在修补我的测试用例中的一个类

@patch('module_one.One', autospec=True)
def test_one(patched_one):
    two = patched_one.return_value

    # Following method should raise error, but doesn't
    two.any_random_non_existing_method()
Run Code Online (Sandbox Code Playgroud)

如前所述,two.any_random_non_existing_method()不会引发任何错误,因为twoMock 对象没有分配任何规范。

如何为two对象指定规格?我正在寻找类似以下片段的内容。

    # note: configure_spec actually doesn't exist.!
    two.configure_spec(module_two.Two)
    two.any_random_non_existing_method() # Error.! 
Run Code Online (Sandbox Code Playgroud)

who*_*ski 4

经过一些评论,看起来mock_add_spec对你有用:

向模拟添加规范。spec 可以是一个对象或字符串列表。只有规范上的属性可以作为属性从模拟中获取。

https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.mock_add_spec

它应该是这样的:

# Add specifications on existing mock object
two.mock_add_spec(module_two.Two)
two.any_random_non_existing_method() # Error.! 
Run Code Online (Sandbox Code Playgroud)