Merge remote-tracking branch 'original-repo/master' into fix-choices-display
This commit is contained in:
commit
e423380d7f
@ -2,6 +2,11 @@
|
|||||||
Changelog
|
Changelog
|
||||||
=========
|
=========
|
||||||
|
|
||||||
|
Development
|
||||||
|
===========
|
||||||
|
- QuerySet limit function behaviour: Passing 0 as parameter will return all the documents in the cursor #1611
|
||||||
|
- (Fill this out as you fix issues and develop your features).
|
||||||
|
=======
|
||||||
Changes in 0.15.4
|
Changes in 0.15.4
|
||||||
=================
|
=================
|
||||||
- Added `DateField` #513
|
- Added `DateField` #513
|
||||||
|
@ -529,7 +529,7 @@ There are a few top level defaults for all indexes that can be set::
|
|||||||
title = StringField()
|
title = StringField()
|
||||||
rating = StringField()
|
rating = StringField()
|
||||||
meta = {
|
meta = {
|
||||||
'index_options': {},
|
'index_opts': {},
|
||||||
'index_background': True,
|
'index_background': True,
|
||||||
'index_cls': False,
|
'index_cls': False,
|
||||||
'auto_create_index': True,
|
'auto_create_index': True,
|
||||||
@ -537,7 +537,7 @@ There are a few top level defaults for all indexes that can be set::
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
:attr:`index_options` (Optional)
|
:attr:`index_opts` (Optional)
|
||||||
Set any default index options - see the `full options list <http://docs.mongodb.org/manual/reference/method/db.collection.ensureIndex/#db.collection.ensureIndex>`_
|
Set any default index options - see the `full options list <http://docs.mongodb.org/manual/reference/method/db.collection.ensureIndex/#db.collection.ensureIndex>`_
|
||||||
|
|
||||||
:attr:`index_background` (Optional)
|
:attr:`index_background` (Optional)
|
||||||
@ -737,6 +737,9 @@ document.::
|
|||||||
.. note:: From 0.8 onwards :attr:`allow_inheritance` defaults
|
.. note:: From 0.8 onwards :attr:`allow_inheritance` defaults
|
||||||
to False, meaning you must set it to True to use inheritance.
|
to False, meaning you must set it to True to use inheritance.
|
||||||
|
|
||||||
|
Setting :attr:`allow_inheritance` to True should also be used in
|
||||||
|
:class:`~mongoengine.EmbeddedDocument` class in case you need to subclass it
|
||||||
|
|
||||||
Working with existing data
|
Working with existing data
|
||||||
--------------------------
|
--------------------------
|
||||||
As MongoEngine no longer defaults to needing :attr:`_cls`, you can quickly and
|
As MongoEngine no longer defaults to needing :attr:`_cls`, you can quickly and
|
||||||
|
@ -159,51 +159,69 @@ class no_sub_classes(object):
|
|||||||
|
|
||||||
|
|
||||||
class query_counter(object):
|
class query_counter(object):
|
||||||
"""Query_counter context manager to get the number of queries."""
|
"""Query_counter context manager to get the number of queries.
|
||||||
|
This works by updating the `profiling_level` of the database so that all queries get logged,
|
||||||
|
resetting the db.system.profile collection at the beginnig of the context and counting the new entries.
|
||||||
|
|
||||||
|
This was designed for debugging purpose. In fact it is a global counter so queries issued by other threads/processes
|
||||||
|
can interfere with it
|
||||||
|
|
||||||
|
Be aware that:
|
||||||
|
- Iterating over large amount of documents (>101) makes pymongo issue `getmore` queries to fetch the next batch of
|
||||||
|
documents (https://docs.mongodb.com/manual/tutorial/iterate-a-cursor/#cursor-batches)
|
||||||
|
- Some queries are ignored by default by the counter (killcursors, db.system.indexes)
|
||||||
|
"""
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
"""Construct the query_counter."""
|
"""Construct the query_counter
|
||||||
self.counter = 0
|
"""
|
||||||
self.db = get_db()
|
self.db = get_db()
|
||||||
|
self.initial_profiling_level = None
|
||||||
|
self._ctx_query_counter = 0 # number of queries issued by the context
|
||||||
|
|
||||||
def __enter__(self):
|
self._ignored_query = {
|
||||||
"""On every with block we need to drop the profile collection."""
|
'ns':
|
||||||
|
{'$ne': '%s.system.indexes' % self.db.name},
|
||||||
|
'op':
|
||||||
|
{'$ne': 'killcursors'}
|
||||||
|
}
|
||||||
|
|
||||||
|
def _turn_on_profiling(self):
|
||||||
|
self.initial_profiling_level = self.db.profiling_level()
|
||||||
self.db.set_profiling_level(0)
|
self.db.set_profiling_level(0)
|
||||||
self.db.system.profile.drop()
|
self.db.system.profile.drop()
|
||||||
self.db.set_profiling_level(2)
|
self.db.set_profiling_level(2)
|
||||||
|
|
||||||
|
def _resets_profiling(self):
|
||||||
|
self.db.set_profiling_level(self.initial_profiling_level)
|
||||||
|
|
||||||
|
def __enter__(self):
|
||||||
|
self._turn_on_profiling()
|
||||||
return self
|
return self
|
||||||
|
|
||||||
def __exit__(self, t, value, traceback):
|
def __exit__(self, t, value, traceback):
|
||||||
"""Reset the profiling level."""
|
self._resets_profiling()
|
||||||
self.db.set_profiling_level(0)
|
|
||||||
|
|
||||||
def __eq__(self, value):
|
def __eq__(self, value):
|
||||||
"""== Compare querycounter."""
|
|
||||||
counter = self._get_count()
|
counter = self._get_count()
|
||||||
return value == counter
|
return value == counter
|
||||||
|
|
||||||
def __ne__(self, value):
|
def __ne__(self, value):
|
||||||
"""!= Compare querycounter."""
|
|
||||||
return not self.__eq__(value)
|
return not self.__eq__(value)
|
||||||
|
|
||||||
def __lt__(self, value):
|
def __lt__(self, value):
|
||||||
"""< Compare querycounter."""
|
|
||||||
return self._get_count() < value
|
return self._get_count() < value
|
||||||
|
|
||||||
def __le__(self, value):
|
def __le__(self, value):
|
||||||
"""<= Compare querycounter."""
|
|
||||||
return self._get_count() <= value
|
return self._get_count() <= value
|
||||||
|
|
||||||
def __gt__(self, value):
|
def __gt__(self, value):
|
||||||
"""> Compare querycounter."""
|
|
||||||
return self._get_count() > value
|
return self._get_count() > value
|
||||||
|
|
||||||
def __ge__(self, value):
|
def __ge__(self, value):
|
||||||
""">= Compare querycounter."""
|
|
||||||
return self._get_count() >= value
|
return self._get_count() >= value
|
||||||
|
|
||||||
def __int__(self):
|
def __int__(self):
|
||||||
"""int representation."""
|
|
||||||
return self._get_count()
|
return self._get_count()
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
@ -211,10 +229,12 @@ class query_counter(object):
|
|||||||
return u"%s" % self._get_count()
|
return u"%s" % self._get_count()
|
||||||
|
|
||||||
def _get_count(self):
|
def _get_count(self):
|
||||||
"""Get the number of queries."""
|
"""Get the number of queries by counting the current number of entries in db.system.profile
|
||||||
ignore_query = {'ns': {'$ne': '%s.system.indexes' % self.db.name}}
|
and substracting the queries issued by this context. In fact everytime this is called, 1 query is
|
||||||
count = self.db.system.profile.find(ignore_query).count() - self.counter
|
issued so we need to balance that
|
||||||
self.counter += 1 # Account for the query we just fired
|
"""
|
||||||
|
count = self.db.system.profile.find(self._ignored_query).count() - self._ctx_query_counter
|
||||||
|
self._ctx_query_counter += 1 # Account for the query we just issued to gather the information
|
||||||
return count
|
return count
|
||||||
|
|
||||||
|
|
||||||
|
@ -396,7 +396,7 @@ class BaseQuerySet(object):
|
|||||||
:meth:`skip` that has been applied to this cursor into account when
|
:meth:`skip` that has been applied to this cursor into account when
|
||||||
getting the count
|
getting the count
|
||||||
"""
|
"""
|
||||||
if self._limit == 0 and with_limit_and_skip or self._none:
|
if self._limit == 0 and with_limit_and_skip is False or self._none:
|
||||||
return 0
|
return 0
|
||||||
return self._cursor.count(with_limit_and_skip=with_limit_and_skip)
|
return self._cursor.count(with_limit_and_skip=with_limit_and_skip)
|
||||||
|
|
||||||
@ -775,10 +775,11 @@ class BaseQuerySet(object):
|
|||||||
"""Limit the number of returned documents to `n`. This may also be
|
"""Limit the number of returned documents to `n`. This may also be
|
||||||
achieved using array-slicing syntax (e.g. ``User.objects[:5]``).
|
achieved using array-slicing syntax (e.g. ``User.objects[:5]``).
|
||||||
|
|
||||||
:param n: the maximum number of objects to return
|
:param n: the maximum number of objects to return if n is greater than 0.
|
||||||
|
When 0 is passed, returns all the documents in the cursor
|
||||||
"""
|
"""
|
||||||
queryset = self.clone()
|
queryset = self.clone()
|
||||||
queryset._limit = n if n != 0 else 1
|
queryset._limit = n
|
||||||
|
|
||||||
# If a cursor object has already been created, apply the limit to it.
|
# If a cursor object has already been created, apply the limit to it.
|
||||||
if queryset._cursor_obj:
|
if queryset._cursor_obj:
|
||||||
|
@ -66,10 +66,10 @@ class ClassMethodsTest(unittest.TestCase):
|
|||||||
"""
|
"""
|
||||||
collection_name = 'person'
|
collection_name = 'person'
|
||||||
self.Person(name='Test').save()
|
self.Person(name='Test').save()
|
||||||
self.assertTrue(collection_name in self.db.collection_names())
|
self.assertIn(collection_name, self.db.collection_names())
|
||||||
|
|
||||||
self.Person.drop_collection()
|
self.Person.drop_collection()
|
||||||
self.assertFalse(collection_name in self.db.collection_names())
|
self.assertNotIn(collection_name, self.db.collection_names())
|
||||||
|
|
||||||
def test_register_delete_rule(self):
|
def test_register_delete_rule(self):
|
||||||
"""Ensure that register delete rule adds a delete rule to the document
|
"""Ensure that register delete rule adds a delete rule to the document
|
||||||
@ -340,7 +340,7 @@ class ClassMethodsTest(unittest.TestCase):
|
|||||||
meta = {'collection': collection_name}
|
meta = {'collection': collection_name}
|
||||||
|
|
||||||
Person(name="Test User").save()
|
Person(name="Test User").save()
|
||||||
self.assertTrue(collection_name in self.db.collection_names())
|
self.assertIn(collection_name, self.db.collection_names())
|
||||||
|
|
||||||
user_obj = self.db[collection_name].find_one()
|
user_obj = self.db[collection_name].find_one()
|
||||||
self.assertEqual(user_obj['name'], "Test User")
|
self.assertEqual(user_obj['name'], "Test User")
|
||||||
@ -349,7 +349,7 @@ class ClassMethodsTest(unittest.TestCase):
|
|||||||
self.assertEqual(user_obj.name, "Test User")
|
self.assertEqual(user_obj.name, "Test User")
|
||||||
|
|
||||||
Person.drop_collection()
|
Person.drop_collection()
|
||||||
self.assertFalse(collection_name in self.db.collection_names())
|
self.assertNotIn(collection_name, self.db.collection_names())
|
||||||
|
|
||||||
def test_collection_name_and_primary(self):
|
def test_collection_name_and_primary(self):
|
||||||
"""Ensure that a collection with a specified name may be used.
|
"""Ensure that a collection with a specified name may be used.
|
||||||
|
@ -694,7 +694,7 @@ class DeltaTest(unittest.TestCase):
|
|||||||
organization.employees.append(person)
|
organization.employees.append(person)
|
||||||
updates, removals = organization._delta()
|
updates, removals = organization._delta()
|
||||||
self.assertEqual({}, removals)
|
self.assertEqual({}, removals)
|
||||||
self.assertTrue('employees' in updates)
|
self.assertIn('employees', updates)
|
||||||
|
|
||||||
def test_delta_with_dbref_false(self):
|
def test_delta_with_dbref_false(self):
|
||||||
person, organization, employee = self.circular_reference_deltas_2(Document, Document, False)
|
person, organization, employee = self.circular_reference_deltas_2(Document, Document, False)
|
||||||
@ -709,7 +709,7 @@ class DeltaTest(unittest.TestCase):
|
|||||||
organization.employees.append(person)
|
organization.employees.append(person)
|
||||||
updates, removals = organization._delta()
|
updates, removals = organization._delta()
|
||||||
self.assertEqual({}, removals)
|
self.assertEqual({}, removals)
|
||||||
self.assertTrue('employees' in updates)
|
self.assertIn('employees', updates)
|
||||||
|
|
||||||
def test_nested_nested_fields_mark_as_changed(self):
|
def test_nested_nested_fields_mark_as_changed(self):
|
||||||
class EmbeddedDoc(EmbeddedDocument):
|
class EmbeddedDoc(EmbeddedDocument):
|
||||||
|
@ -174,8 +174,8 @@ class DynamicTest(unittest.TestCase):
|
|||||||
|
|
||||||
Employee.drop_collection()
|
Employee.drop_collection()
|
||||||
|
|
||||||
self.assertTrue('name' in Employee._fields)
|
self.assertIn('name', Employee._fields)
|
||||||
self.assertTrue('salary' in Employee._fields)
|
self.assertIn('salary', Employee._fields)
|
||||||
self.assertEqual(Employee._get_collection_name(),
|
self.assertEqual(Employee._get_collection_name(),
|
||||||
self.Person._get_collection_name())
|
self.Person._get_collection_name())
|
||||||
|
|
||||||
@ -189,7 +189,7 @@ class DynamicTest(unittest.TestCase):
|
|||||||
self.assertEqual(1, Employee.objects(age=20).count())
|
self.assertEqual(1, Employee.objects(age=20).count())
|
||||||
|
|
||||||
joe_bloggs = self.Person.objects.first()
|
joe_bloggs = self.Person.objects.first()
|
||||||
self.assertTrue(isinstance(joe_bloggs, Employee))
|
self.assertIsInstance(joe_bloggs, Employee)
|
||||||
|
|
||||||
def test_embedded_dynamic_document(self):
|
def test_embedded_dynamic_document(self):
|
||||||
"""Test dynamic embedded documents"""
|
"""Test dynamic embedded documents"""
|
||||||
|
@ -70,7 +70,7 @@ class IndexesTest(unittest.TestCase):
|
|||||||
self.assertEqual(len(info), 4)
|
self.assertEqual(len(info), 4)
|
||||||
info = [value['key'] for key, value in info.iteritems()]
|
info = [value['key'] for key, value in info.iteritems()]
|
||||||
for expected in expected_specs:
|
for expected in expected_specs:
|
||||||
self.assertTrue(expected['fields'] in info)
|
self.assertIn(expected['fields'], info)
|
||||||
|
|
||||||
def _index_test_inheritance(self, InheritFrom):
|
def _index_test_inheritance(self, InheritFrom):
|
||||||
|
|
||||||
@ -102,7 +102,7 @@ class IndexesTest(unittest.TestCase):
|
|||||||
self.assertEqual(len(info), 4)
|
self.assertEqual(len(info), 4)
|
||||||
info = [value['key'] for key, value in info.iteritems()]
|
info = [value['key'] for key, value in info.iteritems()]
|
||||||
for expected in expected_specs:
|
for expected in expected_specs:
|
||||||
self.assertTrue(expected['fields'] in info)
|
self.assertIn(expected['fields'], info)
|
||||||
|
|
||||||
class ExtendedBlogPost(BlogPost):
|
class ExtendedBlogPost(BlogPost):
|
||||||
title = StringField()
|
title = StringField()
|
||||||
@ -117,7 +117,7 @@ class IndexesTest(unittest.TestCase):
|
|||||||
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()]
|
||||||
for expected in expected_specs:
|
for expected in expected_specs:
|
||||||
self.assertTrue(expected['fields'] in info)
|
self.assertIn(expected['fields'], info)
|
||||||
|
|
||||||
def test_indexes_document_inheritance(self):
|
def test_indexes_document_inheritance(self):
|
||||||
"""Ensure that indexes are used when meta[indexes] is specified for
|
"""Ensure that indexes are used when meta[indexes] is specified for
|
||||||
@ -226,7 +226,7 @@ class IndexesTest(unittest.TestCase):
|
|||||||
list(Person.objects)
|
list(Person.objects)
|
||||||
info = Person.objects._collection.index_information()
|
info = Person.objects._collection.index_information()
|
||||||
info = [value['key'] for key, value in info.iteritems()]
|
info = [value['key'] for key, value in info.iteritems()]
|
||||||
self.assertTrue([('rank.title', 1)] in info)
|
self.assertIn([('rank.title', 1)], info)
|
||||||
|
|
||||||
def test_explicit_geo2d_index(self):
|
def test_explicit_geo2d_index(self):
|
||||||
"""Ensure that geo2d indexes work when created via meta[indexes]
|
"""Ensure that geo2d indexes work when created via meta[indexes]
|
||||||
@ -246,7 +246,7 @@ class IndexesTest(unittest.TestCase):
|
|||||||
Place.ensure_indexes()
|
Place.ensure_indexes()
|
||||||
info = Place._get_collection().index_information()
|
info = Place._get_collection().index_information()
|
||||||
info = [value['key'] for key, value in info.iteritems()]
|
info = [value['key'] for key, value in info.iteritems()]
|
||||||
self.assertTrue([('location.point', '2d')] in info)
|
self.assertIn([('location.point', '2d')], info)
|
||||||
|
|
||||||
def test_explicit_geo2d_index_embedded(self):
|
def test_explicit_geo2d_index_embedded(self):
|
||||||
"""Ensure that geo2d indexes work when created via meta[indexes]
|
"""Ensure that geo2d indexes work when created via meta[indexes]
|
||||||
@ -269,7 +269,7 @@ class IndexesTest(unittest.TestCase):
|
|||||||
Place.ensure_indexes()
|
Place.ensure_indexes()
|
||||||
info = Place._get_collection().index_information()
|
info = Place._get_collection().index_information()
|
||||||
info = [value['key'] for key, value in info.iteritems()]
|
info = [value['key'] for key, value in info.iteritems()]
|
||||||
self.assertTrue([('current.location.point', '2d')] in info)
|
self.assertIn([('current.location.point', '2d')], info)
|
||||||
|
|
||||||
def test_explicit_geosphere_index(self):
|
def test_explicit_geosphere_index(self):
|
||||||
"""Ensure that geosphere indexes work when created via meta[indexes]
|
"""Ensure that geosphere indexes work when created via meta[indexes]
|
||||||
@ -289,7 +289,7 @@ class IndexesTest(unittest.TestCase):
|
|||||||
Place.ensure_indexes()
|
Place.ensure_indexes()
|
||||||
info = Place._get_collection().index_information()
|
info = Place._get_collection().index_information()
|
||||||
info = [value['key'] for key, value in info.iteritems()]
|
info = [value['key'] for key, value in info.iteritems()]
|
||||||
self.assertTrue([('location.point', '2dsphere')] in info)
|
self.assertIn([('location.point', '2dsphere')], info)
|
||||||
|
|
||||||
def test_explicit_geohaystack_index(self):
|
def test_explicit_geohaystack_index(self):
|
||||||
"""Ensure that geohaystack indexes work when created via meta[indexes]
|
"""Ensure that geohaystack indexes work when created via meta[indexes]
|
||||||
@ -311,7 +311,7 @@ class IndexesTest(unittest.TestCase):
|
|||||||
Place.ensure_indexes()
|
Place.ensure_indexes()
|
||||||
info = Place._get_collection().index_information()
|
info = Place._get_collection().index_information()
|
||||||
info = [value['key'] for key, value in info.iteritems()]
|
info = [value['key'] for key, value in info.iteritems()]
|
||||||
self.assertTrue([('location.point', 'geoHaystack')] in info)
|
self.assertIn([('location.point', 'geoHaystack')], info)
|
||||||
|
|
||||||
def test_create_geohaystack_index(self):
|
def test_create_geohaystack_index(self):
|
||||||
"""Ensure that geohaystack indexes can be created
|
"""Ensure that geohaystack indexes can be created
|
||||||
@ -323,7 +323,7 @@ class IndexesTest(unittest.TestCase):
|
|||||||
Place.create_index({'fields': (')location.point', 'name')}, bucketSize=10)
|
Place.create_index({'fields': (')location.point', 'name')}, bucketSize=10)
|
||||||
info = Place._get_collection().index_information()
|
info = Place._get_collection().index_information()
|
||||||
info = [value['key'] for key, value in info.iteritems()]
|
info = [value['key'] for key, value in info.iteritems()]
|
||||||
self.assertTrue([('location.point', 'geoHaystack'), ('name', 1)] in info)
|
self.assertIn([('location.point', 'geoHaystack'), ('name', 1)], info)
|
||||||
|
|
||||||
def test_dictionary_indexes(self):
|
def test_dictionary_indexes(self):
|
||||||
"""Ensure that indexes are used when meta[indexes] contains
|
"""Ensure that indexes are used when meta[indexes] contains
|
||||||
@ -356,7 +356,7 @@ class IndexesTest(unittest.TestCase):
|
|||||||
value.get('unique', False),
|
value.get('unique', False),
|
||||||
value.get('sparse', False))
|
value.get('sparse', False))
|
||||||
for key, value in info.iteritems()]
|
for key, value in info.iteritems()]
|
||||||
self.assertTrue(([('addDate', -1)], True, True) in info)
|
self.assertIn(([('addDate', -1)], True, True), info)
|
||||||
|
|
||||||
BlogPost.drop_collection()
|
BlogPost.drop_collection()
|
||||||
|
|
||||||
@ -803,7 +803,7 @@ class IndexesTest(unittest.TestCase):
|
|||||||
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()]
|
||||||
index_item = [('_id', 1), ('comments.comment_id', 1)]
|
index_item = [('_id', 1), ('comments.comment_id', 1)]
|
||||||
self.assertTrue(index_item in info)
|
self.assertIn(index_item, info)
|
||||||
|
|
||||||
def test_compound_key_embedded(self):
|
def test_compound_key_embedded(self):
|
||||||
|
|
||||||
@ -850,8 +850,8 @@ class IndexesTest(unittest.TestCase):
|
|||||||
|
|
||||||
info = MyDoc.objects._collection.index_information()
|
info = MyDoc.objects._collection.index_information()
|
||||||
info = [value['key'] for key, value in info.iteritems()]
|
info = [value['key'] for key, value in info.iteritems()]
|
||||||
self.assertTrue([('provider_ids.foo', 1)] in info)
|
self.assertIn([('provider_ids.foo', 1)], info)
|
||||||
self.assertTrue([('provider_ids.bar', 1)] in info)
|
self.assertIn([('provider_ids.bar', 1)], info)
|
||||||
|
|
||||||
def test_sparse_compound_indexes(self):
|
def test_sparse_compound_indexes(self):
|
||||||
|
|
||||||
@ -876,9 +876,9 @@ class IndexesTest(unittest.TestCase):
|
|||||||
}
|
}
|
||||||
|
|
||||||
indexes = Book.objects._collection.index_information()
|
indexes = Book.objects._collection.index_information()
|
||||||
self.assertTrue("title_text" in indexes)
|
self.assertIn("title_text", indexes)
|
||||||
key = indexes["title_text"]["key"]
|
key = indexes["title_text"]["key"]
|
||||||
self.assertTrue(('_fts', 'text') in key)
|
self.assertIn(('_fts', 'text'), key)
|
||||||
|
|
||||||
def test_hashed_indexes(self):
|
def test_hashed_indexes(self):
|
||||||
|
|
||||||
@ -889,8 +889,8 @@ class IndexesTest(unittest.TestCase):
|
|||||||
}
|
}
|
||||||
|
|
||||||
indexes = Book.objects._collection.index_information()
|
indexes = Book.objects._collection.index_information()
|
||||||
self.assertTrue("ref_id_hashed" in indexes)
|
self.assertIn("ref_id_hashed", indexes)
|
||||||
self.assertTrue(('ref_id', 'hashed') in indexes["ref_id_hashed"]["key"])
|
self.assertIn(('ref_id', 'hashed'), indexes["ref_id_hashed"]["key"])
|
||||||
|
|
||||||
def test_indexes_after_database_drop(self):
|
def test_indexes_after_database_drop(self):
|
||||||
"""
|
"""
|
||||||
@ -1013,7 +1013,7 @@ class IndexesTest(unittest.TestCase):
|
|||||||
TestDoc.ensure_indexes()
|
TestDoc.ensure_indexes()
|
||||||
|
|
||||||
index_info = TestDoc._get_collection().index_information()
|
index_info = TestDoc._get_collection().index_information()
|
||||||
self.assertTrue('shard_1_1__cls_1_txt_1_1' in index_info)
|
self.assertIn('shard_1_1__cls_1_txt_1_1', index_info)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
@ -268,7 +268,7 @@ class InheritanceTest(unittest.TestCase):
|
|||||||
|
|
||||||
collection = self.db[Animal._get_collection_name()]
|
collection = self.db[Animal._get_collection_name()]
|
||||||
obj = collection.find_one()
|
obj = collection.find_one()
|
||||||
self.assertFalse('_cls' in obj)
|
self.assertNotIn('_cls', obj)
|
||||||
|
|
||||||
def test_cant_turn_off_inheritance_on_subclass(self):
|
def test_cant_turn_off_inheritance_on_subclass(self):
|
||||||
"""Ensure if inheritance is on in a subclass you cant turn it off.
|
"""Ensure if inheritance is on in a subclass you cant turn it off.
|
||||||
@ -298,7 +298,7 @@ class InheritanceTest(unittest.TestCase):
|
|||||||
|
|
||||||
# Check that _cls isn't present in simple documents
|
# Check that _cls isn't present in simple documents
|
||||||
doc = Animal(name='dog')
|
doc = Animal(name='dog')
|
||||||
self.assertFalse('_cls' in doc.to_mongo())
|
self.assertNotIn('_cls', doc.to_mongo())
|
||||||
|
|
||||||
def test_abstract_handle_ids_in_metaclass_properly(self):
|
def test_abstract_handle_ids_in_metaclass_properly(self):
|
||||||
|
|
||||||
@ -374,14 +374,14 @@ class InheritanceTest(unittest.TestCase):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
doc = Comment(content='test')
|
doc = Comment(content='test')
|
||||||
self.assertFalse('_cls' in doc.to_mongo())
|
self.assertNotIn('_cls', doc.to_mongo())
|
||||||
|
|
||||||
class Comment(EmbeddedDocument):
|
class Comment(EmbeddedDocument):
|
||||||
content = StringField()
|
content = StringField()
|
||||||
meta = {'allow_inheritance': True}
|
meta = {'allow_inheritance': True}
|
||||||
|
|
||||||
doc = Comment(content='test')
|
doc = Comment(content='test')
|
||||||
self.assertTrue('_cls' in doc.to_mongo())
|
self.assertIn('_cls', doc.to_mongo())
|
||||||
|
|
||||||
def test_document_inheritance(self):
|
def test_document_inheritance(self):
|
||||||
"""Ensure mutliple inheritance of abstract documents
|
"""Ensure mutliple inheritance of abstract documents
|
||||||
@ -434,8 +434,8 @@ class InheritanceTest(unittest.TestCase):
|
|||||||
for cls in [Animal, Fish, Guppy]:
|
for cls in [Animal, Fish, Guppy]:
|
||||||
self.assertEqual(cls._meta[k], v)
|
self.assertEqual(cls._meta[k], v)
|
||||||
|
|
||||||
self.assertFalse('collection' in Animal._meta)
|
self.assertNotIn('collection', Animal._meta)
|
||||||
self.assertFalse('collection' in Mammal._meta)
|
self.assertNotIn('collection', Mammal._meta)
|
||||||
|
|
||||||
self.assertEqual(Animal._get_collection_name(), None)
|
self.assertEqual(Animal._get_collection_name(), None)
|
||||||
self.assertEqual(Mammal._get_collection_name(), None)
|
self.assertEqual(Mammal._get_collection_name(), None)
|
||||||
|
@ -357,7 +357,7 @@ class InstanceTest(MongoDBTestCase):
|
|||||||
|
|
||||||
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.assertNotIn('username', user_son['_id'])
|
||||||
|
|
||||||
User.drop_collection()
|
User.drop_collection()
|
||||||
|
|
||||||
@ -370,7 +370,7 @@ class InstanceTest(MongoDBTestCase):
|
|||||||
|
|
||||||
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.assertNotIn('username', user_son['_id'])
|
||||||
|
|
||||||
def test_document_not_registered(self):
|
def test_document_not_registered(self):
|
||||||
class Place(Document):
|
class Place(Document):
|
||||||
@ -594,10 +594,10 @@ class InstanceTest(MongoDBTestCase):
|
|||||||
# Length = length(assigned fields + id)
|
# Length = length(assigned fields + id)
|
||||||
self.assertEqual(len(person), 5)
|
self.assertEqual(len(person), 5)
|
||||||
|
|
||||||
self.assertTrue('age' in person)
|
self.assertIn('age', person)
|
||||||
person.age = None
|
person.age = None
|
||||||
self.assertFalse('age' in person)
|
self.assertNotIn('age', person)
|
||||||
self.assertFalse('nationality' in person)
|
self.assertNotIn('nationality', person)
|
||||||
|
|
||||||
def test_embedded_document_to_mongo(self):
|
def test_embedded_document_to_mongo(self):
|
||||||
class Person(EmbeddedDocument):
|
class Person(EmbeddedDocument):
|
||||||
@ -627,8 +627,8 @@ class InstanceTest(MongoDBTestCase):
|
|||||||
class Comment(EmbeddedDocument):
|
class Comment(EmbeddedDocument):
|
||||||
content = StringField()
|
content = StringField()
|
||||||
|
|
||||||
self.assertTrue('content' in Comment._fields)
|
self.assertIn('content', Comment._fields)
|
||||||
self.assertFalse('id' in Comment._fields)
|
self.assertNotIn('id', Comment._fields)
|
||||||
|
|
||||||
def test_embedded_document_instance(self):
|
def test_embedded_document_instance(self):
|
||||||
"""Ensure that embedded documents can reference parent instance."""
|
"""Ensure that embedded documents can reference parent instance."""
|
||||||
@ -1455,9 +1455,9 @@ class InstanceTest(MongoDBTestCase):
|
|||||||
user = User.objects.first()
|
user = User.objects.first()
|
||||||
# Even if stored as ObjectId's internally mongoengine uses DBRefs
|
# Even if stored as ObjectId's internally mongoengine uses DBRefs
|
||||||
# As ObjectId's aren't automatically derefenced
|
# As ObjectId's aren't automatically derefenced
|
||||||
self.assertTrue(isinstance(user._data['orgs'][0], DBRef))
|
self.assertIsInstance(user._data['orgs'][0], DBRef)
|
||||||
self.assertTrue(isinstance(user.orgs[0], Organization))
|
self.assertIsInstance(user.orgs[0], Organization)
|
||||||
self.assertTrue(isinstance(user._data['orgs'][0], Organization))
|
self.assertIsInstance(user._data['orgs'][0], Organization)
|
||||||
|
|
||||||
# Changing a value
|
# Changing a value
|
||||||
with query_counter() as q:
|
with query_counter() as q:
|
||||||
@ -1837,9 +1837,8 @@ class InstanceTest(MongoDBTestCase):
|
|||||||
post_obj = BlogPost.objects.first()
|
post_obj = BlogPost.objects.first()
|
||||||
|
|
||||||
# Test laziness
|
# Test laziness
|
||||||
self.assertTrue(isinstance(post_obj._data['author'],
|
self.assertIsInstance(post_obj._data['author'], bson.DBRef)
|
||||||
bson.DBRef))
|
self.assertIsInstance(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')
|
||||||
|
|
||||||
# Ensure that the dereferenced object may be changed and saved
|
# Ensure that the dereferenced object may be changed and saved
|
||||||
@ -2245,12 +2244,12 @@ class InstanceTest(MongoDBTestCase):
|
|||||||
# Make sure docs are properly identified in a list (__eq__ is used
|
# Make sure docs are properly identified in a list (__eq__ is used
|
||||||
# for the comparison).
|
# for the comparison).
|
||||||
all_user_list = list(User.objects.all())
|
all_user_list = list(User.objects.all())
|
||||||
self.assertTrue(u1 in all_user_list)
|
self.assertIn(u1, all_user_list)
|
||||||
self.assertTrue(u2 in all_user_list)
|
self.assertIn(u2, all_user_list)
|
||||||
self.assertTrue(u3 in all_user_list)
|
self.assertIn(u3, all_user_list)
|
||||||
self.assertTrue(u4 not in all_user_list) # New object
|
self.assertNotIn(u4, all_user_list) # New object
|
||||||
self.assertTrue(b1 not in all_user_list) # Other object
|
self.assertNotIn(b1, all_user_list) # Other object
|
||||||
self.assertTrue(b2 not in all_user_list) # Other object
|
self.assertNotIn(b2, all_user_list) # Other object
|
||||||
|
|
||||||
# Make sure docs can be used as keys in a dict (__hash__ is used
|
# Make sure docs can be used as keys in a dict (__hash__ is used
|
||||||
# for hashing the docs).
|
# for hashing the docs).
|
||||||
@ -2268,10 +2267,10 @@ class InstanceTest(MongoDBTestCase):
|
|||||||
# Make sure docs are properly identified in a set (__hash__ is used
|
# Make sure docs are properly identified in a set (__hash__ is used
|
||||||
# for hashing the docs).
|
# for hashing the docs).
|
||||||
all_user_set = set(User.objects.all())
|
all_user_set = set(User.objects.all())
|
||||||
self.assertTrue(u1 in all_user_set)
|
self.assertIn(u1, all_user_set)
|
||||||
self.assertTrue(u4 not in all_user_set)
|
self.assertNotIn(u4, all_user_set)
|
||||||
self.assertTrue(b1 not in all_user_list)
|
self.assertNotIn(b1, all_user_list)
|
||||||
self.assertTrue(b2 not in all_user_list)
|
self.assertNotIn(b2, all_user_list)
|
||||||
|
|
||||||
# Make sure duplicate docs aren't accepted in the set
|
# Make sure duplicate docs aren't accepted in the set
|
||||||
self.assertEqual(len(all_user_set), 3)
|
self.assertEqual(len(all_user_set), 3)
|
||||||
@ -2972,7 +2971,7 @@ class InstanceTest(MongoDBTestCase):
|
|||||||
Person(name="Harry Potter").save()
|
Person(name="Harry Potter").save()
|
||||||
|
|
||||||
person = Person.objects.first()
|
person = Person.objects.first()
|
||||||
self.assertTrue('id' in person._data.keys())
|
self.assertIn('id', person._data.keys())
|
||||||
self.assertEqual(person._data.get('id'), person.id)
|
self.assertEqual(person._data.get('id'), person.id)
|
||||||
|
|
||||||
def test_complex_nesting_document_and_embedded_document(self):
|
def test_complex_nesting_document_and_embedded_document(self):
|
||||||
@ -3064,36 +3063,36 @@ class InstanceTest(MongoDBTestCase):
|
|||||||
|
|
||||||
dbref2 = f._data['test2']
|
dbref2 = f._data['test2']
|
||||||
obj2 = f.test2
|
obj2 = f.test2
|
||||||
self.assertTrue(isinstance(dbref2, DBRef))
|
self.assertIsInstance(dbref2, DBRef)
|
||||||
self.assertTrue(isinstance(obj2, Test2))
|
self.assertIsInstance(obj2, Test2)
|
||||||
self.assertTrue(obj2.id == dbref2.id)
|
self.assertEqual(obj2.id, dbref2.id)
|
||||||
self.assertTrue(obj2 == dbref2)
|
self.assertEqual(obj2, dbref2)
|
||||||
self.assertTrue(dbref2 == obj2)
|
self.assertEqual(dbref2, obj2)
|
||||||
|
|
||||||
dbref3 = f._data['test3']
|
dbref3 = f._data['test3']
|
||||||
obj3 = f.test3
|
obj3 = f.test3
|
||||||
self.assertTrue(isinstance(dbref3, DBRef))
|
self.assertIsInstance(dbref3, DBRef)
|
||||||
self.assertTrue(isinstance(obj3, Test3))
|
self.assertIsInstance(obj3, Test3)
|
||||||
self.assertTrue(obj3.id == dbref3.id)
|
self.assertEqual(obj3.id, dbref3.id)
|
||||||
self.assertTrue(obj3 == dbref3)
|
self.assertEqual(obj3, dbref3)
|
||||||
self.assertTrue(dbref3 == obj3)
|
self.assertEqual(dbref3, obj3)
|
||||||
|
|
||||||
self.assertTrue(obj2.id == obj3.id)
|
self.assertEqual(obj2.id, obj3.id)
|
||||||
self.assertTrue(dbref2.id == dbref3.id)
|
self.assertEqual(dbref2.id, dbref3.id)
|
||||||
self.assertFalse(dbref2 == dbref3)
|
self.assertNotEqual(dbref2, dbref3)
|
||||||
self.assertFalse(dbref3 == dbref2)
|
self.assertNotEqual(dbref3, dbref2)
|
||||||
self.assertTrue(dbref2 != dbref3)
|
self.assertNotEqual(dbref2, dbref3)
|
||||||
self.assertTrue(dbref3 != dbref2)
|
self.assertNotEqual(dbref3, dbref2)
|
||||||
|
|
||||||
self.assertFalse(obj2 == dbref3)
|
self.assertNotEqual(obj2, dbref3)
|
||||||
self.assertFalse(dbref3 == obj2)
|
self.assertNotEqual(dbref3, obj2)
|
||||||
self.assertTrue(obj2 != dbref3)
|
self.assertNotEqual(obj2, dbref3)
|
||||||
self.assertTrue(dbref3 != obj2)
|
self.assertNotEqual(dbref3, obj2)
|
||||||
|
|
||||||
self.assertFalse(obj3 == dbref2)
|
self.assertNotEqual(obj3, dbref2)
|
||||||
self.assertFalse(dbref2 == obj3)
|
self.assertNotEqual(dbref2, obj3)
|
||||||
self.assertTrue(obj3 != dbref2)
|
self.assertNotEqual(obj3, dbref2)
|
||||||
self.assertTrue(dbref2 != obj3)
|
self.assertNotEqual(dbref2, obj3)
|
||||||
|
|
||||||
def test_default_values(self):
|
def test_default_values(self):
|
||||||
class Person(Document):
|
class Person(Document):
|
||||||
|
@ -20,16 +20,16 @@ class ValidatorErrorTest(unittest.TestCase):
|
|||||||
|
|
||||||
# 1st level error schema
|
# 1st level error schema
|
||||||
error.errors = {'1st': ValidationError('bad 1st'), }
|
error.errors = {'1st': ValidationError('bad 1st'), }
|
||||||
self.assertTrue('1st' in error.to_dict())
|
self.assertIn('1st', error.to_dict())
|
||||||
self.assertEqual(error.to_dict()['1st'], 'bad 1st')
|
self.assertEqual(error.to_dict()['1st'], 'bad 1st')
|
||||||
|
|
||||||
# 2nd level error schema
|
# 2nd level error schema
|
||||||
error.errors = {'1st': ValidationError('bad 1st', errors={
|
error.errors = {'1st': ValidationError('bad 1st', errors={
|
||||||
'2nd': ValidationError('bad 2nd'),
|
'2nd': ValidationError('bad 2nd'),
|
||||||
})}
|
})}
|
||||||
self.assertTrue('1st' in error.to_dict())
|
self.assertIn('1st', error.to_dict())
|
||||||
self.assertTrue(isinstance(error.to_dict()['1st'], dict))
|
self.assertIsInstance(error.to_dict()['1st'], dict)
|
||||||
self.assertTrue('2nd' in error.to_dict()['1st'])
|
self.assertIn('2nd', error.to_dict()['1st'])
|
||||||
self.assertEqual(error.to_dict()['1st']['2nd'], 'bad 2nd')
|
self.assertEqual(error.to_dict()['1st']['2nd'], 'bad 2nd')
|
||||||
|
|
||||||
# moar levels
|
# moar levels
|
||||||
@ -40,10 +40,10 @@ class ValidatorErrorTest(unittest.TestCase):
|
|||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
})}
|
})}
|
||||||
self.assertTrue('1st' in error.to_dict())
|
self.assertIn('1st', error.to_dict())
|
||||||
self.assertTrue('2nd' in error.to_dict()['1st'])
|
self.assertIn('2nd', error.to_dict()['1st'])
|
||||||
self.assertTrue('3rd' in error.to_dict()['1st']['2nd'])
|
self.assertIn('3rd', error.to_dict()['1st']['2nd'])
|
||||||
self.assertTrue('4th' in error.to_dict()['1st']['2nd']['3rd'])
|
self.assertIn('4th', error.to_dict()['1st']['2nd']['3rd'])
|
||||||
self.assertEqual(error.to_dict()['1st']['2nd']['3rd']['4th'],
|
self.assertEqual(error.to_dict()['1st']['2nd']['3rd']['4th'],
|
||||||
'Inception')
|
'Inception')
|
||||||
|
|
||||||
@ -58,7 +58,7 @@ class ValidatorErrorTest(unittest.TestCase):
|
|||||||
try:
|
try:
|
||||||
User().validate()
|
User().validate()
|
||||||
except ValidationError as e:
|
except ValidationError as e:
|
||||||
self.assertTrue("User:None" in e.message)
|
self.assertIn("User:None", e.message)
|
||||||
self.assertEqual(e.to_dict(), {
|
self.assertEqual(e.to_dict(), {
|
||||||
'username': 'Field is required',
|
'username': 'Field is required',
|
||||||
'name': 'Field is required'})
|
'name': 'Field is required'})
|
||||||
@ -68,7 +68,7 @@ class ValidatorErrorTest(unittest.TestCase):
|
|||||||
try:
|
try:
|
||||||
user.save()
|
user.save()
|
||||||
except ValidationError as e:
|
except ValidationError as e:
|
||||||
self.assertTrue("User:RossC0" in e.message)
|
self.assertIn("User:RossC0", e.message)
|
||||||
self.assertEqual(e.to_dict(), {
|
self.assertEqual(e.to_dict(), {
|
||||||
'name': 'Field is required'})
|
'name': 'Field is required'})
|
||||||
|
|
||||||
@ -116,7 +116,7 @@ class ValidatorErrorTest(unittest.TestCase):
|
|||||||
try:
|
try:
|
||||||
Doc(id="bad").validate()
|
Doc(id="bad").validate()
|
||||||
except ValidationError as e:
|
except ValidationError as e:
|
||||||
self.assertTrue("SubDoc:None" in e.message)
|
self.assertIn("SubDoc:None", e.message)
|
||||||
self.assertEqual(e.to_dict(), {
|
self.assertEqual(e.to_dict(), {
|
||||||
"e": {'val': 'OK could not be converted to int'}})
|
"e": {'val': 'OK could not be converted to int'}})
|
||||||
|
|
||||||
@ -127,14 +127,14 @@ class ValidatorErrorTest(unittest.TestCase):
|
|||||||
doc = Doc.objects.first()
|
doc = Doc.objects.first()
|
||||||
keys = doc._data.keys()
|
keys = doc._data.keys()
|
||||||
self.assertEqual(2, len(keys))
|
self.assertEqual(2, len(keys))
|
||||||
self.assertTrue('e' in keys)
|
self.assertIn('e', keys)
|
||||||
self.assertTrue('id' in keys)
|
self.assertIn('id', keys)
|
||||||
|
|
||||||
doc.e.val = "OK"
|
doc.e.val = "OK"
|
||||||
try:
|
try:
|
||||||
doc.save()
|
doc.save()
|
||||||
except ValidationError as e:
|
except ValidationError as e:
|
||||||
self.assertTrue("Doc:test" in e.message)
|
self.assertIn("Doc:test", e.message)
|
||||||
self.assertEqual(e.to_dict(), {
|
self.assertEqual(e.to_dict(), {
|
||||||
"e": {'val': 'OK could not be converted to int'}})
|
"e": {'val': 'OK could not be converted to int'}})
|
||||||
|
|
||||||
|
@ -175,7 +175,7 @@ class FieldTest(MongoDBTestCase):
|
|||||||
self.assertEqual(person.name, None)
|
self.assertEqual(person.name, None)
|
||||||
self.assertEqual(person.age, 30)
|
self.assertEqual(person.age, 30)
|
||||||
self.assertEqual(person.userid, 'test')
|
self.assertEqual(person.userid, 'test')
|
||||||
self.assertTrue(isinstance(person.created, datetime.datetime))
|
self.assertIsInstance(person.created, datetime.datetime)
|
||||||
|
|
||||||
self.assertEqual(person._data['name'], person.name)
|
self.assertEqual(person._data['name'], person.name)
|
||||||
self.assertEqual(person._data['age'], person.age)
|
self.assertEqual(person._data['age'], person.age)
|
||||||
@ -211,7 +211,7 @@ class FieldTest(MongoDBTestCase):
|
|||||||
self.assertEqual(person.name, None)
|
self.assertEqual(person.name, None)
|
||||||
self.assertEqual(person.age, 30)
|
self.assertEqual(person.age, 30)
|
||||||
self.assertEqual(person.userid, 'test')
|
self.assertEqual(person.userid, 'test')
|
||||||
self.assertTrue(isinstance(person.created, datetime.datetime))
|
self.assertIsInstance(person.created, datetime.datetime)
|
||||||
self.assertNotEqual(person.created, datetime.datetime(2014, 6, 12))
|
self.assertNotEqual(person.created, datetime.datetime(2014, 6, 12))
|
||||||
|
|
||||||
self.assertEqual(person._data['name'], person.name)
|
self.assertEqual(person._data['name'], person.name)
|
||||||
@ -1602,8 +1602,8 @@ class FieldTest(MongoDBTestCase):
|
|||||||
e.save()
|
e.save()
|
||||||
|
|
||||||
e2 = Simple.objects.get(id=e.id)
|
e2 = Simple.objects.get(id=e.id)
|
||||||
self.assertTrue(isinstance(e2.mapping[0], StringSetting))
|
self.assertIsInstance(e2.mapping[0], StringSetting)
|
||||||
self.assertTrue(isinstance(e2.mapping[1], IntegerSetting))
|
self.assertIsInstance(e2.mapping[1], IntegerSetting)
|
||||||
|
|
||||||
# Test querying
|
# Test querying
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
@ -1772,8 +1772,8 @@ class FieldTest(MongoDBTestCase):
|
|||||||
e.save()
|
e.save()
|
||||||
|
|
||||||
e2 = Simple.objects.get(id=e.id)
|
e2 = Simple.objects.get(id=e.id)
|
||||||
self.assertTrue(isinstance(e2.mapping['somestring'], StringSetting))
|
self.assertIsInstance(e2.mapping['somestring'], StringSetting)
|
||||||
self.assertTrue(isinstance(e2.mapping['someint'], IntegerSetting))
|
self.assertIsInstance(e2.mapping['someint'], IntegerSetting)
|
||||||
|
|
||||||
# Test querying
|
# Test querying
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
@ -1857,8 +1857,8 @@ class FieldTest(MongoDBTestCase):
|
|||||||
e.save()
|
e.save()
|
||||||
|
|
||||||
e2 = Extensible.objects.get(id=e.id)
|
e2 = Extensible.objects.get(id=e.id)
|
||||||
self.assertTrue(isinstance(e2.mapping['somestring'], StringSetting))
|
self.assertIsInstance(e2.mapping['somestring'], StringSetting)
|
||||||
self.assertTrue(isinstance(e2.mapping['someint'], IntegerSetting))
|
self.assertIsInstance(e2.mapping['someint'], IntegerSetting)
|
||||||
|
|
||||||
with self.assertRaises(ValidationError):
|
with self.assertRaises(ValidationError):
|
||||||
e.mapping['someint'] = 123
|
e.mapping['someint'] = 123
|
||||||
@ -2563,7 +2563,7 @@ class FieldTest(MongoDBTestCase):
|
|||||||
bm = Bookmark.objects(bookmark_object=post_1).first()
|
bm = Bookmark.objects(bookmark_object=post_1).first()
|
||||||
|
|
||||||
self.assertEqual(bm.bookmark_object, post_1)
|
self.assertEqual(bm.bookmark_object, post_1)
|
||||||
self.assertTrue(isinstance(bm.bookmark_object, Post))
|
self.assertIsInstance(bm.bookmark_object, Post)
|
||||||
|
|
||||||
bm.bookmark_object = link_1
|
bm.bookmark_object = link_1
|
||||||
bm.save()
|
bm.save()
|
||||||
@ -2571,7 +2571,7 @@ class FieldTest(MongoDBTestCase):
|
|||||||
bm = Bookmark.objects(bookmark_object=link_1).first()
|
bm = Bookmark.objects(bookmark_object=link_1).first()
|
||||||
|
|
||||||
self.assertEqual(bm.bookmark_object, link_1)
|
self.assertEqual(bm.bookmark_object, link_1)
|
||||||
self.assertTrue(isinstance(bm.bookmark_object, Link))
|
self.assertIsInstance(bm.bookmark_object, Link)
|
||||||
|
|
||||||
def test_generic_reference_list(self):
|
def test_generic_reference_list(self):
|
||||||
"""Ensure that a ListField properly dereferences generic references.
|
"""Ensure that a ListField properly dereferences generic references.
|
||||||
@ -2818,7 +2818,7 @@ class FieldTest(MongoDBTestCase):
|
|||||||
doc1 = Doc.objects.create()
|
doc1 = Doc.objects.create()
|
||||||
doc2 = Doc.objects.create(ref=doc1)
|
doc2 = Doc.objects.create(ref=doc1)
|
||||||
|
|
||||||
self.assertTrue(isinstance(doc1.pk, ObjectId))
|
self.assertIsInstance(doc1.pk, ObjectId)
|
||||||
|
|
||||||
doc = Doc.objects.get(ref=doc1.pk)
|
doc = Doc.objects.get(ref=doc1.pk)
|
||||||
self.assertEqual(doc, doc2)
|
self.assertEqual(doc, doc2)
|
||||||
@ -3421,13 +3421,13 @@ class FieldTest(MongoDBTestCase):
|
|||||||
person.save()
|
person.save()
|
||||||
|
|
||||||
person = Person.objects.first()
|
person = Person.objects.first()
|
||||||
self.assertTrue(isinstance(person.like, Car))
|
self.assertIsInstance(person.like, Car)
|
||||||
|
|
||||||
person.like = Dish(food="arroz", number=15)
|
person.like = Dish(food="arroz", number=15)
|
||||||
person.save()
|
person.save()
|
||||||
|
|
||||||
person = Person.objects.first()
|
person = Person.objects.first()
|
||||||
self.assertTrue(isinstance(person.like, Dish))
|
self.assertIsInstance(person.like, Dish)
|
||||||
|
|
||||||
def test_generic_embedded_document_choices(self):
|
def test_generic_embedded_document_choices(self):
|
||||||
"""Ensure you can limit GenericEmbeddedDocument choices."""
|
"""Ensure you can limit GenericEmbeddedDocument choices."""
|
||||||
@ -3452,7 +3452,7 @@ class FieldTest(MongoDBTestCase):
|
|||||||
person.save()
|
person.save()
|
||||||
|
|
||||||
person = Person.objects.first()
|
person = Person.objects.first()
|
||||||
self.assertTrue(isinstance(person.like, Dish))
|
self.assertIsInstance(person.like, Dish)
|
||||||
|
|
||||||
def test_generic_list_embedded_document_choices(self):
|
def test_generic_list_embedded_document_choices(self):
|
||||||
"""Ensure you can limit GenericEmbeddedDocument choices inside
|
"""Ensure you can limit GenericEmbeddedDocument choices inside
|
||||||
@ -3479,7 +3479,7 @@ class FieldTest(MongoDBTestCase):
|
|||||||
person.save()
|
person.save()
|
||||||
|
|
||||||
person = Person.objects.first()
|
person = Person.objects.first()
|
||||||
self.assertTrue(isinstance(person.likes[0], Dish))
|
self.assertIsInstance(person.likes[0], Dish)
|
||||||
|
|
||||||
def test_recursive_validation(self):
|
def test_recursive_validation(self):
|
||||||
"""Ensure that a validation result to_dict is available."""
|
"""Ensure that a validation result to_dict is available."""
|
||||||
@ -3505,18 +3505,17 @@ class FieldTest(MongoDBTestCase):
|
|||||||
except ValidationError as error:
|
except ValidationError as error:
|
||||||
# ValidationError.errors property
|
# ValidationError.errors property
|
||||||
self.assertTrue(hasattr(error, 'errors'))
|
self.assertTrue(hasattr(error, 'errors'))
|
||||||
self.assertTrue(isinstance(error.errors, dict))
|
self.assertIsInstance(error.errors, dict)
|
||||||
self.assertTrue('comments' in error.errors)
|
self.assertIn('comments', error.errors)
|
||||||
self.assertTrue(1 in error.errors['comments'])
|
self.assertIn(1, error.errors['comments'])
|
||||||
self.assertTrue(isinstance(error.errors['comments'][1]['content'],
|
self.assertIsInstance(error.errors['comments'][1]['content'], ValidationError)
|
||||||
ValidationError))
|
|
||||||
|
|
||||||
# ValidationError.schema property
|
# ValidationError.schema property
|
||||||
error_dict = error.to_dict()
|
error_dict = error.to_dict()
|
||||||
self.assertTrue(isinstance(error_dict, dict))
|
self.assertIsInstance(error_dict, dict)
|
||||||
self.assertTrue('comments' in error_dict)
|
self.assertIn('comments', error_dict)
|
||||||
self.assertTrue(1 in error_dict['comments'])
|
self.assertIn(1, error_dict['comments'])
|
||||||
self.assertTrue('content' in error_dict['comments'][1])
|
self.assertIn('content', error_dict['comments'][1])
|
||||||
self.assertEqual(error_dict['comments'][1]['content'],
|
self.assertEqual(error_dict['comments'][1]['content'],
|
||||||
u'Field is required')
|
u'Field is required')
|
||||||
|
|
||||||
@ -3632,7 +3631,7 @@ class FieldTest(MongoDBTestCase):
|
|||||||
|
|
||||||
# Passes regex validation
|
# Passes regex validation
|
||||||
user = User(email='me@example.com')
|
user = User(email='me@example.com')
|
||||||
self.assertTrue(user.validate() is None)
|
self.assertIsNone(user.validate())
|
||||||
|
|
||||||
def test_tuples_as_tuples(self):
|
def test_tuples_as_tuples(self):
|
||||||
"""Ensure that tuples remain tuples when they are inside
|
"""Ensure that tuples remain tuples when they are inside
|
||||||
@ -3659,10 +3658,10 @@ class FieldTest(MongoDBTestCase):
|
|||||||
doc.items = tuples
|
doc.items = tuples
|
||||||
doc.save()
|
doc.save()
|
||||||
x = TestDoc.objects().get()
|
x = TestDoc.objects().get()
|
||||||
self.assertTrue(x is not None)
|
self.assertIsNotNone(x)
|
||||||
self.assertTrue(len(x.items) == 1)
|
self.assertEqual(len(x.items), 1)
|
||||||
self.assertTrue(tuple(x.items[0]) in tuples)
|
self.assertIn(tuple(x.items[0]), tuples)
|
||||||
self.assertTrue(x.items[0] in tuples)
|
self.assertIn(x.items[0], tuples)
|
||||||
|
|
||||||
def test_dynamic_fields_class(self):
|
def test_dynamic_fields_class(self):
|
||||||
class Doc2(Document):
|
class Doc2(Document):
|
||||||
@ -3812,8 +3811,8 @@ class FieldTest(MongoDBTestCase):
|
|||||||
|
|
||||||
doc = TestLongFieldConsideredAsInt64(some_long=42).save()
|
doc = TestLongFieldConsideredAsInt64(some_long=42).save()
|
||||||
db = get_db()
|
db = get_db()
|
||||||
self.assertTrue(isinstance(db.test_long_field_considered_as_int64.find()[0]['some_long'], Int64))
|
self.assertIsInstance(db.test_long_field_considered_as_int64.find()[0]['some_long'], Int64)
|
||||||
self.assertTrue(isinstance(doc.some_long, six.integer_types))
|
self.assertIsInstance(doc.some_long, six.integer_types)
|
||||||
|
|
||||||
|
|
||||||
class EmbeddedDocumentListFieldTestCase(MongoDBTestCase):
|
class EmbeddedDocumentListFieldTestCase(MongoDBTestCase):
|
||||||
@ -4364,7 +4363,7 @@ class CachedReferenceFieldTest(MongoDBTestCase):
|
|||||||
|
|
||||||
ocorrence = Ocorrence.objects(animal__tag='heavy').first()
|
ocorrence = Ocorrence.objects(animal__tag='heavy').first()
|
||||||
self.assertEqual(ocorrence.person, "teste")
|
self.assertEqual(ocorrence.person, "teste")
|
||||||
self.assertTrue(isinstance(ocorrence.animal, Animal))
|
self.assertIsInstance(ocorrence.animal, Animal)
|
||||||
|
|
||||||
def test_cached_reference_field_decimal(self):
|
def test_cached_reference_field_decimal(self):
|
||||||
class PersonAuto(Document):
|
class PersonAuto(Document):
|
||||||
@ -4681,7 +4680,7 @@ class CachedReferenceFieldTest(MongoDBTestCase):
|
|||||||
animal__tag='heavy',
|
animal__tag='heavy',
|
||||||
animal__owner__tp='u').first()
|
animal__owner__tp='u').first()
|
||||||
self.assertEqual(ocorrence.person, "teste")
|
self.assertEqual(ocorrence.person, "teste")
|
||||||
self.assertTrue(isinstance(ocorrence.animal, Animal))
|
self.assertIsInstance(ocorrence.animal, Animal)
|
||||||
|
|
||||||
def test_cached_reference_embedded_list_fields(self):
|
def test_cached_reference_embedded_list_fields(self):
|
||||||
class Owner(EmbeddedDocument):
|
class Owner(EmbeddedDocument):
|
||||||
@ -4735,7 +4734,7 @@ class CachedReferenceFieldTest(MongoDBTestCase):
|
|||||||
animal__tag='heavy',
|
animal__tag='heavy',
|
||||||
animal__owner__tags='cool').first()
|
animal__owner__tags='cool').first()
|
||||||
self.assertEqual(ocorrence.person, "teste 2")
|
self.assertEqual(ocorrence.person, "teste 2")
|
||||||
self.assertTrue(isinstance(ocorrence.animal, Animal))
|
self.assertIsInstance(ocorrence.animal, Animal)
|
||||||
|
|
||||||
|
|
||||||
class LazyReferenceFieldTest(MongoDBTestCase):
|
class LazyReferenceFieldTest(MongoDBTestCase):
|
||||||
|
@ -53,7 +53,7 @@ class FileTest(MongoDBTestCase):
|
|||||||
putfile.save()
|
putfile.save()
|
||||||
|
|
||||||
result = PutFile.objects.first()
|
result = PutFile.objects.first()
|
||||||
self.assertTrue(putfile == result)
|
self.assertEqual(putfile, result)
|
||||||
self.assertEqual("%s" % result.the_file, "<GridFSProxy: hello (%s)>" % result.the_file.grid_id)
|
self.assertEqual("%s" % result.the_file, "<GridFSProxy: hello (%s)>" % result.the_file.grid_id)
|
||||||
self.assertEqual(result.the_file.read(), text)
|
self.assertEqual(result.the_file.read(), text)
|
||||||
self.assertEqual(result.the_file.content_type, content_type)
|
self.assertEqual(result.the_file.content_type, content_type)
|
||||||
@ -71,7 +71,7 @@ class FileTest(MongoDBTestCase):
|
|||||||
putfile.save()
|
putfile.save()
|
||||||
|
|
||||||
result = PutFile.objects.first()
|
result = PutFile.objects.first()
|
||||||
self.assertTrue(putfile == result)
|
self.assertEqual(putfile, result)
|
||||||
self.assertEqual(result.the_file.read(), text)
|
self.assertEqual(result.the_file.read(), text)
|
||||||
self.assertEqual(result.the_file.content_type, content_type)
|
self.assertEqual(result.the_file.content_type, content_type)
|
||||||
result.the_file.delete()
|
result.the_file.delete()
|
||||||
@ -96,7 +96,7 @@ class FileTest(MongoDBTestCase):
|
|||||||
streamfile.save()
|
streamfile.save()
|
||||||
|
|
||||||
result = StreamFile.objects.first()
|
result = StreamFile.objects.first()
|
||||||
self.assertTrue(streamfile == result)
|
self.assertEqual(streamfile, result)
|
||||||
self.assertEqual(result.the_file.read(), text + more_text)
|
self.assertEqual(result.the_file.read(), text + more_text)
|
||||||
self.assertEqual(result.the_file.content_type, content_type)
|
self.assertEqual(result.the_file.content_type, content_type)
|
||||||
result.the_file.seek(0)
|
result.the_file.seek(0)
|
||||||
@ -132,7 +132,7 @@ class FileTest(MongoDBTestCase):
|
|||||||
streamfile.save()
|
streamfile.save()
|
||||||
|
|
||||||
result = StreamFile.objects.first()
|
result = StreamFile.objects.first()
|
||||||
self.assertTrue(streamfile == result)
|
self.assertEqual(streamfile, result)
|
||||||
self.assertEqual(result.the_file.read(), text + more_text)
|
self.assertEqual(result.the_file.read(), text + more_text)
|
||||||
# self.assertEqual(result.the_file.content_type, content_type)
|
# self.assertEqual(result.the_file.content_type, content_type)
|
||||||
result.the_file.seek(0)
|
result.the_file.seek(0)
|
||||||
@ -161,7 +161,7 @@ class FileTest(MongoDBTestCase):
|
|||||||
setfile.save()
|
setfile.save()
|
||||||
|
|
||||||
result = SetFile.objects.first()
|
result = SetFile.objects.first()
|
||||||
self.assertTrue(setfile == result)
|
self.assertEqual(setfile, result)
|
||||||
self.assertEqual(result.the_file.read(), text)
|
self.assertEqual(result.the_file.read(), text)
|
||||||
|
|
||||||
# Try replacing file with new one
|
# Try replacing file with new one
|
||||||
@ -169,7 +169,7 @@ class FileTest(MongoDBTestCase):
|
|||||||
result.save()
|
result.save()
|
||||||
|
|
||||||
result = SetFile.objects.first()
|
result = SetFile.objects.first()
|
||||||
self.assertTrue(setfile == result)
|
self.assertEqual(setfile, result)
|
||||||
self.assertEqual(result.the_file.read(), more_text)
|
self.assertEqual(result.the_file.read(), more_text)
|
||||||
result.the_file.delete()
|
result.the_file.delete()
|
||||||
|
|
||||||
@ -231,8 +231,8 @@ class FileTest(MongoDBTestCase):
|
|||||||
test_file_dupe = TestFile()
|
test_file_dupe = TestFile()
|
||||||
data = test_file_dupe.the_file.read() # Should be None
|
data = test_file_dupe.the_file.read() # Should be None
|
||||||
|
|
||||||
self.assertTrue(test_file.name != test_file_dupe.name)
|
self.assertNotEqual(test_file.name, test_file_dupe.name)
|
||||||
self.assertTrue(test_file.the_file.read() != data)
|
self.assertNotEqual(test_file.the_file.read(), data)
|
||||||
|
|
||||||
TestFile.drop_collection()
|
TestFile.drop_collection()
|
||||||
|
|
||||||
@ -291,7 +291,7 @@ class FileTest(MongoDBTestCase):
|
|||||||
the_file = FileField()
|
the_file = FileField()
|
||||||
|
|
||||||
test_file = TestFile()
|
test_file = TestFile()
|
||||||
self.assertFalse(test_file.the_file in [{"test": 1}])
|
self.assertNotIn(test_file.the_file, [{"test": 1}])
|
||||||
|
|
||||||
def test_file_disk_space(self):
|
def test_file_disk_space(self):
|
||||||
""" Test disk space usage when we delete/replace a file """
|
""" Test disk space usage when we delete/replace a file """
|
||||||
|
@ -298,9 +298,9 @@ class GeoFieldTest(unittest.TestCase):
|
|||||||
polygon = PolygonField()
|
polygon = PolygonField()
|
||||||
|
|
||||||
geo_indicies = Event._geo_indices()
|
geo_indicies = Event._geo_indices()
|
||||||
self.assertTrue({'fields': [('line', '2dsphere')]} in geo_indicies)
|
self.assertIn({'fields': [('line', '2dsphere')]}, geo_indicies)
|
||||||
self.assertTrue({'fields': [('polygon', '2dsphere')]} in geo_indicies)
|
self.assertIn({'fields': [('polygon', '2dsphere')]}, geo_indicies)
|
||||||
self.assertTrue({'fields': [('point', '2dsphere')]} in geo_indicies)
|
self.assertIn({'fields': [('point', '2dsphere')]}, geo_indicies)
|
||||||
|
|
||||||
def test_indexes_2dsphere_embedded(self):
|
def test_indexes_2dsphere_embedded(self):
|
||||||
"""Ensure that indexes are created automatically for GeoPointFields.
|
"""Ensure that indexes are created automatically for GeoPointFields.
|
||||||
@ -316,9 +316,9 @@ class GeoFieldTest(unittest.TestCase):
|
|||||||
venue = EmbeddedDocumentField(Venue)
|
venue = EmbeddedDocumentField(Venue)
|
||||||
|
|
||||||
geo_indicies = Event._geo_indices()
|
geo_indicies = Event._geo_indices()
|
||||||
self.assertTrue({'fields': [('venue.line', '2dsphere')]} in geo_indicies)
|
self.assertIn({'fields': [('venue.line', '2dsphere')]}, geo_indicies)
|
||||||
self.assertTrue({'fields': [('venue.polygon', '2dsphere')]} in geo_indicies)
|
self.assertIn({'fields': [('venue.polygon', '2dsphere')]}, geo_indicies)
|
||||||
self.assertTrue({'fields': [('venue.point', '2dsphere')]} in geo_indicies)
|
self.assertIn({'fields': [('venue.point', '2dsphere')]}, geo_indicies)
|
||||||
|
|
||||||
def test_geo_indexes_recursion(self):
|
def test_geo_indexes_recursion(self):
|
||||||
|
|
||||||
@ -335,9 +335,9 @@ class GeoFieldTest(unittest.TestCase):
|
|||||||
|
|
||||||
Parent(name='Berlin').save()
|
Parent(name='Berlin').save()
|
||||||
info = Parent._get_collection().index_information()
|
info = Parent._get_collection().index_information()
|
||||||
self.assertFalse('location_2d' in info)
|
self.assertNotIn('location_2d', info)
|
||||||
info = Location._get_collection().index_information()
|
info = Location._get_collection().index_information()
|
||||||
self.assertTrue('location_2d' in info)
|
self.assertIn('location_2d', info)
|
||||||
|
|
||||||
self.assertEqual(len(Parent._geo_indices()), 0)
|
self.assertEqual(len(Parent._geo_indices()), 0)
|
||||||
self.assertEqual(len(Location._geo_indices()), 1)
|
self.assertEqual(len(Location._geo_indices()), 1)
|
||||||
|
@ -181,7 +181,7 @@ class OnlyExcludeAllTest(unittest.TestCase):
|
|||||||
employee.save()
|
employee.save()
|
||||||
|
|
||||||
obj = self.Person.objects(id=employee.id).only('age').get()
|
obj = self.Person.objects(id=employee.id).only('age').get()
|
||||||
self.assertTrue(isinstance(obj, Employee))
|
self.assertIsInstance(obj, Employee)
|
||||||
|
|
||||||
# Check field names are looked up properly
|
# Check field names are looked up properly
|
||||||
obj = Employee.objects(id=employee.id).only('salary').get()
|
obj = Employee.objects(id=employee.id).only('salary').get()
|
||||||
|
@ -95,9 +95,9 @@ class GeoQueriesTest(MongoDBTestCase):
|
|||||||
location__within_distance=point_and_distance)
|
location__within_distance=point_and_distance)
|
||||||
self.assertEqual(events.count(), 2)
|
self.assertEqual(events.count(), 2)
|
||||||
events = list(events)
|
events = list(events)
|
||||||
self.assertTrue(event2 not in events)
|
self.assertNotIn(event2, events)
|
||||||
self.assertTrue(event1 in events)
|
self.assertIn(event1, events)
|
||||||
self.assertTrue(event3 in events)
|
self.assertIn(event3, events)
|
||||||
|
|
||||||
# find events within 10 degrees of san francisco
|
# find events within 10 degrees of san francisco
|
||||||
point_and_distance = [[-122.415579, 37.7566023], 10]
|
point_and_distance = [[-122.415579, 37.7566023], 10]
|
||||||
@ -285,9 +285,9 @@ class GeoQueriesTest(MongoDBTestCase):
|
|||||||
location__geo_within_center=point_and_distance)
|
location__geo_within_center=point_and_distance)
|
||||||
self.assertEqual(events.count(), 2)
|
self.assertEqual(events.count(), 2)
|
||||||
events = list(events)
|
events = list(events)
|
||||||
self.assertTrue(event2 not in events)
|
self.assertNotIn(event2, events)
|
||||||
self.assertTrue(event1 in events)
|
self.assertIn(event1, events)
|
||||||
self.assertTrue(event3 in events)
|
self.assertIn(event3, events)
|
||||||
|
|
||||||
def _test_embedded(self, point_field_class):
|
def _test_embedded(self, point_field_class):
|
||||||
"""Helper test method ensuring given point field class works
|
"""Helper test method ensuring given point field class works
|
||||||
|
@ -59,11 +59,10 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
def test_initialisation(self):
|
def test_initialisation(self):
|
||||||
"""Ensure that a QuerySet is correctly initialised by QuerySetManager.
|
"""Ensure that a QuerySet is correctly initialised by QuerySetManager.
|
||||||
"""
|
"""
|
||||||
self.assertTrue(isinstance(self.Person.objects, QuerySet))
|
self.assertIsInstance(self.Person.objects, QuerySet)
|
||||||
self.assertEqual(self.Person.objects._collection.name,
|
self.assertEqual(self.Person.objects._collection.name,
|
||||||
self.Person._get_collection_name())
|
self.Person._get_collection_name())
|
||||||
self.assertTrue(isinstance(self.Person.objects._collection,
|
self.assertIsInstance(self.Person.objects._collection, pymongo.collection.Collection)
|
||||||
pymongo.collection.Collection))
|
|
||||||
|
|
||||||
def test_cannot_perform_joins_references(self):
|
def test_cannot_perform_joins_references(self):
|
||||||
|
|
||||||
@ -89,8 +88,8 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
self.assertEqual(people.count(), 2)
|
self.assertEqual(people.count(), 2)
|
||||||
results = list(people)
|
results = list(people)
|
||||||
|
|
||||||
self.assertTrue(isinstance(results[0], self.Person))
|
self.assertIsInstance(results[0], self.Person)
|
||||||
self.assertTrue(isinstance(results[0].id, (ObjectId, str, unicode)))
|
self.assertIsInstance(results[0].id, (ObjectId, str, unicode))
|
||||||
|
|
||||||
self.assertEqual(results[0], user_a)
|
self.assertEqual(results[0], user_a)
|
||||||
self.assertEqual(results[0].name, 'User A')
|
self.assertEqual(results[0].name, 'User A')
|
||||||
@ -126,6 +125,11 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
self.assertEqual(len(people2), 1)
|
self.assertEqual(len(people2), 1)
|
||||||
self.assertEqual(people2[0], user_a)
|
self.assertEqual(people2[0], user_a)
|
||||||
|
|
||||||
|
# Test limit with 0 as parameter
|
||||||
|
people = self.Person.objects.limit(0)
|
||||||
|
self.assertEqual(people.count(with_limit_and_skip=True), 2)
|
||||||
|
self.assertEqual(len(people), 2)
|
||||||
|
|
||||||
# Test chaining of only after limit
|
# Test chaining of only after limit
|
||||||
person = self.Person.objects().limit(1).only('name').first()
|
person = self.Person.objects().limit(1).only('name').first()
|
||||||
self.assertEqual(person, user_a)
|
self.assertEqual(person, user_a)
|
||||||
@ -225,7 +229,7 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
|
|
||||||
# Retrieve the first person from the database
|
# Retrieve the first person from the database
|
||||||
person = self.Person.objects.first()
|
person = self.Person.objects.first()
|
||||||
self.assertTrue(isinstance(person, self.Person))
|
self.assertIsInstance(person, self.Person)
|
||||||
self.assertEqual(person.name, "User A")
|
self.assertEqual(person.name, "User A")
|
||||||
self.assertEqual(person.age, 20)
|
self.assertEqual(person.age, 20)
|
||||||
|
|
||||||
@ -672,13 +676,13 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
|
|
||||||
result = self.Person(name="Bob", age=25).update(
|
result = self.Person(name="Bob", age=25).update(
|
||||||
upsert=True, full_result=True)
|
upsert=True, full_result=True)
|
||||||
self.assertTrue(isinstance(result, UpdateResult))
|
self.assertIsInstance(result, UpdateResult)
|
||||||
self.assertTrue("upserted" in result.raw_result)
|
self.assertIn("upserted", result.raw_result)
|
||||||
self.assertFalse(result.raw_result["updatedExisting"])
|
self.assertFalse(result.raw_result["updatedExisting"])
|
||||||
|
|
||||||
bob = self.Person.objects.first()
|
bob = self.Person.objects.first()
|
||||||
result = bob.update(set__age=30, full_result=True)
|
result = bob.update(set__age=30, full_result=True)
|
||||||
self.assertTrue(isinstance(result, UpdateResult))
|
self.assertIsInstance(result, UpdateResult)
|
||||||
self.assertTrue(result.raw_result["updatedExisting"])
|
self.assertTrue(result.raw_result["updatedExisting"])
|
||||||
|
|
||||||
self.Person(name="Bob", age=20).save()
|
self.Person(name="Bob", age=20).save()
|
||||||
@ -994,7 +998,7 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
|
|
||||||
# Retrieve the first person from the database
|
# Retrieve the first person from the database
|
||||||
person = self.Person.objects.slave_okay(True).first()
|
person = self.Person.objects.slave_okay(True).first()
|
||||||
self.assertTrue(isinstance(person, self.Person))
|
self.assertIsInstance(person, self.Person)
|
||||||
self.assertEqual(person.name, "User A")
|
self.assertEqual(person.name, "User A")
|
||||||
self.assertEqual(person.age, 20)
|
self.assertEqual(person.age, 20)
|
||||||
|
|
||||||
@ -1061,10 +1065,10 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
self.assertEqual(docs.count(), 1000)
|
self.assertEqual(docs.count(), 1000)
|
||||||
|
|
||||||
docs_string = "%s" % docs
|
docs_string = "%s" % docs
|
||||||
self.assertTrue("Doc: 0" in docs_string)
|
self.assertIn("Doc: 0", docs_string)
|
||||||
|
|
||||||
self.assertEqual(docs.count(), 1000)
|
self.assertEqual(docs.count(), 1000)
|
||||||
self.assertTrue('(remaining elements truncated)' in "%s" % docs)
|
self.assertIn('(remaining elements truncated)', "%s" % docs)
|
||||||
|
|
||||||
# Limit and skip
|
# Limit and skip
|
||||||
docs = docs[1:4]
|
docs = docs[1:4]
|
||||||
@ -1281,7 +1285,7 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
with db_ops_tracker() as q:
|
with db_ops_tracker() as q:
|
||||||
BlogPost.objects.filter(title='whatever').order_by().first()
|
BlogPost.objects.filter(title='whatever').order_by().first()
|
||||||
self.assertEqual(len(q.get_ops()), 1)
|
self.assertEqual(len(q.get_ops()), 1)
|
||||||
self.assertFalse('$orderby' in q.get_ops()[0]['query'])
|
self.assertNotIn('$orderby', q.get_ops()[0]['query'])
|
||||||
|
|
||||||
# calling an explicit order_by should use a specified sort
|
# calling an explicit order_by should use a specified sort
|
||||||
with db_ops_tracker() as q:
|
with db_ops_tracker() as q:
|
||||||
@ -1297,7 +1301,7 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
qs = BlogPost.objects.filter(title='whatever').order_by('published_date')
|
qs = BlogPost.objects.filter(title='whatever').order_by('published_date')
|
||||||
qs.order_by().first()
|
qs.order_by().first()
|
||||||
self.assertEqual(len(q.get_ops()), 1)
|
self.assertEqual(len(q.get_ops()), 1)
|
||||||
self.assertFalse('$orderby' in q.get_ops()[0]['query'])
|
self.assertNotIn('$orderby', q.get_ops()[0]['query'])
|
||||||
|
|
||||||
def test_no_ordering_for_get(self):
|
def test_no_ordering_for_get(self):
|
||||||
""" Ensure that Doc.objects.get doesn't use any ordering.
|
""" Ensure that Doc.objects.get doesn't use any ordering.
|
||||||
@ -1316,13 +1320,13 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
with db_ops_tracker() as q:
|
with db_ops_tracker() as q:
|
||||||
BlogPost.objects.get(title='whatever')
|
BlogPost.objects.get(title='whatever')
|
||||||
self.assertEqual(len(q.get_ops()), 1)
|
self.assertEqual(len(q.get_ops()), 1)
|
||||||
self.assertFalse('$orderby' in q.get_ops()[0]['query'])
|
self.assertNotIn('$orderby', q.get_ops()[0]['query'])
|
||||||
|
|
||||||
# Ordering should be ignored for .get even if we set it explicitly
|
# Ordering should be ignored for .get even if we set it explicitly
|
||||||
with db_ops_tracker() as q:
|
with db_ops_tracker() as q:
|
||||||
BlogPost.objects.order_by('-title').get(title='whatever')
|
BlogPost.objects.order_by('-title').get(title='whatever')
|
||||||
self.assertEqual(len(q.get_ops()), 1)
|
self.assertEqual(len(q.get_ops()), 1)
|
||||||
self.assertFalse('$orderby' in q.get_ops()[0]['query'])
|
self.assertNotIn('$orderby', q.get_ops()[0]['query'])
|
||||||
|
|
||||||
def test_find_embedded(self):
|
def test_find_embedded(self):
|
||||||
"""Ensure that an embedded document is properly returned from
|
"""Ensure that an embedded document is properly returned from
|
||||||
@ -1344,15 +1348,15 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
)
|
)
|
||||||
|
|
||||||
result = BlogPost.objects.first()
|
result = BlogPost.objects.first()
|
||||||
self.assertTrue(isinstance(result.author, User))
|
self.assertIsInstance(result.author, User)
|
||||||
self.assertEqual(result.author.name, 'Test User')
|
self.assertEqual(result.author.name, 'Test User')
|
||||||
|
|
||||||
result = BlogPost.objects.get(author__name=user.name)
|
result = BlogPost.objects.get(author__name=user.name)
|
||||||
self.assertTrue(isinstance(result.author, User))
|
self.assertIsInstance(result.author, User)
|
||||||
self.assertEqual(result.author.name, 'Test User')
|
self.assertEqual(result.author.name, 'Test User')
|
||||||
|
|
||||||
result = BlogPost.objects.get(author={'name': user.name})
|
result = BlogPost.objects.get(author={'name': user.name})
|
||||||
self.assertTrue(isinstance(result.author, User))
|
self.assertIsInstance(result.author, User)
|
||||||
self.assertEqual(result.author.name, 'Test User')
|
self.assertEqual(result.author.name, 'Test User')
|
||||||
|
|
||||||
# Fails, since the string is not a type that is able to represent the
|
# Fails, since the string is not a type that is able to represent the
|
||||||
@ -1470,7 +1474,7 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
code_chunks = ['doc["cmnts"];', 'doc["doc-name"],',
|
code_chunks = ['doc["cmnts"];', 'doc["doc-name"],',
|
||||||
'doc["cmnts"][i]["body"]']
|
'doc["cmnts"][i]["body"]']
|
||||||
for chunk in code_chunks:
|
for chunk in code_chunks:
|
||||||
self.assertTrue(chunk in sub_code)
|
self.assertIn(chunk, sub_code)
|
||||||
|
|
||||||
results = BlogPost.objects.exec_js(code)
|
results = BlogPost.objects.exec_js(code)
|
||||||
expected_results = [
|
expected_results = [
|
||||||
@ -1937,11 +1941,12 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
# ListField operator
|
# ListField operator
|
||||||
BlogPost.objects.update(push__tags='mongo')
|
BlogPost.objects.update(push__tags='mongo')
|
||||||
post.reload()
|
post.reload()
|
||||||
self.assertTrue('mongo' in post.tags)
|
self.assertIn('mongo', post.tags)
|
||||||
|
|
||||||
BlogPost.objects.update_one(push_all__tags=['db', 'nosql'])
|
BlogPost.objects.update_one(push_all__tags=['db', 'nosql'])
|
||||||
post.reload()
|
post.reload()
|
||||||
self.assertTrue('db' in post.tags and 'nosql' in post.tags)
|
self.assertIn('db', post.tags)
|
||||||
|
self.assertIn('nosql', post.tags)
|
||||||
|
|
||||||
tags = post.tags[:-1]
|
tags = post.tags[:-1]
|
||||||
BlogPost.objects.update(pop__tags=1)
|
BlogPost.objects.update(pop__tags=1)
|
||||||
@ -3274,8 +3279,8 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
|
|
||||||
News.drop_collection()
|
News.drop_collection()
|
||||||
info = News.objects._collection.index_information()
|
info = News.objects._collection.index_information()
|
||||||
self.assertTrue('title_text_content_text' in info)
|
self.assertIn('title_text_content_text', info)
|
||||||
self.assertTrue('textIndexVersion' in info['title_text_content_text'])
|
self.assertIn('textIndexVersion', info['title_text_content_text'])
|
||||||
|
|
||||||
News(title="Neymar quebrou a vertebra",
|
News(title="Neymar quebrou a vertebra",
|
||||||
content="O Brasil sofre com a perda de Neymar").save()
|
content="O Brasil sofre com a perda de Neymar").save()
|
||||||
@ -3309,15 +3314,15 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
'$search': 'dilma', '$language': 'pt'},
|
'$search': 'dilma', '$language': 'pt'},
|
||||||
'is_active': False})
|
'is_active': False})
|
||||||
|
|
||||||
self.assertEqual(new.is_active, False)
|
self.assertFalse(new.is_active)
|
||||||
self.assertTrue('dilma' in new.content)
|
self.assertIn('dilma', new.content)
|
||||||
self.assertTrue('planejamento' in new.title)
|
self.assertIn('planejamento', new.title)
|
||||||
|
|
||||||
query = News.objects.search_text("candidata")
|
query = News.objects.search_text("candidata")
|
||||||
self.assertEqual(query._search_text, "candidata")
|
self.assertEqual(query._search_text, "candidata")
|
||||||
new = query.first()
|
new = query.first()
|
||||||
|
|
||||||
self.assertTrue(isinstance(new.get_text_score(), float))
|
self.assertIsInstance(new.get_text_score(), float)
|
||||||
|
|
||||||
# count
|
# count
|
||||||
query = News.objects.search_text('brasil').order_by('$text_score')
|
query = News.objects.search_text('brasil').order_by('$text_score')
|
||||||
@ -3612,7 +3617,7 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
Group.objects(id=group.id).update(set__members=[user1, user2])
|
Group.objects(id=group.id).update(set__members=[user1, user2])
|
||||||
group.reload()
|
group.reload()
|
||||||
|
|
||||||
self.assertTrue(len(group.members) == 2)
|
self.assertEqual(len(group.members), 2)
|
||||||
self.assertEqual(group.members[0].name, user1.name)
|
self.assertEqual(group.members[0].name, user1.name)
|
||||||
self.assertEqual(group.members[1].name, user2.name)
|
self.assertEqual(group.members[1].name, user2.name)
|
||||||
|
|
||||||
@ -3643,13 +3648,13 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
|
|
||||||
self.assertEqual(len(objects), 3)
|
self.assertEqual(len(objects), 3)
|
||||||
|
|
||||||
self.assertTrue(post_1.id in objects)
|
self.assertIn(post_1.id, objects)
|
||||||
self.assertTrue(post_2.id in objects)
|
self.assertIn(post_2.id, objects)
|
||||||
self.assertTrue(post_5.id in objects)
|
self.assertIn(post_5.id, objects)
|
||||||
|
|
||||||
self.assertTrue(objects[post_1.id].title == post_1.title)
|
self.assertEqual(objects[post_1.id].title, post_1.title)
|
||||||
self.assertTrue(objects[post_2.id].title == post_2.title)
|
self.assertEqual(objects[post_2.id].title, post_2.title)
|
||||||
self.assertTrue(objects[post_5.id].title == post_5.title)
|
self.assertEqual(objects[post_5.id].title, post_5.title)
|
||||||
|
|
||||||
BlogPost.drop_collection()
|
BlogPost.drop_collection()
|
||||||
|
|
||||||
@ -3669,7 +3674,7 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
|
|
||||||
Post.drop_collection()
|
Post.drop_collection()
|
||||||
|
|
||||||
self.assertTrue(isinstance(Post.objects, CustomQuerySet))
|
self.assertIsInstance(Post.objects, CustomQuerySet)
|
||||||
self.assertFalse(Post.objects.not_empty())
|
self.assertFalse(Post.objects.not_empty())
|
||||||
|
|
||||||
Post().save()
|
Post().save()
|
||||||
@ -3694,7 +3699,7 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
|
|
||||||
Post.drop_collection()
|
Post.drop_collection()
|
||||||
|
|
||||||
self.assertTrue(isinstance(Post.objects, CustomQuerySet))
|
self.assertIsInstance(Post.objects, CustomQuerySet)
|
||||||
self.assertFalse(Post.objects.not_empty())
|
self.assertFalse(Post.objects.not_empty())
|
||||||
|
|
||||||
Post().save()
|
Post().save()
|
||||||
@ -3741,7 +3746,7 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
Post.drop_collection()
|
Post.drop_collection()
|
||||||
self.assertTrue(isinstance(Post.objects, CustomQuerySet))
|
self.assertIsInstance(Post.objects, CustomQuerySet)
|
||||||
self.assertFalse(Post.objects.not_empty())
|
self.assertFalse(Post.objects.not_empty())
|
||||||
|
|
||||||
Post().save()
|
Post().save()
|
||||||
@ -3769,7 +3774,7 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
Post.drop_collection()
|
Post.drop_collection()
|
||||||
self.assertTrue(isinstance(Post.objects, CustomQuerySet))
|
self.assertIsInstance(Post.objects, CustomQuerySet)
|
||||||
self.assertFalse(Post.objects.not_empty())
|
self.assertFalse(Post.objects.not_empty())
|
||||||
|
|
||||||
Post().save()
|
Post().save()
|
||||||
@ -3860,17 +3865,17 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
|
|
||||||
test = Number.objects
|
test = Number.objects
|
||||||
test2 = test.clone()
|
test2 = test.clone()
|
||||||
self.assertFalse(test == test2)
|
self.assertNotEqual(test, test2)
|
||||||
self.assertEqual(test.count(), test2.count())
|
self.assertEqual(test.count(), test2.count())
|
||||||
|
|
||||||
test = test.filter(n__gt=11)
|
test = test.filter(n__gt=11)
|
||||||
test2 = test.clone()
|
test2 = test.clone()
|
||||||
self.assertFalse(test == test2)
|
self.assertNotEqual(test, test2)
|
||||||
self.assertEqual(test.count(), test2.count())
|
self.assertEqual(test.count(), test2.count())
|
||||||
|
|
||||||
test = test.limit(10)
|
test = test.limit(10)
|
||||||
test2 = test.clone()
|
test2 = test.clone()
|
||||||
self.assertFalse(test == test2)
|
self.assertNotEqual(test, test2)
|
||||||
self.assertEqual(test.count(), test2.count())
|
self.assertEqual(test.count(), test2.count())
|
||||||
|
|
||||||
Number.drop_collection()
|
Number.drop_collection()
|
||||||
@ -3960,7 +3965,7 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
value.get('unique', False),
|
value.get('unique', False),
|
||||||
value.get('sparse', False))
|
value.get('sparse', False))
|
||||||
for key, value in info.iteritems()]
|
for key, value in info.iteritems()]
|
||||||
self.assertTrue(([('_cls', 1), ('message', 1)], False, False) in info)
|
self.assertIn(([('_cls', 1), ('message', 1)], False, False), info)
|
||||||
|
|
||||||
def test_where(self):
|
def test_where(self):
|
||||||
"""Ensure that where clauses work.
|
"""Ensure that where clauses work.
|
||||||
@ -3984,13 +3989,13 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
'this["fielda"] >= this["fieldb"]', query._where_clause)
|
'this["fielda"] >= this["fieldb"]', query._where_clause)
|
||||||
results = list(query)
|
results = list(query)
|
||||||
self.assertEqual(2, len(results))
|
self.assertEqual(2, len(results))
|
||||||
self.assertTrue(a in results)
|
self.assertIn(a, results)
|
||||||
self.assertTrue(c in results)
|
self.assertIn(c, results)
|
||||||
|
|
||||||
query = IntPair.objects.where('this[~fielda] == this[~fieldb]')
|
query = IntPair.objects.where('this[~fielda] == this[~fieldb]')
|
||||||
results = list(query)
|
results = list(query)
|
||||||
self.assertEqual(1, len(results))
|
self.assertEqual(1, len(results))
|
||||||
self.assertTrue(a in results)
|
self.assertIn(a, results)
|
||||||
|
|
||||||
query = IntPair.objects.where(
|
query = IntPair.objects.where(
|
||||||
'function() { return this[~fielda] >= this[~fieldb] }')
|
'function() { return this[~fielda] >= this[~fieldb] }')
|
||||||
@ -3998,8 +4003,8 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
'function() { return this["fielda"] >= this["fieldb"] }', query._where_clause)
|
'function() { return this["fielda"] >= this["fieldb"] }', query._where_clause)
|
||||||
results = list(query)
|
results = list(query)
|
||||||
self.assertEqual(2, len(results))
|
self.assertEqual(2, len(results))
|
||||||
self.assertTrue(a in results)
|
self.assertIn(a, results)
|
||||||
self.assertTrue(c in results)
|
self.assertIn(c, results)
|
||||||
|
|
||||||
with self.assertRaises(TypeError):
|
with self.assertRaises(TypeError):
|
||||||
list(IntPair.objects.where(fielda__gte=3))
|
list(IntPair.objects.where(fielda__gte=3))
|
||||||
@ -4381,7 +4386,7 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
|
|
||||||
Test.drop_collection()
|
Test.drop_collection()
|
||||||
Test.objects(test='foo').update_one(upsert=True, set__test='foo')
|
Test.objects(test='foo').update_one(upsert=True, set__test='foo')
|
||||||
self.assertFalse('_cls' in Test._collection.find_one())
|
self.assertNotIn('_cls', Test._collection.find_one())
|
||||||
|
|
||||||
class Test(Document):
|
class Test(Document):
|
||||||
meta = {'allow_inheritance': True}
|
meta = {'allow_inheritance': True}
|
||||||
@ -4390,7 +4395,7 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
Test.drop_collection()
|
Test.drop_collection()
|
||||||
|
|
||||||
Test.objects(test='foo').update_one(upsert=True, set__test='foo')
|
Test.objects(test='foo').update_one(upsert=True, set__test='foo')
|
||||||
self.assertTrue('_cls' in Test._collection.find_one())
|
self.assertIn('_cls', Test._collection.find_one())
|
||||||
|
|
||||||
def test_update_upsert_looks_like_a_digit(self):
|
def test_update_upsert_looks_like_a_digit(self):
|
||||||
class MyDoc(DynamicDocument):
|
class MyDoc(DynamicDocument):
|
||||||
@ -4602,8 +4607,8 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
|
|
||||||
users = User.objects.only('name', 'price').as_pymongo()
|
users = User.objects.only('name', 'price').as_pymongo()
|
||||||
results = list(users)
|
results = list(users)
|
||||||
self.assertTrue(isinstance(results[0], dict))
|
self.assertIsInstance(results[0], dict)
|
||||||
self.assertTrue(isinstance(results[1], dict))
|
self.assertIsInstance(results[1], dict)
|
||||||
self.assertEqual(results[0]['name'], 'Bob Dole')
|
self.assertEqual(results[0]['name'], 'Bob Dole')
|
||||||
self.assertEqual(results[0]['price'], 1.11)
|
self.assertEqual(results[0]['price'], 1.11)
|
||||||
self.assertEqual(results[1]['name'], 'Barack Obama')
|
self.assertEqual(results[1]['name'], 'Barack Obama')
|
||||||
@ -4611,8 +4616,8 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
|
|
||||||
users = User.objects.only('name', 'last_login').as_pymongo()
|
users = User.objects.only('name', 'last_login').as_pymongo()
|
||||||
results = list(users)
|
results = list(users)
|
||||||
self.assertTrue(isinstance(results[0], dict))
|
self.assertIsInstance(results[0], dict)
|
||||||
self.assertTrue(isinstance(results[1], dict))
|
self.assertIsInstance(results[1], dict)
|
||||||
self.assertEqual(results[0], {
|
self.assertEqual(results[0], {
|
||||||
'name': 'Bob Dole'
|
'name': 'Bob Dole'
|
||||||
})
|
})
|
||||||
@ -4669,12 +4674,10 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
User(name="Bob Dole", organization=whitehouse).save()
|
User(name="Bob Dole", organization=whitehouse).save()
|
||||||
|
|
||||||
qs = User.objects()
|
qs = User.objects()
|
||||||
self.assertTrue(isinstance(qs.first().organization, Organization))
|
self.assertIsInstance(qs.first().organization, Organization)
|
||||||
self.assertFalse(isinstance(qs.no_dereference().first().organization,
|
self.assertNotIsInstance(qs.no_dereference().first().organization, Organization)
|
||||||
Organization))
|
self.assertNotIsInstance(qs.no_dereference().get().organization, Organization)
|
||||||
self.assertFalse(isinstance(qs.no_dereference().get().organization,
|
self.assertIsInstance(qs.first().organization, Organization)
|
||||||
Organization))
|
|
||||||
self.assertTrue(isinstance(qs.first().organization, Organization))
|
|
||||||
|
|
||||||
def test_no_dereference_embedded_doc(self):
|
def test_no_dereference_embedded_doc(self):
|
||||||
|
|
||||||
@ -4707,9 +4710,9 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
|
|
||||||
result = Organization.objects().no_dereference().first()
|
result = Organization.objects().no_dereference().first()
|
||||||
|
|
||||||
self.assertTrue(isinstance(result.admin[0], (DBRef, ObjectId)))
|
self.assertIsInstance(result.admin[0], (DBRef, ObjectId))
|
||||||
self.assertTrue(isinstance(result.member.user, (DBRef, ObjectId)))
|
self.assertIsInstance(result.member.user, (DBRef, ObjectId))
|
||||||
self.assertTrue(isinstance(result.members[0].user, (DBRef, ObjectId)))
|
self.assertIsInstance(result.members[0].user, (DBRef, ObjectId))
|
||||||
|
|
||||||
def test_cached_queryset(self):
|
def test_cached_queryset(self):
|
||||||
class Person(Document):
|
class Person(Document):
|
||||||
@ -4750,18 +4753,27 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
for i in range(100):
|
for i in range(100):
|
||||||
Person(name="No: %s" % i).save()
|
Person(name="No: %s" % i).save()
|
||||||
|
|
||||||
with query_counter() as q:
|
with query_counter() as q:
|
||||||
self.assertEqual(q, 0)
|
try:
|
||||||
people = Person.objects.no_cache()
|
self.assertEqual(q, 0)
|
||||||
|
people = Person.objects.no_cache()
|
||||||
|
|
||||||
[x for x in people]
|
[x for x in people]
|
||||||
self.assertEqual(q, 1)
|
self.assertEqual(q, 1)
|
||||||
|
|
||||||
list(people)
|
list(people)
|
||||||
self.assertEqual(q, 2)
|
self.assertEqual(q, 2)
|
||||||
|
|
||||||
|
people.count()
|
||||||
|
self.assertEqual(q, 3)
|
||||||
|
except AssertionError as exc:
|
||||||
|
db = get_db()
|
||||||
|
msg = ''
|
||||||
|
for q in list(db.system.profile.find())[-50:]:
|
||||||
|
msg += str([q['ts'], q['ns'], q.get('query'), q['op']])+'\n'
|
||||||
|
msg += str(q)
|
||||||
|
raise AssertionError(str(exc) + '\n'+msg)
|
||||||
|
|
||||||
people.count()
|
|
||||||
self.assertEqual(q, 3)
|
|
||||||
|
|
||||||
def test_cache_not_cloned(self):
|
def test_cache_not_cloned(self):
|
||||||
|
|
||||||
@ -5052,7 +5064,7 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
op = q.db.system.profile.find({"ns":
|
op = q.db.system.profile.find({"ns":
|
||||||
{"$ne": "%s.system.indexes" % q.db.name}})[0]
|
{"$ne": "%s.system.indexes" % q.db.name}})[0]
|
||||||
|
|
||||||
self.assertFalse('$orderby' in op['query'],
|
self.assertNotIn('$orderby', op['query'],
|
||||||
'BaseQuerySet cannot use orderby in if stmt')
|
'BaseQuerySet cannot use orderby in if stmt')
|
||||||
|
|
||||||
with query_counter() as p:
|
with query_counter() as p:
|
||||||
@ -5063,8 +5075,7 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
op = p.db.system.profile.find({"ns":
|
op = p.db.system.profile.find({"ns":
|
||||||
{"$ne": "%s.system.indexes" % q.db.name}})[0]
|
{"$ne": "%s.system.indexes" % q.db.name}})[0]
|
||||||
|
|
||||||
self.assertTrue('$orderby' in op['query'],
|
self.assertIn('$orderby', op['query'], 'BaseQuerySet cannot remove orderby in for loop')
|
||||||
'BaseQuerySet cannot remove orderby in for loop')
|
|
||||||
|
|
||||||
def test_bool_with_ordering_from_meta_dict(self):
|
def test_bool_with_ordering_from_meta_dict(self):
|
||||||
|
|
||||||
@ -5088,7 +5099,7 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
op = q.db.system.profile.find({"ns":
|
op = q.db.system.profile.find({"ns":
|
||||||
{"$ne": "%s.system.indexes" % q.db.name}})[0]
|
{"$ne": "%s.system.indexes" % q.db.name}})[0]
|
||||||
|
|
||||||
self.assertFalse('$orderby' in op['query'],
|
self.assertNotIn('$orderby', op['query'],
|
||||||
'BaseQuerySet must remove orderby from meta in boolen test')
|
'BaseQuerySet must remove orderby from meta in boolen test')
|
||||||
|
|
||||||
self.assertEqual(Person.objects.first().name, 'A')
|
self.assertEqual(Person.objects.first().name, 'A')
|
||||||
@ -5266,6 +5277,16 @@ class QuerySetTest(unittest.TestCase):
|
|||||||
# in a way we'd expect) should raise a TypeError, too
|
# in a way we'd expect) should raise a TypeError, too
|
||||||
self.assertRaises(TypeError, BlogPost.objects(authors__in=author).count)
|
self.assertRaises(TypeError, BlogPost.objects(authors__in=author).count)
|
||||||
|
|
||||||
|
def test_create_count(self):
|
||||||
|
self.Person.drop_collection()
|
||||||
|
self.Person.objects.create(name="Foo")
|
||||||
|
self.Person.objects.create(name="Bar")
|
||||||
|
self.Person.objects.create(name="Baz")
|
||||||
|
self.assertEqual(self.Person.objects.count(with_limit_and_skip=True), 3)
|
||||||
|
|
||||||
|
newPerson = self.Person.objects.create(name="Foo_1")
|
||||||
|
self.assertEqual(self.Person.objects.count(with_limit_and_skip=True), 4)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
@ -48,14 +48,14 @@ class TransformTest(unittest.TestCase):
|
|||||||
|
|
||||||
for k, v in (("set", "$set"), ("set_on_insert", "$setOnInsert"), ("push", "$push")):
|
for k, v in (("set", "$set"), ("set_on_insert", "$setOnInsert"), ("push", "$push")):
|
||||||
update = transform.update(DicDoc, **{"%s__dictField__test" % k: doc})
|
update = transform.update(DicDoc, **{"%s__dictField__test" % k: doc})
|
||||||
self.assertTrue(isinstance(update[v]["dictField.test"], dict))
|
self.assertIsInstance(update[v]["dictField.test"], dict)
|
||||||
|
|
||||||
# Update special cases
|
# Update special cases
|
||||||
update = transform.update(DicDoc, unset__dictField__test=doc)
|
update = transform.update(DicDoc, unset__dictField__test=doc)
|
||||||
self.assertEqual(update["$unset"]["dictField.test"], 1)
|
self.assertEqual(update["$unset"]["dictField.test"], 1)
|
||||||
|
|
||||||
update = transform.update(DicDoc, pull__dictField__test=doc)
|
update = transform.update(DicDoc, pull__dictField__test=doc)
|
||||||
self.assertTrue(isinstance(update["$pull"]["dictField"]["test"], dict))
|
self.assertIsInstance(update["$pull"]["dictField"]["test"], dict)
|
||||||
|
|
||||||
update = transform.update(LisDoc, pull__foo__in=['a'])
|
update = transform.update(LisDoc, pull__foo__in=['a'])
|
||||||
self.assertEqual(update, {'$pull': {'foo': {'$in': ['a']}}})
|
self.assertEqual(update, {'$pull': {'foo': {'$in': ['a']}}})
|
||||||
@ -88,17 +88,15 @@ class TransformTest(unittest.TestCase):
|
|||||||
post = BlogPost(**data)
|
post = BlogPost(**data)
|
||||||
post.save()
|
post.save()
|
||||||
|
|
||||||
self.assertTrue('postTitle' in
|
self.assertIn('postTitle', BlogPost.objects(title=data['title'])._query)
|
||||||
BlogPost.objects(title=data['title'])._query)
|
|
||||||
self.assertFalse('title' in
|
self.assertFalse('title' in
|
||||||
BlogPost.objects(title=data['title'])._query)
|
BlogPost.objects(title=data['title'])._query)
|
||||||
self.assertEqual(BlogPost.objects(title=data['title']).count(), 1)
|
self.assertEqual(BlogPost.objects(title=data['title']).count(), 1)
|
||||||
|
|
||||||
self.assertTrue('_id' in BlogPost.objects(pk=post.id)._query)
|
self.assertIn('_id', BlogPost.objects(pk=post.id)._query)
|
||||||
self.assertEqual(BlogPost.objects(pk=post.id).count(), 1)
|
self.assertEqual(BlogPost.objects(pk=post.id).count(), 1)
|
||||||
|
|
||||||
self.assertTrue('postComments.commentContent' in
|
self.assertIn('postComments.commentContent', BlogPost.objects(comments__content='test')._query)
|
||||||
BlogPost.objects(comments__content='test')._query)
|
|
||||||
self.assertEqual(BlogPost.objects(comments__content='test').count(), 1)
|
self.assertEqual(BlogPost.objects(comments__content='test').count(), 1)
|
||||||
|
|
||||||
BlogPost.drop_collection()
|
BlogPost.drop_collection()
|
||||||
@ -116,8 +114,8 @@ class TransformTest(unittest.TestCase):
|
|||||||
post = BlogPost(**data)
|
post = BlogPost(**data)
|
||||||
post.save()
|
post.save()
|
||||||
|
|
||||||
self.assertTrue('_id' in BlogPost.objects(pk=data['title'])._query)
|
self.assertIn('_id', BlogPost.objects(pk=data['title'])._query)
|
||||||
self.assertTrue('_id' in BlogPost.objects(title=data['title'])._query)
|
self.assertIn('_id', BlogPost.objects(title=data['title'])._query)
|
||||||
self.assertEqual(BlogPost.objects(pk=data['title']).count(), 1)
|
self.assertEqual(BlogPost.objects(pk=data['title']).count(), 1)
|
||||||
|
|
||||||
BlogPost.drop_collection()
|
BlogPost.drop_collection()
|
||||||
|
@ -196,7 +196,7 @@ class QTest(unittest.TestCase):
|
|||||||
|
|
||||||
test2 = test.clone()
|
test2 = test.clone()
|
||||||
self.assertEqual(test2.count(), 3)
|
self.assertEqual(test2.count(), 3)
|
||||||
self.assertFalse(test2 == test)
|
self.assertNotEqual(test2, test)
|
||||||
|
|
||||||
test3 = test2.filter(x=6)
|
test3 = test2.filter(x=6)
|
||||||
self.assertEqual(test3.count(), 1)
|
self.assertEqual(test3.count(), 1)
|
||||||
|
@ -39,15 +39,15 @@ class ConnectionTest(unittest.TestCase):
|
|||||||
connect('mongoenginetest')
|
connect('mongoenginetest')
|
||||||
|
|
||||||
conn = get_connection()
|
conn = get_connection()
|
||||||
self.assertTrue(isinstance(conn, pymongo.mongo_client.MongoClient))
|
self.assertIsInstance(conn, pymongo.mongo_client.MongoClient)
|
||||||
|
|
||||||
db = get_db()
|
db = get_db()
|
||||||
self.assertTrue(isinstance(db, pymongo.database.Database))
|
self.assertIsInstance(db, pymongo.database.Database)
|
||||||
self.assertEqual(db.name, 'mongoenginetest')
|
self.assertEqual(db.name, 'mongoenginetest')
|
||||||
|
|
||||||
connect('mongoenginetest2', alias='testdb')
|
connect('mongoenginetest2', alias='testdb')
|
||||||
conn = get_connection('testdb')
|
conn = get_connection('testdb')
|
||||||
self.assertTrue(isinstance(conn, pymongo.mongo_client.MongoClient))
|
self.assertIsInstance(conn, pymongo.mongo_client.MongoClient)
|
||||||
|
|
||||||
def test_connect_in_mocking(self):
|
def test_connect_in_mocking(self):
|
||||||
"""Ensure that the connect() method works properly in mocking.
|
"""Ensure that the connect() method works properly in mocking.
|
||||||
@ -59,31 +59,31 @@ class ConnectionTest(unittest.TestCase):
|
|||||||
|
|
||||||
connect('mongoenginetest', host='mongomock://localhost')
|
connect('mongoenginetest', host='mongomock://localhost')
|
||||||
conn = get_connection()
|
conn = get_connection()
|
||||||
self.assertTrue(isinstance(conn, mongomock.MongoClient))
|
self.assertIsInstance(conn, mongomock.MongoClient)
|
||||||
|
|
||||||
connect('mongoenginetest2', host='mongomock://localhost', alias='testdb2')
|
connect('mongoenginetest2', host='mongomock://localhost', alias='testdb2')
|
||||||
conn = get_connection('testdb2')
|
conn = get_connection('testdb2')
|
||||||
self.assertTrue(isinstance(conn, mongomock.MongoClient))
|
self.assertIsInstance(conn, mongomock.MongoClient)
|
||||||
|
|
||||||
connect('mongoenginetest3', host='mongodb://localhost', is_mock=True, alias='testdb3')
|
connect('mongoenginetest3', host='mongodb://localhost', is_mock=True, alias='testdb3')
|
||||||
conn = get_connection('testdb3')
|
conn = get_connection('testdb3')
|
||||||
self.assertTrue(isinstance(conn, mongomock.MongoClient))
|
self.assertIsInstance(conn, mongomock.MongoClient)
|
||||||
|
|
||||||
connect('mongoenginetest4', is_mock=True, alias='testdb4')
|
connect('mongoenginetest4', is_mock=True, alias='testdb4')
|
||||||
conn = get_connection('testdb4')
|
conn = get_connection('testdb4')
|
||||||
self.assertTrue(isinstance(conn, mongomock.MongoClient))
|
self.assertIsInstance(conn, mongomock.MongoClient)
|
||||||
|
|
||||||
connect(host='mongodb://localhost:27017/mongoenginetest5', is_mock=True, alias='testdb5')
|
connect(host='mongodb://localhost:27017/mongoenginetest5', is_mock=True, alias='testdb5')
|
||||||
conn = get_connection('testdb5')
|
conn = get_connection('testdb5')
|
||||||
self.assertTrue(isinstance(conn, mongomock.MongoClient))
|
self.assertIsInstance(conn, mongomock.MongoClient)
|
||||||
|
|
||||||
connect(host='mongomock://localhost:27017/mongoenginetest6', alias='testdb6')
|
connect(host='mongomock://localhost:27017/mongoenginetest6', alias='testdb6')
|
||||||
conn = get_connection('testdb6')
|
conn = get_connection('testdb6')
|
||||||
self.assertTrue(isinstance(conn, mongomock.MongoClient))
|
self.assertIsInstance(conn, mongomock.MongoClient)
|
||||||
|
|
||||||
connect(host='mongomock://localhost:27017/mongoenginetest7', is_mock=True, alias='testdb7')
|
connect(host='mongomock://localhost:27017/mongoenginetest7', is_mock=True, alias='testdb7')
|
||||||
conn = get_connection('testdb7')
|
conn = get_connection('testdb7')
|
||||||
self.assertTrue(isinstance(conn, mongomock.MongoClient))
|
self.assertIsInstance(conn, mongomock.MongoClient)
|
||||||
|
|
||||||
def test_connect_with_host_list(self):
|
def test_connect_with_host_list(self):
|
||||||
"""Ensure that the connect() method works when host is a list
|
"""Ensure that the connect() method works when host is a list
|
||||||
@ -97,27 +97,27 @@ class ConnectionTest(unittest.TestCase):
|
|||||||
|
|
||||||
connect(host=['mongomock://localhost'])
|
connect(host=['mongomock://localhost'])
|
||||||
conn = get_connection()
|
conn = get_connection()
|
||||||
self.assertTrue(isinstance(conn, mongomock.MongoClient))
|
self.assertIsInstance(conn, mongomock.MongoClient)
|
||||||
|
|
||||||
connect(host=['mongodb://localhost'], is_mock=True, alias='testdb2')
|
connect(host=['mongodb://localhost'], is_mock=True, alias='testdb2')
|
||||||
conn = get_connection('testdb2')
|
conn = get_connection('testdb2')
|
||||||
self.assertTrue(isinstance(conn, mongomock.MongoClient))
|
self.assertIsInstance(conn, mongomock.MongoClient)
|
||||||
|
|
||||||
connect(host=['localhost'], is_mock=True, alias='testdb3')
|
connect(host=['localhost'], is_mock=True, alias='testdb3')
|
||||||
conn = get_connection('testdb3')
|
conn = get_connection('testdb3')
|
||||||
self.assertTrue(isinstance(conn, mongomock.MongoClient))
|
self.assertIsInstance(conn, mongomock.MongoClient)
|
||||||
|
|
||||||
connect(host=['mongomock://localhost:27017', 'mongomock://localhost:27018'], alias='testdb4')
|
connect(host=['mongomock://localhost:27017', 'mongomock://localhost:27018'], alias='testdb4')
|
||||||
conn = get_connection('testdb4')
|
conn = get_connection('testdb4')
|
||||||
self.assertTrue(isinstance(conn, mongomock.MongoClient))
|
self.assertIsInstance(conn, mongomock.MongoClient)
|
||||||
|
|
||||||
connect(host=['mongodb://localhost:27017', 'mongodb://localhost:27018'], is_mock=True, alias='testdb5')
|
connect(host=['mongodb://localhost:27017', 'mongodb://localhost:27018'], is_mock=True, alias='testdb5')
|
||||||
conn = get_connection('testdb5')
|
conn = get_connection('testdb5')
|
||||||
self.assertTrue(isinstance(conn, mongomock.MongoClient))
|
self.assertIsInstance(conn, mongomock.MongoClient)
|
||||||
|
|
||||||
connect(host=['localhost:27017', 'localhost:27018'], is_mock=True, alias='testdb6')
|
connect(host=['localhost:27017', 'localhost:27018'], is_mock=True, alias='testdb6')
|
||||||
conn = get_connection('testdb6')
|
conn = get_connection('testdb6')
|
||||||
self.assertTrue(isinstance(conn, mongomock.MongoClient))
|
self.assertIsInstance(conn, mongomock.MongoClient)
|
||||||
|
|
||||||
def test_disconnect(self):
|
def test_disconnect(self):
|
||||||
"""Ensure that the disconnect() method works properly
|
"""Ensure that the disconnect() method works properly
|
||||||
@ -163,10 +163,10 @@ class ConnectionTest(unittest.TestCase):
|
|||||||
connect("testdb_uri", host='mongodb://username:password@localhost/mongoenginetest')
|
connect("testdb_uri", host='mongodb://username:password@localhost/mongoenginetest')
|
||||||
|
|
||||||
conn = get_connection()
|
conn = get_connection()
|
||||||
self.assertTrue(isinstance(conn, pymongo.mongo_client.MongoClient))
|
self.assertIsInstance(conn, pymongo.mongo_client.MongoClient)
|
||||||
|
|
||||||
db = get_db()
|
db = get_db()
|
||||||
self.assertTrue(isinstance(db, pymongo.database.Database))
|
self.assertIsInstance(db, pymongo.database.Database)
|
||||||
self.assertEqual(db.name, 'mongoenginetest')
|
self.assertEqual(db.name, 'mongoenginetest')
|
||||||
|
|
||||||
c.admin.system.users.remove({})
|
c.admin.system.users.remove({})
|
||||||
@ -179,10 +179,10 @@ class ConnectionTest(unittest.TestCase):
|
|||||||
connect("mongoenginetest", host='mongodb://localhost/')
|
connect("mongoenginetest", host='mongodb://localhost/')
|
||||||
|
|
||||||
conn = get_connection()
|
conn = get_connection()
|
||||||
self.assertTrue(isinstance(conn, pymongo.mongo_client.MongoClient))
|
self.assertIsInstance(conn, pymongo.mongo_client.MongoClient)
|
||||||
|
|
||||||
db = get_db()
|
db = get_db()
|
||||||
self.assertTrue(isinstance(db, pymongo.database.Database))
|
self.assertIsInstance(db, pymongo.database.Database)
|
||||||
self.assertEqual(db.name, 'mongoenginetest')
|
self.assertEqual(db.name, 'mongoenginetest')
|
||||||
|
|
||||||
def test_connect_uri_default_db(self):
|
def test_connect_uri_default_db(self):
|
||||||
@ -192,10 +192,10 @@ class ConnectionTest(unittest.TestCase):
|
|||||||
connect(host='mongodb://localhost/')
|
connect(host='mongodb://localhost/')
|
||||||
|
|
||||||
conn = get_connection()
|
conn = get_connection()
|
||||||
self.assertTrue(isinstance(conn, pymongo.mongo_client.MongoClient))
|
self.assertIsInstance(conn, pymongo.mongo_client.MongoClient)
|
||||||
|
|
||||||
db = get_db()
|
db = get_db()
|
||||||
self.assertTrue(isinstance(db, pymongo.database.Database))
|
self.assertIsInstance(db, pymongo.database.Database)
|
||||||
self.assertEqual(db.name, 'test')
|
self.assertEqual(db.name, 'test')
|
||||||
|
|
||||||
def test_uri_without_credentials_doesnt_override_conn_settings(self):
|
def test_uri_without_credentials_doesnt_override_conn_settings(self):
|
||||||
@ -242,7 +242,7 @@ class ConnectionTest(unittest.TestCase):
|
|||||||
'mongoenginetest?authSource=admin')
|
'mongoenginetest?authSource=admin')
|
||||||
)
|
)
|
||||||
db = get_db('test2')
|
db = get_db('test2')
|
||||||
self.assertTrue(isinstance(db, pymongo.database.Database))
|
self.assertIsInstance(db, pymongo.database.Database)
|
||||||
self.assertEqual(db.name, 'mongoenginetest')
|
self.assertEqual(db.name, 'mongoenginetest')
|
||||||
|
|
||||||
# Clear all users
|
# Clear all users
|
||||||
@ -255,10 +255,10 @@ class ConnectionTest(unittest.TestCase):
|
|||||||
|
|
||||||
self.assertRaises(MongoEngineConnectionError, get_connection)
|
self.assertRaises(MongoEngineConnectionError, get_connection)
|
||||||
conn = get_connection('testdb')
|
conn = get_connection('testdb')
|
||||||
self.assertTrue(isinstance(conn, pymongo.mongo_client.MongoClient))
|
self.assertIsInstance(conn, pymongo.mongo_client.MongoClient)
|
||||||
|
|
||||||
db = get_db('testdb')
|
db = get_db('testdb')
|
||||||
self.assertTrue(isinstance(db, pymongo.database.Database))
|
self.assertIsInstance(db, pymongo.database.Database)
|
||||||
self.assertEqual(db.name, 'mongoenginetest2')
|
self.assertEqual(db.name, 'mongoenginetest2')
|
||||||
|
|
||||||
def test_register_connection_defaults(self):
|
def test_register_connection_defaults(self):
|
||||||
@ -267,7 +267,7 @@ class ConnectionTest(unittest.TestCase):
|
|||||||
register_connection('testdb', 'mongoenginetest', host=None, port=None)
|
register_connection('testdb', 'mongoenginetest', host=None, port=None)
|
||||||
|
|
||||||
conn = get_connection('testdb')
|
conn = get_connection('testdb')
|
||||||
self.assertTrue(isinstance(conn, pymongo.mongo_client.MongoClient))
|
self.assertIsInstance(conn, pymongo.mongo_client.MongoClient)
|
||||||
|
|
||||||
def test_connection_kwargs(self):
|
def test_connection_kwargs(self):
|
||||||
"""Ensure that connection kwargs get passed to pymongo."""
|
"""Ensure that connection kwargs get passed to pymongo."""
|
||||||
@ -326,7 +326,7 @@ class ConnectionTest(unittest.TestCase):
|
|||||||
if IS_PYMONGO_3:
|
if IS_PYMONGO_3:
|
||||||
c = connect(host='mongodb://localhost/test?replicaSet=local-rs')
|
c = connect(host='mongodb://localhost/test?replicaSet=local-rs')
|
||||||
db = get_db()
|
db = get_db()
|
||||||
self.assertTrue(isinstance(db, pymongo.database.Database))
|
self.assertIsInstance(db, pymongo.database.Database)
|
||||||
self.assertEqual(db.name, 'test')
|
self.assertEqual(db.name, 'test')
|
||||||
else:
|
else:
|
||||||
# PyMongo < v3.x raises an exception:
|
# PyMongo < v3.x raises an exception:
|
||||||
@ -343,7 +343,7 @@ class ConnectionTest(unittest.TestCase):
|
|||||||
self.assertEqual(c._MongoClient__options.replica_set_name,
|
self.assertEqual(c._MongoClient__options.replica_set_name,
|
||||||
'local-rs')
|
'local-rs')
|
||||||
db = get_db()
|
db = get_db()
|
||||||
self.assertTrue(isinstance(db, pymongo.database.Database))
|
self.assertIsInstance(db, pymongo.database.Database)
|
||||||
self.assertEqual(db.name, 'test')
|
self.assertEqual(db.name, 'test')
|
||||||
else:
|
else:
|
||||||
# PyMongo < v3.x raises an exception:
|
# PyMongo < v3.x raises an exception:
|
||||||
@ -377,8 +377,8 @@ class ConnectionTest(unittest.TestCase):
|
|||||||
|
|
||||||
mongo_connections = mongoengine.connection._connections
|
mongo_connections = mongoengine.connection._connections
|
||||||
self.assertEqual(len(mongo_connections.items()), 2)
|
self.assertEqual(len(mongo_connections.items()), 2)
|
||||||
self.assertTrue('t1' in mongo_connections.keys())
|
self.assertIn('t1', mongo_connections.keys())
|
||||||
self.assertTrue('t2' in mongo_connections.keys())
|
self.assertIn('t2', mongo_connections.keys())
|
||||||
if not IS_PYMONGO_3:
|
if not IS_PYMONGO_3:
|
||||||
self.assertEqual(mongo_connections['t1'].host, 'localhost')
|
self.assertEqual(mongo_connections['t1'].host, 'localhost')
|
||||||
self.assertEqual(mongo_connections['t2'].host, '127.0.0.1')
|
self.assertEqual(mongo_connections['t2'].host, '127.0.0.1')
|
||||||
|
@ -89,15 +89,15 @@ class ContextManagersTest(unittest.TestCase):
|
|||||||
|
|
||||||
with no_dereference(Group) as Group:
|
with no_dereference(Group) as Group:
|
||||||
group = Group.objects.first()
|
group = Group.objects.first()
|
||||||
self.assertTrue(all([not isinstance(m, User)
|
for m in group.members:
|
||||||
for m in group.members]))
|
self.assertNotIsInstance(m, User)
|
||||||
self.assertFalse(isinstance(group.ref, User))
|
self.assertNotIsInstance(group.ref, User)
|
||||||
self.assertFalse(isinstance(group.generic, User))
|
self.assertNotIsInstance(group.generic, User)
|
||||||
|
|
||||||
self.assertTrue(all([isinstance(m, User)
|
for m in group.members:
|
||||||
for m in group.members]))
|
self.assertIsInstance(m, User)
|
||||||
self.assertTrue(isinstance(group.ref, User))
|
self.assertIsInstance(group.ref, User)
|
||||||
self.assertTrue(isinstance(group.generic, User))
|
self.assertIsInstance(group.generic, User)
|
||||||
|
|
||||||
def test_no_dereference_context_manager_dbref(self):
|
def test_no_dereference_context_manager_dbref(self):
|
||||||
"""Ensure that DBRef items in ListFields aren't dereferenced.
|
"""Ensure that DBRef items in ListFields aren't dereferenced.
|
||||||
@ -129,13 +129,13 @@ class ContextManagersTest(unittest.TestCase):
|
|||||||
group = Group.objects.first()
|
group = Group.objects.first()
|
||||||
self.assertTrue(all([not isinstance(m, User)
|
self.assertTrue(all([not isinstance(m, User)
|
||||||
for m in group.members]))
|
for m in group.members]))
|
||||||
self.assertFalse(isinstance(group.ref, User))
|
self.assertNotIsInstance(group.ref, User)
|
||||||
self.assertFalse(isinstance(group.generic, User))
|
self.assertNotIsInstance(group.generic, User)
|
||||||
|
|
||||||
self.assertTrue(all([isinstance(m, User)
|
self.assertTrue(all([isinstance(m, User)
|
||||||
for m in group.members]))
|
for m in group.members]))
|
||||||
self.assertTrue(isinstance(group.ref, User))
|
self.assertIsInstance(group.ref, User)
|
||||||
self.assertTrue(isinstance(group.generic, User))
|
self.assertIsInstance(group.generic, User)
|
||||||
|
|
||||||
def test_no_sub_classes(self):
|
def test_no_sub_classes(self):
|
||||||
class A(Document):
|
class A(Document):
|
||||||
@ -209,18 +209,99 @@ class ContextManagersTest(unittest.TestCase):
|
|||||||
with no_sub_classes(User):
|
with no_sub_classes(User):
|
||||||
raise TypeError()
|
raise TypeError()
|
||||||
|
|
||||||
|
def test_query_counter_does_not_swallow_exception(self):
|
||||||
|
|
||||||
|
with self.assertRaises(TypeError):
|
||||||
|
with query_counter() as q:
|
||||||
|
raise TypeError()
|
||||||
|
|
||||||
|
def test_query_counter_temporarily_modifies_profiling_level(self):
|
||||||
|
connect('mongoenginetest')
|
||||||
|
db = get_db()
|
||||||
|
|
||||||
|
initial_profiling_level = db.profiling_level()
|
||||||
|
|
||||||
|
try:
|
||||||
|
NEW_LEVEL = 1
|
||||||
|
db.set_profiling_level(NEW_LEVEL)
|
||||||
|
self.assertEqual(db.profiling_level(), NEW_LEVEL)
|
||||||
|
with query_counter() as q:
|
||||||
|
self.assertEqual(db.profiling_level(), 2)
|
||||||
|
self.assertEqual(db.profiling_level(), NEW_LEVEL)
|
||||||
|
except Exception:
|
||||||
|
db.set_profiling_level(initial_profiling_level) # Ensures it gets reseted no matter the outcome of the test
|
||||||
|
raise
|
||||||
|
|
||||||
def test_query_counter(self):
|
def test_query_counter(self):
|
||||||
connect('mongoenginetest')
|
connect('mongoenginetest')
|
||||||
db = get_db()
|
db = get_db()
|
||||||
db.test.find({})
|
|
||||||
|
collection = db.query_counter
|
||||||
|
collection.drop()
|
||||||
|
|
||||||
|
def issue_1_count_query():
|
||||||
|
collection.find({}).count()
|
||||||
|
|
||||||
|
def issue_1_insert_query():
|
||||||
|
collection.insert_one({'test': 'garbage'})
|
||||||
|
|
||||||
|
def issue_1_find_query():
|
||||||
|
collection.find_one()
|
||||||
|
|
||||||
|
counter = 0
|
||||||
|
with query_counter() as q:
|
||||||
|
self.assertEqual(q, counter)
|
||||||
|
self.assertEqual(q, counter) # Ensures previous count query did not get counted
|
||||||
|
|
||||||
|
for _ in range(10):
|
||||||
|
issue_1_insert_query()
|
||||||
|
counter += 1
|
||||||
|
self.assertEqual(q, counter)
|
||||||
|
|
||||||
|
for _ in range(4):
|
||||||
|
issue_1_find_query()
|
||||||
|
counter += 1
|
||||||
|
self.assertEqual(q, counter)
|
||||||
|
|
||||||
|
for _ in range(3):
|
||||||
|
issue_1_count_query()
|
||||||
|
counter += 1
|
||||||
|
self.assertEqual(q, counter)
|
||||||
|
|
||||||
|
def test_query_counter_counts_getmore_queries(self):
|
||||||
|
connect('mongoenginetest')
|
||||||
|
db = get_db()
|
||||||
|
|
||||||
|
collection = db.query_counter
|
||||||
|
collection.drop()
|
||||||
|
|
||||||
|
many_docs = [{'test': 'garbage %s' % i} for i in range(150)]
|
||||||
|
collection.insert_many(many_docs) # first batch of documents contains 101 documents
|
||||||
|
|
||||||
with query_counter() as q:
|
with query_counter() as q:
|
||||||
self.assertEqual(0, q)
|
self.assertEqual(q, 0)
|
||||||
|
list(collection.find())
|
||||||
|
self.assertEqual(q, 2) # 1st select + 1 getmore
|
||||||
|
|
||||||
for i in range(1, 51):
|
def test_query_counter_ignores_particular_queries(self):
|
||||||
db.test.find({}).count()
|
connect('mongoenginetest')
|
||||||
|
db = get_db()
|
||||||
|
|
||||||
self.assertEqual(50, q)
|
collection = db.query_counter
|
||||||
|
collection.insert_many([{'test': 'garbage %s' % i} for i in range(10)])
|
||||||
|
|
||||||
|
with query_counter() as q:
|
||||||
|
self.assertEqual(q, 0)
|
||||||
|
cursor = collection.find()
|
||||||
|
self.assertEqual(q, 0) # cursor wasn't opened yet
|
||||||
|
_ = next(cursor) # opens the cursor and fires the find query
|
||||||
|
self.assertEqual(q, 1)
|
||||||
|
|
||||||
|
cursor.close() # issues a `killcursors` query that is ignored by the context
|
||||||
|
self.assertEqual(q, 1)
|
||||||
|
|
||||||
|
_ = db.system.indexes.find_one() # queries on db.system.indexes are ignored as well
|
||||||
|
self.assertEqual(q, 1)
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
@ -200,8 +200,8 @@ class FieldTest(unittest.TestCase):
|
|||||||
group = Group(author=user, members=[user]).save()
|
group = Group(author=user, members=[user]).save()
|
||||||
|
|
||||||
raw_data = Group._get_collection().find_one()
|
raw_data = Group._get_collection().find_one()
|
||||||
self.assertTrue(isinstance(raw_data['author'], DBRef))
|
self.assertIsInstance(raw_data['author'], DBRef)
|
||||||
self.assertTrue(isinstance(raw_data['members'][0], DBRef))
|
self.assertIsInstance(raw_data['members'][0], DBRef)
|
||||||
group = Group.objects.first()
|
group = Group.objects.first()
|
||||||
|
|
||||||
self.assertEqual(group.author, user)
|
self.assertEqual(group.author, user)
|
||||||
@ -224,8 +224,8 @@ class FieldTest(unittest.TestCase):
|
|||||||
self.assertEqual(group.members, [user])
|
self.assertEqual(group.members, [user])
|
||||||
|
|
||||||
raw_data = Group._get_collection().find_one()
|
raw_data = Group._get_collection().find_one()
|
||||||
self.assertTrue(isinstance(raw_data['author'], ObjectId))
|
self.assertIsInstance(raw_data['author'], ObjectId)
|
||||||
self.assertTrue(isinstance(raw_data['members'][0], ObjectId))
|
self.assertIsInstance(raw_data['members'][0], ObjectId)
|
||||||
|
|
||||||
def test_recursive_reference(self):
|
def test_recursive_reference(self):
|
||||||
"""Ensure that ReferenceFields can reference their own documents.
|
"""Ensure that ReferenceFields can reference their own documents.
|
||||||
@ -469,7 +469,7 @@ class FieldTest(unittest.TestCase):
|
|||||||
self.assertEqual(q, 4)
|
self.assertEqual(q, 4)
|
||||||
|
|
||||||
for m in group_obj.members:
|
for m in group_obj.members:
|
||||||
self.assertTrue('User' in m.__class__.__name__)
|
self.assertIn('User', m.__class__.__name__)
|
||||||
|
|
||||||
# Document select_related
|
# Document select_related
|
||||||
with query_counter() as q:
|
with query_counter() as q:
|
||||||
@ -485,7 +485,7 @@ class FieldTest(unittest.TestCase):
|
|||||||
self.assertEqual(q, 4)
|
self.assertEqual(q, 4)
|
||||||
|
|
||||||
for m in group_obj.members:
|
for m in group_obj.members:
|
||||||
self.assertTrue('User' in m.__class__.__name__)
|
self.assertIn('User', m.__class__.__name__)
|
||||||
|
|
||||||
# Queryset select_related
|
# Queryset select_related
|
||||||
with query_counter() as q:
|
with query_counter() as q:
|
||||||
@ -502,7 +502,7 @@ class FieldTest(unittest.TestCase):
|
|||||||
self.assertEqual(q, 4)
|
self.assertEqual(q, 4)
|
||||||
|
|
||||||
for m in group_obj.members:
|
for m in group_obj.members:
|
||||||
self.assertTrue('User' in m.__class__.__name__)
|
self.assertIn('User', m.__class__.__name__)
|
||||||
|
|
||||||
UserA.drop_collection()
|
UserA.drop_collection()
|
||||||
UserB.drop_collection()
|
UserB.drop_collection()
|
||||||
@ -560,7 +560,7 @@ class FieldTest(unittest.TestCase):
|
|||||||
self.assertEqual(q, 4)
|
self.assertEqual(q, 4)
|
||||||
|
|
||||||
for m in group_obj.members:
|
for m in group_obj.members:
|
||||||
self.assertTrue('User' in m.__class__.__name__)
|
self.assertIn('User', m.__class__.__name__)
|
||||||
|
|
||||||
# Document select_related
|
# Document select_related
|
||||||
with query_counter() as q:
|
with query_counter() as q:
|
||||||
@ -576,7 +576,7 @@ class FieldTest(unittest.TestCase):
|
|||||||
self.assertEqual(q, 4)
|
self.assertEqual(q, 4)
|
||||||
|
|
||||||
for m in group_obj.members:
|
for m in group_obj.members:
|
||||||
self.assertTrue('User' in m.__class__.__name__)
|
self.assertIn('User', m.__class__.__name__)
|
||||||
|
|
||||||
# Queryset select_related
|
# Queryset select_related
|
||||||
with query_counter() as q:
|
with query_counter() as q:
|
||||||
@ -593,7 +593,7 @@ class FieldTest(unittest.TestCase):
|
|||||||
self.assertEqual(q, 4)
|
self.assertEqual(q, 4)
|
||||||
|
|
||||||
for m in group_obj.members:
|
for m in group_obj.members:
|
||||||
self.assertTrue('User' in m.__class__.__name__)
|
self.assertIn('User', m.__class__.__name__)
|
||||||
|
|
||||||
UserA.drop_collection()
|
UserA.drop_collection()
|
||||||
UserB.drop_collection()
|
UserB.drop_collection()
|
||||||
@ -633,7 +633,7 @@ class FieldTest(unittest.TestCase):
|
|||||||
self.assertEqual(q, 2)
|
self.assertEqual(q, 2)
|
||||||
|
|
||||||
for k, m in group_obj.members.iteritems():
|
for k, m in group_obj.members.iteritems():
|
||||||
self.assertTrue(isinstance(m, User))
|
self.assertIsInstance(m, User)
|
||||||
|
|
||||||
# Document select_related
|
# Document select_related
|
||||||
with query_counter() as q:
|
with query_counter() as q:
|
||||||
@ -646,7 +646,7 @@ class FieldTest(unittest.TestCase):
|
|||||||
self.assertEqual(q, 2)
|
self.assertEqual(q, 2)
|
||||||
|
|
||||||
for k, m in group_obj.members.iteritems():
|
for k, m in group_obj.members.iteritems():
|
||||||
self.assertTrue(isinstance(m, User))
|
self.assertIsInstance(m, User)
|
||||||
|
|
||||||
# Queryset select_related
|
# Queryset select_related
|
||||||
with query_counter() as q:
|
with query_counter() as q:
|
||||||
@ -660,7 +660,7 @@ class FieldTest(unittest.TestCase):
|
|||||||
self.assertEqual(q, 2)
|
self.assertEqual(q, 2)
|
||||||
|
|
||||||
for k, m in group_obj.members.iteritems():
|
for k, m in group_obj.members.iteritems():
|
||||||
self.assertTrue(isinstance(m, User))
|
self.assertIsInstance(m, User)
|
||||||
|
|
||||||
User.drop_collection()
|
User.drop_collection()
|
||||||
Group.drop_collection()
|
Group.drop_collection()
|
||||||
@ -715,7 +715,7 @@ class FieldTest(unittest.TestCase):
|
|||||||
self.assertEqual(q, 4)
|
self.assertEqual(q, 4)
|
||||||
|
|
||||||
for k, m in group_obj.members.iteritems():
|
for k, m in group_obj.members.iteritems():
|
||||||
self.assertTrue('User' in m.__class__.__name__)
|
self.assertIn('User', m.__class__.__name__)
|
||||||
|
|
||||||
# Document select_related
|
# Document select_related
|
||||||
with query_counter() as q:
|
with query_counter() as q:
|
||||||
@ -731,7 +731,7 @@ class FieldTest(unittest.TestCase):
|
|||||||
self.assertEqual(q, 4)
|
self.assertEqual(q, 4)
|
||||||
|
|
||||||
for k, m in group_obj.members.iteritems():
|
for k, m in group_obj.members.iteritems():
|
||||||
self.assertTrue('User' in m.__class__.__name__)
|
self.assertIn('User', m.__class__.__name__)
|
||||||
|
|
||||||
# Queryset select_related
|
# Queryset select_related
|
||||||
with query_counter() as q:
|
with query_counter() as q:
|
||||||
@ -748,7 +748,7 @@ class FieldTest(unittest.TestCase):
|
|||||||
self.assertEqual(q, 4)
|
self.assertEqual(q, 4)
|
||||||
|
|
||||||
for k, m in group_obj.members.iteritems():
|
for k, m in group_obj.members.iteritems():
|
||||||
self.assertTrue('User' in m.__class__.__name__)
|
self.assertIn('User', m.__class__.__name__)
|
||||||
|
|
||||||
Group.objects.delete()
|
Group.objects.delete()
|
||||||
Group().save()
|
Group().save()
|
||||||
@ -806,7 +806,7 @@ class FieldTest(unittest.TestCase):
|
|||||||
self.assertEqual(q, 2)
|
self.assertEqual(q, 2)
|
||||||
|
|
||||||
for k, m in group_obj.members.iteritems():
|
for k, m in group_obj.members.iteritems():
|
||||||
self.assertTrue(isinstance(m, UserA))
|
self.assertIsInstance(m, UserA)
|
||||||
|
|
||||||
# Document select_related
|
# Document select_related
|
||||||
with query_counter() as q:
|
with query_counter() as q:
|
||||||
@ -822,7 +822,7 @@ class FieldTest(unittest.TestCase):
|
|||||||
self.assertEqual(q, 2)
|
self.assertEqual(q, 2)
|
||||||
|
|
||||||
for k, m in group_obj.members.iteritems():
|
for k, m in group_obj.members.iteritems():
|
||||||
self.assertTrue(isinstance(m, UserA))
|
self.assertIsInstance(m, UserA)
|
||||||
|
|
||||||
# Queryset select_related
|
# Queryset select_related
|
||||||
with query_counter() as q:
|
with query_counter() as q:
|
||||||
@ -839,7 +839,7 @@ class FieldTest(unittest.TestCase):
|
|||||||
self.assertEqual(q, 2)
|
self.assertEqual(q, 2)
|
||||||
|
|
||||||
for k, m in group_obj.members.iteritems():
|
for k, m in group_obj.members.iteritems():
|
||||||
self.assertTrue(isinstance(m, UserA))
|
self.assertIsInstance(m, UserA)
|
||||||
|
|
||||||
UserA.drop_collection()
|
UserA.drop_collection()
|
||||||
Group.drop_collection()
|
Group.drop_collection()
|
||||||
@ -894,7 +894,7 @@ class FieldTest(unittest.TestCase):
|
|||||||
self.assertEqual(q, 4)
|
self.assertEqual(q, 4)
|
||||||
|
|
||||||
for k, m in group_obj.members.iteritems():
|
for k, m in group_obj.members.iteritems():
|
||||||
self.assertTrue('User' in m.__class__.__name__)
|
self.assertIn('User', m.__class__.__name__)
|
||||||
|
|
||||||
# Document select_related
|
# Document select_related
|
||||||
with query_counter() as q:
|
with query_counter() as q:
|
||||||
@ -910,7 +910,7 @@ class FieldTest(unittest.TestCase):
|
|||||||
self.assertEqual(q, 4)
|
self.assertEqual(q, 4)
|
||||||
|
|
||||||
for k, m in group_obj.members.iteritems():
|
for k, m in group_obj.members.iteritems():
|
||||||
self.assertTrue('User' in m.__class__.__name__)
|
self.assertIn('User', m.__class__.__name__)
|
||||||
|
|
||||||
# Queryset select_related
|
# Queryset select_related
|
||||||
with query_counter() as q:
|
with query_counter() as q:
|
||||||
@ -927,7 +927,7 @@ class FieldTest(unittest.TestCase):
|
|||||||
self.assertEqual(q, 4)
|
self.assertEqual(q, 4)
|
||||||
|
|
||||||
for k, m in group_obj.members.iteritems():
|
for k, m in group_obj.members.iteritems():
|
||||||
self.assertTrue('User' in m.__class__.__name__)
|
self.assertIn('User', m.__class__.__name__)
|
||||||
|
|
||||||
Group.objects.delete()
|
Group.objects.delete()
|
||||||
Group().save()
|
Group().save()
|
||||||
@ -1209,10 +1209,10 @@ class FieldTest(unittest.TestCase):
|
|||||||
|
|
||||||
# Can't use query_counter across databases - so test the _data object
|
# Can't use query_counter across databases - so test the _data object
|
||||||
book = Book.objects.first()
|
book = Book.objects.first()
|
||||||
self.assertFalse(isinstance(book._data['author'], User))
|
self.assertNotIsInstance(book._data['author'], User)
|
||||||
|
|
||||||
book.select_related()
|
book.select_related()
|
||||||
self.assertTrue(isinstance(book._data['author'], User))
|
self.assertIsInstance(book._data['author'], User)
|
||||||
|
|
||||||
def test_non_ascii_pk(self):
|
def test_non_ascii_pk(self):
|
||||||
"""
|
"""
|
||||||
|
Loading…
x
Reference in New Issue
Block a user