Skip to content

Instantly share code, notes, and snippets.

@turtlemonvh
Created October 7, 2014 13:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save turtlemonvh/f2bad44d455230e1d98b to your computer and use it in GitHub Desktop.
Save turtlemonvh/f2bad44d455230e1d98b to your computer and use it in GitHub Desktop.
Django + mongoengine: Isolated test database

Isolated Test database for Django

This gist contains a few snippets that make creating an isolated test database in Django simple when using mongoengine.

The database identified by settings.MY_TEST_DB_NAME will be deleted every time a test is run.

If your test class needs additional tearDown functionality, make sure to call the super(MyClassName, self).tearDown() method within your overridden version of tearDown to handle deleting the database when you are finished.

# Example usage
from my_app.tests.test_utils import TestDatabaseCleanup
class MyModelTests(TestDatabaseCleanup, unittest.TestCase):
"""Common usage """
def test_my_models(self):
# create some models
# no need to clean up
pass
class MyOtherModelTests(TestDatabaseCleanup, unittest.TestCase):
"""Handle additional tearDown functionality """
def test_my_other_models(self):
# create some models
# no need to clean up
pass
def tearDown(self):
# Do some other tearDown related work
# Then call the super() method to clean up the database
super(MyOtherModelTests, self).tearDown()
# Add this to settings.py
TESTING = 'test' in sys.argv
CONNECTION_STRING = 'localhost'
MY_DB_CONN = pymongo.Connection(CONNECTION_STRING, safe=True)
MY_DB_NAME = 'mydb'
MY_TEST_DB_NAME = 'mydb-testing'
if TESTING:
mongoengine.connect(MY_TEST_DB_NAME)
else:
mongoengine.connect(MY_DB_NAME)
# Add this somewhere it can be imported into tests
from django.conf import settings
class TestDatabaseCleanup(object):
def tearDown(self):
settings.MY_DB_CONN.drop_database(settings.MY_TEST_DB_NAME)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment