Skip to main content
 首页 » 编程设计

Python模拟补丁不重置返回值

2025年05月04日9JustinYoung

我正在使用 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 

联系人不受 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