Need to mock a non test method in Django
<p>I have a test class just like the one below: </p>

<pre><code>@mock.patch('myapp.apps.mytask1.views.image_processing.apply_async')
class SortAPITestCase(APITestCase):


    def hit_scan("""some args"""):
        scan_uri = 'some url'
        data = 'some data'
        resp = self.client.post(scan_uri, data=data)
        id = resp.data['id']
        self.assertEqual(resp.status_code, 201)
        return data, id

    def setUp(self):
        super(SortAPITestCase, self).setUp()
        self.scan_data, self.id = self.hit_scan()

    def test_1(self, mock_obj):
        .....

    def test_2(self, mock_obj):
        .....
</code></pre>

<p>In <code>myapp.apps.mytask1.views</code>, there is the Scan API, where there is <code>post</code> method which calls a celery task like:</p>

<pre><code>def post("""some args"""):
    """ here there is a celery task that gets called"""
    image_processing.apply_async(
        args=[img_data], queue='image', countdown=10
    )
</code></pre>

<p><em>The celery task prints out a message when it is called somewhat like below</em></p>

<pre><code>@shared_task
def image_processing(img_data):
    if os.isfile(img_file):
        print "File Not Present"
</code></pre>

<p>So, whenever <code>img_file</code> is not present it prints out <code>File Not Present</code>. When the test fucntions(with mock) post to the Scan API, this print message is not printed on the console because of mock. But the <code>hit_scan()</code> method when posts to Scan API, then this message gets printed as the celery task is not getting mocked. Can I mock the celery task in <code>hit_scan</code>??</p>

<p>So, Is there way to prevent the print statement from coming up in the console when I run the test??</p>

<p>By the way, all the test cases pass. There is no problem from that point of view. I just wanted the console to look better with only <code>....</code> instead of the print statements from celery task also showing up.</p>

<p><strong>Edit</strong>: Solved the problem. Here is what I did</p>

<pre><code>@mock.patch('myapp.apps.mytask1.views.image_processing.apply_async')
def hit_scan(self, mock_obj, """some args"""):
</code></pre>

<p>This has nothing to do with the method being outside of the test; Python makes no such distinction. However your syntax for mocking is consult wrong: you need to reference the thing you want to mock via a Python module path, not a file path.</p>

<pre><code> @mock.patch('path.something.file.apply_async')
</code></pre>

python django unit-testing celery django-celery