utils: Handle exceptions in context management for YAMLFile

When an exception is raised within the context, the YAML file should not
written.

Signed-off-by: Sunil Mohan Adapa <sunil@medhas.org>
Reviewed-by: James Valleroy <jvalleroy@mailbox.org>
This commit is contained in:
Sunil Mohan Adapa 2019-02-14 16:33:27 -08:00 committed by James Valleroy
parent df76e6afa4
commit d3bdaf0729
No known key found for this signature in database
GPG Key ID: 77C0C75E7B650808
2 changed files with 14 additions and 3 deletions

View File

@ -123,3 +123,13 @@ class TestYAMLFileUtil(TestCase):
file_conf = ruamel.yaml.round_trip_load(retrieved_conf)
assert file_conf == {'property1': self.kv_pair,
'property2': self.kv_pair}
def test_context_exception(self):
"""Test that exception during update does not update file."""
test_file = tempfile.NamedTemporaryFile()
with self.assertRaises(ValueError):
with YAMLFile(test_file.name) as yaml_file:
yaml_file['property1'] = 'value1'
raise ValueError('Test')
assert open(test_file.name, 'r').read() == ''

View File

@ -108,9 +108,10 @@ class YAMLFile(object):
return self.conf
def __exit__(self, typ, value, traceback):
with open(self.yaml_file, 'w') as intro_conf:
ruamel.yaml.round_trip_dump(self.conf, intro_conf)
def __exit__(self, type_, value, traceback):
if not traceback:
with open(self.yaml_file, 'w') as intro_conf:
ruamel.yaml.round_trip_dump(self.conf, intro_conf)
def is_file_empty(self):
return os.stat(self.yaml_file).st_size == 0