From 8ba93d31047c67f742662a865b0f09cb45f5d10b Mon Sep 17 00:00:00 2001 From: Brice Parent <34689945+Flowtter@users.noreply.github.com> Date: Thu, 15 Dec 2022 11:10:18 +0100 Subject: [PATCH] Add support for delete_one (#45) --- mongo_thingy/__init__.py | 7 +++++++ tests/__init__.py | 21 +++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/mongo_thingy/__init__.py b/mongo_thingy/__init__.py index 84f116f..ae4be55 100644 --- a/mongo_thingy/__init__.py +++ b/mongo_thingy/__init__.py @@ -161,6 +161,13 @@ def find_one(cls, filter=None, *args, **kwargs): cursor = cls.find(filter, *args, **kwargs) return cursor.first() + @classmethod + def delete_one(cls, filter=None, *args, **kwargs): + if filter is not None and not isinstance(filter, Mapping): + filter = {"_id": filter} + + return cls.collection.delete_one(filter, *args, **kwargs) + @property def id(self): return self.__dict__.get("id") or self._id diff --git a/tests/__init__.py b/tests/__init__.py index 61c05ce..f92c299 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -328,6 +328,27 @@ def test_thingy_find_one(TestThingy, collection): assert thingy is None +def test_thingy_delete_one(TestThingy, collection): + collection.insert_many( + [{"foo": "bar"}, {"bar": "qux"}, {"bar": "baz"}, {"bar": "baz"}] + ) + TestThingy.delete_one({"foo": "bar"}) + assert TestThingy.find_one({"foo": "bar"}) is None + + qux = TestThingy.find_one({"bar": "qux"}) + + TestThingy.delete_one(qux.id) + assert TestThingy.find_one({"bar": "qux"}) is None + + TestThingy.delete_one(qux.id) + assert TestThingy.find_one({"bar": "qux"}) is None + + TestThingy.delete_one({"bar": "baz"}) + assert TestThingy.find_one({"bar": "baz"}) is not None + TestThingy.delete_one({"bar": "baz"}) + assert TestThingy.find_one({"bar": "baz"}) is None + + @pytest.mark.ignore_backends("montydb") def test_thingy_find_one_and_replace(TestThingy, collection): collection.insert_many([{"bar": "baz"}, {"bar": "qux"}])