Skip to content

Instantly share code, notes, and snippets.

@snormore
Created September 29, 2012 02:59
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save snormore/3803003 to your computer and use it in GitHub Desktop.
Save snormore/3803003 to your computer and use it in GitHub Desktop.
Django, MongoDB, and MongoEngine: A custom TestCase managing test database creation and cleanup between test methods.
#coding: utf-8
from nose.plugins.skip import SkipTest
from mongoengine.python_support import PY3
from mongoengine import connect
try:
from django.test import TestCase
from django.conf import settings
except Exception as err:
if PY3:
from unittest import TestCase
# Dummy value so no error
class settings:
MONGO_DATABASE_NAME = 'dummy'
else:
raise err
class MongoTestCase(TestCase):
"""
TestCase class that clear the collection between the tests
"""
mongodb_name = 'test_%s' % settings.MONGO_DATABASE_NAME
def _pre_setup(self):
if PY3:
raise SkipTest('django does not have Python 3 support')
from mongoengine.connection import connect, disconnect
disconnect()
connect(self.mongodb_name, port=settings.MONGO_PORT)
super(MongoTestCase, self)._pre_setup()
def _post_teardown(self):
from mongoengine.connection import get_connection, disconnect
connection = get_connection()
connection.drop_database(self.mongodb_name)
disconnect()
super(MongoTestCase, self)._post_teardown()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment