User_Targaryen User_Targaryen - 1 year ago 116
Python Question

Need to mock a non test method in Django

I have a test class just like the one below:

class SortAPITestCase(APITestCase):

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

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

def test_1(self, mock_obj):

def test_2(self, mock_obj):

, there is the Scan API, where there is
method which calls a celery task like:

def post("""some args"""):
""" here there is a celery task that gets called"""
args=[img_data], queue='image', countdown=10

The celery task prints out a message when it is called somewhat like below

def image_processing(img_data):
if os.isfile(img_file):
print "File Not Present"

So, whenever
is not present it prints out
File Not Present
. 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
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

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

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
instead of the print statements from celery task also showing up.

Edit: Solved the problem. Here is what I did

def hit_scan(self, mock_obj, """some args"""):

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download