diff --git a/tests/test_udict.py b/tests/test_udict.py index f473428..53251aa 100644 --- a/tests/test_udict.py +++ b/tests/test_udict.py @@ -5,11 +5,19 @@ class UDictTestCase(unittest.TestCase): def test_init(self): - d = UDict(hello=1, hi=2, default=10) - d2 = UDict({'hello': 1, 'hi': 2}) + d = UDict(hello=1, hi='world', default=10) + d2 = UDict({'hello': 1, 'hi': 'world'}) + d3 = UDict() self.assertEqual(d.default, 10) + self.assertEqual(d2.default, None) + self.assertEqual(d3.default, None) + self.assertDictEqual(d.dictionary, d2.dictionary) + self.assertDictEqual(d3.dictionary, {}) + self.assertEqual(d, d2) + self.assertNotEqual(d, d3) + self.assertNotEqual(d2, d3) def test_keys_values_items(self): d = UDict(hello=1, hi=2) @@ -63,6 +71,9 @@ def test_get_item(self): self.assertEqual(d[1], d['hello']) + # not existent key + self.assertEqual(d['hey'], None) + def test_set_item(self): d = UDict(hello=1, hi=2) d['hi'] = 3 @@ -96,6 +107,19 @@ def test_get(self): self.assertEqual(d.get(value=3, default='missing'), 'missing') self.assertEqual(d.get(value=3), None) + with self.assertRaises(ValueError): + d.get() + with self.assertRaises(ValueError): + d.get(index=2, value=1) + with self.assertRaises(ValueError): + d.get(index=2, key=2) + with self.assertRaises(ValueError): + d.get(value=1, key=4) + with self.assertRaises(ValueError): + d.get(value=1, key=4, index=3) + with self.assertRaises(IndexError): + d.get(index=4) + def test_len_and_iter(self): d = UDict(hello=1, hi=2) self.assertEqual(len(d), 2) diff --git a/ufpy/udict.py b/ufpy/udict.py index bb61193..f5faa58 100644 --- a/ufpy/udict.py +++ b/ufpy/udict.py @@ -35,7 +35,7 @@ def __init__(self, *, default: CDV, **kwargs: VT): ... def __init__(self, dictionary: AnyDict[KT, VT] = None, *, default: CDV = None, **kwargs: VT): if isinstance(dictionary, UDict): dictionary = dictionary.dictionary - self.__dict = dictionary if dictionary else kwargs + self.__dict = dictionary or kwargs self.__default = default # dictionary @@ -145,7 +145,9 @@ def __getitem__(self, key: KT | int | slice) -> UDict[KT, VT, DV] | VT: def __setitem__(self, key: KT | int | slice, value: VT | list[VT]) -> None: keys = self.__get_keys_from_slice_or_int(key) - values = [value] if not isinstance(value, (list, tuple)) else value + + # Ensure 'values' is always a list for consistent processing + values = value if isinstance(value, (list, tuple)) else [value] if len(keys) > len(values): values.extend([values[-1] for _ in range(len(keys) - len(values) + 1)]) @@ -222,16 +224,16 @@ def get( # Len, iterator and reversed version def __len__(self) -> int: - return len(self.items) + return len(self.__dict) def __iter__(self) -> Iterator[tuple[KT, VT]]: - return iter(self.items) + return iter(self.__dict.items()) # Booleans def is_empty(self) -> bool: return len(self) == 0 - def __nonzero__(self) -> bool: + def __bool__(self) -> bool: return not self.is_empty() def __contains__(self, item: tuple[KT, VT] | list[KT | VT] | KT) -> bool: