---
name: ecc-python-testing
description: Python testing strategies using pytest, TDD methodology, fixtures, mocking, parametrization, and coverage requirements.
---

# Python Testing

Python testing strategies with pytest, TDD, and coverage.

## When to Activate
- Writing tests for Python code
- Setting up pytest configuration
- Debugging flaky tests
- Reviewing test coverage

## TDD Workflow
1. Write a failing test first
2. Write minimal production code to pass it
3. Refactor while keeping tests green

## Fixtures
```python
@pytest.fixture
def db_session():
    session = SessionLocal()
    yield session
    session.close()

def test_create_user(db_session):
    user = User(name="Alice")
    db_session.add(user)
    db_session.commit()
    assert user.id is not None
```

## Parametrization
```python
@pytest.mark.parametrize("input,expected", [
    (1, 2), (2, 4), (3, 6),
])
def test_double(input, expected):
    assert input * 2 == expected
```

## Mocking
```python
from unittest.mock import patch

def test_external_api_call():
    with patch("app.services.requests.get") as mock_get:
        mock_get.return_value.json.return_value = {"status": "ok"}
        result = my_function()
        assert result == "ok"
```

## Coverage
```ini
# .coveragerc
[run]
source = app/
omit = tests/*, migrations/*

[report]
fail_under = 80
```

Run: `pytest --cov=app --cov-report=term-missing`
