Merge remote-tracking branch 'original-repo/master' into fix-choices-display

This commit is contained in:
Sergey Tereschenko 2018-09-11 13:24:52 +03:00
commit e423380d7f
22 changed files with 469 additions and 342 deletions

View File

@ -2,6 +2,11 @@
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
=================
- Added `DateField` #513

View File

@ -529,7 +529,7 @@ There are a few top level defaults for all indexes that can be set::
title = StringField()
rating = StringField()
meta = {
'index_options': {},
'index_opts': {},
'index_background': True,
'index_cls': False,
'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>`_
:attr:`index_background` (Optional)
@ -736,6 +736,9 @@ document.::
.. note:: From 0.8 onwards :attr:`allow_inheritance` defaults
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
--------------------------

View File

@ -159,51 +159,69 @@ class no_sub_classes(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):
"""Construct the query_counter."""
self.counter = 0
"""Construct the query_counter
"""
self.db = get_db()
self.initial_profiling_level = None
self._ctx_query_counter = 0 # number of queries issued by the context
def __enter__(self):
"""On every with block we need to drop the profile collection."""
self._ignored_query = {
'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.system.profile.drop()
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
def __exit__(self, t, value, traceback):
"""Reset the profiling level."""
self.db.set_profiling_level(0)
self._resets_profiling()
def __eq__(self, value):
"""== Compare querycounter."""
counter = self._get_count()
return value == counter
def __ne__(self, value):
"""!= Compare querycounter."""
return not self.__eq__(value)
def __lt__(self, value):
"""< Compare querycounter."""
return self._get_count() < value
def __le__(self, value):
"""<= Compare querycounter."""
return self._get_count() <= value
def __gt__(self, value):
"""> Compare querycounter."""
return self._get_count() > value
def __ge__(self, value):
""">= Compare querycounter."""
return self._get_count() >= value
def __int__(self):
"""int representation."""
return self._get_count()
def __repr__(self):
@ -211,10 +229,12 @@ class query_counter(object):
return u"%s" % self._get_count()
def _get_count(self):
"""Get the number of queries."""
ignore_query = {'ns': {'$ne': '%s.system.indexes' % self.db.name}}
count = self.db.system.profile.find(ignore_query).count() - self.counter
self.counter += 1 # Account for the query we just fired
"""Get the number of queries by counting the current number of entries in db.system.profile
and substracting the queries issued by this context. In fact everytime this is called, 1 query is
issued so we need to balance that
"""
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

View File

@ -396,7 +396,7 @@ class BaseQuerySet(object):
:meth:`skip` that has been applied to this cursor into account when
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 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
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._limit = n if n != 0 else 1
queryset._limit = n
# If a cursor object has already been created, apply the limit to it.
if queryset._cursor_obj:

View File

@ -66,10 +66,10 @@ class ClassMethodsTest(unittest.TestCase):
"""
collection_name = 'person'
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.assertFalse(collection_name in self.db.collection_names())
self.assertNotIn(collection_name, self.db.collection_names())
def test_register_delete_rule(self):
"""Ensure that register delete rule adds a delete rule to the document
@ -340,7 +340,7 @@ class ClassMethodsTest(unittest.TestCase):
meta = {'collection': collection_name}
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()
self.assertEqual(user_obj['name'], "Test User")
@ -349,7 +349,7 @@ class ClassMethodsTest(unittest.TestCase):
self.assertEqual(user_obj.name, "Test User")
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):
"""Ensure that a collection with a specified name may be used.

View File

@ -694,7 +694,7 @@ class DeltaTest(unittest.TestCase):
organization.employees.append(person)
updates, removals = organization._delta()
self.assertEqual({}, removals)
self.assertTrue('employees' in updates)
self.assertIn('employees', updates)
def test_delta_with_dbref_false(self):
person, organization, employee = self.circular_reference_deltas_2(Document, Document, False)
@ -709,7 +709,7 @@ class DeltaTest(unittest.TestCase):
organization.employees.append(person)
updates, removals = organization._delta()
self.assertEqual({}, removals)
self.assertTrue('employees' in updates)
self.assertIn('employees', updates)
def test_nested_nested_fields_mark_as_changed(self):
class EmbeddedDoc(EmbeddedDocument):

View File

@ -174,8 +174,8 @@ class DynamicTest(unittest.TestCase):
Employee.drop_collection()
self.assertTrue('name' in Employee._fields)
self.assertTrue('salary' in Employee._fields)
self.assertIn('name', Employee._fields)
self.assertIn('salary', Employee._fields)
self.assertEqual(Employee._get_collection_name(),
self.Person._get_collection_name())
@ -189,7 +189,7 @@ class DynamicTest(unittest.TestCase):
self.assertEqual(1, Employee.objects(age=20).count())
joe_bloggs = self.Person.objects.first()
self.assertTrue(isinstance(joe_bloggs, Employee))
self.assertIsInstance(joe_bloggs, Employee)
def test_embedded_dynamic_document(self):
"""Test dynamic embedded documents"""

View File

@ -70,7 +70,7 @@ class IndexesTest(unittest.TestCase):
self.assertEqual(len(info), 4)
info = [value['key'] for key, value in info.iteritems()]
for expected in expected_specs:
self.assertTrue(expected['fields'] in info)
self.assertIn(expected['fields'], info)
def _index_test_inheritance(self, InheritFrom):
@ -102,7 +102,7 @@ class IndexesTest(unittest.TestCase):
self.assertEqual(len(info), 4)
info = [value['key'] for key, value in info.iteritems()]
for expected in expected_specs:
self.assertTrue(expected['fields'] in info)
self.assertIn(expected['fields'], info)
class ExtendedBlogPost(BlogPost):
title = StringField()
@ -117,7 +117,7 @@ class IndexesTest(unittest.TestCase):
info = ExtendedBlogPost.objects._collection.index_information()
info = [value['key'] for key, value in info.iteritems()]
for expected in expected_specs:
self.assertTrue(expected['fields'] in info)
self.assertIn(expected['fields'], info)
def test_indexes_document_inheritance(self):
"""Ensure that indexes are used when meta[indexes] is specified for
@ -226,7 +226,7 @@ class IndexesTest(unittest.TestCase):
list(Person.objects)
info = Person.objects._collection.index_information()
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):
"""Ensure that geo2d indexes work when created via meta[indexes]
@ -246,7 +246,7 @@ class IndexesTest(unittest.TestCase):
Place.ensure_indexes()
info = Place._get_collection().index_information()
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):
"""Ensure that geo2d indexes work when created via meta[indexes]
@ -269,7 +269,7 @@ class IndexesTest(unittest.TestCase):
Place.ensure_indexes()
info = Place._get_collection().index_information()
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):
"""Ensure that geosphere indexes work when created via meta[indexes]
@ -289,7 +289,7 @@ class IndexesTest(unittest.TestCase):
Place.ensure_indexes()
info = Place._get_collection().index_information()
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):
"""Ensure that geohaystack indexes work when created via meta[indexes]
@ -311,7 +311,7 @@ class IndexesTest(unittest.TestCase):
Place.ensure_indexes()
info = Place._get_collection().index_information()
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):
"""Ensure that geohaystack indexes can be created
@ -323,7 +323,7 @@ class IndexesTest(unittest.TestCase):
Place.create_index({'fields': (')location.point', 'name')}, bucketSize=10)
info = Place._get_collection().index_information()
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):
"""Ensure that indexes are used when meta[indexes] contains
@ -356,7 +356,7 @@ class IndexesTest(unittest.TestCase):
value.get('unique', False),
value.get('sparse', False))
for key, value in info.iteritems()]
self.assertTrue(([('addDate', -1)], True, True) in info)
self.assertIn(([('addDate', -1)], True, True), info)
BlogPost.drop_collection()
@ -803,7 +803,7 @@ class IndexesTest(unittest.TestCase):
info = BlogPost.objects._collection.index_information()
info = [value['key'] for key, value in info.iteritems()]
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):
@ -850,8 +850,8 @@ class IndexesTest(unittest.TestCase):
info = MyDoc.objects._collection.index_information()
info = [value['key'] for key, value in info.iteritems()]
self.assertTrue([('provider_ids.foo', 1)] in info)
self.assertTrue([('provider_ids.bar', 1)] in info)
self.assertIn([('provider_ids.foo', 1)], info)
self.assertIn([('provider_ids.bar', 1)], info)
def test_sparse_compound_indexes(self):
@ -876,9 +876,9 @@ class IndexesTest(unittest.TestCase):
}
indexes = Book.objects._collection.index_information()
self.assertTrue("title_text" in indexes)
self.assertIn("title_text", indexes)
key = indexes["title_text"]["key"]
self.assertTrue(('_fts', 'text') in key)
self.assertIn(('_fts', 'text'), key)
def test_hashed_indexes(self):
@ -889,8 +889,8 @@ class IndexesTest(unittest.TestCase):
}
indexes = Book.objects._collection.index_information()
self.assertTrue("ref_id_hashed" in indexes)
self.assertTrue(('ref_id', 'hashed') in indexes["ref_id_hashed"]["key"])
self.assertIn("ref_id_hashed", indexes)
self.assertIn(('ref_id', 'hashed'), indexes["ref_id_hashed"]["key"])
def test_indexes_after_database_drop(self):
"""
@ -1013,7 +1013,7 @@ class IndexesTest(unittest.TestCase):
TestDoc.ensure_indexes()
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__':

View File

@ -268,7 +268,7 @@ class InheritanceTest(unittest.TestCase):
collection = self.db[Animal._get_collection_name()]
obj = collection.find_one()
self.assertFalse('_cls' in obj)
self.assertNotIn('_cls', obj)
def test_cant_turn_off_inheritance_on_subclass(self):
"""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
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):
@ -374,14 +374,14 @@ class InheritanceTest(unittest.TestCase):
pass
doc = Comment(content='test')
self.assertFalse('_cls' in doc.to_mongo())
self.assertNotIn('_cls', doc.to_mongo())
class Comment(EmbeddedDocument):
content = StringField()
meta = {'allow_inheritance': True}
doc = Comment(content='test')
self.assertTrue('_cls' in doc.to_mongo())
self.assertIn('_cls', doc.to_mongo())
def test_document_inheritance(self):
"""Ensure mutliple inheritance of abstract documents
@ -434,8 +434,8 @@ class InheritanceTest(unittest.TestCase):
for cls in [Animal, Fish, Guppy]:
self.assertEqual(cls._meta[k], v)
self.assertFalse('collection' in Animal._meta)
self.assertFalse('collection' in Mammal._meta)
self.assertNotIn('collection', Animal._meta)
self.assertNotIn('collection', Mammal._meta)
self.assertEqual(Animal._get_collection_name(), None)
self.assertEqual(Mammal._get_collection_name(), None)

View File

@ -357,7 +357,7 @@ class InstanceTest(MongoDBTestCase):
user_son = User.objects._collection.find_one()
self.assertEqual(user_son['_id'], 'test')
self.assertTrue('username' not in user_son['_id'])
self.assertNotIn('username', user_son['_id'])
User.drop_collection()
@ -370,7 +370,7 @@ class InstanceTest(MongoDBTestCase):
user_son = User.objects._collection.find_one()
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):
class Place(Document):
@ -594,10 +594,10 @@ class InstanceTest(MongoDBTestCase):
# Length = length(assigned fields + id)
self.assertEqual(len(person), 5)
self.assertTrue('age' in person)
self.assertIn('age', person)
person.age = None
self.assertFalse('age' in person)
self.assertFalse('nationality' in person)
self.assertNotIn('age', person)
self.assertNotIn('nationality', person)
def test_embedded_document_to_mongo(self):
class Person(EmbeddedDocument):
@ -627,8 +627,8 @@ class InstanceTest(MongoDBTestCase):
class Comment(EmbeddedDocument):
content = StringField()
self.assertTrue('content' in Comment._fields)
self.assertFalse('id' in Comment._fields)
self.assertIn('content', Comment._fields)
self.assertNotIn('id', Comment._fields)
def test_embedded_document_instance(self):
"""Ensure that embedded documents can reference parent instance."""
@ -1455,9 +1455,9 @@ class InstanceTest(MongoDBTestCase):
user = User.objects.first()
# Even if stored as ObjectId's internally mongoengine uses DBRefs
# As ObjectId's aren't automatically derefenced
self.assertTrue(isinstance(user._data['orgs'][0], DBRef))
self.assertTrue(isinstance(user.orgs[0], Organization))
self.assertTrue(isinstance(user._data['orgs'][0], Organization))
self.assertIsInstance(user._data['orgs'][0], DBRef)
self.assertIsInstance(user.orgs[0], Organization)
self.assertIsInstance(user._data['orgs'][0], Organization)
# Changing a value
with query_counter() as q:
@ -1837,9 +1837,8 @@ class InstanceTest(MongoDBTestCase):
post_obj = BlogPost.objects.first()
# Test laziness
self.assertTrue(isinstance(post_obj._data['author'],
bson.DBRef))
self.assertTrue(isinstance(post_obj.author, self.Person))
self.assertIsInstance(post_obj._data['author'], bson.DBRef)
self.assertIsInstance(post_obj.author, self.Person)
self.assertEqual(post_obj.author.name, 'Test User')
# 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
# for the comparison).
all_user_list = list(User.objects.all())
self.assertTrue(u1 in all_user_list)
self.assertTrue(u2 in all_user_list)
self.assertTrue(u3 in all_user_list)
self.assertTrue(u4 not in all_user_list) # New object
self.assertTrue(b1 not in all_user_list) # Other object
self.assertTrue(b2 not in all_user_list) # Other object
self.assertIn(u1, all_user_list)
self.assertIn(u2, all_user_list)
self.assertIn(u3, all_user_list)
self.assertNotIn(u4, all_user_list) # New object
self.assertNotIn(b1, 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
# for hashing the docs).
@ -2268,10 +2267,10 @@ class InstanceTest(MongoDBTestCase):
# Make sure docs are properly identified in a set (__hash__ is used
# for hashing the docs).
all_user_set = set(User.objects.all())
self.assertTrue(u1 in all_user_set)
self.assertTrue(u4 not in all_user_set)
self.assertTrue(b1 not in all_user_list)
self.assertTrue(b2 not in all_user_list)
self.assertIn(u1, all_user_set)
self.assertNotIn(u4, all_user_set)
self.assertNotIn(b1, all_user_list)
self.assertNotIn(b2, all_user_list)
# Make sure duplicate docs aren't accepted in the set
self.assertEqual(len(all_user_set), 3)
@ -2972,7 +2971,7 @@ class InstanceTest(MongoDBTestCase):
Person(name="Harry Potter").save()
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)
def test_complex_nesting_document_and_embedded_document(self):
@ -3064,36 +3063,36 @@ class InstanceTest(MongoDBTestCase):
dbref2 = f._data['test2']
obj2 = f.test2
self.assertTrue(isinstance(dbref2, DBRef))
self.assertTrue(isinstance(obj2, Test2))
self.assertTrue(obj2.id == dbref2.id)
self.assertTrue(obj2 == dbref2)
self.assertTrue(dbref2 == obj2)
self.assertIsInstance(dbref2, DBRef)
self.assertIsInstance(obj2, Test2)
self.assertEqual(obj2.id, dbref2.id)
self.assertEqual(obj2, dbref2)
self.assertEqual(dbref2, obj2)
dbref3 = f._data['test3']
obj3 = f.test3
self.assertTrue(isinstance(dbref3, DBRef))
self.assertTrue(isinstance(obj3, Test3))
self.assertTrue(obj3.id == dbref3.id)
self.assertTrue(obj3 == dbref3)
self.assertTrue(dbref3 == obj3)
self.assertIsInstance(dbref3, DBRef)
self.assertIsInstance(obj3, Test3)
self.assertEqual(obj3.id, dbref3.id)
self.assertEqual(obj3, dbref3)
self.assertEqual(dbref3, obj3)
self.assertTrue(obj2.id == obj3.id)
self.assertTrue(dbref2.id == dbref3.id)
self.assertFalse(dbref2 == dbref3)
self.assertFalse(dbref3 == dbref2)
self.assertTrue(dbref2 != dbref3)
self.assertTrue(dbref3 != dbref2)
self.assertEqual(obj2.id, obj3.id)
self.assertEqual(dbref2.id, dbref3.id)
self.assertNotEqual(dbref2, dbref3)
self.assertNotEqual(dbref3, dbref2)
self.assertNotEqual(dbref2, dbref3)
self.assertNotEqual(dbref3, dbref2)
self.assertFalse(obj2 == dbref3)
self.assertFalse(dbref3 == obj2)
self.assertTrue(obj2 != dbref3)
self.assertTrue(dbref3 != obj2)
self.assertNotEqual(obj2, dbref3)
self.assertNotEqual(dbref3, obj2)
self.assertNotEqual(obj2, dbref3)
self.assertNotEqual(dbref3, obj2)
self.assertFalse(obj3 == dbref2)
self.assertFalse(dbref2 == obj3)
self.assertTrue(obj3 != dbref2)
self.assertTrue(dbref2 != obj3)
self.assertNotEqual(obj3, dbref2)
self.assertNotEqual(dbref2, obj3)
self.assertNotEqual(obj3, dbref2)
self.assertNotEqual(dbref2, obj3)
def test_default_values(self):
class Person(Document):

View File

@ -20,16 +20,16 @@ class ValidatorErrorTest(unittest.TestCase):
# 1st level error schema
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')
# 2nd level error schema
error.errors = {'1st': ValidationError('bad 1st', errors={
'2nd': ValidationError('bad 2nd'),
})}
self.assertTrue('1st' in error.to_dict())
self.assertTrue(isinstance(error.to_dict()['1st'], dict))
self.assertTrue('2nd' in error.to_dict()['1st'])
self.assertIn('1st', error.to_dict())
self.assertIsInstance(error.to_dict()['1st'], dict)
self.assertIn('2nd', error.to_dict()['1st'])
self.assertEqual(error.to_dict()['1st']['2nd'], 'bad 2nd')
# moar levels
@ -40,10 +40,10 @@ class ValidatorErrorTest(unittest.TestCase):
}),
}),
})}
self.assertTrue('1st' in error.to_dict())
self.assertTrue('2nd' in error.to_dict()['1st'])
self.assertTrue('3rd' in error.to_dict()['1st']['2nd'])
self.assertTrue('4th' in error.to_dict()['1st']['2nd']['3rd'])
self.assertIn('1st', error.to_dict())
self.assertIn('2nd', error.to_dict()['1st'])
self.assertIn('3rd', error.to_dict()['1st']['2nd'])
self.assertIn('4th', error.to_dict()['1st']['2nd']['3rd'])
self.assertEqual(error.to_dict()['1st']['2nd']['3rd']['4th'],
'Inception')
@ -58,7 +58,7 @@ class ValidatorErrorTest(unittest.TestCase):
try:
User().validate()
except ValidationError as e:
self.assertTrue("User:None" in e.message)
self.assertIn("User:None", e.message)
self.assertEqual(e.to_dict(), {
'username': 'Field is required',
'name': 'Field is required'})
@ -68,7 +68,7 @@ class ValidatorErrorTest(unittest.TestCase):
try:
user.save()
except ValidationError as e:
self.assertTrue("User:RossC0" in e.message)
self.assertIn("User:RossC0", e.message)
self.assertEqual(e.to_dict(), {
'name': 'Field is required'})
@ -116,7 +116,7 @@ class ValidatorErrorTest(unittest.TestCase):
try:
Doc(id="bad").validate()
except ValidationError as e:
self.assertTrue("SubDoc:None" in e.message)
self.assertIn("SubDoc:None", e.message)
self.assertEqual(e.to_dict(), {
"e": {'val': 'OK could not be converted to int'}})
@ -127,14 +127,14 @@ class ValidatorErrorTest(unittest.TestCase):
doc = Doc.objects.first()
keys = doc._data.keys()
self.assertEqual(2, len(keys))
self.assertTrue('e' in keys)
self.assertTrue('id' in keys)
self.assertIn('e', keys)
self.assertIn('id', keys)
doc.e.val = "OK"
try:
doc.save()
except ValidationError as e:
self.assertTrue("Doc:test" in e.message)
self.assertIn("Doc:test", e.message)
self.assertEqual(e.to_dict(), {
"e": {'val': 'OK could not be converted to int'}})

View File

@ -175,7 +175,7 @@ class FieldTest(MongoDBTestCase):
self.assertEqual(person.name, None)
self.assertEqual(person.age, 30)
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['age'], person.age)
@ -211,7 +211,7 @@ class FieldTest(MongoDBTestCase):
self.assertEqual(person.name, None)
self.assertEqual(person.age, 30)
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.assertEqual(person._data['name'], person.name)
@ -1602,8 +1602,8 @@ class FieldTest(MongoDBTestCase):
e.save()
e2 = Simple.objects.get(id=e.id)
self.assertTrue(isinstance(e2.mapping[0], StringSetting))
self.assertTrue(isinstance(e2.mapping[1], IntegerSetting))
self.assertIsInstance(e2.mapping[0], StringSetting)
self.assertIsInstance(e2.mapping[1], IntegerSetting)
# Test querying
self.assertEqual(
@ -1772,8 +1772,8 @@ class FieldTest(MongoDBTestCase):
e.save()
e2 = Simple.objects.get(id=e.id)
self.assertTrue(isinstance(e2.mapping['somestring'], StringSetting))
self.assertTrue(isinstance(e2.mapping['someint'], IntegerSetting))
self.assertIsInstance(e2.mapping['somestring'], StringSetting)
self.assertIsInstance(e2.mapping['someint'], IntegerSetting)
# Test querying
self.assertEqual(
@ -1857,8 +1857,8 @@ class FieldTest(MongoDBTestCase):
e.save()
e2 = Extensible.objects.get(id=e.id)
self.assertTrue(isinstance(e2.mapping['somestring'], StringSetting))
self.assertTrue(isinstance(e2.mapping['someint'], IntegerSetting))
self.assertIsInstance(e2.mapping['somestring'], StringSetting)
self.assertIsInstance(e2.mapping['someint'], IntegerSetting)
with self.assertRaises(ValidationError):
e.mapping['someint'] = 123
@ -2563,7 +2563,7 @@ class FieldTest(MongoDBTestCase):
bm = Bookmark.objects(bookmark_object=post_1).first()
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.save()
@ -2571,7 +2571,7 @@ class FieldTest(MongoDBTestCase):
bm = Bookmark.objects(bookmark_object=link_1).first()
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):
"""Ensure that a ListField properly dereferences generic references.
@ -2818,7 +2818,7 @@ class FieldTest(MongoDBTestCase):
doc1 = Doc.objects.create()
doc2 = Doc.objects.create(ref=doc1)
self.assertTrue(isinstance(doc1.pk, ObjectId))
self.assertIsInstance(doc1.pk, ObjectId)
doc = Doc.objects.get(ref=doc1.pk)
self.assertEqual(doc, doc2)
@ -3421,13 +3421,13 @@ class FieldTest(MongoDBTestCase):
person.save()
person = Person.objects.first()
self.assertTrue(isinstance(person.like, Car))
self.assertIsInstance(person.like, Car)
person.like = Dish(food="arroz", number=15)
person.save()
person = Person.objects.first()
self.assertTrue(isinstance(person.like, Dish))
self.assertIsInstance(person.like, Dish)
def test_generic_embedded_document_choices(self):
"""Ensure you can limit GenericEmbeddedDocument choices."""
@ -3452,7 +3452,7 @@ class FieldTest(MongoDBTestCase):
person.save()
person = Person.objects.first()
self.assertTrue(isinstance(person.like, Dish))
self.assertIsInstance(person.like, Dish)
def test_generic_list_embedded_document_choices(self):
"""Ensure you can limit GenericEmbeddedDocument choices inside
@ -3479,7 +3479,7 @@ class FieldTest(MongoDBTestCase):
person.save()
person = Person.objects.first()
self.assertTrue(isinstance(person.likes[0], Dish))
self.assertIsInstance(person.likes[0], Dish)
def test_recursive_validation(self):
"""Ensure that a validation result to_dict is available."""
@ -3505,18 +3505,17 @@ class FieldTest(MongoDBTestCase):
except ValidationError as error:
# ValidationError.errors property
self.assertTrue(hasattr(error, 'errors'))
self.assertTrue(isinstance(error.errors, dict))
self.assertTrue('comments' in error.errors)
self.assertTrue(1 in error.errors['comments'])
self.assertTrue(isinstance(error.errors['comments'][1]['content'],
ValidationError))
self.assertIsInstance(error.errors, dict)
self.assertIn('comments', error.errors)
self.assertIn(1, error.errors['comments'])
self.assertIsInstance(error.errors['comments'][1]['content'], ValidationError)
# ValidationError.schema property
error_dict = error.to_dict()
self.assertTrue(isinstance(error_dict, dict))
self.assertTrue('comments' in error_dict)
self.assertTrue(1 in error_dict['comments'])
self.assertTrue('content' in error_dict['comments'][1])
self.assertIsInstance(error_dict, dict)
self.assertIn('comments', error_dict)
self.assertIn(1, error_dict['comments'])
self.assertIn('content', error_dict['comments'][1])
self.assertEqual(error_dict['comments'][1]['content'],
u'Field is required')
@ -3632,7 +3631,7 @@ class FieldTest(MongoDBTestCase):
# Passes regex validation
user = User(email='me@example.com')
self.assertTrue(user.validate() is None)
self.assertIsNone(user.validate())
def test_tuples_as_tuples(self):
"""Ensure that tuples remain tuples when they are inside
@ -3659,10 +3658,10 @@ class FieldTest(MongoDBTestCase):
doc.items = tuples
doc.save()
x = TestDoc.objects().get()
self.assertTrue(x is not None)
self.assertTrue(len(x.items) == 1)
self.assertTrue(tuple(x.items[0]) in tuples)
self.assertTrue(x.items[0] in tuples)
self.assertIsNotNone(x)
self.assertEqual(len(x.items), 1)
self.assertIn(tuple(x.items[0]), tuples)
self.assertIn(x.items[0], tuples)
def test_dynamic_fields_class(self):
class Doc2(Document):
@ -3812,8 +3811,8 @@ class FieldTest(MongoDBTestCase):
doc = TestLongFieldConsideredAsInt64(some_long=42).save()
db = get_db()
self.assertTrue(isinstance(db.test_long_field_considered_as_int64.find()[0]['some_long'], Int64))
self.assertTrue(isinstance(doc.some_long, six.integer_types))
self.assertIsInstance(db.test_long_field_considered_as_int64.find()[0]['some_long'], Int64)
self.assertIsInstance(doc.some_long, six.integer_types)
class EmbeddedDocumentListFieldTestCase(MongoDBTestCase):
@ -4364,7 +4363,7 @@ class CachedReferenceFieldTest(MongoDBTestCase):
ocorrence = Ocorrence.objects(animal__tag='heavy').first()
self.assertEqual(ocorrence.person, "teste")
self.assertTrue(isinstance(ocorrence.animal, Animal))
self.assertIsInstance(ocorrence.animal, Animal)
def test_cached_reference_field_decimal(self):
class PersonAuto(Document):
@ -4681,7 +4680,7 @@ class CachedReferenceFieldTest(MongoDBTestCase):
animal__tag='heavy',
animal__owner__tp='u').first()
self.assertEqual(ocorrence.person, "teste")
self.assertTrue(isinstance(ocorrence.animal, Animal))
self.assertIsInstance(ocorrence.animal, Animal)
def test_cached_reference_embedded_list_fields(self):
class Owner(EmbeddedDocument):
@ -4735,7 +4734,7 @@ class CachedReferenceFieldTest(MongoDBTestCase):
animal__tag='heavy',
animal__owner__tags='cool').first()
self.assertEqual(ocorrence.person, "teste 2")
self.assertTrue(isinstance(ocorrence.animal, Animal))
self.assertIsInstance(ocorrence.animal, Animal)
class LazyReferenceFieldTest(MongoDBTestCase):

