python-testing-patterns
하는 일
이 안내서는 Python 코드를 철저히 테스트하는 방법을 가르칩니다. pytest 같은 도구를 쓰는 방법, 프로그램의 다른 부분을 위한 테스트를 만드는 방법, 외부 요소를 흉내 내서 테스트가 더 잘 작동하도록 하는 방법을 보여 줍니다.
사용하는 경우
- ✓Python 코드를 위한 테스트를 쓰고 있을 때.
- ✓테스트 묶음이나 실행 구조를 정리할 때.
- ✓출시 전에 코드가 기대대로 작동하는지 확인하고 싶을 때.
스킬 링크
https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/python-testing-patterns/SKILL.md복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.
사용 방법
가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
AI에게 요청하는 예시
“Python에서 두 숫자를 더하는 함수를 위한 간단한 테스트를 어떻게 작성할 수 있나요?”
매주 새 스킬 5개. 읽는 데 1분.
작동 방식
안내서는 여러 종류의 테스트와 그 구조를 설명합니다. 테스트 이름을 명확하게 짓는 예시와, 외부 의존성을 흉내 내거나 시간을 제어하는 도구 사용법도 보여 줍니다.
기술 내용 (원본 SKILL.md)
작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.
Python Testing Patterns
Comprehensive guide to implementing robust testing strategies in Python using pytest, fixtures, mocking, parameterization, and test-driven development practices.
When to Use This Skill
- Writing unit tests for Python code
- Setting up test suites and test infrastructure
- Implementing test-driven development (TDD)
- Creating integration tests for APIs and services
- Mocking external dependencies and services
- Testing async code and concurrent operations
- Setting up continuous testing in CI/CD
- Implementing property-based testing
- Testing database operations
- Debugging failing tests
Core Concepts
1. Test Types
- Unit Tests: Test individual functions/classes in isolation
- Integration Tests: Test interaction between components
- Functional Tests: Test complete features end-to-end
- Performance Tests: Measure speed and resource usage
2. Test Structure (AAA Pattern)
- Arrange: Set up test data and preconditions
- Act: Execute the code under test
- Assert: Verify the results
3. Test Coverage
- Measure what code is exercised by tests
- Identify untested code paths
- Aim for meaningful coverage, not just high percentages
4. Test Isolation
- Tests should be independent
- No shared state between tests
- Each test should clean up after itself
Quick Start
# test_example.py
def add(a, b):
return a + b
def test_add():
"""Basic test example."""
result = add(2, 3)
assert result == 5
def test_add_negative():
"""Test with negative numbers."""
assert add(-1, 1) == 0
# Run with: pytest test_example.py
Detailed patterns and worked examples
Detailed pattern documentation lives in references/details.md. Read that file when the navigation tier above is insufficient.
Testing Best Practices
Test Organization
# tests/
# __init__.py
# conftest.py # Shared fixtures
# test_unit/ # Unit tests
# test_models.py
# test_utils.py
# test_integration/ # Integration tests
# test_api.py
# test_database.py
# test_e2e/ # End-to-end tests
# test_workflows.py
Test Naming Convention
A common pattern: test_<unit>_<scenario>_<expected_outcome>. Adapt to your team's preferences.
# Pattern: test_<unit>_<scenario>_<expected>
def test_create_user_with_valid_data_returns_user():
...
def test_create_user_with_duplicate_email_raises_conflict():
...
def test_get_user_with_unknown_id_returns_none():
...
# Good test names - clear and descriptive
def test_user_creation_with_valid_data():
"""Clear name describes what is being tested."""
pass
def test_login_fails_with_invalid_password():
"""Name describes expected behavior."""
pass
def test_api_returns_404_for_missing_resource():
"""Specific about inputs and expected outcomes."""
pass
# Bad test names - avoid these
def test_1(): # Not descriptive
pass
def test_user(): # Too vague
pass
def test_function(): # Doesn't explain what's tested
pass
Testing Retry Behavior
Verify that retry logic works correctly using mock side effects.
from unittest.mock import Mock
def test_retries_on_transient_error():
"""Test that service retries on transient failures."""
client = Mock()
# Fail twice, then succeed
client.request.side_effect = [
ConnectionError("Failed"),
ConnectionError("Failed"),
{"status": "ok"},
]
service = ServiceWithRetry(client, max_retries=3)
result = service.fetch()
assert result == {"status": "ok"}
assert client.request.call_count == 3
def test_gives_up_after_max_retries():
"""Test that service stops retrying after max attempts."""
client = Mock()
client.request.side_effect = ConnectionError("Failed")
service = ServiceWithRetry(client, max_retries=3)
with pytest.raises(ConnectionError):
service.fetch()
assert client.request.call_count == 3
def test_does_not_retry_on_permanent_error():
"""Test that permanent errors are not retried."""
client = Mock()
client.request.side_effect = ValueError("Invalid input")
service = ServiceWithRetry(client, max_retries=3)
with pytest.raises(ValueError):
service.fetch()
# Only called once - no retry for ValueError
assert client.request.call_count == 1
Mocking Time with Freezegun
…
자주 묻는 질문
단위 테스트와 통합 테스트란 무엇인가요?
단위 테스트는 코드의 작은 부분을 따로 확인하고, 통합 테스트는 코드의 여러 부분이 함께 어떻게 작동하는지 확인합니다.
'모킹'이란 무엇인가요?
네트워크 호출이나 데이터베이스처럼 코드의 일부나 외부 요소를 가짜 버전으로 만드는 것입니다. 그래서 외부 부분에 의존하지 않고 주요 코드를 테스트할 수 있습니다.
TDD(테스트 주도 개발)란 무엇인가요?
실제 코드를 쓰기 전에 테스트를 먼저 작성하는 방식입니다. 테스트가 정의한 요구 사항을 코드가 충족하도록 보장합니다.
상세 정보
작성자의 원본 설명
Implement comprehensive testing strategies with pytest, fixtures, mocking, and test-driven development. Use when writing Python tests, setting up test suites, or implementing testing best practices.
repo: wshobson/agents
인기도
- GitHub 스타
- 41k
- 순위
- #6768
- 라이선스
- MIT
- 업데이트
- 2026. 10. 15.
댓글
- …
이 저장소의 다른 스킬
screen-reader-testing
41k에이전트가 스크린 리더로 웹사이트를 테스트해 접근성을 확인하도록 돕습니다.
wcag-audit-patterns
41k에이전트가 WCAG 지침에 따라 웹사이트의 접근성을 감사하고 문제를 고치도록 돕습니다.
multi-reviewer-patterns
41k에이전트가 병렬 코드 리뷰를 조율하고, 중복된 발견 사항을 정리하며, 보고서를 통합하도록 돕습니다.
parallel-debugging
41k에이전트가 병렬 조사와 근본 원인 분석으로 복잡한 문제를 디버그하도록 돕습니다.
비슷한 스킬
test-driven-development
311k에이전트가 기능이나 수정을 만들기 전에 실패하는 테스트를 먼저 쓰고, 그것을 통과시키는 가장 작은 코드를 작성하도록 가르칩니다.
verification-before-completion
311k에이전트가 작업, 수정, 빌드가 완료되었거나 통과했다고 말하기 전에 실제 점검을 실행하고 결과를 읽도록 가르칩니다.
migrate-to-shoehorn
310k테스트 파일의 위험한 타입 캐스팅을 shoehorn 라이브러리로 바꿔, 테스트가 일부 데이터만 써도 타입 검사를 통과하도록 돕습니다.