From d3bdaf0729ce0400db295ce0d3ab175ec61b891f Mon Sep 17 00:00:00 2001 From: Sunil Mohan Adapa Date: Thu, 14 Feb 2019 16:33:27 -0800 Subject: [PATCH] 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 Reviewed-by: James Valleroy --- plinth/tests/test_utils.py | 10 ++++++++++ plinth/utils.py | 7 ++++--- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/plinth/tests/test_utils.py b/plinth/tests/test_utils.py index b47e5d5ef..1fa461f9e 100644 --- a/plinth/tests/test_utils.py +++ b/plinth/tests/test_utils.py @@ -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() == '' diff --git a/plinth/utils.py b/plinth/utils.py index 3d3c9b977..512755193 100644 --- a/plinth/utils.py +++ b/plinth/utils.py @@ -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