django-dev-test
БесплатноБез исполняемых скриптовНе проверенThis skill should be used when the user asks to "write tests", "django tests", "pytest", "test factories", "create test", "add tests", "test coverage", or…
от sergio-bershadsky★ 15 звёзд на GitHubОб этом скилле
Django Testing Patterns
pytest-django testing with factory_boy for fixture management.
Core Principles
- pytest only - Never use Django's TestCase
- factory_boy - Use factories for all test data
- Mirror structure - Tests mirror app structure
- Isolation - Each test fully isolated
- Fast fixtures - Prefer
@pytest.fixtureover setUp
Installation
pip install pytest pytest-django factory-boy pytest-cov
Configuration
pytest.ini or pyproject.toml:
# pyproject.toml
[tool.pytest.ini_options]
DJANGO_SETTINGS_MODULE = "config.settings"
python_files = ["test_*.py", "*_test.py"]
python_classes = ["Test*"]
python_functions = ["test_*"]
addopts = [
"--strict-markers",
"-ra",
"--tb=short",
]
markers = [
"slow: marks tests as slow",
"integration: marks tests as integration tests",
]
Test Structure
tests/
├── conftest.py # Shared fixtures
├── factories/
│ ├── __init__.py
│ ├── user.py # UserFactory
│ ├── product.py # ProductFactory
│ └── order.py # OrderFactory
├── unit/
│ ├── models/
│ │ ├── test_user.py
│ │ └── test_product.py
│ └── services/
│ └── test_user_service.py
├── integration/
│ └── api/
│ ├── test_users.py
│ └── test_products.py
└── e2e/
└── test_checkout.py
Conftest Setup
tests/conftest.py:
import pytest
from django.test import Client
from ninja.testing import TestClient
from apps.myapp.api import api
@pytest.fixture
def client():
"""Django test client."""
return Client()
@pytest.fixture
def api_client():
"""Django Ninja test client."""
return TestClient(api)
@pytest.fixture
def authenticated_client(api_client, user):
"""API client with authentication."""
api_client.headers["Authorization"] = f"Bearer {user.get_token()}"
return api_client
@pytest.fixture
def user(user_factory):
"""Default test user."""
return user_factory()
@pytest.fixture
def admin_user(user_factory):
"""Admin test user."""
return user_factory(is_staff=True, is_superuser=True)
Factory Pattern
Base factory in factories/__init__.py:
import factory
from factory.django import DjangoModelFactory
class BaseFactory(DjangoModelFactory):
"""Base factory with common patterns."""
class Meta:
abstract = True
@classmethod
def _create(cls, model_class, *args, **kwargs):
"""Override to handle soft-deleted models."""
obj = super()._create(model_class, *args, **kwargs)
return obj
User factory in factories/user.py:
import factory
from factory import fuzzy
from apps.users.models import User
from . import BaseFactory
class UserFactory(BaseFactory):
"""Factory for User model."""
class Meta:
model = User
skip_postgeneration_save = True
email = factory.LazyAttribute(
lambda obj: f"{obj.name.lower().replace(' ', '.')}@example.com"
)
name = factory.Faker("name")
is_active = True
@factory.post_generation
def password(obj, create, extracted, **kwargs):
password = extracted or "testpass123"
obj.set_password(password)
if create:
obj.save(update_fields=["password"])
@classmethod
def _create(cls, model_class, *args, **kwargs):
"""Create with explicit password handling."""
password = kwargs.pop("password", None)
user = super()._create(model_class, *args, **kwargs)
if password:
user.set_password(password)
user.save(update_fields=["password"])
return user
Order factory with relationships (factories/order.py):
import factory
from decimal import Decimal
from apps.orders.models import Order, OrderItem
from . import BaseFactory
from .user import UserFactory
from .product import ProductFactory
class OrderFactory(BaseFactory):
"""Factory for Order model."""
class Meta:
model = Order
user = factory.SubFactory(UserFactory)
status = "pending"
total = factory.LazyAttribute(lambda obj: Decimal("0.00"))
@factory.post_generation
def items(obj, create, extracted, **kwargs):
if not create:
return
if extracted:
for item in extracted:
OrderItemFactory(order=obj, **item)
else:
# Create 1-3 random items
import random
for _ in range(random.randint(1, 3)):
OrderItemFactory(order=obj)
# Update total
obj.total = sum(item.subtotal for item in obj.items.all())
obj.save(update_fields=["total"])
class OrderItemFactory(BaseFactory):
"""Factory for OrderItem model."""
class Meta:
model = OrderItem
order = factory.SubFactory(OrderFactory)
product = factory.SubFactory(ProductFactory)
quantity = factory.fuzzy.FuzzyInteger(1, 5)
unit_price = factory.La
Установить django-dev-test в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл django-dev-test?
This skill should be used when the user asks to "write tests", "django tests", "pytest", "test factories", "create test", "add tests", "test coverage", or mentions testing Django applications, fixtures, or factory_boy. Provides pytest-django patterns with factory_boy for test data generation.
Как установить скилл django-dev-test?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл django-dev-test запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic