使用mock修补函数时,可以选择将autospec指定为True:
If you set autospec=True then the mock with be created with a spec from the object being replaced. All attributes of the mock will also have the spec of the corresponding attribute of the object being replaced. Methods and functions being mocked will have their arguments checked and will raise a TypeError if they are called with the wrong signature.
(http://www.voidspace.org.uk/python/mock/patch.html)
我想知道为什么这不是默认行为?当然,我们几乎总是希望捕捉到向我们修补的任何函数传递错误参数的情况?
自动规范本身的操作可以执行代码,例如通过调用描述符。
因此,在默认情况下启用和 仅限选择加入。
解释这一点的唯一明确方法是,实际引用使用auto speccing的下行上的documentation,以及为什么在使用时要小心:
我认为这里的关键是要注意这一行:autospec不能知道任何动态创建的属性,并将api限制为可见属性
因此,为了帮助更明确地说明自动选择中断的位置,从文档中获取的示例显示如下:
如您所见,在创建
Something
对象时,auto speccing并不知道正在创建属性a
。为实例属性分配值没有错。
请注意以下功能示例:
所以,我只是说对于我的测试用例,我想确保
some_external_thing()
方法不会影响unittest的行为,所以我只是为实例属性分配mock permock_some_external_thing.return_value = "there be dragons"
。多年后,我回答了自己的问题——另一个原因是速度。
根据对象的复杂程度,使用autospec可能会显著降低测试速度。我发现这一点,特别是在修补Django模型时。
相关问题 更多 >
编程相关推荐