Source

django-mongodb / testproject / testapp / tests.py

#-*- coding:utf-8 -*-

from django.db import models, connection, DatabaseError
from django.test import TestCase

from testapp.models import CRUDTestModel, NoAutoPK_CRUDTestModel

class TestCRUD(TestCase):

    def setUp(self):
        self.db = connection.cursor()
        self.crud_col_name = CRUDTestModel._meta.db_table
        self.nopk_crud_col_name = NoAutoPK_CRUDTestModel._meta.db_table

    def tearDown(self):
        self.db.drop_collection(self.crud_col_name)
        self.db.drop_collection(self.nopk_crud_col_name)
        self.db.logout()

    def test_insert(self):
        # Normal insert
        for i in xrange(10):
            obj = CRUDTestModel(text="text%d" % i)
            obj.save()
            self.assertTrue(isinstance(obj.pk, str))
            query = {'text':"text%d" % i}
            self.assertTrue(self.db[self.crud_col_name].find_one(query) is not None)
        self.assertEqual(self.db[self.crud_col_name].find().count(), 10)
        
        # Insert with skipped primary key in model without AutoField
        self.assertRaises(DatabaseError, lambda: NoAutoPK_CRUDTestModel(text="text").save())
        self.assertEqual(self.db[self.nopk_crud_col_name].find().count(), 0)