我正在使用python模拟库编写测试用例。

class AddressByPhoneTestCase(TestCase):
    def test_no_content_found_with_mock(self):
        print "this function will mock Contact model get_by_phone to return none"
        with mock.patch('user_directory.models.Contact') as fake_contact:
            print "fake_contact_id ", id(fake_contact)
            conf = { 'get_by_phone.return_value': None }
            fake_contact.configure_mock(**conf)
            resp = self.client.get(reverse('get_address_by_phone'), {'phone_no' : 1234567891})
            self.assertTrue(resp.status_code == 204)

    def test_success_with_mock(self):
        print  "this function will test the address by phone view after mocking model"
        with mock.patch('user_directory.models.Contact') as fake_contact:
            print "fake_contact_id ", id(fake_contact)
            contact_obj = Contact(recent_address_id = 123, best_address_id = 456)
            conf = { 'get_by_phone.return_value': contact_obj }
            fake_contact.configure_mock(**conf)
            resp = self.client.get(reverse('get_address_by_phone'), {'phone_no' : 1234567891})
            resp_body = json.loads(resp.content)
            self.assertTrue(resp_body == {  'recent_address_id' : 123,
                                            'frequent_address_id' : 456
                                        }
                        )


在第二种情况下,即使我将其更改为返回contact_obj,Contact.get_by_phone仍然返回None,但是当我删除上部测试用例时,该测试用例通过了,但由于上面的原因而失败
有人帮助,我如何制作python模拟补丁来重置值。

最佳答案

不知道真正的原因,但是似乎您需要导入要测试的函数/类的父级。

我已经在views.py中写下了这一行

from user_directory.models import Contact


联系人不受嘲笑的影响。请参见示例here。因此,我将代码更改为以下代码,它就像一个魅力。

def test_no_content_found_with_patch(self):
    print "this function will mock Contact model get_by_phone to return none"
    with mock.patch('user_directory.models.Contact.get_by_phone') as fake_func:
        fake_func.return_value = None
        resp = self.client.get(self.get_address_by_phone, {'phone_no' : 1234567891})
        self.assertTrue(resp.status_code == 204)

def test_success_with_patch(self):
    print  "this function will test the address by phone view after mocking model"
    with mock.patch('user_directory.models.Contact.get_by_phone') as fake_func:
        contact_obj = Contact(recent_address_id = 123, best_address_id = 457)
        fake_func.return_value = contact_obj
        resp = self.client.get(self.get_address_by_phone, {'phone_no' : 1234567891})
        resp_body = json.loads(resp.content)
        self.assertTrue(resp_body == {  'recent_address_id' : contact_obj.recent_address_id,
                                        'frequent_address_id' : 457
                                    }
                    )


看到这条线

with mock.patch('user_directory.models.Contact.get_by_phone') as fake_func

关于python - Python模拟补丁未重置返回值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34953721/

10-10 17:47
查看更多