From f8c99a7b08210e3c1ae5abc8d11670b05f33ccde Mon Sep 17 00:00:00 2001 From: Yuval Adam <_@yuv.al> Date: Thu, 9 May 2024 11:49:27 +0200 Subject: Implement delete() and exists() --- tests/test_stash.py | 15 +++++++++++++++ ymlstash/stash.py | 16 +++++++++++++--- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/tests/test_stash.py b/tests/test_stash.py index 88cc466..0e84eae 100644 --- a/tests/test_stash.py +++ b/tests/test_stash.py @@ -28,11 +28,26 @@ def test_invalid_path(): def test_stash(): stash = YmlStash(User, TEST_STASH_PATH) + yuval = User(name="yuval", age=42) stash.save(yuval, "foo") + assert stash.exists("foo") + assert not stash.exists("goo") assert stash.list_keys() == ["foo"] + obj = stash.load("foo") assert obj == yuval + + goo = User(name="goo", age=10) + stash.save(goo, "goo") + assert stash.list_keys() == ["foo", "goo"] + + stash.delete("foo") + assert stash.list_keys() == ["goo"] + + with pytest.raises(Exception): + stash.delete("foo") + stash.drop() assert stash.list_keys() == [] diff --git a/ymlstash/stash.py b/ymlstash/stash.py index 5034ae0..52d74e0 100644 --- a/ymlstash/stash.py +++ b/ymlstash/stash.py @@ -39,6 +39,17 @@ class YmlStash: with open(self._get_path(key), "w") as f: f.write(yaml.dump(asdict(obj))) + def delete(self, key): + try: + os.remove(self._get_path(key)) + except FileNotFoundError: + raise Exception( + f"Attempting to delete key '{key}' which was not found in stash" + ) + + def exists(self, key): + return self._get_path(key).exists() + def _list_files(self): return [f for f in os.listdir(self.path) if f.endswith(self.file_suffix)] @@ -46,6 +57,5 @@ class YmlStash: return [f.replace(self.file_suffix, "") for f in self._list_files()] def drop(self): - for f in self._list_files(): - if f.endswith(self.file_suffix): - os.remove(self.path / f) + for key in self.list_keys(): + self.delete(key) -- cgit v1.3.1