問題描述
我正在使用 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
這篇關于如何為 python 單元測試模擬 mongodb?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!