我有一堂课:
class MyClass(object):
@property
def myproperty(self):
return 'hello'
Using mox http://code.google.com/p/pymox/ and py.test
,我如何模拟myproperty
?
我试过了:
mock.StubOutWithMock(myclass, 'myproperty')
myclass.myproperty = 'goodbye'
and
mock.StubOutWithMock(myclass, 'myproperty')
myclass.myproperty.AndReturns('goodbye')
但都失败了AttributeError: can't set attribute
.
删除类属性时mox
uses setattr
. Thus
mock.StubOutWithMock(myinstance, 'myproperty')
myinstance.myproperty = 'goodbye'
相当于
# Save old attribute so it can be replaced during teardown
saved = getattr(myinstance, 'myproperty')
# Replace the existing attribute with a mock
mocked = MockAnything()
setattr(myinstance, 'myproperty', mocked)
请注意,因为myproperty
是一个财产getattr
and setattr
将调用该属性的__get__
and __set__
方法,而不是实际“模拟”属性本身。
因此,为了获得您想要的结果,您只需更深入地模拟实例类上的属性即可。
mock.StubOutWithMock(myinstance.__class__, 'myproperty')
myinstance.myproperty = 'goodbye'
请注意,如果您希望同时使用不同的方式模拟 MyClass 的多个实例,这可能会导致问题myproperty
values.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)