I want to be able to do conditional connect() based on either I started django in testing mode or not.
in my settings.py I use mongoengine connect() method to connect to
What I do is use register_connection
, and then mock the connections on test.
In the file that I define the Mongo Documents I have this:
import mongoengine
from django.conf import settings
mongoengine.register_connection(
'default', settings.MONGOENGINE_DB, **settings.MONGOENGINE_CONNECTION)
Then in the tests I use the mock library to change the behave of connections (it would be possible too to mock one of the functions on the connection
sub module like get_db
) like this:
connections = patch.dict(
mongoengine.connection._connections, {'default': None})
dbs = patch.dict(
mongoengine.connection._dbs, {'default': {
'your_collection': None,
'another_collection': None,
}})
dbs.start()
connections.start()
insert = patch.object(mongoengine.queryset.QuerySet, 'insert')
insert_mock = insert.start()
...
insert_mock.assert_called_once(...)