Skip to content

Commit

Permalink
add keys() function
Browse files Browse the repository at this point in the history
  • Loading branch information
thesimj committed Jan 9, 2019
1 parent 45d2330 commit f9779bf
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 12 deletions.
36 changes: 24 additions & 12 deletions envyaml/envyaml.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

from yaml import safe_load

__version__ = '0.1904'
__version__ = '0.1905'


class YDict:
Expand All @@ -35,17 +35,6 @@ def __init__(self, dictionary):
"""
self.__data = dictionary

def __getattr__(self, item):
attr = self.__data[item]

if isinstance(attr, dict):
return YDict(attr)

return self.__data[item]

def __getitem__(self, item):
return self.__data[item]

def get(self, key, default=None):
"""Get configuration variable with default value. If no `default` value set use None
Expand All @@ -60,6 +49,24 @@ def get(self, key, default=None):

return default

def keys(self):
"""Set-like object providing a view on keys"""
if isinstance(self.__data, dict):
self.__data.keys()

return self.__data

def __getattr__(self, item):
attr = self.__data[item]

if isinstance(attr, dict):
return YDict(attr)

return self.__data[item]

def __getitem__(self, item):
return self.__data[item]


class EnvYAML:
__version__ = __version__
Expand Down Expand Up @@ -179,6 +186,11 @@ def __dict_flat(self, config, deep=None):
dest_ = {}
for key_, value_ in config.items():
key_ = str(key_)

# check for special words
if key_ in ['keys', 'get']:
raise ValueError('Wrong key name: "' + key_ + '" reserved word!')

if isinstance(value_, dict):
if deep:
dest_.update(self.__dict_flat(value_, deep=deep + [key_]))
Expand Down
4 changes: 4 additions & 0 deletions tests/env.test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ one:
three:
value: one-two-three-value

test:
one: 123
two: 345

env_file:
config: $ENV_CONFIG_VERSION
project:
Expand Down
6 changes: 6 additions & 0 deletions tests/test_envyaml.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,12 @@ def test_it_should_return_dict_on_export():
assert isinstance(config.export(), dict) and len(config.export()) >= 4


def test_it_should_convert_config_to_dict():
config = EnvYAML('tests/env.test.yaml')

assert isinstance(dict(config.test), dict)


def test_is_should_read_config_from_env_variable():
# Set env file
os.environ['ENV_YAML_FILE'] = 'tests/env.test.yaml'
Expand Down

0 comments on commit f9779bf

Please sign in to comment.