Django Test with MongoEngine and test database
Problem:
Performing Tests with MongoEngine does not use an alternative database for testing (as the case with Django and relational databases).Then why not just connect to the alternative database when performing the tests? Well, that is the problem, the first connection (which is made in the settings.py), and even after disconnecting, when a model (class defined in models.py) is referenced, it will reconnect with the old ('default') database.
If you don't know how to use mongoengine with django, please refer to my other post here
Proposed Workaround:
If you are not interested in the details, you can skip down to the code sectionThe Document class (that classes defined in models.py inherit from) perform the reconnection with the old database if the _collection is None , and since this is a class variable (not an member of an instance), so we need to set it for each class.
Code:
class NoSQLTestRunner(DjangoTestSuiteRunner):def setup_databases(self):
settings.test_conf['local'] = True
settings.TEST = True
self.clearing_db_connection()
new_db_name = "your_test_db"
connect(new_db_name)
def teardown_databases(self, *args):
db_name = connection._connection_settings['default']['name']
connection.get_connection().drop_database(db_name)
connection.disconnect()
@classmethod
def clearing_db_connection(cls):
# disconnect the connection with the db
connection.disconnect()
# remove the connection details
connection._dbs = {}
connection._connections = {}
connection._connection_settings = {}
# getting call classes defined in models.py
models = pyclbr.readmodule("yourapp.models").keys()
for class_model in models:
# delete the collection to prevent automatically connecting with the old db (the live one)
del globals()[class_model]._collection
Check my other post here on how to use this class
Resources:http://stackoverflow.com/questions/15886469/dropping-all-collections-in-mongoengine
https://github.com/MongoEngine/mongoengine/blob/0.8/mongoengine/connection.py
https://github.com/MongoEngine/mongoengine/blob/0.8/mongoengine/document.py
https://docs.djangoproject.com/en/1.7/topics/testing/overview/
Comments
Post a Comment