我有连接到 MongoDB 客户端的代码,我正在尝试对其进行测试。为了测试,我不想连接到实际的客户端,所以我试图找出制作一个用于测试目的的假客户端。代码的基本流程是我在某处有一个函数来创建一个pymongo客户端,然后查询它并制作一个在其他地方使用的字典。
我想使用 pytest 编写一些测试来测试将调用get_stuff. 我的问题是get_stuff调用mongo()实际上是连接到数据库的原因。我试图只是使用pytest.fixture(autouse=True)和mongomock.MongoClient()替换mongo().
但这并不能取代mongo_stuff.mongo(). 有什么方法可以告诉 pytest 替换一个函数,以便fixture调用我的函数而不是实际函数?我认为使fixture我的测试mongo()在命名空间中的优先级高于实际模块中的函数。
这是我的示例的示例文件结构:
.
??? project
? ??? __init__.py
? ??? mongo_stuff
? ? ??? __init__.py
? ? ??? mongo_stuff.py
? ??? working_class
? ??? __init__.py
? ??? somewhere_else.py
??? testing
??? __init__.py
??? test_stuff.py
Run Code Online (Sandbox Code Playgroud)
mongo_stuff.py
import pymongo
def mongo():
return pymongo.MongoClient(connection_params)
def get_stuff():
db = mongo() # Makes …Run Code Online (Sandbox Code Playgroud) 在单元测试期间,我打电话给:
self.connection = connect(db="testdb", host="mongomock://localhost")
self.connection.drop_database("testdb")
Run Code Online (Sandbox Code Playgroud)
在两次测试之间,但是数据仍然存在。是否有已知的解决方法?
我在$lookup里面有一个聚合查询:
pipeline = [{
'$match': {
'_id': ObjectId(layout_id)
}
}, {
'$lookup': {
'from': 'units',
'localField': 'unit_id',
'foreignField': '_id',
'as': 'layout_unit'
}
}, {
'$replaceRoot': {
'newRoot': {
'$mergeObjects': [{
'$arrayElemAt': ["$layout_unit", 0]
}]
}
}
}, {
'$project': {
'layout_unit': 0
}
}, {
'$lookup': {
'from': 'users',
'localField': 'user_id',
'foreignField': '_id',
'as': 'unit_user'
}
}, {
'$unwind': '$unit_user'
}]
Run Code Online (Sandbox Code Playgroud)
我想使用mongomock. 这里的问题是,从 3.9.0 版本开始,它不支持$lookup聚合。
NotImplementedError: Although '$lookup' is a valid operator for the …
我想为我的 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
Run Code Online (Sandbox Code Playgroud)
测试我的端点的最佳方法是什么?
我想使用假数据库进行测试,例如 json 文件
db = {
todos: [...]
}
Run Code Online (Sandbox Code Playgroud) mongomock ×4
mongodb ×3
python ×3
pytest ×2
unit-testing ×2
fastapi ×1
fixtures ×1
mongoengine ×1
pymongo ×1