PYTHON · 테스트
pytest — 기초 & fixture & parametrize
Python 최고의 테스트 프레임워크 pytest로 효율적인 테스트를 작성합니다.
테스트중급pytestfixtureparametrizemonkeypatchtmp_path
핵심 설명
Python 최고의 테스트 프레임워크 pytest로 효율적인 테스트를 작성합니다.
Python code
# test_calculator.py
import pytest
from calculator import add, divide
# 기본 테스트
def test_add_positive():
assert add(2, 3) == 5
def test_add_negative():
assert add(-1, 1) == 0
# 예외 테스트
def test_divide_by_zero():
with pytest.raises(ZeroDivisionError, match="division by zero"):
divide(10, 0)
# @pytest.mark.parametrize — 여러 케이스 자동 실행
@pytest.mark.parametrize("a, b, expected", [
(2, 3, 5),
(0, 0, 0),
(-1, 1, 0),
(100, -50, 50),
])
def test_add_cases(a, b, expected):
assert add(a, b) == expected
# fixture — 테스트 전후 설정/정리
@pytest.fixture
def sample_data():
data = {"users": ["Alice", "Bob"], "count": 2}
yield data # 여기서 테스트 실행됨
# yield 이후는 teardown
print("\n정리 완료")
def test_with_fixture(sample_data):
assert sample_data["count"] == 2
assert "Alice" in sample_data["users"]
# tmp_path fixture (pytest 내장)
def test_file_write(tmp_path):
file = tmp_path / "test.txt"
file.write_text("hello")
assert file.read_text() == "hello"
# monkeypatch — 의존성 교체
def test_with_mock(monkeypatch):
monkeypatch.setattr("builtins.input", lambda _: "42")
# input()이 항상 "42"를 반환학습 팁
pytest는 test_로 시작하는 파일과 함수를 자동 발견합니다. pytest -v로 상세 출력, pytest -k "add"로 이름 필터링이 가능합니다.
주의할 점
assert add(2,3) == 5에서 실패 시 pytest는 자동으로 값을 출력해줍니다. assertEqual 같은 메서드 없이 일반 assert만으로 충분합니다.
자주 묻는 질문
pytest — 기초 & fixture & parametrize란 무엇인가요?
Python 최고의 테스트 프레임워크 pytest로 효율적인 테스트를 작성합니다.
pytest — 기초 & fixture & parametrize 학습 시 주의할 점은 무엇인가요?
assert add(2,3) == 5 에서 실패 시 pytest는 자동으로 값을 출력해줍니다. assertEqual 같은 메서드 없이 일반 assert 만으로 충분합니다.
Continue Learning
Python 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.