Skip to content

Commit

Permalink
Merge branch 'jedipi-feature/dump'
Browse files Browse the repository at this point in the history
  • Loading branch information
staffanm committed Jul 27, 2016
2 parents 8072fd5 + 58251bb commit 9e9b4f0
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 19 deletions.
50 changes: 31 additions & 19 deletions layeredconfig/layeredconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
# if on python 2.6
from ordereddict import OrderedDict


class LayeredConfig(object):
def __init__(self, *sources, **kwargs):
"""Creates a config object from one or more sources and provides
Expand Down Expand Up @@ -139,7 +140,7 @@ def set(config, key, value, sourceid="defaults"):
for source in config._sources:
if source.identifier == sourceid:
source.set(key, value)
# What if no source is found? We silently ignore...
# What if no source is found? We silently ignore...

@staticmethod
def get(config, key, default=None):
Expand All @@ -152,22 +153,33 @@ def get(config, key, default=None):
else:
return default

# These are methods i'd like to implement next
#
# @staticmethod
# def where(config, key):
# """returns the identifier of a source where a given key is found, or None."""
# pass
#
# @staticmethod
# def dump(config):
# """Returns the contents of config as a dict."""
# pass
#
# @staticmethod
# def load(config, d):
# """Recreates a dump()ed config object."""
# pass
@staticmethod
def dump(config):
"""Returns the contents of config as a dict."""
def _dump(element):
if not isinstance(element, config.__class__):
return element

section = dict()
for key, subsection in element._subsections.items():
section[key] = _dump(subsection)
for key in element:
section[key] = getattr(element, key)
return section

return _dump(config)

# These are methods i'd like to implement next
#
# @staticmethod
# def where(config, key):
# """returns the identifier of a source where a given key is found, or None."""
# pass
#
# @staticmethod
# def load(config, d):
# """Recreates a dump()ed config object."""
# pass

@staticmethod
def datetimeconvert(value):
Expand All @@ -181,7 +193,6 @@ def datetimeconvert(value):
except ValueError:
return datetime.strptime(value, "%Y-%m-%d %H:%M:%S")


@staticmethod
def dateconvert(value):
"""Convert the string *value* to a :py:class:`~datetime.date`
Expand All @@ -208,6 +219,8 @@ def boolconvert(value):
else:
return value

def __repr__(self):
return self.dump(self).__repr__()

def __iter__(self):
l = set()
Expand Down Expand Up @@ -311,4 +324,3 @@ def __setattr__(self, name, value):
return self._parent.__setattr__(name, value)
else:
raise AttributeError("Configuration key %s doesn't exist" % name)

26 changes: 26 additions & 0 deletions tests/test_layeredconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -1478,5 +1478,31 @@ def test_get(self):
self.assertEqual(None, LayeredConfig.get(cfg, "nonexistent"))
self.assertEqual("NO!", LayeredConfig.get(cfg, "nonexistent", "NO!"))


class TestDump(unittest.TestCase):
def test_dump(self):
defaults = {
'home': 'mydata',
'processes': 4,
'force': True,
'extra': ['foo', 'bar'],
'mymodule': {
'force': False,
'extra': ['foo', 'baz'],
'arbitrary': {
'nesting': {
'depth': 'works'
}
}
},
'extramodule': {
'unique': True
}
}

config = LayeredConfig(Defaults(defaults))
self.assertEquals(defaults, LayeredConfig.dump(config))


if __name__ == '__main__':
unittest.main()

0 comments on commit 9e9b4f0

Please sign in to comment.