Skip to content

Instantly share code, notes, and snippets.

@pydanny
Created July 21, 2014 00:30
Show Gist options
  • Save pydanny/f7118294a5cf66a9e984 to your computer and use it in GitHub Desktop.
Save pydanny/f7118294a5cf66a9e984 to your computer and use it in GitHub Desktop.
import os
def unicode_open(filename, *args, **kwargs):
"""
Opens a file as usual on Python 3, and with UTF-8 encoding on Python 2.
:param filename: Name of file to open.
"""
filename = fix_path(filename)
kwargs['encoding'] = "utf-8"
if PY3:
return open(filename, *args, **kwargs)
return codecs.open(filename, *args, **kwargs)
def fix_path(path):
return path.replace("/", os.sep)
# config.py
def get_config(config_path):
"""
Retrieve the config from the specified path, returning it as a config dict.
"""
config_path = fix_path(config_path)
if not os.path.exists(config_path):
raise ConfigDoesNotExistException
print("config_path is {0}".format(config_path))
with unicode_open(config_path) as file_handle:
try:
yaml_dict = yaml.safe_load(file_handle)
except yaml.scanner.ScannerError:
raise InvalidConfiguration(
"%s is no a valid YAML file" % config_path)
config_dict = copy.copy(DEFAULT_CONFIG)
config_dict.update(yaml_dict)
config_dict['cookiecutters_dir'] = os.path.expanduser(config_dict['cookiecutters_dir'])
return config_dict
# test_config
class TestGetConfig(unittest.TestCase):
def test_get_config(self):
""" Opening and reading config file """
conf = config.get_config(
'tests/test-config/valid-config.yaml'
)
expected_conf = {
'cookiecutters_dir': os.path.expanduser(
fix_path('~/example/some-path-to-templates')
),
'default_context': {
"full_name": "Firstname Lastname",
"email": "firstname.lastname@gmail.com",
"github_username": "example"
}
}
self.assertEqual(conf, expected_conf)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment