Python Testing Patterns
БесплатноБез исполняемых скриптовНе проверенComprehensive Python testing best practices with pytest, covering unit testing, integration testing, mocking, fixtures, property-based testing, and test…
от PramodDutta★ 253 звезды на GitHubОб этом скилле
Python Testing Patterns Skill
You are an expert Python developer specializing in testing patterns and best practices. When the user asks you to write, review, or improve Python tests, follow these detailed instructions.
Core Principles
- Test behavior, not implementation -- Focus on what the code does, not how it does it.
- DAMP over DRY -- Descriptive And Meaningful Phrases over Don't Repeat Yourself in tests.
- Arrange-Act-Assert -- Clear structure in every test.
- Fast and isolated -- Tests should run in milliseconds and have zero dependencies on each other.
- Fail fast with clear messages -- Assertion messages should explain what went wrong.
Project Structure
project/
src/
myapp/
__init__.py
services/
user_service.py
order_service.py
models/
user.py
order.py
utils/
validators.py
formatters.py
tests/
__init__.py
conftest.py
unit/
test_user_service.py
test_validators.py
integration/
test_api_endpoints.py
test_database.py
fixtures/
user_fixtures.py
order_fixtures.py
pytest.ini
pyproject.toml
Configuration
pytest.ini
[pytest]
testpaths = tests
python_files = test_*.py
python_classes = Test*
python_functions = test_*
addopts =
-v
--tb=short
--strict-markers
--cov=src
--cov-report=term-missing
--cov-report=html
--cov-fail-under=80
markers =
slow: marks tests as slow (deselect with '-m "not slow"')
integration: marks integration tests
unit: marks unit tests
smoke: marks smoke tests
skip_ci: marks tests to skip in CI
pyproject.toml
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = [
"-v",
"--strict-markers",
"--cov=src",
"--cov-report=term-missing",
]
[tool.coverage.run]
source = ["src"]
omit = ["tests/*", "*/__init__.py"]
[tool.coverage.report]
fail_under = 80
show_missing = true
skip_covered = false
Unit Testing Patterns
1. Testing Pure Functions
# validators.py
from typing import Optional
def is_valid_email(email: str) -> bool:
"""Validate email address format."""
import re
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return bool(re.match(pattern, email))
def calculate_discount(price: float, discount_percent: float) -> float:
"""Calculate discounted price."""
if not 0 <= discount_percent <= 100:
raise ValueError("Discount must be between 0 and 100")
return price * (1 - discount_percent / 100)
# test_validators.py
import pytest
from myapp.utils.validators import is_valid_email, calculate_discount
class TestEmailValidation:
"""Test suite for email validation."""
@pytest.mark.parametrize("email", [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
])
def test_valid_emails(self, email):
"""Should accept valid email addresses."""
assert is_valid_email(email) is True
@pytest.mark.parametrize("email", [
"",
"not-an-email",
"@missing-local.com",
"missing-at.com",
"spaces [email protected]",
"missing@domain",
])
def test_invalid_emails(self, email):
"""Should reject invalid email addresses."""
assert is_valid_email(email) is False
class TestDiscountCalculation:
"""Test suite for discount calculation."""
def test_no_discount(self):
"""Should return original price when discount is 0."""
assert calculate_discount(100.0, 0) == 100.0
def test_full_discount(self):
"""Should return 0 when discount is 100%."""
assert calculate_discount(100.0, 100) == 0.0
def test_partial_discount(self):
"""Should calculate correct discounted price."""
assert calculate_discount(100.0, 20) == 80.0
assert calculate_discount(50.0, 10) == 45.0
def test_invalid_discount_raises_error(self):
"""Should raise ValueError for invalid discount percentage."""
with pytest.raises(ValueError, match="Discount must be between 0 and 100"):
calculate_discount(100.0, 101)
with pytest.raises(ValueError, match="Discount must be between 0 and 100"):
calculate_discount(100.0, -10)
2. Testing Classes and Services
# user_service.py
from typing import Optional
from myapp.models.user import User
from myapp.repositories.user_repository import UserRepository
from myapp.services.email_service import EmailService
class UserService:
"""Service for managing users."""
def __init__(
self,
user_repository: UserRepository,
email_service: EmailService,
):
self.user_repository = user_repository
self.email_service = email_service
async def create_user(self, email: str, name: str) -> User:
"""Create a new u
Установить Python Testing Patterns в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл Python Testing Patterns?
Comprehensive Python testing best practices with pytest, covering unit testing, integration testing, mocking, fixtures, property-based testing, and test architecture.
Как установить скилл Python Testing Patterns?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл Python Testing Patterns запускает скрипты?
Нет, скилл состоит только из инструкций (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