我正在尝试使用 pytest 来测试 FastAPI 方法是否存在。为什么 pytest 代码返回 404 错误?
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
client = TestClient(app)
def test_read_main():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"message": "Hello World"}
错误:
E assert 404 == 200
E + where 404 = <Response [404 Not Found]>.status_code
这是因为我需要在 TestClient 中导入并重用相同的应用程序变量 FastAPI 对象。这是工作代码:
from fastapi import FastAPI
from fastapi.testclient import TestClient
from .main import app
app = FastAPI()
client = TestClient(app)
def test_read_main():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"message": "Hello World"}