Testing Celery Tasks

Prerequisites

  • You should know the basics of Celery to follow the tutorial.
  • If you know basics of writing tests then its awesome but not mandatory for this tutorial.

Environment Setup

  • This tutorial is written for python 2.x and should work or python 3.x also.
  • You must have working installation of Celery, RabbitMQ and Redis (redis because we want to store the results)
from celery import Celery
from time import sleep
BROKER_URL = ‘amqp://guest@localhost:5672//’
REDIS = ‘redis://localhost/0’
app = Celery(‘test’, broker=BROKER_URL, backend=REDIS)
@app.task(name=”add”)
def add(x, y):
return x+y
from tasks import add, app
import unittest
class TestAddTask(unittest.TestCase):
def setUp(self):
self.task = add.apply_async(args=[3, 5])
self.results = self.task.get()
def test_task_state(self):
self.assertEqual(self.task.state, ‘SUCCESS’)
def test_addition(self):
self.assertEqual(self.results, 8)
from tasks import add, app
import unittest
class TestAddTask(unittest.TestCase):
def setUp(self):
self.task = add.apply_async(args=[3, 5])
self.results = self.task.get()
def test_task_state(self):
self.assertEqual(self.task.state, ‘SUCCESS’)
def test_addition(self):
self.assertEqual(self.results, 8)
➜ python -m unittest discover
..
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Ran 2 tests in 5.353s
OK
self.task = app.send_task(‘add’, args=[3, 5])
import requests
@app
.task(name=’download-image’, ignore_results=True)
def download_image(url):
r = requests.get(url)
with open(‘image.jpg’, ‘wb’) as f:
f.write(r.content)
import os
class TestDownloadTask(unittest.TestCase):
def setUp(self):
self.task = app.send_task(‘download-image’, args= [‘https://www.math.ust.hk/~masyleung/Teaching/CAS/MATLAB/image/images/cameraman.jpg'])
self.results = self.task.get()
def test_task_state(self):
self.assertEqual(self.task.state, ‘SUCCESS’)
def test_download(self):
self.assertEqual(os.path.exists(‘image.jpg’), True)

--

--

--

A bird wants to fly to the end of the world. Also me at https://stackoverflow.com/users/5250746/arpit-solanki

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Arpit Solanki

Arpit Solanki

A bird wants to fly to the end of the world. Also me at https://stackoverflow.com/users/5250746/arpit-solanki

More from Medium

DID YOU KNOW ?

K-Nearest Neighbour -

Palm Sunday Thoughts