Python 模拟补丁未重置 return 值

Python mock patch not reseting the return value

我正在使用 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 仍然 returning None 即使我将其更改为 return a contact_obj,当我移除上部测试用例,这个测试用例通过但失败,否则引用上面的原因 有人帮忙,我怎样才能制作 python 模拟补丁来重置值。

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

我在 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