FastAPI/테스트 코드

GET 단일 조회 API

hyunai 2026. 7. 7. 17:28
# main.py
@app.get("/todos/{todo_id}", status_code=200)
def get_todo_handler(
        todo_id: int,
        session: Session = Depends(get_db),
) -> ToDoSchema:
    todo: ToDo | None = get_todo_by_todo_id(session=session, todo_id=todo_id)
    if todo:
        return ToDoSchema.model_validate(todo)
    # 만약 todo가 없다면
    raise HTTPException(status_code=404, detail="ToDo Not Found")
    
# test_main.py
def test_get_todo(client, mocker):
    mocker.patch(
        "main.get_todo_by_todo_id",
        return_value=ToDo(id=1, contents="todo", is_done=True),
    )
    response = client.get("/todos/1")
    assert response.status_code == 200
    assert response.json() == {"id":1, "contents":"todo", "is_done": True}
  • mocker, client fixture를 사용하기 위해 인자로 추가
  • mocking을 처리하여 ToDo 객체 생성

에러 상황일 때 테스트

def test_get_todo(client, mocker):
    # 200
    mocker.patch(
        "main.get_todo_by_todo_id",
        return_value=ToDo(id=1, contents="todo", is_done=True),
    )
    response = client.get("/todos/1")
    assert response.status_code == 200
    assert response.json() == {"id":1, "contents":"todo", "is_done": True}

    # 404
    mocker.patch(
        "main.get_todo_by_todo_id",
        return_value=None,
    )
    response = client.get("/todos/1")
    assert response.status_code == 404
    assert response.json() == {"detail": "ToDo Not Found"}
  • 위의 main.py를 보면 raise 문에 에러가 났을 때 상황도 있다.
  • return_value 값을 None값을 주고 status_code 값을 404로 바꾸고 에러가 났을 때 key와 value 값으로 바꿔준다.

테스트를 하나씩 해보기

pytest tests/test_main.py::test_get_todo

pytest 뒤에 파일 이름을 적고 :: 뒤에 함수 이름을 적게 되면 하나씩 테스트를 해볼 수 있다.

(todos) PS C:\Users\user\Desktop\hyun\fastpai\todos\src> pytest
=============================================================== test session starts ===============================================================
platform win32 -- Python 3.14.6, pytest-9.1.1, pluggy-1.6.0
rootdir: C:\Users\user\Desktop\hyun\fastpai\todos\src
plugins: anyio-4.13.0, mock-3.15.1
collected 3 items                                                                                                                                  

tests\test_main.py ...                                                                                                                       [100%]

================================================================ warnings summary =================================================================
..\Lib\site-packages\fastapi\testclient.py:1
  C:\Users\user\Desktop\hyun\fastpai\todos\Lib\site-packages\fastapi\testclient.py:1: StarletteDeprecationWarning: Using `httpx` with `starlette.testclient` is deprecated; install `httpx2` instead.
    from starlette.testclient import TestClient as TestClient  # noqa

schema\response.py:6
  C:\Users\user\Desktop\hyun\fastpai\todos\src\schema\response.py:6: PydanticDeprecatedSince20: Support for class-based `config` is deprecated, use ConfigDict instead. Deprecated in Pydantic V2.0 to be removed in V3.0. See Pydantic V2 Migration Guide at https://errors.pydantic.dev/2.13/migration/
    class ToDoSchema(BaseModel):

-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
========================================================== 3 passed, 2 warnings in 0.04s =========================================================

그럼 이와 같이 테스트가 정상 동작한다.

'FastAPI > 테스트 코드' 카테고리의 다른 글

POST API  (0) 2026.07.10
PyTest Fixture  (0) 2026.07.07
PyTest Mocking  (0) 2026.07.07
GET 전체 조회 API  (0) 2026.07.06
PyTest란?  (0) 2026.07.01