Python 기초집LESSON 22
pytest로 자동 테스트 작성
난이도입문
예상 시간30분
선수지식이전 강의
22강. pytest로 자동 테스트 작성
1. 이번 강의에서 해결할 문제
매번 눈으로 평균과 승률을 확인하면 경계값을 놓치고 수정 때마다 같은 검사를 반복합니다. 기대 결과를 실행 가능한 테스트로 저장합니다.
2. 학습 목표
3. 핵심 개념
pytest는 기본적으로 test_*.py, *_test.py 파일과 test_ 함수를 발견합니다. 각 테스트는 하나의 행동을 검증하고 서로 상태를 공유하지 않아야 합니다. 부동소수점은 pytest.approx로 오차를 고려합니다.
4. 단계별 코드 예시
파일 경로: C:\dev\game-log-analyzer\tests\test_analysis.py
tests/test_analysis.py
import pytest
from battle_analyzer.analysis import average_damage
from battle_analyzer.models import BattleRecord
def make_record(damage=100, result="win"):
return BattleRecord("Knight", "Slime", "Slash", damage, result)
def test_average_damage():
records = [make_record(80), make_record(120)]
assert average_damage(records) == pytest.approx(100.0)
def test_empty_average_is_zero():
assert average_damage([]) == 0.0
def test_negative_damage_is_rejected():
with pytest.raises(ValueError, match="0 이상"):
make_record(-1)
파일 경로: C:\dev\game-log-analyzer\tests\test_files.py
tests/test_files.py
def test_tmp_path_can_store_report(tmp_path):
report = tmp_path / "report.json"
report.write_text('{"battle_count": 2}', encoding="utf-8")
assert report.exists()
assert "battle_count" in report.read_text(encoding="utf-8")
PowerShell · 실행
.\.venv\Scripts\python.exe -m pytest -q
.\.venv\Scripts\python.exe -m pytest .\tests\test_analysis.py -vv
5. 코드가 동작하는 이유
assert가 거짓이면 pytest가 표현식의 실제 값을 상세히 보여 줍니다. raises는 지정 예외와 메시지가 발생해야 성공합니다. tmp_path는 테스트마다 고유한 임시 디렉터리를 제공해 실제 프로젝트 파일을 덮어쓰지 않습니다.
6. 자주 하는 실수와 해결법
7. 직접 실습
8. 이해 점검 질문 3개
9. 핵심 요약
MINI QUIZ
0 / 2pytest로 자동 테스트 작성 미니 퀴즈
선택 즉시 정답과 해설을 확인할 수 있습니다. 결과는 이 브라우저에만 저장됩니다.
LESSON STATUS
22강. pytest로 자동 테스트 작성 미완료 상태학습을 마쳤나요?
직접 실습과 점검 질문까지 확인한 뒤 완료로 표시하세요.