Del and contains for DB

pull/24/head^2
Michael Egorov 2017-09-05 16:02:25 -07:00
parent 1219734484
commit abfbdc7c16
2 changed files with 22 additions and 1 deletions

View File

@ -23,7 +23,20 @@ class DB(object):
def __getitem__(self, key):
with self.db.begin(write=False) as tx:
return tx.get(key)
result = tx.get(key)
if result is None:
raise KeyError(key)
else:
return result
def __delitem__(self, key):
with self.db.begin(write=True) as tx:
tx.pop(key)
def __contains__(self, key):
with self.db.begin(write=False) as tx:
cursor = tx.cursor()
return cursor.set_key(key)
def close(self):
self.db.close()

View File

@ -1,6 +1,7 @@
import nkms.db
from nkms.db import DB
import shutil
import pytest
# Monkey-patching for tests so that we don't overwrite the default db
nkms.db.DB_NAME = 'debug-rekeys-db'
@ -13,9 +14,16 @@ def test_db():
db.close()
db2 = DB()
assert b'x' in db2
assert db2[b'x'] == b'y'
del db2[b'x']
db2.close()
db = DB()
with pytest.raises(KeyError):
db[b'x']
assert b'x' not in db
assert db.path == db2.path
shutil.rmtree(db.path)