test_items.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. from fastapi import FastAPI
  2. from starlette.testclient import TestClient
  3. from fastapi import APIRouter, HTTPException
  4. from pydantic import BaseModel
  5. class Item(BaseModel):
  6. id: int
  7. name: str
  8. app = FastAPI()
  9. res = [
  10. {"id": 1, "name": "jack"},
  11. {"id": 2, "name": "mark"},
  12. {"id": 3, "name": "tom"},
  13. {"id": 4, "name": "sery"}
  14. ]
  15. @app.get("/item/res")
  16. async def get_res():
  17. return res
  18. @app.get("/item/res/{res_id}")
  19. async def get_res_id(res_id:int):
  20. for data in res:
  21. if data["id"] == res_id:
  22. return data
  23. @app.post("/item/res")
  24. async def create_res(item:Item):
  25. res.append(item.dict())
  26. return res
  27. @app.put("/item/res/{res_id}")
  28. async def update_res(res_id:int,item:Item):
  29. for data in res:
  30. print(data["id"])
  31. print(res_id)
  32. if data["id"] == res_id:
  33. res.remove(data)
  34. data = item.dict()
  35. res.append(data)
  36. return {"status":True}
  37. else:
  38. return HTTPException(status_code=404, detail="id:{} not found.".format(res_id))
  39. @app.delete("/item/res/{res_id}")
  40. async def delete_res(res_id:int):
  41. for data in res:
  42. if data["id"] == res_id:
  43. res.remove(data)
  44. return {"status":True}
  45. client = TestClient(app)
  46. def test_read_main():
  47. response = client.get("/item/res")
  48. assert response.status_code == 200
  49. assert response.json() == res
  50. def test_get_res_id():
  51. response = client.get(f"/item/res/1")
  52. assert response.status_code == 200
  53. assert response.json() == {"id": 1, "name": "jack"}