简体   繁体   English

使用模拟MongoDB服务器进行单元测试

[英]Use mock MongoDB server for unit test

I have to implement nosetests for Python code using a MongoDB store. 我必须使用MongoDB存储为Python代码实现nosetests。 Is there any python library which permits me initializing a mock in-memory MongoDB server? 是否有任何python库允许我初始化一个模拟内存中的MongoDB服务器?

I am using continuous integration. 我正在使用持续集成。 So, I want my tests to be independent of any MongoDB running server. 所以,我希望我的测试独立于任何运行MongoDB的服务器。 Is there a way to mock mongoDM Server in memory to test the code independently of connecting to a Mongo server? 有没有办法在内存中模拟mongoDM Server来独立于连接到Mongo服务器来测试代码?

Thanks in advance! 提前致谢!

You could try: https://github.com/vmalloc/mongomock , which aims to be a small library for mocking pymongo collection objects for testing purposes. 您可以尝试: https//github.com/vmalloc/mongomock ,其目的是成为一个小型库,用于模拟pymongo集合对象以进行测试。

However, I'm not sure that the cost of just running mongodb would be prohibitive compared to ensuring some mocking library is feature complete. 但是,与确保某些模拟库功能完整相比,我不确定运行mongodb的成本是否会过高。

I don't know about Python, but I had a similar concern with C#. 我不知道Python,但我对C#有类似的担忧。 I decided to just run a real instance of Mongo on my workstation pointed at an empty directory. 我决定在我的工作站上运行一个真实的Mongo实例,指向一个空目录。 It's not great because the code isn't isolated but it's fast and easy. 这并不好,因为代码不是孤立的,而是快速而简单的。

Only the data access layer actually calls Mongo during the test. 在测试期间,只有数据访问层实际上调用了Mongo。 The rest can rely on the mocks of the data access layer. 其余的可以依赖于数据访问层的模拟。 I didn't feel like faking Mongo was worth the effort when really I want to verify the interaction with Mongo is correct anyway. 我不觉得伪装Mongo值得付出努力,我真的想验证与Mongo的交互是否正确无论如何。

You can use Ming which has an in-memory mongo db pymongo connection replacement. 您可以使用其中有一个内存蒙戈DB pymongo连接更换。

import ming
mg = ming.create_datastore('mim://')
mg.conn # is the connection
mg.db # is a db with no name
mg.conn.somedb.somecol
# >> mim.Collection(mim.Database(somedb), somecol)
col = mg.conn.somedb.somecol
col.insert({'a': 1})
# >> ObjectId('5216ac3fe0323a1218f4e9aa')
col.find().count()
# >> 1

I am also using pymongo and MockupDB is working very well for my purpose (integration tests). 我也在使用pymongoMockupDB非常适合我的目的(集成测试)。

To use it is as simple as: 使用它很简单:

from mockupdb import *
server = MockupDB()
port = server.run()
from pymongo import MongoClient
client = MongoClient(server.uri)
import module_i_want_to_patch
module_i_want_to_patch.client = client

You can check the official tutorial for MockupDB here 你可以在这里查看MockupDB的官方教程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM