Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

unit-testing

БесплатноЗапускает вложенные скриптыНе проверен

Unit testing standards following TDD methodology, test pyramid principles, and comprehensive coverage practices. Covers pytest, Jest, mocking, fixtures, and…

williamzujkowskiот williamzujkowski★ 23 звезды на GitHub19 установок в других каталогах

Об этом скилле

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

  1. Test-Driven Development (TDD): Write tests before implementation (Red-Green-Refactor)
  2. Test Pyramid: 70% unit tests, 20% integration, 10% E2E
  3. Fast and Isolated: Tests run in milliseconds, no external dependencies
  4. Comprehensive Coverage: Aim for 80-90% code coverage minimum
  5. 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
Полный SKILL.md на GitHub

Установить unit-testing в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

config/jest.config.jsconfig/pytest.iniresources/README.mdresources/configs/jest.config.jsresources/configs/pytest.iniresources/coverage-configs/.coveragercresources/test-pyramid-diagram.mdscripts/README.mdtemplates/README.mdtemplates/example.test.jstemplates/example_test.gotemplates/test-template-go.gotemplates/test-template-jest.jstemplates/test-template-pytest.pytemplates/test_example.py

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 запускает скрипты?

Да, скилл несёт исполняемые скрипты. Проверь исходник перед установкой.

Похожие скиллы

Сравнить unit-testing с