Skip to content

Commit

Permalink
Support for direct deep dictionary value retrieval
Browse files Browse the repository at this point in the history
  • Loading branch information
psss committed Jun 28, 2018
1 parent 03b3602 commit b537c59
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 3 deletions.
11 changes: 11 additions & 0 deletions examples/deep/main.fmf
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,14 @@

/one/two/three:
key: value


# Values from a deep dictionary can be retrieved easily using the
# get() method which supports providing default values as well.
# Example: tree.get(['hardware', 'memory', 'size'], default)

hardware:
memory:
size: 8
network:
model: e1000
29 changes: 26 additions & 3 deletions fmf/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,11 +174,34 @@ def update(self, data):
log.debug("Data for '{0}' updated.".format(self))
log.data(pretty(self.data))

def get(self, name=None):
""" Get desired attribute """
def get(self, name=None, default=None):
"""
Get attribute value or return default
Whole data dictionary is returned when no attribute provided.
Supports direct values retrieval from deep dictionaries as well.
Dictionary path should be provided as list. The following two
examples are equal:
tree.data['hardware']['memory']['size']
tree.get(['hardware', 'memory', 'size'])
However the latter approach will also correctly handle providing
default value when any of the dictionary keys does not exist.
"""
# Return the whole dictionary if no attribute specified
if name is None:
return self.data
return self.data[name]
if not isinstance(name, list):
name = [name]
data = self.data
try:
for key in name:
data = data[key]
except KeyError:
return default
return data

def child(self, name, data, source=None):
""" Create or update child with given data """
Expand Down
9 changes: 9 additions & 0 deletions tests/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,14 @@ def test_deep_hierarchy(self):
deep = Tree(EXAMPLES + "deep")
assert len(deep.children) == 1

def test_deep_dictionary(self):
""" Get value from a deep dictionary """
deep = Tree(EXAMPLES + "deep")
assert deep.data['hardware']['memory']['size'] == 8
assert deep.get(['hardware', 'memory', 'size']) == 8
assert deep.get(['hardware', 'bad', 'size'], 12) == 12
assert deep.get('nonexistent', default=3) == 3

def test_merge(self):
""" Attribute merging """
child = self.merge.find('/parent/child')
Expand Down Expand Up @@ -123,3 +131,4 @@ def test_yaml_syntax_errors(self):
with pytest.raises(utils.FileError):
tree = fmf.Tree(path)
rmtree(path)

0 comments on commit b537c59

Please sign in to comment.