unit-testing
БесплатноЗапускает вложенные скриптыНе проверенUnit testing standards following TDD methodology, test pyramid principles, and comprehensive coverage practices. Covers pytest, Jest, mocking, fixtures, and…
Об этом скилле
Unit Testing Standards
Quick Navigation: Level 1: Quick Start (5 min) → Level 2: Implementation (30 min) → Level 3: Mastery (Extended)
Level 1: Quick Start (<2,000 tokens, 5 minutes)
Core Principles
- Test-Driven Development (TDD): Write tests before implementation (Red-Green-Refactor)
- Test Pyramid: 70% unit tests, 20% integration, 10% E2E
- Fast and Isolated: Tests run in milliseconds, no external dependencies
- Comprehensive Coverage: Aim for 80-90% code coverage minimum
- Clear and Maintainable: Tests serve as living documentation
Essential Checklist
- TDD workflow: Write failing test → Implement → Refactor
- Coverage targets: 80%+ overall, 95%+ for critical paths
- Naming convention:
test_<function>_<scenario>_<expected_result> - AAA pattern: Arrange, Act, Assert structure in every test
- Mocking: Mock external dependencies (database, APIs, filesystem)
- Fixtures: Reusable test data and setup/teardown
- Parametrized tests: Test multiple inputs efficiently
- CI integration: Tests run automatically on every commit
Quick Example
# pytest unit testing example
import pytest
from datetime import datetime
def calculate_discount(user_age: int, purchase_amount: float) -> float:
"""Calculate discount based on age and purchase amount."""
if user_age < 18:
return 0.0
elif user_age >= 65:
return purchase_amount * 0.15
elif purchase_amount >= 100:
return purchase_amount * 0.10
return 0.0
# Unit tests following TDD
def test_calculate_discount_no_discount_for_minors():
"""Test that users under 18 receive no discount."""
# Arrange
user_age = 16
purchase_amount = 100.0
# Act
discount = calculate_discount(user_age, purchase_amount)
# Assert
assert discount == 0.0
def test_calculate_discount_senior_discount():
"""Test that seniors (65+) receive 15% discount."""
assert calculate_discount(65, 100.0) == 15.0
assert calculate_discount(70, 200.0) == 30.0
def test_calculate_discount_large_purchase():
"""Test that purchases >= $100 receive 10% discount."""
assert calculate_discount(30, 100.0) == 10.0
assert calculate_discount(30, 150.0) == 15.0
@pytest.mark.parametrize("age,amount,expected", [
(16, 100, 0.0), # Minor
(30, 50, 0.0), # No discount
(30, 100, 10.0), # Large purchase
(65, 50, 7.5), # Senior
(70, 200, 30.0), # Senior large purchase
])
def test_calculate_discount_parametrized(age, amount, expected):
"""Test multiple discount scenarios."""
assert calculate_discount(age, amount) == expected
Quick Links to Level 2
Level 2: Implementation (<5,000 tokens, 30 minutes)
TDD Workflow
Red-Green-Refactor Cycle (see resources/tdd-workflow.md)
# Step 1: RED - Write failing test
def test_user_authentication_success():
"""Test successful user authentication."""
auth_service = AuthenticationService()
result = auth_service.authenticate('[email protected]', 'password123')
assert result.success is True
assert result.token is not None
# Step 2: GREEN - Write minimum code to pass
class AuthenticationService:
def authenticate(self, email: str, password: str):
# Minimal implementation
return AuthResult(success=True, token='dummy_token')
# Step 3: REFACTOR - Improve implementation
class AuthenticationService:
def __init__(self, user_repository, token_generator):
self.user_repo = user_repository
self.token_gen = token_generator
def authenticate(self, email: str, password: str):
user = self.user_repo.find_by_email(email)
if not user or not user.verify_password(password):
return AuthResult(success=False, error='Invalid credentials')
token = self.token_gen.generate(user.id)
return AuthResult(success=True, token=token)
Test Organization
Test Structure (see templates/test-template-pytest.py)
# tests/test_user_service.py
import pytest
from unittest.mock import Mock, MagicMock
from app.services.user_service import UserService
from app.models.user import User
@pytest.fixture
def mock_database():
"""Create mock database connection."""
db = Mock()
db.query = MagicMock(return_value=[])
return db
@pytest.fixture
def user_service(mock_database):
"""Create UserService with mocked dependencies."""
return UserService(database=mock_database)
class TestUserService:
"""Test suite for UserService
Установить unit-testing в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл unit-testing?
Unit testing standards following TDD methodology, test pyramid principles, and comprehensive coverage practices. Covers pytest, Jest, mocking, fixtures, and CI integration for reliable test suites.
Как установить скилл unit-testing?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл unit-testing запускает скрипты?
Да, скилл несёт исполняемые скрипты. Проверь исходник перед установкой.
Похожие скиллы
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