From ee374e7a5f4dea538fcd942f5b6a42a6ebd1503f Mon Sep 17 00:00:00 2001 From: ajmiller Date: Mon, 24 Aug 2015 21:04:02 -0700 Subject: [PATCH] Add optional file permission argument to replace_file() The replace_file() utility function currently sets the mode of all files it creates to 0o644. This is not appropriate for all files. This patch adds an optional "file_mode" argument to the function. Change-Id: I9744abde10b95fadef6e74c55332d041e5372071 Partial-Bug: 1488320 --- neutron/agent/linux/utils.py | 4 ++-- neutron/tests/unit/agent/linux/test_utils.py | 17 ++++++++++++++--- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/neutron/agent/linux/utils.py b/neutron/agent/linux/utils.py index 67be8ad49..5588d299c 100644 --- a/neutron/agent/linux/utils.py +++ b/neutron/agent/linux/utils.py @@ -172,7 +172,7 @@ def get_interface_mac(interface): for char in info[MAC_START:MAC_END]])[:-1] -def replace_file(file_name, data): +def replace_file(file_name, data, file_mode=0o644): """Replaces the contents of file_name with data in a safe manner. First write to a temp file and then rename. Since POSIX renames are @@ -185,7 +185,7 @@ def replace_file(file_name, data): tmp_file = tempfile.NamedTemporaryFile('w+', dir=base_dir, delete=False) tmp_file.write(data) tmp_file.close() - os.chmod(tmp_file.name, 0o644) + os.chmod(tmp_file.name, file_mode) os.rename(tmp_file.name, file_name) diff --git a/neutron/tests/unit/agent/linux/test_utils.py b/neutron/tests/unit/agent/linux/test_utils.py index b4db92f95..7476050c6 100644 --- a/neutron/tests/unit/agent/linux/test_utils.py +++ b/neutron/tests/unit/agent/linux/test_utils.py @@ -170,22 +170,33 @@ class AgentUtilsGetInterfaceMAC(base.BaseTestCase): class AgentUtilsReplaceFile(base.BaseTestCase): - def test_replace_file(self): + def _test_replace_file_helper(self, explicit_perms=None): # make file to replace with mock.patch('tempfile.NamedTemporaryFile') as ntf: ntf.return_value.name = '/baz' with mock.patch('os.chmod') as chmod: with mock.patch('os.rename') as rename: - utils.replace_file('/foo', 'bar') + if explicit_perms is None: + expected_perms = 0o644 + utils.replace_file('/foo', 'bar') + else: + expected_perms = explicit_perms + utils.replace_file('/foo', 'bar', explicit_perms) expected = [mock.call('w+', dir='/', delete=False), mock.call().write('bar'), mock.call().close()] ntf.assert_has_calls(expected) - chmod.assert_called_once_with('/baz', 0o644) + chmod.assert_called_once_with('/baz', expected_perms) rename.assert_called_once_with('/baz', '/foo') + def test_replace_file_with_default_perms(self): + self._test_replace_file_helper() + + def test_replace_file_with_0o600_perms(self): + self._test_replace_file_helper(0o600) + class TestFindChildPids(base.BaseTestCase): -- 2.45.2