View File

@ -53,7 +53,7 @@ class FileTest(MongoDBTestCase):
putfile.save()
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(result.the_file.read(), text)
self.assertEqual(result.the_file.content_type, content_type)
@ -71,7 +71,7 @@ class FileTest(MongoDBTestCase):
putfile.save()
result = PutFile.objects.first()
self.assertTrue(putfile == result)
self.assertEqual(putfile, result)
self.assertEqual(result.the_file.read(), text)
self.assertEqual(result.the_file.content_type, content_type)
result.the_file.delete()
@ -96,7 +96,7 @@ class FileTest(MongoDBTestCase):
streamfile.save()
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.content_type, content_type)
result.the_file.seek(0)
@ -132,7 +132,7 @@ class FileTest(MongoDBTestCase):
streamfile.save()
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.content_type, content_type)
result.the_file.seek(0)
@ -161,7 +161,7 @@ class FileTest(MongoDBTestCase):
setfile.save()
result = SetFile.objects.first()
self.assertTrue(setfile == result)
self.assertEqual(setfile, result)
self.assertEqual(result.the_file.read(), text)
# Try replacing file with new one
@ -169,7 +169,7 @@ class FileTest(MongoDBTestCase):
result.save()
result = SetFile.objects.first()
self.assertTrue(setfile == result)
self.assertEqual(setfile, result)
self.assertEqual(result.the_file.read(), more_text)
result.the_file.delete()
@ -231,8 +231,8 @@ class FileTest(MongoDBTestCase):
test_file_dupe = TestFile()
data = test_file_dupe.the_file.read() # Should be None
self.assertTrue(test_file.name != test_file_dupe.name)
self.assertTrue(test_file.the_file.read() != data)
self.assertNotEqual(test_file.name, test_file_dupe.name)
self.assertNotEqual(test_file.the_file.read(), data)
TestFile.drop_collection()
@ -291,7 +291,7 @@ class FileTest(MongoDBTestCase):
the_file = FileField()
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):
""" Test disk space usage when we delete/replace a file """

