我正在尝试模拟一个类,该类在构造函数中设置实例变量,而不在该类中设置默认值。因此,我在调用spec_set
时将False
设置为unittest.mock.create_autospec
,因为根据docs:
如果
spec_set
为True,则尝试设置spec对象上不存在的属性将引发AttributeError
。
为了清楚起见,使用SSCCE似乎spec_set
并不像广告宣传那样起作用:
class Foo:
def __init__(self):
self.bar = 'thing'
def test_foo():
f = create_autospec(Foo, spec_set=False, instance=True)
f.bar.return_value = 'otherthing'
正在测试:
=================================== FAILURES ===================================
___________________________________ test_foo ___________________________________
def test_foo():
f = create_autospec(Foo, spec_set=False, instance=True)
> f.bar.return_value = 'otherthing'
[line info]
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <NonCallableMagicMock spec='Foo' id='47049312794160'>, name = 'bar'
def __getattr__(self, name):
if name in {'_mock_methods', '_mock_unsafe'}:
raise AttributeError(name)
elif self._mock_methods is not None:
if name not in self._mock_methods or name in _all_magics:
> raise AttributeError("Mock object has no attribute %r" % name)
E AttributeError: Mock object has no attribute 'bar'
../../anaconda3/lib/python3.6/unittest/mock.py:582: AttributeError
FWIW,instance=False
不会更改行为。
Python版本是Anaconda 3.6.5。