Reputation: 2062
I am writing test cases using python mock library.
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
}
)
In the second case Contact.get_by_phone is still returning None even though I changed it to return a contact_obj, when I removed the upper test case, this test cases passes but fails otherwise citing the upper reason Someone help, how can i make the python mock patch to reset the value.
Upvotes: 3
Views: 1308
Reputation: 2062
Don't know the real reason for it, but it seems you need to import the parent of the function/class you are testing.
I had written this line in my views.py
from user_directory.models import Contact
Contact was unaffected by mock.patch. See an example here. Hence I changed my code to the following and it worked like a charm.
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
}
)
See this line
with mock.patch('user_directory.models.Contact.get_by_phone') as fake_func
Upvotes: 1