FastAPI接口pytest测试返回404 Not Found问题求助
问题原因与解决方案
核心原因
你代码里没有为根路径/定义任何接口处理逻辑,FastAPI不会自动生成默认的根路由,所以当测试请求/时,服务找不到对应的处理函数,返回404错误。
修正后的代码
from fastapi import FastAPI from fastapi.testclient import TestClient app = FastAPI() # 新增根路径的接口处理函数 @app.get("/") def read_main(): return {"message": "Hello World"} client = TestClient(app) def test_read_main(): response = client.get("/") assert response.status_code == 200 assert response.json() == {"message": "Hello World"}
说明
添加@app.get("/")装饰器和对应的read_main函数后,FastAPI会将根路径/绑定到这个处理函数上,测试请求时就能正确返回200状态码和预期的JSON数据,测试即可通过。
内容的提问来源于stack exchange,提问作者user1689987
相关产品推荐
相关产品推荐

