celery-tests
БесплатноБез исполняемых скриптовНе проверенUse whenever Python Celery tasks need unit or integration tests: pytest-celery celery_app and worker fixtures, apply() for synchronous calls, why…
от testland★ 18 звёзд на GitHubОб этом скилле
celery-tests
Overview
Per docs.celeryq.dev/en/stable/userguide/testing.html:
"Testing with Celery is divided into two parts: Unit & Integration: Using
celery.contrib.pytest. Smoke / Production: Using pytest-celery >= 1.0.0"
The test model uses pytest fixtures from the celery.contrib.pytest
plugin (or the standalone pytest-celery package for newer versions).
When to use
- The repo has Celery task definitions (
@app.taskor@shared_task). - The user writes unit tests for the task body (no need for a real worker).
- The user writes integration tests that require a real Celery worker thread.
- A test verifies retry / chord / chain semantics.
How to use
- Confirm the repo has Celery tasks (
@app.task/@shared_task) and pick the level: unit (task body) vs integration (real worker). - For unit tests, call the task function directly and assert its side
effects; do NOT enable
task_always_eager(Step 1, Step 2). - For retry logic,
unittest.mock.patchthe<task>.retryand the failing dependency, then assertRetryis raised (Step 3). - For an in-process synchronous run with no broker, invoke
task.apply(args=[...])and assert onresult.successful()/result.result(Step 5). - For integration tests that need a real worker, add the
celery_worker(per-test) orcelery_session_worker(per-session) fixture, calltask.delay(...), and readresult.get(timeout=N)(Step 4). - Test
chord/chain/groupend-to-end withcelery_worker, or mock at boundaries for unit level (Step 6). - Wire
pytestinto CI, addingredis/rabbitmqservice containers only when a test needs a real broker (Step 7).
Step 1 - Don't rely on task_always_eager for unit tests
Per cel-test:
"The eager mode enabled by the [task_always_eager] setting is by definition not suitable for unit tests."
Reason (per cel-test): "eagerly executed tasks don't write results to backend by default."
For unit tests, prefer to call the task function directly (test the logic) and mock the dispatch where queue interaction matters.
Step 2 - Direct task-function unit tests
Test the task function as if it were a regular function:
from proj.tasks import send_order
from decimal import Decimal
def test_send_order_calls_product_order():
product = Product.objects.create(name='Foo')
send_order(product.pk, 3, Decimal('30.30'))
# Assert side effects (DB row, external call, etc.)
This bypasses Celery's dispatch entirely - fastest, most direct.
Step 3 - Mock retry behavior
Per cel-test (verbatim retry-test pattern):
from pytest import raises
from celery.exceptions import Retry
from unittest.mock import patch
from proj.models import Product
from proj.tasks import send_order
class test_send_order:
@patch('proj.tasks.Product.order')
def test_success(self, product_order):
product = Product.objects.create(name='Foo')
send_order(product.pk, 3, Decimal(30.3))
product_order.assert_called_with(3, Decimal(30.3))
@patch('proj.tasks.send_order.retry')
def test_failure(self, send_order_retry, product_order):
send_order_retry.side_effect = Retry()
product_order.side_effect = OperationalError()
with raises(Retry):
send_order(product.pk, 3, Decimal(30.6))
Patch <task>.retry to assert the task triggers a retry; patch the
side-effect dependency to control failure mode.
Step 4 - pytest-celery fixtures (integration tests)
Per cel-test, the canonical pytest-celery fixtures:
| Fixture | Use |
|---|---|
celery_app |
"This fixture returns a Celery app you can use for testing." |
celery_worker |
"This fixture starts a Celery worker instance that you can use for integration tests. The worker will be started in a separate thread." |
celery_session_worker |
"This fixture starts a worker that lives throughout the testing session (it won't be started/stopped for every test)." |
Choose celery_worker for tests that need clean worker state per
test; celery_session_worker for fast suites where the worker can
be reused.
def test_task_runs_via_real_worker(celery_app, celery_worker):
@celery_app.task
def add(x, y):
return x + y
result = add.delay(2, 3)
assert result.get(timeout=10) == 5
Step 5 - apply() for synchronous test invocation
When you want to invoke the task synchronously without spawning a worker:
from proj.tasks import send_order
result = send_order.apply(args=[product_id, qty, amount])
assert result.successful()
assert result.result == expected_value
apply() runs the task in-process; delay() enqueues for a worker.
For tests, prefer apply() (no Redis / RabbitMQ dependency) unless
testing the dispatch
Установить celery-tests в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл celery-tests?
Use whenever Python Celery tasks need unit or integration tests: pytest-celery celery_app and worker fixtures, apply() for synchronous calls, why task_always_eager misleads, and mocking task.retry to test retry behavior, for function and class-based tasks.
Как установить скилл celery-tests?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл celery-tests запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic