title: Using mock to patch a celery task in Django unit tests
body: <p>I'm trying to use the python mock library to patch a Celery task that is run when a model is saved in my django app, to see that it's being called correctly.</p>
  
  <p>Basically, the task is defined inside <code>myapp.tasks</code>, and is imported at the top of my models.py-file like so:</p>
  
  <p><code>from .tasks import mytask</code></p>
  
  <p>...and then runs on <code>save()</code> inside the model using <code>mytask.delay(foo, bar)</code>. So far so good - works out fine when I'm actually running Celeryd etc.</p>
  
  <p>I want to construct a unit test that mocks the task, just to check that it gets called with the correct arguments, and doesn't actually try to run the Celery task ever.</p>
  
  <p>So in the test file, I've got something like this inside of a standard TestCase:</p>
  
  <pre><code>from mock import patch # at the top of the file
  
  # ...then later
  def test_celery_task(self):
      with patch('myapp.models.mytask.delay') as mock_task:
          # ...create an instance of the model and save it etc
          self.assertTrue(mock_task.called)
  </code></pre>
  
  <p>...but it never gets called/is always false. I've tried various incarnations (patching <code>myapp.models.mytask</code> instead, and checking if <code>mock_task.delay</code> was called instead. I've gathered from the mock docs that the import path is crucial, and googling tells me that it should be the path as it is seen inside the module under tests (which would be <code>myapp.models.mytask.delay</code> rather than <code>myapp.tasks.mytask.delay</code>, if I understand it correctly).</p>
  
  <p>Where am I going wrong here? Is there some specific difficulties in patching Celery tasks? Could I patch <code>celery.task</code> (which is used as a decorator to <code>mytask</code>) instead?</p>