跳到正文
cccskills
免费在 GitHub 公开

celery-tests

Authors and runs Celery task tests in Python - `pytest-celery` fixtures (`celery_app`, `celery_worker` per-test, `celery_session_worker` per-session); `task_always_eager` config NOT recommended for unit tests; `apply()` for synchronous test invocation; mock-and-patch retry patterns via `unittest.mock.patch` on `task.retry`. Use when the user works with Celery task workers and needs unit / integration tests across function-style or class-style tasks.

中文简介正在准备中。当前显示原文说明。

testland/qa星标 13(GitHub 13 + cccskills 0)
集成工具Redis

实测评分 未实测

查看安装方法

包含的文件(2)

  • SKILL.md8.8 KB
  • .tessl-plugin/plugin.json581 B

SKILL.md(原文)

安装前可以查看交给 AI 代理的指令内容。

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.task or @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

  1. Confirm the repo has Celery tasks (@app.task / @shared_task) and pick the level: unit (task body) vs integration (real worker).
  2. For unit tests, call the task function directly and assert its side effects; do NOT enable task_always_eager (Step 1, Step 2).
  3. For retry logic, unittest.mock.patch the <task>.retry and the failing dependency, then assert Retry is raised (Step 3).
  4. For an in-process synchronous run with no broker, invoke task.apply(args=[...]) and assert on result.successful() / result.result (Step 5).
  5. For integration tests that need a real worker, add the celery_worker (per-test) or celery_session_worker (per-session) fixture, call task.delay(...), and read result.get(timeout=N) (Step 4).
  6. Test chord / chain / group end-to-end with celery_worker, or mock at boundaries for unit level (Step 6).
  7. Wire pytest into CI, adding redis / rabbitmq service 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:

FixtureUse
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 path itself.

Step 6 - Test chord / chain / group

Celery's primitives compose:

from celery import chain, group, chord

# Chain: A -> B -> C
chain(task_a.s(1), task_b.s(), task_c.s())()

# Group: parallel execution
group(task_a.s(i) for i in range(3))()

# Chord: parallel group + callback
chord([task_a.s(i) for i in range(3)])(callback.s())

For unit tests, mock the primitives at boundaries; for integration tests, use celery_worker fixture (Step 4) - primitives execute end-to-end.

Step 7 - CI integration

- run: pip install -r requirements-dev.txt   # includes pytest, celery, pytest-celery
- run: pytest -v

For tests requiring real broker (RabbitMQ / Redis):

services:
  redis: { image: redis:7, ports: [6379:6379] }
  # or rabbitmq:
  rabbitmq: { image: rabbitmq:3-management, ports: [5672:5672, 15672:15672] }

Worked example

An order-processing task must run its side effect on success and retry on a transient DB error. Two fast unit tests cover both paths, with no broker.

  1. Success path - call the task function directly, patch the dependency, and assert the side effect:
@patch('proj.tasks.Product.order')
def test_send_order_success(product_order):
    product = Product.objects.create(name='Foo')
    send_order(product.pk, 3, Decimal('30.30'))
    product_order.assert_called_with(3, Decimal('30.30'))
  1. Retry path - patch send_order.retry to raise Retry, force the dependency to fail, then assert the task retries:
@patch('proj.tasks.send_order.retry', side_effect=Retry())
@patch('proj.tasks.Product.order', side_effect=OperationalError())
def test_send_order_retries_on_db_error(order, retry):
    with raises(Retry):
        send_order(1, 3, Decimal('30.30'))

Running pytest -v reports both tests passing in milliseconds with no Redis / RabbitMQ dependency - the success side effect and the retry trigger are both proven without spawning a worker.

Anti-patterns

Anti-patternWhy it failsFix
task_always_eager = True for unit testsPer cel-test, "not suitable for unit tests"; results don't write to backendDirect function call (Step 2) or apply() (Step 5)
Use delay() in tests without a real workerTasks enqueue but never execute; tests hang or never assertUse apply() for sync; celery_worker fixture for real-worker integration
Skip patching the broker side-effectTests hit real broker / DBunittest.mock.patch the boundary (Step 3)
Reuse celery_session_worker for tests with conflicting task definitionsWorker has stale task registry; later tests failUse celery_worker for changing-registry tests; celery_session_worker for stable

Limitations

  • Worker-thread fixtures slow tests substantially vs direct function calls - use them only when integration matters.
  • result.get(timeout=N) with too-short N causes intermittent CI failures on slow runners; pick generous timeouts.
  • pytest-celery v1.0+ has a different API than legacy celery.contrib.pytest; pin one and stick with it per project.

References

  • cel-test - official testing guide, fixtures, retry patterns, eager-mode warning
  • docs.celeryq.dev - full Celery documentation
  • pypi.org/project/pytest-celery - pytest-celery package
  • sidekiq-tests, bullmq-tests, sqs-tests, rabbitmq-tests - sister tools
  • idempotency-test-author, cron-job-test-author - build-an-X authors

