简体   繁体   中英

Use mock MongoDB server for unit test

I have to implement nosetests for Python code using a MongoDB store. Is there any python library which permits me initializing a mock in-memory MongoDB server?

I am using continuous integration. So, I want my tests to be independent of any MongoDB running server. Is there a way to mock mongoDM Server in memory to test the code independently of connecting to a Mongo server?

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.

However, I'm not sure that the cost of just running mongodb would be prohibitive compared to ensuring some mocking library is feature complete.

I don't know about Python, but I had a similar concern with C#. I decided to just run a real instance of Mongo on my workstation pointed at an empty directory. 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. 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.

You can use Ming which has an in-memory mongo db pymongo connection replacement.

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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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