View File

@ -298,9 +298,9 @@ class GeoFieldTest(unittest.TestCase):
polygon = PolygonField()
geo_indicies = Event._geo_indices()
self.assertTrue({'fields': [('line', '2dsphere')]} in geo_indicies)
self.assertTrue({'fields': [('polygon', '2dsphere')]} in geo_indicies)
self.assertTrue({'fields': [('point', '2dsphere')]} in geo_indicies)
self.assertIn({'fields': [('line', '2dsphere')]}, geo_indicies)
self.assertIn({'fields': [('polygon', '2dsphere')]}, geo_indicies)
self.assertIn({'fields': [('point', '2dsphere')]}, geo_indicies)
def test_indexes_2dsphere_embedded(self):
"""Ensure that indexes are created automatically for GeoPointFields.
@ -316,9 +316,9 @@ class GeoFieldTest(unittest.TestCase):
venue = EmbeddedDocumentField(Venue)
geo_indicies = Event._geo_indices()
self.assertTrue({'fields': [('venue.line', '2dsphere')]} in geo_indicies)
self.assertTrue({'fields': [('venue.polygon', '2dsphere')]} in geo_indicies)
self.assertTrue({'fields': [('venue.point', '2dsphere')]} in geo_indicies)
self.assertIn({'fields': [('venue.line', '2dsphere')]}, geo_indicies)
self.assertIn({'fields': [('venue.polygon', '2dsphere')]}, geo_indicies)
self.assertIn({'fields': [('venue.point', '2dsphere')]}, geo_indicies)
def test_geo_indexes_recursion(self):
@ -335,9 +335,9 @@ class GeoFieldTest(unittest.TestCase):
Parent(name='Berlin').save()
info = Parent._get_collection().index_information()
self.assertFalse('location_2d' in info)
self.assertNotIn('location_2d', info)
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(Location._geo_indices()), 1)

View File

@ -181,7 +181,7 @@ class OnlyExcludeAllTest(unittest.TestCase):
employee.save()
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
obj = Employee.objects(id=employee.id).only('salary').get()

View File

@ -95,9 +95,9 @@ class GeoQueriesTest(MongoDBTestCase):
location__within_distance=point_and_distance)
self.assertEqual(events.count(), 2)
events = list(events)
self.assertTrue(event2 not in events)
self.assertTrue(event1 in events)
self.assertTrue(event3 in events)
self.assertNotIn(event2, events)
self.assertIn(event1, events)
self.assertIn(event3, events)
# find events within 10 degrees of san francisco
point_and_distance = [[-122.415579, 37.7566023], 10]
@ -285,9 +285,9 @@ class GeoQueriesTest(MongoDBTestCase):
location__geo_within_center=point_and_distance)
self.assertEqual(events.count(), 2)
events = list(events)
self.assertTrue(event2 not in events)
self.assertTrue(event1 in events)
self.assertTrue(event3 in events)
self.assertNotIn(event2, events)
self.assertIn(event1, events)
self.assertIn(event3, events)
def _test_embedded(self, point_field_class):
"""Helper test method ensuring given point field class works

