Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock MongoClient for python unit test?

I have following piece of code to UT, which makes me in trouble:

  def initialize():
    try :
        self.client = MongoClient("127.0.0.1", 27017)
        self.conn = self.client["DB_NAME"]
    except Exception:
        print "Except in initialize!"
        return False
    return True

I write following test case to cover the above function, hope to get return value "True":

def mock_mongodb_mongoclient_init(self, para1, para2):
    pass

def mock_mongodb_mongoclient_getitem(self, name):
    return {"DB_NAME":"Something"}

def test_mongodb_initialize_true(self):
    self.patcher1 = patch('pymongo.MongoClient.__init__', new=self.mock_mongodb_mongoclient_init)
    self.patcher2 = patch('pymongo.MongoClient.__getitem__', new=self.mock_mongodb_mongoclient_getitem)
    self.patcher1.start()
    self.patcher2.start()
    self.assertEqual(initialize(), True)
    self.patcher1.stop()
    self.patcher2.stop()

But this never works! It always report "Exception in initialize!"! and return "False".

How could I UT this MongoClient and makes the function return "True"?

like image 631
user992570 Avatar asked Mar 28 '26 20:03

user992570


1 Answers

Since you are unit testing and not trying to actually connect to Mongo in any way, I think you should just care that the client API has been called. So I would suggest the following -

from unittest import mock
@mock.patch("pymongo.MongoClient")
def test_mongodb_initialize(self, mock_pymongo):
    MyMongo.initialize()
    self.assertTrue(mock_pymongo.called)

(Forgive me if my syntax is off, I use pytest rather than unittest.)

like image 159
Pedro Jiménez Avatar answered Mar 30 '26 11:03

Pedro Jiménez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!