[FastAPI] FastAPI 에서 pytest를 통한 서버 테스트 코드 작성

이홍준·2023년 9월 6일
1

FastAPI

목록 보기
2/4

FastAPI를 통해서 API를 개발하는데 있어서 postman이나 swagger를 통해 테스트를 직접 수동으로 하는 것이 작업량이 많이 질 수록 테스트 수도 많아지기 때문에 불편함을 느꼈다. 그래서 이번 개발하는데 있어서 통합테스트 코드를 작성함으로써 개발시간에 좀 더 집중할 수 있게끔 하고자 파이썬에서 사용하는 테스트툴에 대해서 공부 해보도록 한다.

기본세팅

필요 모듈들 설치

$ pip install pytest
$ pip install pytest-asyncio
$ pip install httpx
  • pytest: Spring의 JUnit과 같이 파이썬에서 가장 대중적인 테스팅 프레임워크
  • pytest-asyncio: 비동기 코드를 테스트하기 위한 모듈
  • httpx: 최신 python 비동기 기능을 지원하는 http 클라이언트 라이브러리, requests 라이브러리와 유사한 API를 제공하지만, 동기/비동기를 모두 지원함 Spring에서는 RestTemplate, WebClient와 유사

폴더 구성

기본적으로 실제 app 폴더와 test폴더로 구성된다. 폴더구조는 일관성을 위해 둘 다 똑같이 세팅하였다.

소스코드

  • app/routers/post.py
    # app/routers/post.py
    from fastapi import APIRouter
    
    post_router = APIRouter()
    
    @post_router.get("")
    def get_items():
        return [{"name": "item1"}, {"name": "item2"}]
    
    @post_router.get("/{item_id}")
    def get_item(item_id: int):
        return {"name": "item1", "id": item_id}
  • test/routers/post_test.py
    # test/routers/post_test.py
    from fastapi.testclient import TestClient
    from app.main import create_app
    
    app = create_app()
    client = TestClient(app)
    
    def test_get_items():
        response = client.get("/posts")
        assert response.status_code == 200
        assert response.json() == [{"name": "item1"}, {"name": "item2"}]
  • app/main.py
    # app/main.py
    from fastapi import FastAPI
    import uvicorn
    from routers.post import post_router
    
    def create_app() -> FastAPI:
        """ app 변수 생성 및 초기값 설정 """
    
        
        _app = FastAPI(
            title="fastapi-pytest",
            description="fastapi 테스트 코드 연습장",
            version="1.0.0",
        )
        _app.include_router(post_router, prefix="/posts", tags=["게시판 - posts"])
        return _app
    
    app = create_app()
    
    if __name__ == "__main__":
        uvicorn.run("main:app", host='0.0.0.0', port=8000, reload=True)

Test 실행 시 폴더 경로 설정

pytest를 실행 시 from app.main import create_app 부분은 test폴더 내에 있는 상대 경로를 나타내기 때문에 경로를 찾지 못한다. 그러므로 미리 명시를 해줘야 한다. (VScode 기준)
루트 폴더에 pytest.ini 을 생성해 주고 해당 스크립트를 넣어준다.

[pytest]
pythonpath = app

테스트 실행

해당 명령어를 실행해보면 잘 실행되는 것을 볼 수 있다.

$ pytest .\test\routers\post_test.py


References

profile
I'm a web developer.

0개의 댓글

관련 채용 정보