PYTHON · 테스트
스냅샷 테스트
스냅샷 테스트로 복잡한 출력을 저장하고 변경 여부를 자동 감지합니다.
테스트고급snapshot스냅샷테스트회귀
핵심 설명
스냅샷 테스트로 복잡한 출력을 저장하고 변경 여부를 자동 감지합니다.
Python code
import json
import hashlib
class SnapshotTester:
def __init__(self):
self._snapshots: dict[str, str] = {}
def assert_match(self, name: str, value) -> bool:
serialized = json.dumps(value, sort_keys=True,
ensure_ascii=False, indent=2)
checksum = hashlib.md5(serialized.encode()).hexdigest()[:8]
if name not in self._snapshots:
self._snapshots[name] = serialized
print(f" 📸 스냅샷 저장: {name} [{checksum}]")
return True
if self._snapshots[name] == serialized:
print(f" ✅ 스냅샷 일치: {name} [{checksum}]")
return True
print(f" ❌ 스냅샷 불일치: {name}")
print(f" 기대: {self._snapshots[name][:50]}...")
print(f" 실제: {serialized[:50]}...")
return False
# 사용 예시
def generate_report(users):
return {
"total": len(users),
"names": sorted(u["name"] for u in users),
"avg_age": sum(u["age"] for u in users) / len(users),
}
snap = SnapshotTester()
users = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25},
]
report = generate_report(users)
snap.assert_match("user_report", report)
snap.assert_match("user_report", report) # 일치
# 변경 감지
report["total"] = 999
snap.assert_match("user_report", report) # 불일치!
# 실제 사용: pip install pytest-snapshot 또는 syrupy
# def test_report(snapshot):
# assert generate_report(users) == snapshot학습 팁
스냅샷 파일은 버전 관리에 포함하여 코드 리뷰 시 출력 변경을 확인하세요.
주의할 점
스냅샷을 무분별하게 업데이트(--snapshot-update)하면 의도하지 않은 변경이 승인될 수 있습니다. 항상 diff를 확인하세요.
자주 묻는 질문
스냅샷 테스트란 무엇인가요?
스냅샷 테스트로 복잡한 출력을 저장하고 변경 여부를 자동 감지합니다.
스냅샷 테스트 학습 시 주의할 점은 무엇인가요?
스냅샷을 무분별하게 업데이트( --snapshot-update )하면 의도하지 않은 변경이 승인될 수 있습니다. 항상 diff를 확인하세요.
Continue Learning
Python 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.