Skip to main content
ClaudeWave
Skill355 estrellas del repoactualizado today

python-pytest-patterns

This skill provides modern pytest patterns for Python testing, covering fixtures with scopes, parametrization for multiple test cases, exception handling with pytest.raises, custom markers for test organization, and mocking strategies. Use it when building unit and integration tests, setting up test fixtures with lifecycle management, validating multiple input combinations, testing error conditions, or mocking external dependencies.

Instalar en Claude Code
Copiar
git clone --depth 1 https://github.com/aiskillstore/marketplace /tmp/python-pytest-patterns && cp -r /tmp/python-pytest-patterns/skills/0xdarkmatter/python-pytest-patterns ~/.claude/skills/python-pytest-patterns
Después abre una sesión nueva de Claude Code; el skill carga automáticamente.

SKILL.md

# Python pytest Patterns

Modern pytest patterns for effective testing.

## Basic Test Structure

```python
import pytest

def test_basic():
    """Simple assertion test."""
    assert 1 + 1 == 2

def test_with_description():
    """Descriptive name and docstring."""
    result = calculate_total([1, 2, 3])
    assert result == 6, "Sum should equal 6"
```

## Fixtures

```python
import pytest

@pytest.fixture
def sample_user():
    """Create test user."""
    return {"id": 1, "name": "Test User"}

@pytest.fixture
def db_connection():
    """Fixture with setup and teardown."""
    conn = create_connection()
    yield conn
    conn.close()

def test_user(sample_user):
    """Fixtures injected by name."""
    assert sample_user["name"] == "Test User"
```

### Fixture Scopes

```python
@pytest.fixture(scope="function")  # Default - per test
@pytest.fixture(scope="class")     # Per test class
@pytest.fixture(scope="module")    # Per test file
@pytest.fixture(scope="session")   # Entire test run
```

## Parametrize

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

# Multiple parameters
@pytest.mark.parametrize("x", [1, 2])
@pytest.mark.parametrize("y", [10, 20])
def test_multiply(x, y):  # 4 test combinations
    assert x * y > 0
```

## Exception Testing

```python
def test_raises():
    with pytest.raises(ValueError) as exc_info:
        raise ValueError("Invalid input")
    assert "Invalid" in str(exc_info.value)

def test_raises_match():
    with pytest.raises(ValueError, match=r".*[Ii]nvalid.*"):
        raise ValueError("Invalid input")
```

## Markers

```python
@pytest.mark.skip(reason="Not implemented yet")
def test_future_feature():
    pass

@pytest.mark.skipif(sys.platform == "win32", reason="Unix only")
def test_unix_feature():
    pass

@pytest.mark.xfail(reason="Known bug")
def test_buggy():
    assert broken_function() == expected

@pytest.mark.slow
def test_performance():
    """Custom marker - register in pytest.ini."""
    pass
```

## Mocking

```python
from unittest.mock import Mock, patch, MagicMock

def test_with_mock():
    mock_api = Mock()
    mock_api.get.return_value = {"status": "ok"}
    result = mock_api.get("/endpoint")
    assert result["status"] == "ok"

@patch("module.external_api")
def test_with_patch(mock_api):
    mock_api.return_value = {"data": []}
    result = function_using_api()
    mock_api.assert_called_once()
```

### pytest-mock (Recommended)

```python
def test_with_mocker(mocker):
    mock_api = mocker.patch("module.api_call")
    mock_api.return_value = {"success": True}
    result = process_data()
    assert result["success"]
```

## conftest.py

```python
# tests/conftest.py - Shared fixtures

import pytest

@pytest.fixture(scope="session")
def app():
    """Application fixture available to all tests."""
    return create_app(testing=True)

@pytest.fixture
def client(app):
    """Test client fixture."""
    return app.test_client()
```

## Quick Reference

| Command | Description |
|---------|-------------|
| `pytest` | Run all tests |
| `pytest -v` | Verbose output |
| `pytest -x` | Stop on first failure |
| `pytest -k "test_name"` | Run matching tests |
| `pytest -m slow` | Run marked tests |
| `pytest --lf` | Rerun last failed |
| `pytest --cov=src` | Coverage report |
| `pytest -n auto` | Parallel (pytest-xdist) |

## Additional Resources

- `./references/fixtures-advanced.md` - Factory fixtures, autouse, conftest patterns
- `./references/mocking-patterns.md` - Mock, patch, MagicMock, side_effect
- `./references/async-testing.md` - pytest-asyncio patterns
- `./references/coverage-strategies.md` - pytest-cov, branch coverage, reports
- `./references/integration-testing.md` - Database fixtures, API testing, testcontainers
- `./references/property-testing.md` - Hypothesis framework, strategies, shrinking
- `./references/test-architecture.md` - Test pyramid, organization, isolation strategies

## Scripts

- `./scripts/run-tests.sh` - Run tests with recommended options
- `./scripts/generate-conftest.sh` - Generate conftest.py boilerplate

## Assets

- `./assets/pytest.ini.template` - Recommended pytest configuration
- `./assets/conftest.py.template` - Common fixture patterns

---

## See Also

**Related Skills:**
- `python-typing-patterns` - Type-safe test code
- `python-async-patterns` - Async test patterns (pytest-asyncio)

**Testing specific frameworks:**
- `python-fastapi-patterns` - TestClient, API testing
- `python-database-patterns` - Database fixtures, transactions
jira-safeSkill

Implement SAFe methodology in Jira. Use when creating Epics, Features, Stories with proper hierarchy, acceptance criteria, and parent-child linking.

jira-workflowSkill

Orchestrate Jira workflows end-to-end. Use when building stories with approvals, transitioning items through lifecycle states, or syncing task completion with Jira.

chinese-learning-assistantSkill

HSK4級レベルから流暢さを目指す学習者向け。中国語表現の使用場面・自然さを分析し、作文を「ネイティブらしい流暢な表現」に改善。bilibili等のコンテンツ理解とネイティブとの会話をサポート。実際の用例をWeb検索で提示

frontend-dev-guidelinesSkill

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

skill-developerSkill

Claude Code 스킬, 훅, 에이전트, 명령어를 생성하고 관리하기 위한 메타 스킬. 새 스킬 생성, 스킬 트리거 설정, 훅 설정, Claude Code 인프라 관리 시 사용.

sitemapkitSkill

Discover and extract sitemaps from any website using SitemapKit. Use this skill whenever the user wants to find pages on a website, get a list of URLs from a domain, audit a site's structure, crawl a sitemap, check what pages exist on a site, or do anything involving sitemaps or site URL discovery — even if they don't explicitly say "sitemap". Requires the sitemapkit MCP server configured with a valid SITEMAPKIT_API_KEY.

create-prSkill

GitHubのプルリクエスト(PR)を作成する際に使用します。変更のコミット、プッシュ、PR作成を含む完全なワークフローを日本語で実行します。「PRを作って」「プルリクエストを作成」「pull requestを作成」などのリクエストで自動的に起動します。

create-svg-from-promptSkill

Generate an SVG of a user-requested image or scene