Skip to content

Commit

Permalink
utils: fix repteable values MementoDict
Browse files Browse the repository at this point in the history
* Fixes MementoDict to key a list of values when the key has more that
  value and is initialized with a tuple.
  • Loading branch information
egabancho authored and ludmilamarian committed Jul 5, 2017
1 parent 0e51c32 commit 1635560
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
17 changes: 15 additions & 2 deletions cds_dojson/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,8 @@
"""The CDS DoJson Utils."""

import functools
from collections import defaultdict
from collections import MutableMapping, MutableSequence, defaultdict

from collections import MutableMapping, MutableSequence
import arrow
import six

Expand All @@ -32,6 +31,19 @@ class MementoDict(dict):
def __init__(self, *args, **kwargs):
"""Set memory and create the dictionary."""
self.memory = set()
if args and isinstance(args[0], MutableSequence):
args = list(args)
d = {}
for k, v in args[0]:
if k in d:
try:
d[k].append(v)
except AttributeError:
d[k] = [d[k], v]
else:
d[k] = v
args[0] = [(k, v) for k, v in six.iteritems(d)]

super(MementoDict, self).__init__(*args, **kwargs)

def iteritems(self, skyp_memento=False):
Expand All @@ -40,6 +52,7 @@ def iteritems(self, skyp_memento=False):
if not skyp_memento:
self.memory.add(key)
yield (key, value)

items = iteritems

def __getitem__(self, key):
Expand Down
21 changes: 20 additions & 1 deletion tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def test_not_accessed_keys():
d1 = MementoDict()
assert not not_accessed_keys(d1)

d1['a'] = [1, 2, 3]
d1 = MementoDict([('a', [1, 2, 3])])
assert not_accessed_keys(d1) == {'a'}
d1['b'] = MementoDict({'1': 1})
assert not_accessed_keys(d1) == {'a', 'b1'}
Expand All @@ -79,3 +79,22 @@ def test_not_accessed_keys():
for k, v in d2.iteritems():
pass
assert not_accessed_keys(d1) == {'a', 'c', 'd1', 'd2'}

d1['e'] = MementoDict([('1', 1), ('1', 2), ('1', 3)])
assert not_accessed_keys(d1) == {'a', 'c', 'd1', 'd2', 'e1'}


def test_memento_dict():
"""Check MementoDict class."""
d = MementoDict({'a': 1, 'b': 2})
assert d == {'a': 1, 'b': 2}

d = MementoDict([('a', 1), ('b', 2)])
assert d == {'a': 1, 'b': 2}

d = MementoDict([('a', 1), ('a', 2)])
assert d == {'a': [1, 2]}

# NOTE: is this the expected behavior?
d = MementoDict([('a', 1), ('a', [2, 3])])
assert d == {'a': [1, [2, 3]]}

0 comments on commit 1635560

Please sign in to comment.