导入TestClient. 通过传入你的FastAPI应用创建一个TestClient。 创建名字以test_开头的函数(这是标准的pytest约定)。 像使用httpx那样使用TestClient对象。 为你需要检查的地方用标准的Python表达式写个简单的assert语句(重申,标准的pytest)。 Python 3.8+ fromfastapiimportFastAPIfromfastapi.testclientimportTestClientapp=...
client = TestClient(app) 这样,我们就创建了一个TestClient实例client,并将我们的FastAPI应用程序app传递给它。 发送HTTP请求 TestClient提供了各种方法来发送不同类型的HTTP请求,包括get()、post()、put()、delete()等。你可以使用这些方法来测试API的不同端点和功能。 以下是一个使用TestClient发送GET请求的示例:...
assertresponse.status_code==400assertresponse.json()=={"detail":"Invalid X-Token header"}deftest_create_existing_item():response=client.post("/items/",headers={"X-Token":"coneofsilence"},json={"id":"foo","title":"The Foo ID Stealers","description":"There goes my stealer",},)assert...
首先,你需要安装一些必要的测试工具,比如使用pytest来进行测试,用httpx来发送HTTP请求,并且用fastapi.testclient来测试FastAPI应用。 pip install pytest httpx 2. 创建项目结构: 这里有一个基本的结构供你的FastAPI项目使用(FastAPI是一个现代的Web框架): my_project/ ├── app/ │ ├── __init__.py │ ...
POST http://localhost:8000/items/?query_param=test Content-Type: application/json { "name": "example", "price": 9.99 } 在上述示例中,查询参数query_param的值为test,POST请求的正文中提供了一个JSON对象作为数据。 FastAPI应用程序将使用POST请求中的数据创建一个Item对象,并将查询参数query_param作为函数...
9. 使用Starlette的TestClient进行测试 FastAPI支持使用Starlette的TestClient编写简洁的测试用例。from...
fromfastapiimportFastAPIapp=FastAPI() @app.post("/items/",status_code=201) asyncdefcreate_item(name:str): return{"name":name} status_code也可以是IntEnum,比如Python的http.HTTPStatus。 常见响应状态码: 100以上,信息;很少直接使用; 200以上,成功;200是OK,201是Created,204是No Content; ...
fromfastapi.testclient import TestClientfrom. import crudfrom.main import appdef test_post_items(db):client = TestClient(app)client.post("/items/", json={"title":"Item 1"})client.post("/items/", json={"title":"Item 2"})client.post("/items/", json={"title":"Item 3"})items =...
client=TestClient(app) deftest_read_main(): response=client.get(/) assertresponse.status_code==200 assertresponse.json()=={message:HelloWorld} deftest_create_item(): response=client.post( /items/, json={name:Foo,description:Thepretender,price:42.0}, ) assertresponse.status_code==200 assert...
from fastapi.testclient import TestClient def test_myroute(): client = TestClient(api) response = client.post("/myroute/", json={"a": "dog", "b": "cat"}) assert response.status_code == 200 单元测试因HTTP 422不可处理实体而失败。