From adce9e6220616ee030041da7ee6c12f78a133132 Mon Sep 17 00:00:00 2001 From: Emmanuel Leblond Date: Fri, 19 Feb 2016 01:58:15 +0100 Subject: [PATCH] Raise OperationError in drop_collection if no collection is set --- docs/changelog.rst | 1 + mongoengine/document.py | 12 +++++++++++- tests/fields/fields.py | 10 ++++++++++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 3794e9e3..069872ec 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -7,6 +7,7 @@ Changes in 0.10.7 - DEV - Fixed not being able to specify `use_db_field=False` on `ListField(EmbeddedDocumentField)` instances - Fixed cascade delete mixing among collections #1224 - Add `signal_kwargs` argument to `Document.save`, `Document.delete` and `BaseQuerySet.insert` to be passed to signals calls #1206 +- Raise `OperationError` when trying to do a `drop_collection` on document with no collection set. Changes in 0.10.6 ================= diff --git a/mongoengine/document.py b/mongoengine/document.py index 8211d95e..52353523 100644 --- a/mongoengine/document.py +++ b/mongoengine/document.py @@ -679,10 +679,20 @@ class Document(BaseDocument): def drop_collection(cls): """Drops the entire collection associated with this :class:`~mongoengine.Document` type from the database. + + Raises :class:`OperationError` if the document has no collection set + (i.g. if it is `abstract`) + + .. versionchanged:: 0.10.7 + :class:`OperationError` exception raised if no collection available """ + col_name = cls._get_collection_name() + if not col_name: + raise OperationError('Document %s has no collection defined ' + '(is it abstract ?)' % cls) cls._collection = None db = cls._get_db() - db.drop_collection(cls._get_collection_name()) + db.drop_collection(col_name) @classmethod def create_index(cls, keys, background=False, **kwargs): diff --git a/tests/fields/fields.py b/tests/fields/fields.py index bf2b5dd5..eb2f46c7 100644 --- a/tests/fields/fields.py +++ b/tests/fields/fields.py @@ -2285,6 +2285,16 @@ class FieldTest(unittest.TestCase): Member.drop_collection() BlogPost.drop_collection() + def test_drop_abstract_document(self): + """Ensure that an abstract document cannot be dropped given it + has no underlying collection. + """ + class AbstractDoc(Document): + name = StringField() + meta = {"abstract": True} + + self.assertRaises(OperationError, AbstractDoc.drop_collection) + def test_reference_class_with_abstract_parent(self): """Ensure that a class with an abstract parent can be referenced. """