Python Unit Testing | FastAPI with Pytest Tutorial
깃허브 : https://github.com/codingwithroby/Youtube/blob/main/2023/fastapi-testing/
https://www.youtube.com/watch?v=jM-zWp8dNQA
FastAPI unit test
1. 가상환경 생성, 진입, FastAPI 설치
python3 -m venv env
source env/bin/activate
pip install --upgrade pip
에러시 경로 포함 시도:
C:\Users\sangmun\AppData\Local\Programs\Python\Python39\python.exe -m pip install --upgrade pip
pip install fastapi uvicorn
pip install pytest
pip install httpx
[참고] requirements.txt
fastapi
uvicorn
httpx
pytest
2. main.py ------------------------------------------------
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Optional
app = FastAPI()
class Todo(BaseModel):
name: str
completed: bool
# Mock database
todos = {}
@app.get("/", response_model=List[Todo])
async def read_todos():
return list(todos.values())
@app.post("/", response_model=Todo)
async def create_todo(todo: Todo):
todo_id = str(len(todos) + 1)
todos[todo_id] = todo
return todo
@app.get("/{todo_id}", response_model=Todo)
async def read_todo(todo_id: str):
todo = todos.get(todo_id)
if todo is None:
raise HTTPException(status_code=404, detail="Todo not found")
return todo
@app.put("/{todo_id}", response_model=Todo)
async def update_todo(todo_id: str, updated_todo: Todo):
todo = todos.get(todo_id)
if todo is None:
raise HTTPException(status_code=404, detail="Todo not found")
todos[todo_id] = updated_todo
return updated_todo
@app.delete("/{todo_id}", response_model=Todo)
async def delete_todo(todo_id: str):
todo = todos.get(todo_id)
if todo is None:
raise HTTPException(status_code=404, detail="Todo not found")
del todos[todo_id]
return todo
3. test_main.py -------------------------------------------------
from fastapi.testclient import TestClient
from .main import app, todos
client = TestClient(app)
def setup_function():
todos.clear()
def test_read_todos():
response = client.get("/")
assert response.status_code == 200
assert response.json() == []
def test_create_todo():
response = client.post("/", json={"name": "Buy groceries", "completed": False})
assert response.status_code == 200
assert response.json() == {"name": "Buy groceries", "completed": False}
def test_read_todo():
client.post("/", json={"name": "Buy groceries", "completed": False})
response = client.get("/1")
assert response.status_code == 200
assert response.json() == {"name": "Buy groceries", "completed": False}
def test_update_todo():
client.post("/", json={"name": "Buy groceries", "completed": False})
response = client.put("/1", json={"name": "Buy vegetables", "completed": True})
assert response.status_code == 200
assert response.json() == {"name": "Buy vegetables", "completed": True}
def test_delete_todo():
client.post("/", json={"name": "Buy groceries", "completed": False})
response = client.delete("/1")
assert response.status_code == 200
assert response.json() == {"name": "Buy groceries", "completed": False}
'FastAPI' 카테고리의 다른 글
백엔드씬에 긴장감을 주는 FastAPI 프레임워크 (0) | 2024.05.02 |
---|---|
파이썬 FastAPI + JAVA (Jpype) 예제 (1) | 2023.11.24 |
FastAPI, 인증 API (Authentication APIs) (0) | 2023.11.10 |
How to Use FastAPI: A Detailed Python Tutorial (1) | 2023.10.23 |
FastAPI, NGINX 사용 시 Client IP 확인 (0) | 2023.10.18 |