Testing Django apps with MongoDB

I've fallen in love with #NoSQL. So I'm doing my storage with MongoDB for an application I'm working on. But since I'm also a testing zealot I had to figure out how to test my app properly, with fixtures and all.

There's already some good code out there that will help you develop your Django app using MongoDB - namely MongoKit and django-mongokit.

MongoKit is a great way to make a structure for your document. Complete with validation and all. And by combining it with django-mongokit you also get automatic test database create/drop.

models.py:

from django_mongokit.document import DjangoDocument
from django_mongokit import connection

class Country(DjangoDocument):
    structure = {
        'iso3': unicode,
        'iso2': unicode,
        'name': unicode,
    }

    required_fields = ['iso3', 'iso2', 'name']
    use_dot_notation = True

connection.register([Country])

tests.py

from django_mongokit import get_database 

from django.test import TestCase
from models import *
class ModelsTest(TestCase):
db = get_database()
def test_should_save_country(self): country = self.db.countries.Country() country.iso2 = u'GB' country.iso3 = u'GBR' country.name = u'UNITED KINGDOM' country.save() self.assertTrue(self.db.countries.find())

But the fun doesn't stop there. You can also easily add some fixtures by creating a python file to hold some dicts for you:

countries.py:

countries = [
{"iso2" : "AF", "iso3" : "AFG", "name" : "AFGHANISTAN" },
{"iso2" : "AL", "iso3" : "ALB", "name" : "ALBANIA" },
]
And add this to tests.py:
from countries import countries

class ModelsTest(TestCase):
    def setUp(self):
        db = get_database()
        db.countries.insert(countries)

    def tearDown(self):
        db = get_database()
        db.drop_collection('countries')

Your countries collection will now be populated every time TestCase is created, and dropped when the tests are done running.
Be Sociable, Share!

You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

AddThis Social Bookmark Button

One Response to “Testing Django apps with MongoDB”

  1. Great writeup – thanks! Hadn’t seen django-mongokit before, looks nice.