PYTHON · 비동기
비동기 테스트
pytest-asyncio를 사용하여 비동기 코드를 테스트하는 방법입니다.
비동기고급pytest-asyncio비동기 테스트testasync
핵심 설명
pytest-asyncio를 사용하여 비동기 코드를 테스트하는 방법입니다.
Python code
import asyncio
# 테스트할 비동기 코드
async def fetch_user(user_id: int) -> dict:
await asyncio.sleep(0.1) # DB 조회 시뮬레이션
if user_id <= 0:
raise ValueError("유효하지 않은 ID")
return {"id": user_id, "name": f"User-{user_id}"}
async def get_users(ids: list[int]) -> list[dict]:
tasks = [fetch_user(uid) for uid in ids]
return await asyncio.gather(*tasks)
# pytest-asyncio 패턴 시뮬레이션
async def test_fetch_user():
user = await fetch_user(1)
assert user["id"] == 1
assert user["name"] == "User-1"
print("test_fetch_user 통과")
async def test_fetch_user_invalid():
try:
await fetch_user(-1)
assert False, "예외가 발생해야 함"
except ValueError as e:
assert "유효하지 않은 ID" in str(e)
print("test_fetch_user_invalid 통과")
async def test_get_users():
users = await get_users([1, 2, 3])
assert len(users) == 3
assert all(u["name"].startswith("User-") for u in users)
print("test_get_users 통과")
async def run_tests():
await test_fetch_user()
await test_fetch_user_invalid()
await test_get_users()
print("모든 비동기 테스트 통과!")
asyncio.run(run_tests())학습 팁
pip install pytest-asyncio 후 테스트 함수에 @pytest.mark.asyncio를 붙이면 자동으로 이벤트 루프를 관리합니다.
주의할 점
비동기 테스트에서 asyncio.run()을 직접 호출하면 이벤트 루프 충돌이 발생할 수 있습니다. pytest-asyncio를 사용하세요.
자주 묻는 질문
비동기 테스트란 무엇인가요?
pytest-asyncio 를 사용하여 비동기 코드를 테스트하는 방법입니다.
비동기 테스트 학습 시 주의할 점은 무엇인가요?
비동기 테스트에서 asyncio.run() 을 직접 호출하면 이벤트 루프 충돌이 발생할 수 있습니다. pytest-asyncio를 사용하세요.