I want to mock a function which is called within a class method while testing the class method in a Django project. Consider the following structure:
app/utils.py
def func():...return resp # outcome is a HTTPResponse object
app/models.py
from app.utils import funcclass MyModel(models.Model):# fieldsdef call_func(self):...func()...
app/tests/test_my_model.py
from django.test import TestCase
import mock from app.models import MyModelclass MyModelTestCase(TestCase):fixtures = ['my_model_fixtures.json']def setUp(self):my_model = MyModel.objects.get(id=1)@mock.patch('app.utils.func')def fake_func(self):return mock.MagicMock(headers={'content-type': 'text/html'},status_code=2000, content="Fake 200 Response"))def test_my_model(self):my_model.call_func()... # and asserting the parameters returned by func
When I run the test the mock function fake_func()
is avoided and the real func()
is called instead. I guess the scope in the mock.patch
decorator might be wrong, but I couldn't find a way to make it work. What should I do?