如何创建一个模拟的mongo db对象来使用python测试我的软件?
我尝试了https://pytest-mock-resources.readthedocs.io/en/latest/mongo.html,但得到了错误。
首先,我尝试了下面的代码:
def insert_into_customer(mongodb_connection):
collection = mongodb_connection['customer']
to_insert = {"name": "John", "address": "Highway 37"}
collection.insert_one(to_insert)
from pytest_mock_resources import create_mongo_fixture
mongo = create_mongo_fixture()
def test_insert_into_customer(mongo):
insert_into_customer(mongo)
collection = mongo['customer']
returned = collection.find_one()
assert returned == {"name": "John", "address": "Highway 37"}
test_insert_into_customer(mongo)
我得到了下面的错误:
Traceback (most recent call last):
File "/home/ehasan-karbasian/Desktop/NationalEliteFoundation/serp_matcher/src/mock_mongo.py", line 19, in <module>
test_insert_into_customer(mongo)
File "/home/ehasan-karbasian/Desktop/NationalEliteFoundation/serp_matcher/src/mock_mongo.py", line 11, in test_insert_into_customer
insert_into_customer(mongo)
File "/home/ehasan-karbasian/Desktop/NationalEliteFoundation/serp_matcher/src/mock_mongo.py", line 2, in insert_into_customer
collection = mongodb_connection['customer']
TypeError: 'function' object is not subscriptable
然后我试了下代码:
def insert_into_customer(mongodb_connection):
collection = mongodb_connection['customer']
to_insert = {"name": "John", "address": "Highway 37"}
collection.insert_one(to_insert)
from pymongo import MongoClient
from pytest_mock_resources import create_mongo_fixture
mongo = create_mongo_fixture()
def test_create_custom_connection(mongo):
client = MongoClient(**mongo.pmr_credentials.as_mongo_kwargs())
db = client[mongo.config["database"]]
collection = db["customers"]
to_insert = [
{"name": "John"},
{"name": "Viola"},
]
collection.insert_many(to_insert)
result = collection.find().sort("name")
returned = [row for row in result]
assert returned == to_insert
test_create_custom_connection(mongo)
并得到错误:
Traceback (most recent call last):
File "/home/ehasan-karbasian/Desktop/NationalEliteFoundation/serp_matcher/src/mock_mongo.py", line 30, in <module>
test_create_custom_connection(mongo)
File "/home/ehasan-karbasian/Desktop/NationalEliteFoundation/serp_matcher/src/mock_mongo.py", line 14, in test_create_custom_connection
client = MongoClient(**mongo.pmr_credentials.as_mongo_kwargs())
AttributeError: 'function' object has no attribute 'pmr_credentials'
它看起来像mongo
是function
而不是MongoClient
。
如何使用pytest_mock_resources
库来模拟mongo?
有没有更好的库来模拟monodb,用pytest测试?
1条答案
按热度按时间9jyewag01#
这段代码的工作原理:
您可以同时定义所需的客户端、数据库和集合。