2014-02-19 90 views
1

该测试是给我的异常问题的API:修补使用Python模拟

我测试的略微简化的版本:

def test_credit_create_view(self): 
    """ Can we create cards? """ 
    card_data = {'creditcard_data': 'blah blah blah'} 
    with patch('apps.users.forms.CustomerAccount.psigate') as psigate: 
     info = MagicMock() 
     info.CardInfo.SerialNo = 42 
     create = MagicMock(return_value=info) 
     psigate.credit.return_value = create 
     self.client.post('/make-creditcard-now', card_data) 

我试图模仿看起来像这样的电话:

psigate.credit().create().CardInfo.SerialNo 

在测试中,该调用只返回一个MagicMock对象。

如果我只是看在通话的最后三个节点,我得到正确的结果:

create().CardInfo.SerialNo 

收益42

为什么不充分调用“psigate.credit() .create().CardInfo.SerialNo'return 42?

+0

CardInfo应该是什么?一类?如果是这样,你可以查看[PropertyMock](http://www.voidspace.org.uk/python/mock/mock.html#mock.PropertyMock) – Silfheed

+0

CardInfo是一个lxml.objectify.ObjectifiedElement。我不得不承认我很困惑应该在什么时候使用PropertyMock。 – LiavK

回答

2

您正在设置创建psigate.credit的返回值,这意味着psigate.credit()是您的模拟“创建”,而不是psigate.credit()。create。如果你调用了psigate.credit()(),这可以按预期工作。

当您调用psigate.credit()。create()时,您正在动态创建一个新的MagicMock对象,而不是调用您定义的对象。

+0

再次看看模拟文档。您可以一次性在return_value上设置属性。以下工作:psigate.credit.return_value.create.return_value.CardInfo.SerialNo = 42 – LiavK