問(wèn)題描述
我正在使用 Python 2.7 的 mock
模塊來(lái)模擬我的其他函數(shù)并使用
I am using mock
module for Python 2.7 to mock my other functions and using
unittest
用于編寫單元測(cè)試.
我想知道模擬 MongoDB 是否與使用模擬功能不同(mock.patch
一個(gè)被調(diào)用的函數(shù)?)或者我需要為此目的使用另一個(gè)不同的包?
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?
我認(rèn)為我不想運(yùn)行測(cè)試 mongodb 實(shí)例.我想要的只是一些速度數(shù)據(jù)并且能夠調(diào)用 pymongo
功能.我只是有點(diǎn)迷失在思考是否有一種方法可以為模塊(如 pymongo
)編寫模擬,或者任何可以通過(guò) mock
模塊實(shí)現(xiàn)的方法.
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.
如果您能提供一個(gè)示例或教程,非常感謝.
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)
為了測(cè)試這個(gè),我真的不希望測(cè)試 mongodb 啟動(dòng)并運(yùn)行!而且,我想我不想模擬 db.userssave 和 db.users.find 因?yàn)槲蚁M嬲軌驒z索我保存的數(shù)據(jù)并確保它在數(shù)據(jù)庫(kù)中.我認(rèn)為我需要為記憶中的每個(gè)模型創(chuàng)建一些 fixtures 并與它們一起使用.只是我需要一個(gè)外部工具來(lái)執(zhí)行此操作嗎?
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?
我正在考慮保留一些這樣的假數(shù)據(jù),只是不知道如何正確處理.
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 來(lái)模擬 mongodb.它基本上是一個(gè)帶有 pymongo 接口的內(nèi)存中 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
這篇關(guān)于如何為 python 單元測(cè)試模擬 mongodb?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!