| name | python-testing |
| description | pytest, TDD 방법론, fixtures, 모킹, 매개변수화 및 커버리지 요구 사항을 사용하는 Python 테스트 전략입니다. |
| origin | ECC |
Python 테스트 패턴
pytest, TDD 방법론 및 모범 사례를 사용한 Python 애플리케이션을 위한 포괄적인 테스트 전략입니다.
활성화 시점
- 새로운 Python 코드를 작성할 때 (TDD 준수: red, green, refactor)
- Python 프로젝트를 위한 테스트 스위트를 설계할 때
- Python 테스트 커버리지를 검토할 때
- 테스트 인프라를 구축할 때
핵심 테스트 철학
테스트 주도 개발 (TDD)
항상 TDD 사이클을 따르십시오:
- RED: 원하는 동작에 대해 실패하는 테스트를 작성합니다.
- GREEN: 테스트를 통과시키기 위한 최소한의 코드를 작성합니다.
- REFACTOR: 테스트가 green 상태를 유지하는 동안 코드를 개선합니다.
def test_add_numbers():
result = add(2, 3)
assert result == 5
def add(a, b):
return a + b
커버리지 요구 사항
- 목표: 코드 커버리지 80% 이상
- 중요 경로: 커버리지 100% 필수
- 커버리지 측정을 위해
pytest --cov를 사용하십시오.
pytest --cov=mypackage --cov-report=term-missing --cov-report=html
pytest 기초
기본 테스트 구조
import pytest
def test_addition():
"""기본적인 덧셈 테스트."""
assert 2 + 2 == 4
def test_string_uppercase():
"""문자열 대문자 변환 테스트."""
text = "hello"
assert text.upper() == "HELLO"
def test_list_append():
"""리스트 추가 테스트."""
items = [1, 2, 3]
items.append(4)
assert 4 in items
assert len(items) == 4
단언문 (Assertions)
assert result == expected
assert result != unexpected
assert result
assert not result
assert result is True
assert result is False
assert result is None
assert item in collection
assert item not in collection
assert result > 0
assert 0 <= result <= 100
assert isinstance(result, str)
with pytest.raises(ValueError):
raise ValueError("error message")
with pytest.raises(ValueError, match="invalid input"):
raise ValueError("invalid input provided")
with pytest.raises(ValueError) as exc_info:
raise ValueError()
(exc_info.value) ==
Fixtures
기본적인 Fixture 사용법
import pytest
@pytest.fixture
def sample_data():
"""샘플 데이터를 제공하는 fixture."""
return {"name": "Alice", "age": 30}
def test_sample_data(sample_data):
"""fixture를 사용하는 테스트."""
assert sample_data["name"] == "Alice"
assert sample_data["age"] == 30
Setup/Teardown 기능이 있는 Fixture
@pytest.fixture
def database():
"""설정 및 정리 기능이 있는 fixture."""
db = Database(":memory:")
db.create_tables()
db.insert_test_data()
yield db
db.close()
def test_database_query(database):
"""데이터베이스 작업 테스트."""
result = database.query("SELECT * FROM users")
assert len(result) > 0
Fixture 스코프 (Scopes)
@pytest.fixture
def temp_file():
with open("temp.txt", "w") as f:
yield f
os.remove("temp.txt")
@pytest.fixture(scope="module")
def module_db():
db = Database(":memory:")
db.create_tables()
yield db
db.close()
@pytest.fixture(scope="session")
def shared_resource():
resource = ExpensiveResource()
yield resource
resource.cleanup()
매개변수화된 Fixture
@pytest.fixture(params=[1, 2, 3])
def number(request):
"""매개변수가 있는 fixture."""
return request.param
def test_numbers(number):
"""각 매개변수마다 한 번씩, 총 3번 실행됩니다."""
assert number > 0
여러 개의 Fixture 사용
@pytest.fixture
def user():
return User(id=1, name="Alice")
@pytest.fixture
def admin():
return User(id=2, name="Admin", role="admin")
def test_user_admin_interaction(user, admin):
"""여러 fixture를 사용하는 테스트."""
assert admin.can_manage(user)
자동 실행 Fixture (Autouse)
@pytest.fixture(autouse=True)
def reset_config():
"""모든 테스트 전에 자동으로 실행됩니다."""
Config.reset()
yield
Config.cleanup()
def test_without_fixture_call():
assert Config.get_setting("debug") is False
Fixture 공유를 위한 conftest.py
import pytest
@pytest.fixture
def client():
"""모든 테스트에서 공유되는 fixture."""
app = create_app(testing=True)
with app.test_client() as client:
yield client
@pytest.fixture
def auth_headers(client):
"""API 테스트를 위한 인증 헤더 생성."""
response = client.post("/api/login", json={
"username": "test",
"password": "test"
})
token = response.json["token"]
return {"Authorization": f"Bearer {token}"}
매개변수화 (Parametrization)
기본적인 매개변수화
@pytest.mark.parametrize("input,expected", [
("hello", "HELLO"),
("world", "WORLD"),
("PyThOn", "PYTHON"),
])
def test_uppercase(input, expected):
"""서로 다른 입력으로 3번 실행됩니다."""
assert input.upper() == expected
여러 개의 매개변수
@pytest.mark.parametrize("a,b,expected", [
(2, 3, 5),
(0, 0, 0),
(-1, 1, 0),
(100, 200, 300),
])
def test_add(a, b, expected):
"""여러 입력 조합으로 덧셈을 테스트합니다."""
assert add(a, b) == expected
ID를 사용한 매개변수화
@pytest.mark.parametrize("input,expected", [
("valid@email.com", True),
("invalid", False),
("@no-domain.com", False),
], ids=["valid-email", "missing-at", "missing-domain"])
def test_email_validation(input, expected):
"""읽기 좋은 테스트 ID와 함께 이메일 유효성을 검증합니다."""
assert is_valid_email(input) is expected
마커 (Markers) 및 테스트 선택
커스텀 마커
@pytest.mark.slow
def test_slow_operation():
time.sleep(5)
@pytest.mark.integration
def test_api_integration():
response = requests.get("https://api.example.com")
assert response.status_code == 200
@pytest.mark.unit
def test_unit_logic():
assert calculate(2, 3) == 5
특정 테스트 실행
pytest -m "not slow"
pytest -m integration
pytest -m "integration or slow"
pytest -m "unit and not slow"
모킹 (Mocking) 및 패칭 (Patching)
함수 모킹
from unittest.mock import patch, Mock
@patch("mypackage.external_api_call")
def test_with_mock(api_call_mock):
"""외부 API를 모킹하여 테스트합니다."""
api_call_mock.return_value = {"status": "success"}
result = my_function()
api_call_mock.assert_called_once()
assert result["status"] == "success"
반환값 모킹
@patch("mypackage.Database.connect")
def test_database_connection(connect_mock):
"""데이터베이스 연결을 모킹하여 테스트합니다."""
connect_mock.return_value = MockConnection()
db = Database()
db.connect()
connect_mock.assert_called_once_with("localhost")
예외 모킹
@patch("mypackage.api_call")
def test_api_error_handling(api_call_mock):
"""모킹된 예외를 사용하여 오류 처리를 테스트합니다."""
api_call_mock.side_effect = ConnectionError("Network error")
with pytest.raises(ConnectionError):
api_call()
api_call_mock.assert_called_once()
컨텍스트 관리자 모킹
@patch("builtins.open", new_callable=mock_open)
def test_file_reading(mock_file):
"""open을 모킹하여 파일 읽기를 테스트합니다."""
mock_file.return_value.read.return_value = "file content"
result = read_file("test.txt")
mock_file.assert_called_once_with("test.txt", "r")
assert result == "file content"
비동기 코드 테스트
pytest-asyncio를 사용한 비동기 테스트
import pytest
@pytest.mark.asyncio
async def test_async_function():
"""비동기 함수를 테스트합니다."""
result = await async_add(2, 3)
assert result == 5
@pytest.mark.asyncio
async def test_async_with_fixture(async_client):
"""비동기 fixture와 함께 비동기 테스트를 수행합니다."""
response = await async_client.get("/api/users")
assert response.status_code == 200
부수 효과(Side Effects) 테스트
파일 작업 테스트
import tempfile
import os
def test_file_processing():
"""임시 파일을 사용하여 파일 처리를 테스트합니다."""
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.txt') as f:
f.write("test content")
temp_path = f.name
try:
result = process_file(temp_path)
assert result == "processed: test content"
finally:
os.unlink(temp_path)
pytest의 tmp_path fixture 사용 (권장)
def test_with_tmp_path(tmp_path):
"""pytest 내장 임시 경로 fixture를 사용하여 테스트합니다."""
test_file = tmp_path / "test.txt"
test_file.write_text("hello world")
result = process_file(str(test_file))
assert result == "hello world"
테스트 조직화
디렉토리 구조
tests/
├── conftest.py # 공유 fixtures
├── __init__.py
├── unit/ # 단위 테스트
│ ├── __init__.py
│ ├── test_models.py
│ ├── test_utils.py
│ └── test_services.py
├── integration/ # 통합 테스트
│ ├── __init__.py
│ ├── test_api.py
│ └── test_database.py
└── e2e/ # End-to-end 테스트
├── __init__.py
└── test_user_flow.py
모범 사례
권장 사항 (DO)
- TDD 준수: 코드보다 테스트를 먼저 작성하십시오 (red-green-refactor)
- 한 번에 하나만 테스트: 각 테스트는 하나의 동작만 검증해야 합니다.
- 설명적인 이름 사용:
test_user_login_with_invalid_credentials_fails
- Fixture 활용: fixture를 사용하여 중복을 제거하십시오.
- 외부 의존성 모킹: 외부 서비스에 의존하지 마십시오.
- 엣지 케이스 테스트: 빈 입력, None 값, 경계 조건 등을 테스트하십시오.
- 80% 이상의 커버리지 목표: 핵심 경로에 집중하십시오.
- 테스트 속도 유지: 마커를 사용하여 느린 테스트를 분리하십시오.
금지 사항 (DON'T)
- 구현을 테스트하지 마십시오: 내부 구조가 아니라 동작과 출력을 테스트하십시오.
- 복잡한 조건문 사용 금지: 테스트는 단순하게 유지하십시오.
- 테스트 실패를 무시하지 마십시오: 모든 테스트가 통과해야 합니다.
- 서드파티 코드를 테스트하지 마십시오: 라이브러리가 잘 작동한다고 믿으십시오.
- 테스트 간 상태 공유 금지: 테스트는 독립적이어야 합니다.
- 테스트에서 직접 예외를 잡지 마십시오:
pytest.raises를 사용하십시오.
- print 문 사용 금지: 단언문과 pytest 출력을 활용하십시오.
- 너무 깨지기 쉬운 테스트 작성 금지: 과도하게 구체적인 모킹은 피하십시오.
공통 패턴
API 엔드포인트 테스트 (FastAPI/Flask)
@pytest.fixture
def client():
app = create_app(testing=True)
return app.test_client()
def test_get_user(client):
response = client.get("/api/users/1")
assert response.status_code == 200
assert response.json["id"] == 1
데이터베이스 작업 테스트
@pytest.fixture
def db_session():
"""테스트용 데이터베이스 세션을 생성합니다."""
session = Session(bind=engine)
session.begin_nested()
yield session
session.rollback()
session.close()
def test_create_user(db_session):
user = User(name="Alice", email="alice@example.com")
db_session.add(user)
db_session.commit()
retrieved = db_session.query(User).filter_by(name="Alice").first()
assert retrieved.email == "alice@example.com"
... (중략) ...
테스트 실행
pytest
pytest tests/test_utils.py
pytest tests/test_utils.py::test_function
pytest -v
pytest --cov=mypackage --cov-report=html
pytest -m "not slow"
pytest -x
pytest --lf
pytest --pdb
기억하십시오: 테스트도 코드입니다. 깔끔하고 읽기 쉬우며 유지보수가 가능하게 관리하십시오. 좋은 테스트는 버그를 찾아내고, 훌륭한 테스트는 버그를 예방합니다.