Python模拟补丁没有重置返回值

时间:2016-01-22 18:39:16

标签: python unit-testing mocking

我正在使用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.get_by_phone仍然返回None,即使我将其更改为返回contact_obj,当我删除了上层测试用例时,此测试用例通过但未成功引用上层原因 有人帮忙,我怎样才能使python模拟补丁重置值。

1 个答案:

答案 0 :(得分:1)

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

我在views.py

中写了这一行
from user_directory.models import Contact

联系人不受mock.patch的影响。查看示例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
相关问题