Skip to content

Commit

Permalink
update and test behaviour of dump_to_file
Browse files Browse the repository at this point in the history
  • Loading branch information
Samuel Walladge committed Dec 26, 2017
1 parent cba4106 commit b660020
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 10 deletions.
19 changes: 9 additions & 10 deletions piqueserver/config.py
Expand Up @@ -79,7 +79,7 @@ def get_dict(self):

def load_from_file(self, fobj, format_=DEFAULT_FORMAT):
'''
Clear the current configuration and load new configuration from a file like object
Clear the current configuration and load new configuration from a file-like object
in a supported format.
'''
self._raw_config = {}
Expand Down Expand Up @@ -113,18 +113,17 @@ def update_from_dict(self, config):
self._raw_config = self._nested_update(self._raw_config, config)
self._validate_all()

def dump_to_file(self, out_file, format_=DEFAULT_FORMAT):
def dump_to_file(self, fobj, format_=DEFAULT_FORMAT):
'''
Writes the current configuration to a file (filename specified by `out_file`),
Writes the current configuration to a file-like objection,
with the format specified by `format_`.
'''
with open(out_file, 'w') as f:
if format_ == TOML_FORMAT:
toml.dump(self._raw_config, f)
elif format_ == JSON_FORMAT:
json.dump(self._raw_config, f, indent=2)
else:
raise ValueError('Unsupported config file format: {}'.format(format_))
if format_ == TOML_FORMAT:
toml.dump(self._raw_config, fobj)
elif format_ == JSON_FORMAT:
json.dump(self._raw_config, fobj, indent=2)
else:
raise ValueError('Unsupported config file format: {}'.format(format_))

def _get(self, name, default=None):
if name not in self._raw_config:
Expand Down
25 changes: 25 additions & 0 deletions tests/piqueserver/test_config.py
@@ -1,3 +1,5 @@
import tempfile

import unittest
from piqueserver.config import config, JSON_FORMAT, TOML_FORMAT

Expand Down Expand Up @@ -168,3 +170,26 @@ def test_nested_update(self):
self.assertEqual(raw['server']['things']['thing1'], 'something')
self.assertEqual(raw['server']['things']['thing2'], 'added')
self.assertEqual(raw['server']['name'], 'piqueserver instance')

def test_dump_to_file(self):
f = 'tests/example_config/simple.toml'
config.load_from_file(open(f))

with self.assertRaises(ValueError):
config.dump_to_file(None, format_='garbage123')

with tempfile.TemporaryFile(mode='w+') as f:
config.dump_to_file(f, JSON_FORMAT)
f.seek(0)
out = f.read().strip()
# at least make sure it wrote something that could be json
self.assertEqual(out[0], '{')
self.assertEqual(out[-1], '}')


with tempfile.TemporaryFile(mode='w+') as f:
config.dump_to_file(f, TOML_FORMAT)
f.seek(0)
out = f.read().strip()
# at least make sure it wrote something that could be toml
self.assertIn('[server]', out)

0 comments on commit b660020

Please sign in to comment.