123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- from fastapi import FastAPI
- from starlette.testclient import TestClient
- from fastapi import APIRouter, HTTPException
- from pydantic import BaseModel
- class Item(BaseModel):
- id: int
- name: str
- app = FastAPI()
- res = [
- {"id": 1, "name": "jack"},
- {"id": 2, "name": "mark"},
- {"id": 3, "name": "tom"},
- {"id": 4, "name": "sery"}
- ]
- @app.get("/item/res")
- async def get_res():
- return res
- @app.get("/item/res/{res_id}")
- async def get_res_id(res_id:int):
- for data in res:
- if data["id"] == res_id:
- return data
- @app.post("/item/res")
- async def create_res(item:Item):
- res.append(item.dict())
- return res
- @app.put("/item/res/{res_id}")
- async def update_res(res_id:int,item:Item):
- for data in res:
- print(data["id"])
- print(res_id)
- if data["id"] == res_id:
- res.remove(data)
- data = item.dict()
- res.append(data)
- return {"status":True}
- else:
- return HTTPException(status_code=404, detail="id:{} not found.".format(res_id))
- @app.delete("/item/res/{res_id}")
- async def delete_res(res_id:int):
- for data in res:
- if data["id"] == res_id:
- res.remove(data)
- return {"status":True}
- client = TestClient(app)
- def test_read_main():
- response = client.get("/item/res")
- assert response.status_code == 200
- assert response.json() == res
- def test_get_res_id():
- response = client.get(f"/item/res/1")
- assert response.status_code == 200
- assert response.json() == {"id": 1, "name": "jack"}
|