[BangPypers] Django - Testing Celery Tasks!

Pradip Caulagi ppc.lists at gmail.com
Wed Aug 6 10:03:58 CEST 2014


On Wednesday 06 August 2014 12:17 PM, Anand Reddy Pandikunta wrote:
> Hi,
>
> Here is one simple model and a celery task.
> Can some one tell me how to write a test for this task?
> Thank you!
>
> *my_app/models.py*
> *class MyModel(models.Model):*
> *    x = models.IntegerField()*
> *    y = models.IntegerField()*
> *    sum = models.IntegerField()*

Derived fields should not be stored in database.  You should remove sum 
and instead have -

     def sum(self):
	return self.x + self.y

> *my_app/tests/test_tasks.py*

You probably mean - my_app/tasks.py

> *@celery.task()*

@celery.task

> *def add(id):*
> *    m = MyModel.objects.get(pk=id)*
> *    m.sum = m.x + m.y*
> *    m.save()*
> *    return True*

So this should read -

     @celery.task
     def add(id):
	m = MyModel.objects.get(pk=id)
         return m.sum()

Untested code for testing - my_app/test/test_tasks.py

from django.test import TestCase
from my_app.models import MyModel
from my_app.tasks import add

class AdditionTaskTestCase(TestCase):

     def setUp(self):
         self.m = MyModel.objects.create(x=5, y=6)

     def test_addition(self):
         self.assertEqual(11, add(self.m.id), "invalid sum")

In short, when testing, you don't have to worry about testing the celery 
parts and instead just focus that the task is doing what you expect it to.

--
Pradip P Caulagi


More information about the BangPypers mailing list