如何为 python 单元测试模拟 mongodb?
问题描述
我正在使用 Python 2.7 的 mock
模块来模拟我的其他函数并使用
I am using mock
module for Python 2.7 to mock my other functions and using
unittest
用于编写单元测试.
我想知道模拟 MongoDB 是否与使用模拟功能不同(mock.patch
一个被调用的函数?)或者我需要为此目的使用另一个不同的包?
I am wondering if mocking the MongoDB is different than using mock functionality (mock.patch
a function that is being called?) Or I need to use another different package for that purpose?
我认为我不想运行测试 mongodb 实例.我想要的只是一些速度数据并且能够调用 pymongo
功能.我只是有点迷失在思考是否有一种方法可以为模块(如 pymongo
)编写模拟,或者任何可以通过 mock
模块实现的方法.
I do not think I want to have a test mongodb instance running. All I want is some tempo data and being able to call pymongo
functionality. I am just a bit lost in thinking of is there a way to write a mock for a module (like pymongo
), or anything is achievable by mock
module.
如果您能提供一个示例或教程,非常感谢.
So appreciate if you could provide an example or tutorial on this.
from pymongo import MongoClient
monog_url = 'mongodb://localhost:27017'
client = MongoClient(monog_url)
db = client.db
class Dao(object):
def __init__(self):
pass
def save(self, user):
db_doc = {
'name': user.name,
'email': user.email
}
db.users.save(db_doc)
def getbyname(self, user):
db_doc = {
'name': user.name,
}
return db.users.find(db_doc)
为了测试这个,我真的不希望测试 mongodb 启动并运行!而且,我想我不想模拟 db.userssave 和 db.users.find 因为我希望真正能够检索我保存的数据并确保它在数据库中.我认为我需要为记忆中的每个模型创建一些 fixtures 并与它们一起使用.只是我需要一个外部工具来执行此操作吗?
To test this, I do not really want a test mongodb up and running! But also, I think I do not want to mock db.userssave and db.users.find because I want to actually be able to retrieve the data that I saved and make sure it is in the db. I think I need to create some fixtures per models that are in my memory and work with them. Just do I need an external tool to do so?
我正在考虑保留一些这样的假数据,只是不知道如何正确处理.
I am thinking of keeping some fake data like this, just do not know how to properly deal with it.
users = {
{'name' : 'Kelly', 'email' : 'kelly@gmail.com'},
{'name': 'Sam', 'email': 'sam@gmail.com'}
}
解决方案
我推荐使用 mongomock 来模拟 mongodb.它基本上是一个带有 pymongo 接口的内存中 mongodb,专门为此目的而制作.
I recommend using mongomock for mocking mongodb. It's basically an in-memory mongodb with pymongo interface and made specifically for this purpose.
https://github.com/mongomock/mongomock
相关文章