mongodb - 如何用MongoDB(Motor)实现FastAPI的pytest

标签 mongodb unit-testing pytest fastapi mongomock

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

我的代码示例:

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文件

db = {
todos: [...]
}

最佳答案

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

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

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

conftest.py

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

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

关于mongodb - 如何用MongoDB(Motor)实现FastAPI的pytest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72009629/

相关文章:

javascript - ngresource 无法使用基于 oData 的 Rest Controller 正确过滤

mongodb - 如何查找集合中每个ID的最新版本文档?

javascript - 如何在 jest 测试文件中需要 jQuery 插件?

java - 为什么这不起作用 - 使用 Junit 的参数化数据对同步方法进行单元测试?

ruby-on-rails - 如何在单元测试中重新加载模型类

python - 如何使 py.test 或 nose 在所有 python 文件中查找测试?

java - SolrIndexerJob : runtime error

java - Spring : Can a class be both @Document and @Table

python - 我们可以在 pytest 的 setup_module() 或 setup_class 中打印命令行参数吗?

python - 在 pytest 中运行单个文件,该文件是 PEP 420 隐式命名空间包中的模块