Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_big_doc():
class Contact(EmbeddedDocument):
name = StringField()
title = StringField()
address = StringField()
class Company(Document):
name = StringField()
contacts = ListField(EmbeddedDocumentField(Contact))
Company.drop_collection()
def init_company():
return Company(
name="MongoDB, Inc.",
contacts=[
Contact(name="Contact %d" % x, title="CEO", address="Address %d" % x)
for x in range(1000)
],
)
company = init_company()
print("Big doc to mongo: %.3fms" % (timeit(company.to_mongo, 100) * 10 ** 3))
def test_inheritance_to_mongo_keys(self):
"""Ensure that document may inherit fields from a superclass document.
"""
class Person(Document):
name = StringField()
age = IntField()
meta = {'allow_inheritance': True}
class Employee(Person):
salary = IntField()
self.assertEqual(['_cls', 'age', 'id', 'name', 'salary'],
sorted(Employee._fields.keys()))
self.assertEqual(Person(name="Bob", age=35).to_mongo().keys(),
['_cls', 'name', 'age'])
self.assertEqual(Employee(name="Bob", age=35, salary=0).to_mongo().keys(),
['_cls', 'name', 'age', 'salary'])
self.assertEqual(Employee._get_collection_name(),
Person._get_collection_name())
"""Ensure that a list field only accepts lists with valid elements."""
access_level_choices = (
("a", u"Administration"),
("b", u"Manager"),
("c", u"Staff"),
)
class User(Document):
pass
class Comment(EmbeddedDocument):
content = StringField()
class BlogPost(Document):
content = StringField()
comments = ListField(EmbeddedDocumentField(Comment))
tags = ListField(StringField())
authors = ListField(ReferenceField(User))
authors_as_lazy = ListField(LazyReferenceField(User))
generic = ListField(GenericReferenceField())
generic_as_lazy = ListField(GenericLazyReferenceField())
access_list = ListField(choices=access_level_choices, display_sep=", ")
User.drop_collection()
BlogPost.drop_collection()
post = BlogPost(content="Went for a walk today...")
post.validate()
post.tags = "fun"
self.assertRaises(ValidationError, post.validate)
post.tags = [1, 2]
def test_default_value_is_not_used_when_changing_value_to_empty_list_for_dyn_doc(
self
):
"""List field with default can be set to the empty list (dynamic)"""
# Issue #1733
class Doc(DynamicDocument):
x = ListField(IntField(), default=lambda: [42])
doc = Doc(x=[1]).save()
doc.x = []
doc.y = 2 # Was triggering the bug
doc.save()
reloaded = Doc.objects.get(id=doc.id)
self.assertEqual(reloaded.x, [])
def test_nondefault_date_created_field(self):
# redefine to get entirely new class
class SimpleDoc(Document):
a = StringField()
b = IntField()
sett = SETTINGS.copy()
sett['DATE_CREATED'] = 'created_at'
app = Eve(settings=sett)
app.debug = True
ext = EveMongoengine(app)
ext.add_model(SimpleDoc)
app = app.test_client()
self._test_default_values(app, SimpleDoc, created_name='created_at')
"""Test schema."""
email = db.EmailField(primary_key=True)
class Seller(EmbeddedDocument):
"""Test schema."""
name = db.StringField()
address = db.EmbeddedDocumentField(Address)
class ArticleMetaData(EmbeddedDocument):
"""Test schema."""
price = db.IntField()
seller = db.EmbeddedDocumentField(Seller)
class Article(Document):
"""Test schema."""
user = db.ReferenceField(User)
addition = db.EmbeddedDocumentField(ArticleMetaData)
title = db.StringField()
date = db.DateTimeField()
body = db.BinaryField()
uuid = db.UUIDField()
class ExtraInformation(db.EmbeddedDocument):
"""Extra information."""
def test_default_values_set_to_None(self):
"""Ensure that default field values are used even when
we explcitly initialize the doc with None values.
"""
class Person(Document):
name = StringField()
age = IntField(default=30, required=False)
userid = StringField(default=lambda: "test", required=True)
created = DateTimeField(default=datetime.datetime.utcnow)
# Trying setting values to None
person = Person(name=None, age=None, userid=None, created=None)
# Confirm saving now would store values
data_to_be_saved = sorted(person.to_mongo().keys())
self.assertEqual(data_to_be_saved, ["age", "created", "userid"])
self.assertTrue(person.validate() is None)
self.assertEqual(person.name, person.name)
self.assertEqual(person.age, person.age)
self.assertEqual(person.userid, person.userid)
self.assertEqual(person.created, person.created)
self.assertEqual(person._data["name"], person.name)
if IS_PYMONGO_3:
test_conn = connect(
'mongoenginetest', alias='test1',
host='mongodb://username2:password@localhost/mongoenginetest'
)
self.assertRaises(OperationFailure, test_conn.server_info)
else:
self.assertRaises(
MongoEngineConnectionError,
connect, 'mongoenginetest', alias='test1',
host='mongodb://username2:password@localhost/mongoenginetest'
)
self.assertRaises(MongoEngineConnectionError, get_db, 'test1')
# Authentication succeeds with "authSource"
authd_conn = connect(
'mongoenginetest', alias='test2',
host=('mongodb://username2:password@localhost/'
'mongoenginetest?authSource=admin')
)
db = get_db('test2')
self.assertTrue(isinstance(db, pymongo.database.Database))
self.assertEqual(db.name, 'mongoenginetest')
# Clear all users
authd_conn.admin.system.users.remove({})
class B(Document):
shard_b = ReferenceField(Shard)
ref = ReferenceField(A)
class C(Document):
shard_c = ReferenceField(Shard)
ref_a = ReferenceField(A)
class D(Document):
shard_d = ReferenceField(Shard)
ref_c = ReferenceField(C)
ref_a = ReferenceField(A)
class E(Document):
shard_e = ReferenceField(Shard)
refs_a = SafeReferenceListField(ReferenceField(A))
ref_b = SafeReferenceField(B)
class F(Document):
shard_f = ReferenceField(Shard)
ref_a = ReferenceField(A)
A.drop_collection()
B.drop_collection()
C.drop_collection()
D.drop_collection()
E.drop_collection()
F.drop_collection()
self.Shard = Shard
self.A = A
def test_reference_class_with_abstract_parent(self):
"""Ensure that a class with an abstract parent can be referenced.
"""
class Sibling(Document):
name = StringField()
meta = {"abstract": True}
class Sister(Sibling):
pass
class Brother(Sibling):
sibling = ReferenceField(Sibling)
Sister.drop_collection()
Brother.drop_collection()
sister = Sister(name="Alice")
sister.save()
brother = Brother(name="Bob", sibling=sister)
brother.save()
self.assertEqual(Brother.objects[0].sibling.name, sister.name)