Tuesday, February 25, 2014

django tests, mongoengine, and unique_with constraint

Hi everybody,

I'm facing the following problem with Mongodb.

I've got the following model : 


from mongoengine import Document, StringField, DateTimeField


class Author(Document):
    name = StringField(max_length=50, required=True)
    first_name = StringField(max_length=50, required=True, unique_with='name')
    birthday = DateTimeField(default=None)
    death_day = DateTimeField(default=None)

    meta = {
        'indexes': [('name', '+first_name')]
    }

Nothing special there, except that 'firstname' should be unique with 'name'.

I wrote the following test suite :

from django.test import TestCase
from les_classiques.models import Author
import mongoengine


class DatabaseTest(TestCase):
    def setUp(self):
        db = mongoengine.connection.get_db()
        for collection in db.collection_names(include_system_collections=False):
            db.drop_collection(collection)

    def test_insert_new_author(self):
        author = Author(name='Hugo', first_name='Victor')
        author.save()
        db_author = Author.objects(name='Hugo', first_name='Victor')[0]
        self.assertEqual(db_author.name, 'Hugo')

    def test_insert_duplicate_author_failure(self):
        author = Author(name='Peguy', first_name='Charles')
        author2 = Author(name='Peguy', first_name='Charles')
        author.save()
        self.assertRaises(mongoengine.NotUniqueError, author2.save)

The second test fails with the following error : "AssertionError: NotUniqueError not raised by save"


It's very strange. After some tests, I realized that the objects of the second function, are created with a duplicate key :
> db.author.find()
{ "_id" : ObjectId("530c96b7893e2808f8435e49"), "name" : "Peguy", "first_name" : "Charles" }
{ "_id" : ObjectId("530c96b7893e2808f8435e4a"), "name" : "Peguy", "first_name" : "Charles" }

I read the docs, this should work. StringField inherits from BaseField and should accept unique_with parameter.

Any idea ?


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/dc7a6a09-7540-448f-a412-016cca0dc146%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

No comments:

Post a Comment