Search code examples
pythonunit-testingcelery

How do you unit test a Celery task?


The Celery documentation mentions testing Celery within Django but doesn't explain how to test a Celery task if you are not using Django. How do you do this?


Solution

  • It is possible to test tasks synchronously using any unittest lib out there. I normally do 2 different test sessions when working with celery tasks. The first one (as I'm suggesting below) is completely synchronous and should be the one that makes sure the algorithm does what it should do. The second session uses the whole system (including the broker) and makes sure I'm not having serialization issues or any other distribution, communication problem.

    So:

    from celery import Celery
    
    celery = Celery()
    
    @celery.task
    def add(x, y):
        return x + y
    

    And your test:

    from nose.tools import eq_
    
    def test_add_task():
        rst = add.apply(args=(4, 4)).get()
        eq_(rst, 8)