评价

还没有评价。欢迎分享你的使用感受。

评论

无需登录即可发表。欢迎分享使用感受、提问,或说明在哪些环境下无法运行。

还没有评论。来写第一条吧。

提交后会立即公开。请勿填写邮箱、电话等个人信息。URL 最多 2 个。

0 / 1000 字

此表单受 reCAPTCHA 保护,适用 Google 的隐私权政策和服务条款。

同一仓库的技能

Builds a CI gate that fails the build on **new** WCAG / a11y violations introduced by a PR while grandfathering pre-existing violations on a per-rule / per-page baseline. Aggregates verdicts from axe-core / pa11y / Lighthouse a11y / WAVE / IBM Equal Access scans. Use when a project has accumulated a11y debt and a strict "zero violations" gate would block every PR - the ratchet pattern lets the team ship while preventing regressions.

中文简介正在准备中。当前显示原文说明。

testland/qa132026年10月20日 更新

Workflow skill that builds an A/B-test validity checklist from an experiment proposal, walking the canonical design-correctness gates - pre-registered OEC/power/guardrails, randomization unit + SRM check, assignment integrity, telemetry, peeking discipline, novelty/primacy, post-experiment SRM re-check - into a per-experiment checklist + sign-off form. Use when launching, auditing, or governing an experiment. For pitfall mechanics (guardrails, peeking) see experiment-results-interpreter's references; to read an already-valid result use experiment-results-interpreter; for per-SDK harness tests use experiment-sdk-testing - this gates DESIGN, not SDK code.

中文简介正在准备中。当前显示原文说明。

testland/qa132026年10月20日 更新

The single install-flow skill: the reference contract for the PWA install flow (installability gate fields, `beforeinstallprompt` handshake, per-platform paths - Android WebAPK / iOS Share menu / Firefox no-op - and the `display-mode` post-install signal, in references/install-flow-reference.md) plus the build-an-X workflow that emits the Add-to-Home-Screen suite. Walks the four-stage timeline, emitting one test per gate cell per [web.dev/articles/install-criteria][install-criteria], the deferred-prompt → `prompt()` → `userChoice` chain per [web.dev/articles/customize-install][customize-install], the iOS Safari manual-metadata branch (`apple-touch-icon`) per [web.dev/learn/pwa/installation][learn-pwa], and the post-install `(display-mode: standalone)` MQ assertion. Output: a Playwright spec with per-stage cells plus a coverage matrix. Use when a PWA's manifest, icons, or install handler change, when install conversion drops at an unknown stage, or when triaging a flaky install assertion.

中文简介正在准备中。当前显示原文说明。

testland/qa132026年10月20日 更新

Build-an-X workflow that uses an LLM to map existing tests to spec sections - given a spec doc + the test suite, the LLM identifies which tests cover which sections, surfaces uncovered sections (gap), and recommends specific tests to add. Output is a coverage matrix per spec ID. Scope is mapping tests that already exist and naming the gaps, not authoring tests for new acceptance criteria. Use when a spec doc and a test suite both exist but nobody can say which requirements are actually covered - before a release sign-off, an audit, or a decision about where to spend the next round of test effort.

中文简介正在准备中。当前显示原文说明。

testland/qa132026年10月20日 更新

Generates tests from natural-language specs (acceptance criteria, user stories, requirements) using an LLM, with confidence scoring per test case (LLM self-assessment plus heuristics: assertion quality, naming, completeness), batching uncertain cases for human review, and integration with the team's existing test framework. Use when the user asks to generate unit tests from acceptance criteria, convert user stories to test cases, automate test creation from requirements, or augment a spec-driven test suite with AI-generated stubs that are then curated before merge.

中文简介正在准备中。当前显示原文说明。

testland/qa132026年10月20日 更新

Configures Allure Report (test-runner adapter install, `allure-results` directory wiring, `categories.json` for failure classification, `history-trend.json` retention via the copy-history-between-runs pattern), runs the Allure CLI to convert `allure-results` to a static HTML site, and uploads the report as a CI artifact. Use when the team needs richer test reporting than JUnit XML - step-level attachments, per-test history, retry tracking, and severity / epic / feature labeling across framework-agnostic adapters (pytest, Jest, JUnit, TestNG, NUnit, Mocha). As a rich static HTML report generator, it is the open-source alternative to the sunset ExtentReports (JVM/.NET per-test HTML narrative); for hosted cross-run flakiness analytics rather than a static per-run report use currents-integration.

中文简介正在准备中。当前显示原文说明。

testland/qa132026年10月20日 更新

查看 testland 的全部技能

报告此技能的问题