Fastapi

Chapter 2-5 테스트 스크립트 작성 가이드

Chansman 2025. 5. 23. 10:34

🧪 테스트 스크립트 작성 가이드

🧰 pytest-asyncio 설치 및 설정

📦 설치 명령어:

poetry add --group=dev pytest-asyncio==0.25.0

📄 pyproject.toml 설정:

[tool.pytest.ini_options]
asyncio_mode = "auto"
asyncio_default_fixture_loop_scope = "session"
  • pytest는 기본적으로 async def로 작성된 테스트를 실행하지 않음
  • pytest-asyncio 플러그인을 사용하면 비동기 테스트도 지원 가능
  • 지금은 사용하지 않더라도 미리 설정해두는 것이 좋음
  • async/await는 추후 강의에서 별도로 다룰 예정

⚙️ test.sh 생성 (리눅스/맥 유저용)

📄 test.sh 파일 내용:

#!/bin/bash
set -eo pipefail

COLOR_GREEN=`tput setaf 2`
COLOR_NC=`tput sgr0`  # No Color

echo "Starting black"
poetry run black .
echo "OK"

echo "Starting ruff"
poetry run ruff check --select I --fix
poetry run ruff check --fix
echo "OK"

echo "Starting mypy"
poetry run mypy .
echo "OK"

echo "Starting pytest with coverage"
poetry run coverage run -m pytest
poetry run coverage report -m
poetry run coverage html

echo "${COLOR_GREEN}All tests passed successfully!${COLOR_NC}"

📌 기능 요약:

  • 코드 포매팅, 린트, 타입체크, 테스트, 커버리지 보고까지 한번에 실행
  • 에러 발생 시 즉시 중단 (set -eo pipefail)
  • 모든 툴이 정상 작동하면 초록색 메시지 출력

⚙️ Windows의 WSL에선 #!/bin/bash로 명시하지 않으면 dash가 실행되기 때문에 깨진다.

Windows에서 만든 파일은 줄 끝이 CRLF라서 Linux 셸이 오류를 낼 수 있어!

# 오류 여부 확인
file test.sh

# 에러메세지
test.sh: ASCII text, with CRLF line terminators

# 설치
which dos2unix
sudo apt update
sudo apt install dos2unix

# 줄바꿈 변환
dos2unix test.sh

# 권한 부여및 실행
chmod +x test.sh
./test.sh

 

⚙️ 실행

# 실행 권한부여
chomd +x ./test.sh

# 실행
./test.sh

⚙️ test.ps1 생성 (윈도우 PowerShell 유저용)

📄 test.ps1 파일 내용:

poetry run black .
if(!$?) { throw }

poetry run ruff check --select I --fix
if(!$?) { throw }

poetry run ruff check --fix
if(!$?) { throw }

poetry run mypy .
if(!$?) { throw }

poetry run coverage run -m pytest .
if(!$?) { throw }

poetry run coverage report -m
poetry run coverage html
if(!$?) { throw }

Write-Host "Done" -ForegroundColor Green

📌 주의사항:

  • PowerShell 전용 (cmd, WSL 등에서는 작동 방식이 다름)
  • if(!$?) { throw } 로 각 단계의 실패 여부 체크
  • 성공 시 초록색 텍스트 출력

📚 참고: https://stackoverflow.com/questions/47032005/why-does-a-powershell-script-not-end-when-there-is-a-non-zero-exit-code-using-th


✅ Recap

  • ✅ pytest-asyncio를 통해 비동기 테스트도 대응 가능
  • ✅ test.sh, test.ps1을 사용해 전체 테스트 자동화
  • ✅ CI/CD 통합 전에도 로컬에서 모든 검사를 일괄 수행 가능

"테스트는 자동화될 때 비로소 진짜 테스트다."