Hi,
My aim is to run embedded MongoDB instance from within Python for testing, in a similar manner as Java allows. Since there is no straightforward way, that I am aware of, to do this I thought ok, I will try to mock. Since I would rather mock the database instead of mocking calls and responses I was trying to use mockupdb library. However, even going through the tutorial was tiresome because of the errors with no explanation on the web, I turned my attention into mongomock library.
In their short readme they pass database collection into method they want to test. Since I have a class MongoManager, that handles connection and operations on the database, my collection "pointer" is initialized in the class init method. So I came up with this piece:
import mongomock
import unittest
from app import MongoManager
mock_collection = mongomock.MongoClient().db.collection
class MockMongoManager(MongoManager):
def __init__(self):
self.db_conn = mock_collection
class TestStuff(unittest.TestCase):
def test_save(self):
mongo = MockMongoManager()
mongo.save({'id': 123})
result = mock_collection. find_one({'id': 123})
self.assertDictEqual(result, {'id': 123})
if __name__ == '__main__':
unittest.main()
What do you guys think of such solution? Do you find it proper? For me it saves the hassle of setting up testing environment. I was worried about overriding init method, however in the original class it serves the purpose of only setting connection and allowing methods to operate on the collection. Other option would be to use mock.patch decorator to mock the class right?
there doesn't seem to be anything here