implement more standard hashindex.setdefault behaviour

the .get() like behaviour (== returning the value) was missing.

it's still not 100% like dict.setdefault, because there is no
default value None. but None doesn't make sense here, because we
usually need a N-tuple matching the hash table's value format.

note: this "bug" (or unusual implementation) was without consequences,
      because hashindex.setdefault is not used anywhere in borg, so
      it was also not used in a wrong way anywhere.

https://docs.python.org/3/library/stdtypes.html#dict.setdefault
This commit is contained in:
Thomas Waldmann 2022-02-13 03:42:26 +01:00 committed by Andrey Bienkowski
parent 0624d7f18f
commit 07ae21e94d
2 changed files with 17 additions and 0 deletions

View file

@ -128,6 +128,7 @@ cdef class IndexBase:
def setdefault(self, key, value):
if not key in self:
self[key] = value
return self[key]
def __delitem__(self, key):
assert len(key) == self.key_size

View file

@ -71,6 +71,22 @@ class HashIndexTestCase(BaseTestCase):
del idx
self.assert_equal(len(cls.read(idx_name.name)), 0)
idx = cls()
# Test setdefault - set non-existing key
idx.setdefault(H(0), make_value(42))
assert H(0) in idx
assert idx[H(0)] == make_value(42)
# Test setdefault - do not set existing key
idx.setdefault(H(0), make_value(23))
assert H(0) in idx
assert idx[H(0)] == make_value(42)
# Test setdefault - get-like return value, key not present
assert idx.setdefault(H(1), make_value(23)) == make_value(23)
# Test setdefault - get-like return value, key present
assert idx.setdefault(H(0), make_value(23)) == make_value(42)
# clean up setdefault test
del idx
def test_nsindex(self):
self._generic_test(NSIndex, lambda x: (x, x),
'85f72b036c692c8266e4f51ccf0cff2147204282b5e316ae508d30a448d88fef')