Skip to content
This repository has been archived by the owner on Jan 11, 2022. It is now read-only.

Commit

Permalink
Allow default data where bool(defaultdata)==False
Browse files Browse the repository at this point in the history
  • Loading branch information
Stefan Nordhausen committed Aug 28, 2015
1 parent 5bd777e commit 9eb71d3
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
16 changes: 11 additions & 5 deletions src/yamlreader.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@
import os
import logging

class NoDefault(object):
def __str__(self):
return "No default data"


NO_DEFAULT = NoDefault()

class YamlReaderError(Exception):
pass
Expand Down Expand Up @@ -49,7 +55,7 @@ def data_merge(a, b):
return a


def yaml_load(source, defaultdata=None):
def yaml_load(source, defaultdata=NO_DEFAULT):
"""merge YAML data from files found in source
Always returns a dict. The YAML files are expected to contain some kind of
Expand All @@ -66,10 +72,10 @@ def yaml_load(source, defaultdata=None):
"""
logger = logging.getLogger(__name__)
logger.debug("initilized with source=%s, defaultdata=%s" % (source, defaultdata))
if defaultdata:
data = defaultdata
else:
if defaultdata is NO_DEFAULT:
data = None
else:
data = defaultdata
files = []
if type(source) is not str and len(source) == 1:
# when called from __main source is always a list, even if it contains only one item.
Expand Down Expand Up @@ -103,7 +109,7 @@ def yaml_load(source, defaultdata=None):
if new_data is not None:
data = data_merge(data, new_data)
else:
if not defaultdata:
if defaultdata is NO_DEFAULT:
logger.error("No YAML data found in %s and no default data given" % source)
raise YamlReaderError("No YAML data found in %s" % source)

Expand Down
14 changes: 14 additions & 0 deletions test/yamlreader_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,20 @@ def test_should_fail_on_invalid_yaml_dir(self):
def test_should_return_default_data_if_invalid_dir_given(self):
self.assertEqual(yaml_load("testdata", defaultdata={"foo":"bar"}), {"foo":"bar"})

def test_empty_directory_is_ok(self):
default_config = {'default': 'config'}
config = yaml_load("testdata/empty_yaml_dir", default_config)
self.assertEqual(config, default_config)

def test_falsy_default_config_works(self):
default_config = {}
config = yaml_load("testdata/empty_yaml_dir", default_config)
self.assertEqual(config, default_config)

default_config = None
config = yaml_load("testdata/empty_yaml_dir", default_config)
self.assertEqual(config, default_config)

def test_merge_complex_list_to_list(self):
self.assertEqual(data_merge([1, 2], [{1:2}, 1]), [1, 2, {1: 2}, 1])

Expand Down

0 comments on commit 9eb71d3

Please sign in to comment.