View File

@ -59,11 +59,10 @@ class QuerySetTest(unittest.TestCase):
def test_initialisation(self):
"""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.Person._get_collection_name())
self.assertTrue(isinstance(self.Person.objects._collection,
pymongo.collection.Collection))
self.assertIsInstance(self.Person.objects._collection, pymongo.collection.Collection)
def test_cannot_perform_joins_references(self):
@ -89,8 +88,8 @@ class QuerySetTest(unittest.TestCase):
self.assertEqual(people.count(), 2)
results = list(people)
self.assertTrue(isinstance(results[0], self.Person))
self.assertTrue(isinstance(results[0].id, (ObjectId, str, unicode)))
self.assertIsInstance(results[0], self.Person)
self.assertIsInstance(results[0].id, (ObjectId, str, unicode))
self.assertEqual(results[0], user_a)
self.assertEqual(results[0].name, 'User A')
@ -126,6 +125,11 @@ class QuerySetTest(unittest.TestCase):
self.assertEqual(len(people2), 1)
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
person = self.Person.objects().limit(1).only('name').first()
self.assertEqual(person, user_a)
@ -225,7 +229,7 @@ class QuerySetTest(unittest.TestCase):
# Retrieve the first person from the database
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.age, 20)
@ -672,13 +676,13 @@ class QuerySetTest(unittest.TestCase):
result = self.Person(name="Bob", age=25).update(
upsert=True, full_result=True)
self.assertTrue(isinstance(result, UpdateResult))
self.assertTrue("upserted" in result.raw_result)
self.assertIsInstance(result, UpdateResult)
self.assertIn("upserted", result.raw_result)
self.assertFalse(result.raw_result["updatedExisting"])
bob = self.Person.objects.first()
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.Person(name="Bob", age=20).save()
@ -994,7 +998,7 @@ class QuerySetTest(unittest.TestCase):
# Retrieve the first person from the database
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.age, 20)
@ -1061,10 +1065,10 @@ class QuerySetTest(unittest.TestCase):
self.assertEqual(docs.count(), 1000)
docs_string = "%s" % docs
self.assertTrue("Doc: 0" in docs_string)
self.assertIn("Doc: 0", docs_string)
self.assertEqual(docs.count(), 1000)
self.assertTrue('(remaining elements truncated)' in "%s" % docs)
self.assertIn('(remaining elements truncated)', "%s" % docs)
# Limit and skip
docs = docs[1:4]
@ -1281,7 +1285,7 @@ class QuerySetTest(unittest.TestCase):
with db_ops_tracker() as q:
BlogPost.objects.filter(title='whatever').order_by().first()
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
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.order_by().first()
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):
""" Ensure that Doc.objects.get doesn't use any ordering.
@ -1316,13 +1320,13 @@ class QuerySetTest(unittest.TestCase):
with db_ops_tracker() as q:
BlogPost.objects.get(title='whatever')
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
with db_ops_tracker() as q:
BlogPost.objects.order_by('-title').get(title='whatever')
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):
"""Ensure that an embedded document is properly returned from
@ -1344,15 +1348,15 @@ class QuerySetTest(unittest.TestCase):
)
result = BlogPost.objects.first()
self.assertTrue(isinstance(result.author, User))
self.assertIsInstance(result.author, User)
self.assertEqual(result.author.name, 'Test User')
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')
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')
# 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"],',
'doc["cmnts"][i]["body"]']
for chunk in code_chunks:
self.assertTrue(chunk in sub_code)
self.assertIn(chunk, sub_code)
results = BlogPost.objects.exec_js(code)
expected_results = [
@ -1937,11 +1941,12 @@ class QuerySetTest(unittest.TestCase):
# ListField operator
BlogPost.objects.update(push__tags='mongo')
post.reload()
self.assertTrue('mongo' in post.tags)
self.assertIn('mongo', post.tags)
BlogPost.objects.update_one(push_all__tags=['db', 'nosql'])
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]
BlogPost.objects.update(pop__tags=1)
@ -3274,8 +3279,8 @@ class QuerySetTest(unittest.TestCase):
News.drop_collection()
info = News.objects._collection.index_information()
self.assertTrue('title_text_content_text' in info)
self.assertTrue('textIndexVersion' in info['title_text_content_text'])
self.assertIn('title_text_content_text', info)
self.assertIn('textIndexVersion', info['title_text_content_text'])
News(title="Neymar quebrou a vertebra",
content="O Brasil sofre com a perda de Neymar").save()
@ -3309,15 +3314,15 @@ class QuerySetTest(unittest.TestCase):
'$search': 'dilma', '$language': 'pt'},
'is_active': False})
self.assertEqual(new.is_active, False)
self.assertTrue('dilma' in new.content)
self.assertTrue('planejamento' in new.title)
self.assertFalse(new.is_active)
self.assertIn('dilma', new.content)
self.assertIn('planejamento', new.title)
query = News.objects.search_text("candidata")
self.assertEqual(query._search_text, "candidata")
new = query.first()
self.assertTrue(isinstance(new.get_text_score(), float))
self.assertIsInstance(new.get_text_score(), float)
# count
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.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[1].name, user2.name)
@ -3643,13 +3648,13 @@ class QuerySetTest(unittest.TestCase):
self.assertEqual(len(objects), 3)
self.assertTrue(post_1.id in objects)
self.assertTrue(post_2.id in objects)
self.assertTrue(post_5.id in objects)
self.assertIn(post_1.id, objects)
self.assertIn(post_2.id, objects)
self.assertIn(post_5.id, objects)
self.assertTrue(objects[post_1.id].title == post_1.title)
self.assertTrue(objects[post_2.id].title == post_2.title)
self.assertTrue(objects[post_5.id].title == post_5.title)
self.assertEqual(objects[post_1.id].title, post_1.title)
self.assertEqual(objects[post_2.id].title, post_2.title)
self.assertEqual(objects[post_5.id].title, post_5.title)
BlogPost.drop_collection()
@ -3669,7 +3674,7 @@ class QuerySetTest(unittest.TestCase):
Post.drop_collection()
self.assertTrue(isinstance(Post.objects, CustomQuerySet))
self.assertIsInstance(Post.objects, CustomQuerySet)
self.assertFalse(Post.objects.not_empty())
Post().save()
@ -3694,7 +3699,7 @@ class QuerySetTest(unittest.TestCase):
Post.drop_collection()
self.assertTrue(isinstance(Post.objects, CustomQuerySet))
self.assertIsInstance(Post.objects, CustomQuerySet)
self.assertFalse(Post.objects.not_empty())
Post().save()
@ -3741,7 +3746,7 @@ class QuerySetTest(unittest.TestCase):
pass
Post.drop_collection()
self.assertTrue(isinstance(Post.objects, CustomQuerySet))
self.assertIsInstance(Post.objects, CustomQuerySet)
self.assertFalse(Post.objects.not_empty())
Post().save()
@ -3769,7 +3774,7 @@ class QuerySetTest(unittest.TestCase):
pass
Post.drop_collection()
self.assertTrue(isinstance(Post.objects, CustomQuerySet))
self.assertIsInstance(Post.objects, CustomQuerySet)
self.assertFalse(Post.objects.not_empty())
Post().save()
@ -3860,17 +3865,17 @@ class QuerySetTest(unittest.TestCase):
test = Number.objects
test2 = test.clone()
self.assertFalse(test == test2)
self.assertNotEqual(test, test2)
self.assertEqual(test.count(), test2.count())
test = test.filter(n__gt=11)
test2 = test.clone()
self.assertFalse(test == test2)
self.assertNotEqual(test, test2)
self.assertEqual(test.count(), test2.count())
test = test.limit(10)
test2 = test.clone()
self.assertFalse(test == test2)
self.assertNotEqual(test, test2)
self.assertEqual(test.count(), test2.count())
Number.drop_collection()
@ -3960,7 +3965,7 @@ class QuerySetTest(unittest.TestCase):
value.get('unique', False),
value.get('sparse', False))
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):
"""Ensure that where clauses work.
@ -3984,13 +3989,13 @@ class QuerySetTest(unittest.TestCase):
'this["fielda"] >= this["fieldb"]', query._where_clause)
results = list(query)
self.assertEqual(2, len(results))
self.assertTrue(a in results)
self.assertTrue(c in results)
self.assertIn(a, results)
self.assertIn(c, results)
query = IntPair.objects.where('this[~fielda] == this[~fieldb]')
results = list(query)
self.assertEqual(1, len(results))
self.assertTrue(a in results)
self.assertIn(a, results)
query = IntPair.objects.where(
'function() { return this[~fielda] >= this[~fieldb] }')
@ -3998,8 +4003,8 @@ class QuerySetTest(unittest.TestCase):
'function() { return this["fielda"] >= this["fieldb"] }', query._where_clause)
results = list(query)
self.assertEqual(2, len(results))
self.assertTrue(a in results)
self.assertTrue(c in results)
self.assertIn(a, results)
self.assertIn(c, results)
with self.assertRaises(TypeError):
list(IntPair.objects.where(fielda__gte=3))
@ -4381,7 +4386,7 @@ class QuerySetTest(unittest.TestCase):
Test.drop_collection()
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):
meta = {'allow_inheritance': True}
@ -4390,7 +4395,7 @@ class QuerySetTest(unittest.TestCase):
Test.drop_collection()
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):
class MyDoc(DynamicDocument):
@ -4602,8 +4607,8 @@ class QuerySetTest(unittest.TestCase):
users = User.objects.only('name', 'price').as_pymongo()
results = list(users)
self.assertTrue(isinstance(results[0], dict))
self.assertTrue(isinstance(results[1], dict))
self.assertIsInstance(results[0], dict)
self.assertIsInstance(results[1], dict)
self.assertEqual(results[0]['name'], 'Bob Dole')
self.assertEqual(results[0]['price'], 1.11)
self.assertEqual(results[1]['name'], 'Barack Obama')
@ -4611,8 +4616,8 @@ class QuerySetTest(unittest.TestCase):
users = User.objects.only('name', 'last_login').as_pymongo()
results = list(users)
self.assertTrue(isinstance(results[0], dict))
self.assertTrue(isinstance(results[1], dict))
self.assertIsInstance(results[0], dict)
self.assertIsInstance(results[1], dict)
self.assertEqual(results[0], {
'name': 'Bob Dole'
})
@ -4669,12 +4674,10 @@ class QuerySetTest(unittest.TestCase):
User(name="Bob Dole", organization=whitehouse).save()
qs = User.objects()
self.assertTrue(isinstance(qs.first().organization, Organization))
self.assertFalse(isinstance(qs.no_dereference().first().organization,
Organization))
self.assertFalse(isinstance(qs.no_dereference().get().organization,
Organization))
self.assertTrue(isinstance(qs.first().organization, Organization))
self.assertIsInstance(qs.first().organization, Organization)
self.assertNotIsInstance(qs.no_dereference().first().organization, Organization)
self.assertNotIsInstance(qs.no_dereference().get().organization, Organization)
self.assertIsInstance(qs.first().organization, Organization)
def test_no_dereference_embedded_doc(self):
@ -4707,9 +4710,9 @@ class QuerySetTest(unittest.TestCase):
result = Organization.objects().no_dereference().first()
self.assertTrue(isinstance(result.admin[0], (DBRef, ObjectId)))
self.assertTrue(isinstance(result.member.user, (DBRef, ObjectId)))
self.assertTrue(isinstance(result.members[0].user, (DBRef, ObjectId)))
self.assertIsInstance(result.admin[0], (DBRef, ObjectId))
self.assertIsInstance(result.member.user, (DBRef, ObjectId))
self.assertIsInstance(result.members[0].user, (DBRef, ObjectId))
def test_cached_queryset(self):
class Person(Document):
@ -4750,18 +4753,27 @@ class QuerySetTest(unittest.TestCase):
for i in range(100):
Person(name="No: %s" % i).save()
with query_counter() as q:
self.assertEqual(q, 0)
people = Person.objects.no_cache()
with query_counter() as q:
try:
self.assertEqual(q, 0)
people = Person.objects.no_cache()
[x for x in people]
self.assertEqual(q, 1)
[x for x in people]
self.assertEqual(q, 1)
list(people)
self.assertEqual(q, 2)
list(people)
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):
@ -5052,7 +5064,7 @@ class QuerySetTest(unittest.TestCase):
op = q.db.system.profile.find({"ns":
{"$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')
with query_counter() as p:
@ -5063,8 +5075,7 @@ class QuerySetTest(unittest.TestCase):
op = p.db.system.profile.find({"ns":
{"$ne": "%s.system.indexes" % q.db.name}})[0]
self.assertTrue('$orderby' in op['query'],
'BaseQuerySet cannot remove orderby in for loop')
self.assertIn('$orderby', op['query'], 'BaseQuerySet cannot remove orderby in for loop')
def test_bool_with_ordering_from_meta_dict(self):
@ -5088,7 +5099,7 @@ class QuerySetTest(unittest.TestCase):
op = q.db.system.profile.find({"ns":
{"$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')
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
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__':
unittest.main()

View File

@ -48,15 +48,15 @@ class TransformTest(unittest.TestCase):
for k, v in (("set", "$set"), ("set_on_insert", "$setOnInsert"), ("push", "$push")):
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 = transform.update(DicDoc, unset__dictField__test=doc)
self.assertEqual(update["$unset"]["dictField.test"], 1)
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'])
self.assertEqual(update, {'$pull': {'foo': {'$in': ['a']}}})
@ -88,17 +88,15 @@ class TransformTest(unittest.TestCase):
post = BlogPost(**data)
post.save()
self.assertTrue('postTitle' in
BlogPost.objects(title=data['title'])._query)
self.assertIn('postTitle', BlogPost.objects(title=data['title'])._query)
self.assertFalse('title' in
BlogPost.objects(title=data['title'])._query)
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.assertTrue('postComments.commentContent' in
BlogPost.objects(comments__content='test')._query)
self.assertIn('postComments.commentContent', BlogPost.objects(comments__content='test')._query)
self.assertEqual(BlogPost.objects(comments__content='test').count(), 1)
BlogPost.drop_collection()
@ -116,8 +114,8 @@ class TransformTest(unittest.TestCase):
post = BlogPost(**data)
post.save()
self.assertTrue('_id' in BlogPost.objects(pk=data['title'])._query)
self.assertTrue('_id' in BlogPost.objects(title=data['title'])._query)
self.assertIn('_id', BlogPost.objects(pk=data['title'])._query)
self.assertIn('_id', BlogPost.objects(title=data['title'])._query)
self.assertEqual(BlogPost.objects(pk=data['title']).count(), 1)
BlogPost.drop_collection()
@ -260,31 +258,31 @@ class TransformTest(unittest.TestCase):
events = Event.objects(location__within=box)
with self.assertRaises(InvalidQueryError):
events.count()
def test_update_pull_for_list_fields(self):
"""
Test added to check pull operation in update for
"""
Test added to check pull operation in update for
EmbeddedDocumentListField which is inside a EmbeddedDocumentField
"""
class Word(EmbeddedDocument):
word = StringField()
index = IntField()
class SubDoc(EmbeddedDocument):
heading = ListField(StringField())
text = EmbeddedDocumentListField(Word)
class MainDoc(Document):
title = StringField()
content = EmbeddedDocumentField(SubDoc)
word = Word(word='abc', index=1)
update = transform.update(MainDoc, pull__content__text=word)
self.assertEqual(update, {'$pull': {'content.text': SON([('word', u'abc'), ('index', 1)])}})
update = transform.update(MainDoc, pull__content__heading='xyz')
self.assertEqual(update, {'$pull': {'content.heading': 'xyz'}})
if __name__ == '__main__':
unittest.main()

View File

@ -196,7 +196,7 @@ class QTest(unittest.TestCase):
test2 = test.clone()
self.assertEqual(test2.count(), 3)
self.assertFalse(test2 == test)
self.assertNotEqual(test2, test)
test3 = test2.filter(x=6)
self.assertEqual(test3.count(), 1)

View File

@ -39,15 +39,15 @@ class ConnectionTest(unittest.TestCase):
connect('mongoenginetest')
conn = get_connection()
self.assertTrue(isinstance(conn, pymongo.mongo_client.MongoClient))
self.assertIsInstance(conn, pymongo.mongo_client.MongoClient)
db = get_db()
self.assertTrue(isinstance(db, pymongo.database.Database))
self.assertIsInstance(db, pymongo.database.Database)
self.assertEqual(db.name, 'mongoenginetest')
connect('mongoenginetest2', alias='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):
"""Ensure that the connect() method works properly in mocking.
@ -59,31 +59,31 @@ class ConnectionTest(unittest.TestCase):
connect('mongoenginetest', host='mongomock://localhost')
conn = get_connection()
self.assertTrue(isinstance(conn, mongomock.MongoClient))
self.assertIsInstance(conn, mongomock.MongoClient)
connect('mongoenginetest2', host='mongomock://localhost', alias='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')
conn = get_connection('testdb3')
self.assertTrue(isinstance(conn, mongomock.MongoClient))
self.assertIsInstance(conn, mongomock.MongoClient)
connect('mongoenginetest4', is_mock=True, alias='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')
conn = get_connection('testdb5')
self.assertTrue(isinstance(conn, mongomock.MongoClient))
self.assertIsInstance(conn, mongomock.MongoClient)
connect(host='mongomock://localhost:27017/mongoenginetest6', alias='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')
conn = get_connection('testdb7')
self.assertTrue(isinstance(conn, mongomock.MongoClient))
self.assertIsInstance(conn, mongomock.MongoClient)
def test_connect_with_host_list(self):
"""Ensure that the connect() method works when host is a list
@ -97,27 +97,27 @@ class ConnectionTest(unittest.TestCase):
connect(host=['mongomock://localhost'])
conn = get_connection()
self.assertTrue(isinstance(conn, mongomock.MongoClient))
self.assertIsInstance(conn, mongomock.MongoClient)
connect(host=['mongodb://localhost'], is_mock=True, alias='testdb2')
conn = get_connection('testdb2')
self.assertTrue(isinstance(conn, mongomock.MongoClient))
self.assertIsInstance(conn, mongomock.MongoClient)
connect(host=['localhost'], is_mock=True, alias='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')
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')
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')
conn = get_connection('testdb6')
self.assertTrue(isinstance(conn, mongomock.MongoClient))
self.assertIsInstance(conn, mongomock.MongoClient)
def test_disconnect(self):
"""Ensure that the disconnect() method works properly
@ -163,10 +163,10 @@ class ConnectionTest(unittest.TestCase):
connect("testdb_uri", host='mongodb://username:password@localhost/mongoenginetest')
conn = get_connection()
self.assertTrue(isinstance(conn, pymongo.mongo_client.MongoClient))
self.assertIsInstance(conn, pymongo.mongo_client.MongoClient)
db = get_db()
self.assertTrue(isinstance(db, pymongo.database.Database))
self.assertIsInstance(db, pymongo.database.Database)
self.assertEqual(db.name, 'mongoenginetest')
c.admin.system.users.remove({})
@ -179,10 +179,10 @@ class ConnectionTest(unittest.TestCase):
connect("mongoenginetest", host='mongodb://localhost/')
conn = get_connection()
self.assertTrue(isinstance(conn, pymongo.mongo_client.MongoClient))
self.assertIsInstance(conn, pymongo.mongo_client.MongoClient)
db = get_db()
self.assertTrue(isinstance(db, pymongo.database.Database))
self.assertIsInstance(db, pymongo.database.Database)
self.assertEqual(db.name, 'mongoenginetest')
def test_connect_uri_default_db(self):
@ -192,10 +192,10 @@ class ConnectionTest(unittest.TestCase):
connect(host='mongodb://localhost/')
conn = get_connection()
self.assertTrue(isinstance(conn, pymongo.mongo_client.MongoClient))
self.assertIsInstance(conn, pymongo.mongo_client.MongoClient)
db = get_db()
self.assertTrue(isinstance(db, pymongo.database.Database))
self.assertIsInstance(db, pymongo.database.Database)
self.assertEqual(db.name, 'test')
def test_uri_without_credentials_doesnt_override_conn_settings(self):
@ -242,7 +242,7 @@ class ConnectionTest(unittest.TestCase):
'mongoenginetest?authSource=admin')
)
db = get_db('test2')
self.assertTrue(isinstance(db, pymongo.database.Database))
self.assertIsInstance(db, pymongo.database.Database)
self.assertEqual(db.name, 'mongoenginetest')
# Clear all users
@ -255,10 +255,10 @@ class ConnectionTest(unittest.TestCase):
self.assertRaises(MongoEngineConnectionError, get_connection)
conn = get_connection('testdb')
self.assertTrue(isinstance(conn, pymongo.mongo_client.MongoClient))
self.assertIsInstance(conn, pymongo.mongo_client.MongoClient)
db = get_db('testdb')
self.assertTrue(isinstance(db, pymongo.database.Database))
self.assertIsInstance(db, pymongo.database.Database)
self.assertEqual(db.name, 'mongoenginetest2')
def test_register_connection_defaults(self):
@ -267,7 +267,7 @@ class ConnectionTest(unittest.TestCase):
register_connection('testdb', 'mongoenginetest', host=None, port=None)
conn = get_connection('testdb')
self.assertTrue(isinstance(conn, pymongo.mongo_client.MongoClient))
self.assertIsInstance(conn, pymongo.mongo_client.MongoClient)
def test_connection_kwargs(self):
"""Ensure that connection kwargs get passed to pymongo."""
@ -326,7 +326,7 @@ class ConnectionTest(unittest.TestCase):
if IS_PYMONGO_3:
c = connect(host='mongodb://localhost/test?replicaSet=local-rs')
db = get_db()
self.assertTrue(isinstance(db, pymongo.database.Database))
self.assertIsInstance(db, pymongo.database.Database)
self.assertEqual(db.name, 'test')
else:
# PyMongo < v3.x raises an exception:
@ -343,7 +343,7 @@ class ConnectionTest(unittest.TestCase):
self.assertEqual(c._MongoClient__options.replica_set_name,
'local-rs')
db = get_db()
self.assertTrue(isinstance(db, pymongo.database.Database))
self.assertIsInstance(db, pymongo.database.Database)
self.assertEqual(db.name, 'test')
else:
# PyMongo < v3.x raises an exception:
@ -377,8 +377,8 @@ class ConnectionTest(unittest.TestCase):
mongo_connections = mongoengine.connection._connections
self.assertEqual(len(mongo_connections.items()), 2)
self.assertTrue('t1' in mongo_connections.keys())
self.assertTrue('t2' in mongo_connections.keys())
self.assertIn('t1', mongo_connections.keys())
self.assertIn('t2', mongo_connections.keys())
if not IS_PYMONGO_3:
self.assertEqual(mongo_connections['t1'].host, 'localhost')
self.assertEqual(mongo_connections['t2'].host, '127.0.0.1')

View File

@ -89,15 +89,15 @@ class ContextManagersTest(unittest.TestCase):
with no_dereference(Group) as Group:
group = Group.objects.first()
self.assertTrue(all([not isinstance(m, User)
for m in group.members]))
self.assertFalse(isinstance(group.ref, User))
self.assertFalse(isinstance(group.generic, User))
for m in group.members:
self.assertNotIsInstance(m, User)
self.assertNotIsInstance(group.ref, User)
self.assertNotIsInstance(group.generic, User)
self.assertTrue(all([isinstance(m, User)
for m in group.members]))
self.assertTrue(isinstance(group.ref, User))
self.assertTrue(isinstance(group.generic, User))
for m in group.members:
self.assertIsInstance(m, User)
self.assertIsInstance(group.ref, User)
self.assertIsInstance(group.generic, User)
def test_no_dereference_context_manager_dbref(self):
"""Ensure that DBRef items in ListFields aren't dereferenced.
@ -129,13 +129,13 @@ class ContextManagersTest(unittest.TestCase):
group = Group.objects.first()
self.assertTrue(all([not isinstance(m, User)
for m in group.members]))
self.assertFalse(isinstance(group.ref, User))
self.assertFalse(isinstance(group.generic, User))
self.assertNotIsInstance(group.ref, User)
self.assertNotIsInstance(group.generic, User)
self.assertTrue(all([isinstance(m, User)
for m in group.members]))
self.assertTrue(isinstance(group.ref, User))
self.assertTrue(isinstance(group.generic, User))
self.assertIsInstance(group.ref, User)
self.assertIsInstance(group.generic, User)
def test_no_sub_classes(self):
class A(Document):
@ -209,18 +209,99 @@ class ContextManagersTest(unittest.TestCase):
with no_sub_classes(User):
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):
connect('mongoenginetest')
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:
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):
db.test.find({}).count()
def test_query_counter_ignores_particular_queries(self):
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__':
unittest.main()

View File

@ -200,8 +200,8 @@ class FieldTest(unittest.TestCase):
group = Group(author=user, members=[user]).save()
raw_data = Group._get_collection().find_one()
self.assertTrue(isinstance(raw_data['author'], DBRef))
self.assertTrue(isinstance(raw_data['members'][0], DBRef))
self.assertIsInstance(raw_data['author'], DBRef)
self.assertIsInstance(raw_data['members'][0], DBRef)
group = Group.objects.first()
self.assertEqual(group.author, user)
@ -224,8 +224,8 @@ class FieldTest(unittest.TestCase):
self.assertEqual(group.members, [user])
raw_data = Group._get_collection().find_one()
self.assertTrue(isinstance(raw_data['author'], ObjectId))
self.assertTrue(isinstance(raw_data['members'][0], ObjectId))
self.assertIsInstance(raw_data['author'], ObjectId)
self.assertIsInstance(raw_data['members'][0], ObjectId)
def test_recursive_reference(self):
"""Ensure that ReferenceFields can reference their own documents.
@ -469,7 +469,7 @@ class FieldTest(unittest.TestCase):
self.assertEqual(q, 4)
for m in group_obj.members:
self.assertTrue('User' in m.__class__.__name__)
self.assertIn('User', m.__class__.__name__)
# Document select_related
with query_counter() as q:
@ -485,7 +485,7 @@ class FieldTest(unittest.TestCase):
self.assertEqual(q, 4)
for m in group_obj.members:
self.assertTrue('User' in m.__class__.__name__)
self.assertIn('User', m.__class__.__name__)
# Queryset select_related
with query_counter() as q:
@ -502,7 +502,7 @@ class FieldTest(unittest.TestCase):
self.assertEqual(q, 4)
for m in group_obj.members:
self.assertTrue('User' in m.__class__.__name__)
self.assertIn('User', m.__class__.__name__)
UserA.drop_collection()
UserB.drop_collection()
@ -560,7 +560,7 @@ class FieldTest(unittest.TestCase):
self.assertEqual(q, 4)
for m in group_obj.members:
self.assertTrue('User' in m.__class__.__name__)
self.assertIn('User', m.__class__.__name__)
# Document select_related
with query_counter() as q:
@ -576,7 +576,7 @@ class FieldTest(unittest.TestCase):
self.assertEqual(q, 4)
for m in group_obj.members:
self.assertTrue('User' in m.__class__.__name__)
self.assertIn('User', m.__class__.__name__)
# Queryset select_related
with query_counter() as q:
@ -593,7 +593,7 @@ class FieldTest(unittest.TestCase):
self.assertEqual(q, 4)
for m in group_obj.members:
self.assertTrue('User' in m.__class__.__name__)
self.assertIn('User', m.__class__.__name__)
UserA.drop_collection()
UserB.drop_collection()
@ -633,7 +633,7 @@ class FieldTest(unittest.TestCase):
self.assertEqual(q, 2)
for k, m in group_obj.members.iteritems():
self.assertTrue(isinstance(m, User))
self.assertIsInstance(m, User)
# Document select_related
with query_counter() as q:
@ -646,7 +646,7 @@ class FieldTest(unittest.TestCase):
self.assertEqual(q, 2)
for k, m in group_obj.members.iteritems():
self.assertTrue(isinstance(m, User))
self.assertIsInstance(m, User)
# Queryset select_related
with query_counter() as q:
@ -660,7 +660,7 @@ class FieldTest(unittest.TestCase):
self.assertEqual(q, 2)
for k, m in group_obj.members.iteritems():
self.assertTrue(isinstance(m, User))
self.assertIsInstance(m, User)
User.drop_collection()
Group.drop_collection()
@ -715,7 +715,7 @@ class FieldTest(unittest.TestCase):
self.assertEqual(q, 4)
for k, m in group_obj.members.iteritems():
self.assertTrue('User' in m.__class__.__name__)
self.assertIn('User', m.__class__.__name__)
# Document select_related
with query_counter() as q:
@ -731,7 +731,7 @@ class FieldTest(unittest.TestCase):
self.assertEqual(q, 4)
for k, m in group_obj.members.iteritems():
self.assertTrue('User' in m.__class__.__name__)
self.assertIn('User', m.__class__.__name__)
# Queryset select_related
with query_counter() as q:
@ -748,7 +748,7 @@ class FieldTest(unittest.TestCase):
self.assertEqual(q, 4)
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().save()
@ -806,7 +806,7 @@ class FieldTest(unittest.TestCase):
self.assertEqual(q, 2)
for k, m in group_obj.members.iteritems():
self.assertTrue(isinstance(m, UserA))
self.assertIsInstance(m, UserA)
# Document select_related
with query_counter() as q:
@ -822,7 +822,7 @@ class FieldTest(unittest.TestCase):
self.assertEqual(q, 2)
for k, m in group_obj.members.iteritems():
self.assertTrue(isinstance(m, UserA))
self.assertIsInstance(m, UserA)
# Queryset select_related
with query_counter() as q:
@ -839,7 +839,7 @@ class FieldTest(unittest.TestCase):
self.assertEqual(q, 2)
for k, m in group_obj.members.iteritems():
self.assertTrue(isinstance(m, UserA))
self.assertIsInstance(m, UserA)
UserA.drop_collection()
Group.drop_collection()
@ -894,7 +894,7 @@ class FieldTest(unittest.TestCase):
self.assertEqual(q, 4)
for k, m in group_obj.members.iteritems():
self.assertTrue('User' in m.__class__.__name__)
self.assertIn('User', m.__class__.__name__)
# Document select_related
with query_counter() as q:
@ -910,7 +910,7 @@ class FieldTest(unittest.TestCase):
self.assertEqual(q, 4)
for k, m in group_obj.members.iteritems():
self.assertTrue('User' in m.__class__.__name__)
self.assertIn('User', m.__class__.__name__)
# Queryset select_related
with query_counter() as q:
@ -927,7 +927,7 @@ class FieldTest(unittest.TestCase):
self.assertEqual(q, 4)
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().save()
@ -1209,10 +1209,10 @@ class FieldTest(unittest.TestCase):
# Can't use query_counter across databases - so test the _data object
book = Book.objects.first()
self.assertFalse(isinstance(book._data['author'], User))
self.assertNotIsInstance(book._data['author'], User)
book.select_related()
self.assertTrue(isinstance(book._data['author'], User))
self.assertIsInstance(book._data['author'], User)
def test_non_ascii_pk(self):
"""