spec_set似乎不适用于create_autospec,但适用于Mock(spec_set = True)

时间:2019-02-10 10:24:31

标签: python-3.x mocking

Mockcreate_autospec采用spec_set,它将生成的模拟实例设置为拒绝设置spec对象上尚未存在的属性。但是,使用Mock(spec_set=True)创建模拟实例确实会阻止设置ghost属性,但是create_autospec(.., spec_set=True)不会设置。

我写了一些代码来检查这个问题。

from unittest.mock import Mock, create_autospec


def foo(a, b, c):
    pass


m = Mock(spec_set=foo)
try:
    m.bar = 'value'
except AttributeError:
    print("m has no attribute 'bar'")
else:
    assert False

m2 = create_autospec(spec=foo, spec_set=True)
try:
    m2.bar = 'value'
except AttributeError:
    print("m2 has no attribute 'bar'")
else:
    assert False

m2.bar跳过spec_set=True,在最后一行产生assert False。我认为m2.bar = ...应该失败了,因为spec_setTrue。我是否误读了文档?我从文档中提取了相关部分:

  

spec_set:规范的更严格变体。如果使用了该属性,则尝试在模拟上设置或获取不是以spec_set传递的对象上的属性,将会引发AttributeError。

我使用python 3.7。预先感谢。

0 个答案:

没有答案