Use mock MongoDB server for unit test

匿名 (未验证) 提交于 2019-12-03 01:07:01

问题:

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!

回答1:

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.



回答2:

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.



回答3:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!