User_Targaryen User_Targaryen - 1 month ago 16
Python Question

Need to mock a non test method in Django

I have a test class just like the one below:

@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):
.....


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

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


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

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


So, whenever
img_file
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
hit_scan()
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
hit_scan
??

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

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

Answer

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.

 @mock.patch('path.something.file.apply_async')
Comments