如何模拟mongodb for python unittests? [英] How to mock mongodb for python unittests?

查看:87
本文介绍了如何模拟mongodb for python unittests?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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,因为我希望实际上能够检索我保存的数据并确保它在db中.我想我需要为记忆中的每个模型创建一些夹具并与它们一起使用.我是否需要外部工具来做到这一点?

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

这篇关于如何模拟mongodb for python unittests?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