首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用FastAPI (电机)实现FastAPI测试

如何用FastAPI (电机)实现FastAPI测试
EN

Stack Overflow用户
提问于 2022-04-26 07:02:20
回答 1查看 2.8K关注 0票数 3

我想为我的FastAPI端点编写测试

我的代码示例:

代码语言:javascript
复制
from fastapi import FastAPI
from fastapi.testclient import TestClient

app = FastAPI()

@app.get("/todos")
async def get_todo_by_title(title: str,current_user: User = Depends(get_current_user))
    document = await collection.find_one({"title": title})
    return document

client = TestClient(app)

def test_get_todo_by_title():
    response = client.get("/todos")
    assert response.status_code == 200

测试我的端点的最好方法是什么?

我想使用假数据库进行测试,比如json文件。

代码语言:javascript
复制
db = {
todos: [...]
}
EN

回答 1

Stack Overflow用户

发布于 2022-07-14 16:17:27

使用JSON文件中的假数据并不是最好的选择。相反,您可以使用测试DB (基于运行应用程序的env )或任何其他DB (dev、stg、..etc),并在运行所有单元测试后删除测试数据。

下面是如何简单地将后一种方法应用于FastAPI;

  • 假设您有3个简单表(或集合) X、Y和Z
  • MongoDB is DB服务
  • PyTest是测试引擎

conftest.py

代码语言:javascript
复制
from pytest import fixture
from starlette.config import environ
from starlette.testclient import TestClient
from config.db_connection import database, X_collection, Y_collection, Z_collection


@fixture(scope="session")
def test_X():
    return {
        "_id": "10",
        "name": "test",
        "description": "test",
        "type": "single value",
        "crt_at": "2022-06-27T12:23:15.143Z",
        "upd_at": "2022-06-27T12:23:15.143Z"
    }

//test_Y and test_Z fixtures should be like test_X


@fixture(scope="session", autouse=True)
def test_client(test_X, test_Y, test_Z):
    import main
    application = main.app
    with TestClient(application) as test_client:
        yield test_client

    db = database
    //Here, delete any objects you have created for your tests
    db[X_collection].delete_one({"_id": test_X["_id"]})
    db[Y_collection].delete_one({"_id": test_Y["_id"]})
    db[Z_collection].delete_one({"_id": test_Z["_id"]})


environ['TESTING'] = 'TRUE'

单元测试应该类似于下面的示例。

test_X_endpoints.py

代码语言:javascript
复制
def test_create_X(test_client, test_X):
    response = test_client.post("/create_X_URI/", json=test_X)
    assert response.status_code == 201
    //Add assertions as needed

def test_list_X(test_client):
    response = test_client.get("/list_X_objects_URI/?page=1&size=1")
    assert response.status_code == 200
    //Add assertions as needed
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72009629

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档