This commit is contained in:
Ross Lawley 2011-05-18 12:26:51 +01:00
parent 7ba40062d3
commit 5cbc76ea81

View File

@ -7,7 +7,7 @@ from mongoengine.connection import _get_db
class DocumentTest(unittest.TestCase): class DocumentTest(unittest.TestCase):
def setUp(self): def setUp(self):
connect(db='mongoenginetest') connect(db='mongoenginetest')
self.db = _get_db() self.db = _get_db()
@ -38,7 +38,7 @@ class DocumentTest(unittest.TestCase):
name = name_field name = name_field
age = age_field age = age_field
non_field = True non_field = True
self.assertEqual(Person._fields['name'], name_field) self.assertEqual(Person._fields['name'], name_field)
self.assertEqual(Person._fields['age'], age_field) self.assertEqual(Person._fields['age'], age_field)
self.assertFalse('non_field' in Person._fields) self.assertFalse('non_field' in Person._fields)
@ -60,7 +60,7 @@ class DocumentTest(unittest.TestCase):
mammal_superclasses = {'Animal': Animal} mammal_superclasses = {'Animal': Animal}
self.assertEqual(Mammal._superclasses, mammal_superclasses) self.assertEqual(Mammal._superclasses, mammal_superclasses)
dog_superclasses = { dog_superclasses = {
'Animal': Animal, 'Animal': Animal,
'Animal.Mammal': Mammal, 'Animal.Mammal': Mammal,
@ -68,7 +68,7 @@ class DocumentTest(unittest.TestCase):
self.assertEqual(Dog._superclasses, dog_superclasses) self.assertEqual(Dog._superclasses, dog_superclasses)
def test_get_subclasses(self): def test_get_subclasses(self):
"""Ensure that the correct list of subclasses is retrieved by the """Ensure that the correct list of subclasses is retrieved by the
_get_subclasses method. _get_subclasses method.
""" """
class Animal(Document): pass class Animal(Document): pass
@ -78,15 +78,15 @@ class DocumentTest(unittest.TestCase):
class Dog(Mammal): pass class Dog(Mammal): pass
mammal_subclasses = { mammal_subclasses = {
'Animal.Mammal.Dog': Dog, 'Animal.Mammal.Dog': Dog,
'Animal.Mammal.Human': Human 'Animal.Mammal.Human': Human
} }
self.assertEqual(Mammal._get_subclasses(), mammal_subclasses) self.assertEqual(Mammal._get_subclasses(), mammal_subclasses)
animal_subclasses = { animal_subclasses = {
'Animal.Fish': Fish, 'Animal.Fish': Fish,
'Animal.Mammal': Mammal, 'Animal.Mammal': Mammal,
'Animal.Mammal.Dog': Dog, 'Animal.Mammal.Dog': Dog,
'Animal.Mammal.Human': Human 'Animal.Mammal.Human': Human
} }
self.assertEqual(Animal._get_subclasses(), animal_subclasses) self.assertEqual(Animal._get_subclasses(), animal_subclasses)
@ -124,7 +124,7 @@ class DocumentTest(unittest.TestCase):
self.assertTrue('name' in Employee._fields) self.assertTrue('name' in Employee._fields)
self.assertTrue('salary' in Employee._fields) self.assertTrue('salary' in Employee._fields)
self.assertEqual(Employee._meta['collection'], self.assertEqual(Employee._meta['collection'],
self.Person._meta['collection']) self.Person._meta['collection'])
# Ensure that MRO error is not raised # Ensure that MRO error is not raised
@ -146,7 +146,7 @@ class DocumentTest(unittest.TestCase):
class Dog(Animal): class Dog(Animal):
pass pass
self.assertRaises(ValueError, create_dog_class) self.assertRaises(ValueError, create_dog_class)
# Check that _cls etc aren't present on simple documents # Check that _cls etc aren't present on simple documents
dog = Animal(name='dog') dog = Animal(name='dog')
dog.save() dog.save()
@ -161,7 +161,7 @@ class DocumentTest(unittest.TestCase):
class Employee(self.Person): class Employee(self.Person):
meta = {'allow_inheritance': False} meta = {'allow_inheritance': False}
self.assertRaises(ValueError, create_employee_class) self.assertRaises(ValueError, create_employee_class)
# Test the same for embedded documents # Test the same for embedded documents
class Comment(EmbeddedDocument): class Comment(EmbeddedDocument):
content = StringField() content = StringField()
@ -186,7 +186,7 @@ class DocumentTest(unittest.TestCase):
class Person(Document): class Person(Document):
name = StringField() name = StringField()
meta = {'collection': collection} meta = {'collection': collection}
user = Person(name="Test User") user = Person(name="Test User")
user.save() user.save()
self.assertTrue(collection in self.db.collection_names()) self.assertTrue(collection in self.db.collection_names())
@ -280,7 +280,7 @@ class DocumentTest(unittest.TestCase):
tags = ListField(StringField()) tags = ListField(StringField())
meta = { meta = {
'indexes': [ 'indexes': [
'-date', '-date',
'tags', 'tags',
('category', '-date') ('category', '-date')
], ],
@ -296,12 +296,12 @@ class DocumentTest(unittest.TestCase):
list(BlogPost.objects) list(BlogPost.objects)
info = BlogPost.objects._collection.index_information() info = BlogPost.objects._collection.index_information()
info = [value['key'] for key, value in info.iteritems()] info = [value['key'] for key, value in info.iteritems()]
self.assertTrue([('_types', 1), ('category', 1), ('addDate', -1)] self.assertTrue([('_types', 1), ('category', 1), ('addDate', -1)]
in info) in info)
self.assertTrue([('_types', 1), ('addDate', -1)] in info) self.assertTrue([('_types', 1), ('addDate', -1)] in info)
# tags is a list field so it shouldn't have _types in the index # tags is a list field so it shouldn't have _types in the index
self.assertTrue([('tags', 1)] in info) self.assertTrue([('tags', 1)] in info)
class ExtendedBlogPost(BlogPost): class ExtendedBlogPost(BlogPost):
title = StringField() title = StringField()
meta = {'indexes': ['title']} meta = {'indexes': ['title']}
@ -311,7 +311,7 @@ class DocumentTest(unittest.TestCase):
list(ExtendedBlogPost.objects) list(ExtendedBlogPost.objects)
info = ExtendedBlogPost.objects._collection.index_information() info = ExtendedBlogPost.objects._collection.index_information()
info = [value['key'] for key, value in info.iteritems()] info = [value['key'] for key, value in info.iteritems()]
self.assertTrue([('_types', 1), ('category', 1), ('addDate', -1)] self.assertTrue([('_types', 1), ('category', 1), ('addDate', -1)]
in info) in info)
self.assertTrue([('_types', 1), ('addDate', -1)] in info) self.assertTrue([('_types', 1), ('addDate', -1)] in info)
self.assertTrue([('_types', 1), ('title', 1)] in info) self.assertTrue([('_types', 1), ('title', 1)] in info)
@ -380,7 +380,7 @@ class DocumentTest(unittest.TestCase):
class EmailUser(User): class EmailUser(User):
email = StringField() email = StringField()
user = User(username='test', name='test user') user = User(username='test', name='test user')
user.save() user.save()
@ -391,20 +391,20 @@ class DocumentTest(unittest.TestCase):
user_son = User.objects._collection.find_one() user_son = User.objects._collection.find_one()
self.assertEqual(user_son['_id'], 'test') self.assertEqual(user_son['_id'], 'test')
self.assertTrue('username' not in user_son['_id']) self.assertTrue('username' not in user_son['_id'])
User.drop_collection() User.drop_collection()
user = User(pk='mongo', name='mongo user') user = User(pk='mongo', name='mongo user')
user.save() user.save()
user_obj = User.objects.first() user_obj = User.objects.first()
self.assertEqual(user_obj.id, 'mongo') self.assertEqual(user_obj.id, 'mongo')
self.assertEqual(user_obj.pk, 'mongo') self.assertEqual(user_obj.pk, 'mongo')
user_son = User.objects._collection.find_one() user_son = User.objects._collection.find_one()
self.assertEqual(user_son['_id'], 'mongo') self.assertEqual(user_son['_id'], 'mongo')
self.assertTrue('username' not in user_son['_id']) self.assertTrue('username' not in user_son['_id'])
User.drop_collection() User.drop_collection()
def test_creation(self): def test_creation(self):
@ -457,18 +457,18 @@ class DocumentTest(unittest.TestCase):
""" """
class Comment(EmbeddedDocument): class Comment(EmbeddedDocument):
content = StringField() content = StringField()
self.assertTrue('content' in Comment._fields) self.assertTrue('content' in Comment._fields)
self.assertFalse('id' in Comment._fields) self.assertFalse('id' in Comment._fields)
self.assertFalse('collection' in Comment._meta) self.assertFalse('collection' in Comment._meta)
def test_embedded_document_validation(self): def test_embedded_document_validation(self):
"""Ensure that embedded documents may be validated. """Ensure that embedded documents may be validated.
""" """
class Comment(EmbeddedDocument): class Comment(EmbeddedDocument):
date = DateTimeField() date = DateTimeField()
content = StringField(required=True) content = StringField(required=True)
comment = Comment() comment = Comment()
self.assertRaises(ValidationError, comment.validate) self.assertRaises(ValidationError, comment.validate)
@ -496,7 +496,7 @@ class DocumentTest(unittest.TestCase):
# Test skipping validation on save # Test skipping validation on save
class Recipient(Document): class Recipient(Document):
email = EmailField(required=True) email = EmailField(required=True)
recipient = Recipient(email='root@localhost') recipient = Recipient(email='root@localhost')
self.assertRaises(ValidationError, recipient.save) self.assertRaises(ValidationError, recipient.save)
try: try:
@ -517,19 +517,19 @@ class DocumentTest(unittest.TestCase):
"""Ensure that a document may be saved with a custom _id. """Ensure that a document may be saved with a custom _id.
""" """
# Create person object and save it to the database # Create person object and save it to the database
person = self.Person(name='Test User', age=30, person = self.Person(name='Test User', age=30,
id='497ce96f395f2f052a494fd4') id='497ce96f395f2f052a494fd4')
person.save() person.save()
# Ensure that the object is in the database with the correct _id # Ensure that the object is in the database with the correct _id
collection = self.db[self.Person._meta['collection']] collection = self.db[self.Person._meta['collection']]
person_obj = collection.find_one({'name': 'Test User'}) person_obj = collection.find_one({'name': 'Test User'})
self.assertEqual(str(person_obj['_id']), '497ce96f395f2f052a494fd4') self.assertEqual(str(person_obj['_id']), '497ce96f395f2f052a494fd4')
def test_save_custom_pk(self): def test_save_custom_pk(self):
"""Ensure that a document may be saved with a custom _id using pk alias. """Ensure that a document may be saved with a custom _id using pk alias.
""" """
# Create person object and save it to the database # Create person object and save it to the database
person = self.Person(name='Test User', age=30, person = self.Person(name='Test User', age=30,
pk='497ce96f395f2f052a494fd4') pk='497ce96f395f2f052a494fd4')
person.save() person.save()
# Ensure that the object is in the database with the correct _id # Ensure that the object is in the database with the correct _id
@ -565,7 +565,7 @@ class DocumentTest(unittest.TestCase):
BlogPost.drop_collection() BlogPost.drop_collection()
def test_save_embedded_document(self): def test_save_embedded_document(self):
"""Ensure that a document with an embedded document field may be """Ensure that a document with an embedded document field may be
saved in the database. saved in the database.
""" """
class EmployeeDetails(EmbeddedDocument): class EmployeeDetails(EmbeddedDocument):
@ -591,7 +591,7 @@ class DocumentTest(unittest.TestCase):
def test_save_reference(self): def test_save_reference(self):
"""Ensure that a document reference field may be saved in the database. """Ensure that a document reference field may be saved in the database.
""" """
class BlogPost(Document): class BlogPost(Document):
meta = {'collection': 'blogpost_1'} meta = {'collection': 'blogpost_1'}
content = StringField() content = StringField()
@ -610,7 +610,7 @@ class DocumentTest(unittest.TestCase):
post_obj = BlogPost.objects.first() post_obj = BlogPost.objects.first()
# Test laziness # Test laziness
self.assertTrue(isinstance(post_obj._data['author'], self.assertTrue(isinstance(post_obj._data['author'],
pymongo.dbref.DBRef)) pymongo.dbref.DBRef))
self.assertTrue(isinstance(post_obj.author, self.Person)) self.assertTrue(isinstance(post_obj.author, self.Person))
self.assertEqual(post_obj.author.name, 'Test User') self.assertEqual(post_obj.author.name, 'Test User')
@ -737,7 +737,7 @@ class DocumentTest(unittest.TestCase):
class BlogPost(Document): class BlogPost(Document):
pass pass
# Clear old datas # Clear old datas
User.drop_collection() User.drop_collection()
BlogPost.drop_collection() BlogPost.drop_collection()
@ -774,9 +774,9 @@ class DocumentTest(unittest.TestCase):
# in Set # in Set
all_user_set = set(User.objects.all()) all_user_set = set(User.objects.all())
self.assertTrue(u1 in all_user_set ) self.assertTrue(u1 in all_user_set )
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()