Pytest Celery Plugin

1.3.0 · active · verified Sat Apr 11

pytest-celery is a pytest plugin that provides fixtures and utilities for testing Celery applications. It streamlines setting up and tearing down Celery workers and brokers (like Redis, RabbitMQ, SQS) within your pytest test suite. Currently at version 1.3.0, it maintains an active development pace with frequent updates to support new Python and Celery versions, and address compatibility issues.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a basic test for a Celery task using pytest-celery's fixtures. It configures Celery to use Redis, starts a worker, and executes a task. Ensure your test environment has a running Redis instance or adjust the `celery_config` fixture accordingly. Remember to replace `my_app.tasks` with the actual path to your Celery tasks.

import pytest
from celery import Celery

@pytest.fixture(scope="session")
def celery_config():
    return {
        "broker_url": "redis://localhost:6379/0",
        "result_backend": "redis://localhost:6379/0",
        "task_always_eager": False,
        "task_eager_propagates": False
    }

@pytest.fixture(scope="session")
def celery_enable_logging():
    return True

@pytest.fixture(scope="session")
def celery_worker_parameters():
    return {
        'queue': ['celery'],
        'pool': 'solo'
    }

# Assuming you have a tasks.py module with a simple task
# e.g., tasks.py:
# from celery import shared_task
# @shared_task
# def add(x, y):
#     return x + y

def test_add_task(celery_app: Celery, celery_worker):
    # Ensure tasks.py is discoverable, e.g., by adding a custom Celery app fixture
    # or importing tasks directly if they are in the test file.
    from my_app.tasks import add # Replace with your actual task module
    result = add.delay(2, 3)
    assert result.get(timeout=10) == 5
    assert result.successful()

view raw JSON →