summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorYuval Adam <_@yuv.al>2024-05-09 11:49:27 +0200
committerYuval Adam <_@yuv.al>2024-05-09 11:49:27 +0200
commitf8c99a7b08210e3c1ae5abc8d11670b05f33ccde (patch)
tree8a226fafa0ebb0f2ec8e8d5c5090f1962784188a
parent0c5ad432730824ced43d32bac0028727a42945f5 (diff)
Implement delete() and exists()
-rw-r--r--tests/test_stash.py15
-rw-r--r--ymlstash/stash.py16
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)