How to Mock a mongodb

Jean-Michel Pichavant jeanmichel at sequans.com
Mon Feb 9 08:56:35 EST 2015


----- Original Message -----
> From: "Xavier Pegenaute" <xpegenaute at poblenousensefils.net>
> To: python-list at python.org
> Sent: Saturday, 7 February, 2015 11:09:10 PM
> Subject: How to Mock a mongodb
> 
> Dear,
> 
> I am trying to mock the use of a mongo db and I am having some
> trouble.
> Appears that I am not able to return a desired value from
> mongo.find().count(). I made a proof of concept to try to reduce
> complexity of the real problem.
> 
> You can find the code which is going to be tested in [1], and the
> code
> of the test case in [2].
> 
> Do you know exactly wat's wrong with it?, or may you point me to some
> direction?
> 
> Thanks,
> Xavi

You've mocked the pymongo.cursor but since you've mocked the entire mongo client, this mocked client will never return a pymongo.cursor, it will return only mock objects.

What you can do is mock the entire chain call of you mocked client:


from mock import patch
from mmongo import MongoHelper

class TestMongoHelper(object):

  @patch("mmongo.pymongo")
  def test_count_data(self, fake_mongo_client):
    mhelper = MongoHelper()

    # mock self.db[MongoHelper.db_name][MongoHelper.coll_name].find().count()
    fake_mongo_client.__getitem__.return_value.__getitem__.return_value.find.return_value.count.return_value = 5


JM


-- IMPORTANT NOTICE: 

The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you.


More information about the Python-list mailing list