Python模拟补丁不重置返回值

问题描述:

我正在使用python模拟库编写测试用例。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仍没有返回,即使我改变了它返回一个contact_obj,当我删除了上测试的情况下,这个测试用例通过,但未能否则援引上的原因 有人帮,我如何使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 
+0

这应该做工精细,但原帖应该正常工作。请更新,当您可以使您原来的职位工作,谢谢 – Gang

+0

@广州没有上述不起作用。如果在我的观点中,我将在user_directory导入模型中执行 以上操作。 并使用 models.Contact而不是联系人 –