title: mocking a function within a class method
body: <p>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:</p>
  <h3>app/utils.py</h3>
  <pre><code>def func():
      ...
      return resp  # outcome is a HTTPResponse object
  </code></pre>
  <h3>app/models.py</h3>
  <pre><code>from app.utils import func
  
  class MyModel(models.Model):
      
      # fields
      
      def call_func(self):
          ...
          func()
          ...
  </code></pre>
  <h3>app/tests/test_my_model.py</h3>
  <pre><code>from django.test import TestCase
  import mock    
  
  from app.models import MyModel
  
  class 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=&quot;Fake 200 Response&quot;))
  
      def test_my_model(self):
          my_model.call_func()
          ...  # and asserting the parameters returned by func
  </code></pre>
  <p>When I run the test the mock function <code>fake_func()</code> is avoided and the real <code>func()</code> is called instead. I guess the scope in the <code>mock.patch</code> decorator might be wrong, but I couldn't find a way to make it work. What should I do?</p>