Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion mongoengine/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,10 @@ class from the :data:`mongoengine.common._class_registry_cache`.
queryset_classes = ('OperationError',)
deref_classes = ('DeReference',)

if cls_name in doc_classes:
if cls_name == 'BaseDocument':
from mongoengine.base import document as module
import_classes = ['BaseDocument']
elif cls_name in doc_classes:
from mongoengine import document as module
import_classes = doc_classes
elif cls_name in field_classes:
Expand Down
17 changes: 15 additions & 2 deletions mongoengine/queryset/transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,21 @@ def query(_doc_cls=None, **kwargs):
value = value['_id']

elif op in ('in', 'nin', 'all', 'near') and not isinstance(value, dict):
# 'in', 'nin' and 'all' require a list of values
value = [field.prepare_query_value(op, v) for v in value]
# Raise an error if the in/nin/all/near param is not iterable. We need a
# special check for BaseDocument, because - although it's iterable - using
# it as such in the context of this method is most definitely a mistake.
BaseDocument = _import_class('BaseDocument')
if isinstance(value, BaseDocument):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If all of the above truly expect an iterable, then we should raise an error for any non-iterable, not just a BaseDocument.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, the problem is actually that BaseDocument is iterable.

Copy link
Contributor Author

@malthejorgensen malthejorgensen Dec 4, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both the checks mentioned in this StackOverflow thread will say that BaseDocument is iterable. (for k in user will iterate over each field of the document user)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ahh, I missed that, thanks for clearing that up! I think in such case we can change this condition to:

# Raise an error if the in/nin/all/near param is not iterable. We need a
# special check for BaseDocument, because - although it's iterable - using
# it as such in the context of this method is most definitely a mistake.
if not hasattr(value, '__iter__') or isinstance(value, BaseDocument):
   raise TypeError(...)

The comment is crucial, too, given that this is a pretty unintuitive isinstance check.What do you think @malthejorgensen ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree, I'll make the change

raise TypeError("When using the `in`, `nin`, `all`, or "
"`near`-operators you can\'t use a "
"`Document`, you must wrap your object "
"in a list (object -> [object]).")
elif not hasattr(value, '__iter__'):
raise TypeError("The `in`, `nin`, `all`, or "
"`near`-operators must be applied to an "
"iterable (e.g. a list).")
else:
value = [field.prepare_query_value(op, v) for v in value]

# If we're querying a GenericReferenceField, we need to alter the
# key depending on the value:
Expand Down
2 changes: 1 addition & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@ cover-package=mongoengine
[flake8]
ignore=E501,F401,F403,F405,I201
exclude=build,dist,docs,venv,venv3,.tox,.eggs,tests
max-complexity=45
max-complexity=47
application-import-names=mongoengine,tests
50 changes: 50 additions & 0 deletions tests/queryset/queryset.py
Original file line number Diff line number Diff line change
Expand Up @@ -4963,6 +4963,56 @@ class Data(Document):
self.assertEqual(i, 249)
self.assertEqual(j, 249)

def test_in_operator_on_non_iterable(self):
"""Ensure that using the `__in` operator on a non-iterable raises an
error.
"""
class User(Document):
name = StringField()

class BlogPost(Document):
content = StringField()
authors = ListField(ReferenceField(User))

User.drop_collection()
BlogPost.drop_collection()

author = User(name='Test User')
author.save()
post = BlogPost(content='Had a good coffee today...', authors=[author])
post.save()

blog_posts = BlogPost.objects(authors__in=[author])
self.assertEqual(list(blog_posts), [post])

# Using the `__in`-operator with a non-iterable should raise a TypeError
self.assertRaises(TypeError, BlogPost.objects(authors__in=author.id).count)

def test_in_operator_on_document(self):
"""Ensure that using the `__in` operator on a `Document` raises an
error.
"""
class User(Document):
name = StringField()

class BlogPost(Document):
content = StringField()
authors = ListField(ReferenceField(User))

User.drop_collection()
BlogPost.drop_collection()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These are redundant - by convention we should just take care of dropping existing collections at the beginning of each test (which you already do).


author = User(name='Test User')
author.save()
post = BlogPost(content='Had a good coffee today...', authors=[author])
post.save()

blog_posts = BlogPost.objects(authors__in=[author])
self.assertEqual(list(blog_posts), [post])

# Using the `__in`-operator with a `Document` should raise a TypeError
self.assertRaises(TypeError, BlogPost.objects(authors__in=author).count)


if __name__ == '__main__':
unittest.main()