dvf/opinionated-django/dj-pytest
Claude Code and agent skill by dvf/opinionated-django
- community
- ext:[{"type":"hook","description":"Pre/post lifecycle hooks"}]
Checking that the SKILL.md file is still in the repository.
Set up and write pytest tests for an op-django project — pytest-django configuration, two-sided Celery testing (patched dispatch sites + plain-function task bodies, never eager mode), freezegun for time-sensitive logic, shared conftest fixtures for DTOs and svcs overrides, and the three-layer test convention (repository against a real DB, service against mocked repos, API through HTTP). Use when adding tests to a new project, writing tests for a new feature, setting up test infrastructure, or explaining how tests should be organized.
Install
npx vskill@latest install dvf/opinionated-django/dj-pytestSemi-extensibleMentions customization, but needs skill-specific knowledge. Read the extensible skills standard
SKILL.md
The same SKILL.md was published earlier as dvf/opinionated-django/dj-pytest.
Pytest for op-django
Testing in this project is layered the same way the code is. Each layer has its own rules, its own fixtures, and its own performance characteristics. The goal is to keep the fast tests fast — service tests should never touch a database — and to isolate the slow tests at the edges.
The Three Layers
| File | What it covers | DB? | Speed | |
|---|---|---|---|---|
test_repo.py | ORM ↔ DTO conversion, prefetches, transactions, ID prefixes | ✅ real | slow | |
test_service.py | Business logic, validation, orchestration | ❌ mocked | fast | |
test_api.py | HTTP integration — request → view → service → repo | ✅ real | slow |
Service tests are the most valuable layer and should outnumber the others. If a service test needs @pytest.mark.django_db, something has leaked — find the ORM call and push it into a repository.
Dependencies
- pytest-django — the
django_dbmarker,clientfixture, settings integration,django_capture_on_commit_callbacks. - pytest-xdist —
-n autoparallel runs. Keep it out ofaddoptsso debugger runs stay serial. - pytest-celery is deliberately absent — tasks are never executed through Celery machinery in tests (see Celery in Tests).
- freezegun — freezes
datetime.now(),time.time(), and friends. Required for any logic that touches timestamps, TTLs, scheduled work, or ULIDs whose sort order matters to the test. - pytest-mock — the
mockerfixture (a thin wrapper aroundunittest.mockwith autouse cleanup).
Configuration
Add to pyproject.toml:
Notes:
pythonpath = ["src"]is what letsfrom project.services import getresolve without an editable install.--strict-markerscatches typos in@pytest.mark.xxx.--strict-configdoes the same for the config file.- Keep the
markerslist small and meaningful — one or two genuine custom markers maximum.
Celery in Tests
Tasks are tested two-sided, and never executed through Celery machinery:
- Dispatch-site tests — where business code calls
some_task.delay(...)/.apply_async(...), patch the task and assert it was dispatched with the right args. - Task-body tests — call the task function directly as a plain function, with its dependencies mocked.
Do NOT set CELERY_TASK_ALWAYS_EAGER. Eager mode executes tasks inline inside the test transaction, which breaks any task that opens its own connection ("Cannot open a new connection in an atomic block") and silently couples every service test to every receiver. It also tests less than it appears to: the dispatch args and the body still need their own assertions either way.
The broker must be unreachable-by-design under pytest so an unpatched .delay() can never publish a real message (a live local broker means a dev worker will consume and execute test tasks against the dev database). Add to src/project/settings.py:
send_reliable() defers dispatch to transaction.on_commit. To flush those hooks in a test, use pytest-django's django_capture_on_commit_callbacks(execute=True) — not django_db(transaction=True), which pays a full-table TRUNCATE teardown per test. More on that below.
tests/conftest.py
A single project-level conftest.py holds the fixtures every test layer can pull from. Keep it small and generic — feature-specific fixtures go in per-app conftest.py files.
A few patterns worth calling out:
- Factories over fixtures for data.
make_product_dto()is more flexible than aproduct_dtofixture because tests can ask formake_product_dto(stock=0)instead of mutating a shared instance. - `spec=` on mocks. Always pass
spec=SomeRepositorytoMagicMock— it makes the mock fail fast on attribute typos and keeps tests honest when the real class changes. - `override_service` lets API tests substitute a fake service without monkey-patching imports. The yield/restore dance is important so a test's override doesn't bleed into the next one.
Writing Each Layer
test_repo.py — Real database
- Always assert on the prefix — it's a cheap proof the ULID generator is wired up.
- Assert on the DTO type at least once per repo — catches a repo accidentally returning an ORM instance.
- To assert on
transaction.on_commitbehavior (i.e. reliable-signal dispatch), wrap the act step indjango_capture_on_commit_callbacks(execute=True)under the plain marker. Reserve@pytest.mark.django_db(transaction=True)for tests that genuinely need real commits — thread-based concurrency tests, or code that reads from a second connection — because its teardown flushes every table and it is by far the slowest thing a test can ask for.
test_service.py — No database
- No `@pytest.mark.django_db`. If you reach for it in a service test, you've found a leak.
- Assert on both the return value and the repo calls. The return value proves the outcome; the call assertion proves the service routed the work correctly and didn't swallow arguments.
- Use
assert_not_called()on negative paths — it's the cleanest way to prove that a validation error short-circuited a write.
test_api.py — HTTP integration
clientis provided by pytest-django.- Prefer asserting on shape and a prefix over a full dict comparison — test becomes resilient to added optional fields.
- If a route is just a passthrough to a service, one happy-path test is enough — the service tests cover the business logic, the repo tests cover persistence, and this test proves the wiring.
Testing the exception handler
Services raise plain Python exceptions (ValueError, LookupError, PermissionError); the central exception handler in src/project/api/__init__.py maps them to HTTP responses (400, 404, 403) with a {"detail": "..."} body. API tests are the layer that proves the round-trip — assert on the status code and the JSON body, not on the raised exception.
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 100 of 100Pattern checks on the skill's files.
- Model reviewNot runA model review is scheduled for the next rescan.
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/dj-pytest/SKILL.md
Popularity
- Repository stars
- 109
- Repository forks
- 6
- 7-day trend score
- 24
Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.
Extension points
hookPre/post lifecycle hooks
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/dvf/opinionated-django/dj-pytest)