From 09cc7cf5f749e577c7abb449e3ae2554dfde968a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 6 Feb 2019 16:01:39 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Fix=20unicode=20vs=20bytes=20iss?= =?UTF-8?q?ues=20for=20atomic=5Fwrite?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit NamedTemporaryFile doesn't support the encoding parameter under py2. However, without it specifying text mode defaults to ascii, causing some issues especially with config files containing utf-8. By swapping NamedTemporaryFile for mkstemp and a custom io.open call (parameterized according to the open mode) we can support a proper encoding aware atomic_write. --- src/octoprint/filemanager/storage.py | 4 +- src/octoprint/settings.py | 2 +- src/octoprint/util/__init__.py | 12 +- tests/util/test_file_helpers.py | 159 +++++++++++++++++++-------- 4 files changed, 124 insertions(+), 53 deletions(-) diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index 3cbaa66ef..8f03e9e38 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -1539,7 +1539,7 @@ class LocalFileStorage(StorageInterface): metadata_path = os.path.join(path, ".metadata.json") try: import json - with atomic_write(metadata_path, mode='wt') as f: + with atomic_write(metadata_path, mode='wb') as f: json.dump(metadata, f, indent=4, separators=(",", ": ")) except Exception: self._logger.exception("Error while writing .metadata.json to {path}".format(**locals())) @@ -1588,7 +1588,7 @@ class LocalFileStorage(StorageInterface): # looks invalid, ignore it return - with atomic_write(metadata_path_json, mode='wt') as f: + with atomic_write(metadata_path_json, mode='wb') as f: json.dump(metadata, f, indent=4, separators=(",", ": ")) # TODO 1.3.10 Remove ".metadata.yaml" files diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index a469200fb..b4f58e5d2 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -1772,7 +1772,7 @@ class Settings(object): path, _ = os.path.split(filename) if not os.path.exists(path): os.makedirs(path) - with atomic_write(filename, mode='wb', max_permissions=0o666) as f: + with atomic_write(filename, mode='wt', max_permissions=0o666) as f: f.write(script) def generateApiKey(self): diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index aecb7da76..46331246e 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -1007,12 +1007,20 @@ def mime_type_matches(mime, other): return type_matches and subtype_matches @contextlib.contextmanager -def atomic_write(filename, mode="w+b", prefix="tmp", suffix="", permissions=0o644, max_permissions=0o777): +def atomic_write(filename, mode="w+b", encoding="utf-8", prefix="tmp", suffix="", permissions=0o644, max_permissions=0o777): if os.path.exists(filename): permissions |= os.stat(filename).st_mode permissions &= max_permissions - temp_config = tempfile.NamedTemporaryFile(mode=mode, prefix=prefix, suffix=suffix, delete=False) + # NamedTemporaryFile doesn't yet have an encoding parameter in py2, so we go the long way + fd, path = tempfile.mkstemp(suffix=suffix, prefix=prefix) + os.close(fd) + + if "b" in mode: + temp_config = io.open(path, mode=mode) + else: + temp_config = io.open(path, mode=mode, encoding=encoding) + try: yield temp_config finally: diff --git a/tests/util/test_file_helpers.py b/tests/util/test_file_helpers.py index 384973f49..873018c56 100644 --- a/tests/util/test_file_helpers.py +++ b/tests/util/test_file_helpers.py @@ -85,16 +85,23 @@ class TestAtomicWrite(unittest.TestCase): pass @mock.patch("shutil.move") - @mock.patch("tempfile.NamedTemporaryFile") + @mock.patch("tempfile.mkstemp") + @mock.patch("io.open") + @mock.patch("os.close") @mock.patch("os.chmod") @mock.patch("os.path.exists") - def test_atomic_write(self, mock_exists, mock_chmod, mock_tempfile, mock_move): + def test_atomic_write(self, mock_exists, mock_chmod, mock_close, mock_open, mock_mkstemp, mock_move): """Tests the regular basic "good" case.""" # setup + fd = 0 + path = "tempfile.tmp" + mock_file = mock.MagicMock() - mock_file.name = "tempfile.tmp" - mock_tempfile.return_value = mock_file + mock_file.name = path + + mock_mkstemp.return_value = fd, path + mock_open.return_value = mock_file mock_exists.return_value = False # test @@ -102,24 +109,33 @@ class TestAtomicWrite(unittest.TestCase): f.write("test") # assert - mock_tempfile.assert_called_once_with(mode="w+b", prefix="tmp", suffix="", delete=False) + mock_mkstemp.assert_called_once_with(prefix="tmp", suffix="") + mock_close.assert_called_once_with(fd) + mock_open.assert_called_once_with(path, mode="w+b") mock_file.write.assert_called_once_with("test") mock_file.close.assert_called_once_with() - mock_chmod.assert_called_once_with("tempfile.tmp", 0o644) - mock_move.assert_called_once_with("tempfile.tmp", "somefile.yaml") + mock_chmod.assert_called_once_with(path, 0o644) + mock_move.assert_called_once_with(path, "somefile.yaml") @mock.patch("shutil.move") - @mock.patch("tempfile.NamedTemporaryFile") + @mock.patch("tempfile.mkstemp") + @mock.patch("io.open") + @mock.patch("os.close") @mock.patch("os.chmod") @mock.patch("os.path.exists") - def test_atomic_write_error_on_write(self, mock_exists, mock_chmod, mock_tempfile, mock_move): + def test_atomic_write_error_on_write(self, mock_exists, mock_chmod, mock_close, mock_open, mock_mkstemp, mock_move): """Tests the error case where something in the wrapped code fails.""" # setup + fd = 0 + path = "tempfile.tmp" + mock_file = mock.MagicMock() - mock_file.name = "tempfile.tmp" + mock_file.name = path mock_file.write.side_effect = RuntimeError() - mock_tempfile.return_value = mock_file + + mock_mkstemp.return_value = fd, path + mock_open.return_value = mock_file mock_exists.return_value = False # test @@ -131,21 +147,30 @@ class TestAtomicWrite(unittest.TestCase): pass # assert - mock_tempfile.assert_called_once_with(mode="w+b", prefix="tmp", suffix="", delete=False) + mock_mkstemp.assert_called_once_with(prefix="tmp", suffix="") + mock_close.assert_called_once_with(fd) + mock_open.assert_called_once_with(path, mode="w+b") mock_file.close.assert_called_once_with() self.assertFalse(mock_move.called) self.assertFalse(mock_chmod.called) @mock.patch("shutil.move") - @mock.patch("tempfile.NamedTemporaryFile") + @mock.patch("tempfile.mkstemp") + @mock.patch("io.open") + @mock.patch("os.close") @mock.patch("os.chmod") @mock.patch("os.path.exists") - def test_atomic_write_error_on_move(self, mock_exists, mock_chmod, mock_tempfile, mock_move): + def test_atomic_write_error_on_move(self, mock_exists, mock_chmod, mock_close, mock_open, mock_mkstemp, mock_move): """Tests the error case where the final move fails.""" # setup + fd = 0 + path = "tempfile.tmp" + mock_file = mock.MagicMock() - mock_file.name = "tempfile.tmp" - mock_tempfile.return_value = mock_file + mock_file.name = path + + mock_mkstemp.return_value = fd, path + mock_open.return_value = mock_file mock_move.side_effect = RuntimeError() mock_exists.return_value = False @@ -158,22 +183,31 @@ class TestAtomicWrite(unittest.TestCase): pass # assert - mock_tempfile.assert_called_once_with(mode="w+b", prefix="tmp", suffix="", delete=False) + mock_mkstemp.assert_called_once_with(prefix="tmp", suffix="") + mock_close.assert_called_once_with(fd) + mock_open.assert_called_once_with(path, mode="w+b") mock_file.close.assert_called_once_with() self.assertTrue(mock_move.called) self.assertTrue(mock_chmod.called) @mock.patch("shutil.move") - @mock.patch("tempfile.NamedTemporaryFile") + @mock.patch("tempfile.mkstemp") + @mock.patch("io.open") + @mock.patch("os.close") @mock.patch("os.chmod") @mock.patch("os.path.exists") - def test_atomic_write_parameters(self, mock_exists, mock_chmod, mock_tempfile, mock_move): + def test_atomic_write_parameters(self, mock_exists, mock_chmod, mock_close, mock_open, mock_mkstemp, mock_move): """Tests that the open parameters are propagated properly.""" # setup + fd = 0 + path = "tempfile.tmp" + mock_file = mock.MagicMock() - mock_file.name = "tempfile.tmp" - mock_tempfile.return_value = mock_file + mock_file.name = path + + mock_mkstemp.return_value = fd, path + mock_open.return_value = mock_file mock_exists.return_value = False # test @@ -181,47 +215,65 @@ class TestAtomicWrite(unittest.TestCase): f.write("test") # assert - mock_tempfile.assert_called_once_with(mode="w", prefix="foo", suffix="bar", delete=False) + mock_mkstemp.assert_called_once_with(prefix="foo", suffix="bar") + mock_close.assert_called_once_with(fd) + mock_open.assert_called_once_with(path, mode="w", encoding="utf-8") mock_file.close.assert_called_once_with() - mock_chmod.assert_called_once_with("tempfile.tmp", 0o644) - mock_move.assert_called_once_with("tempfile.tmp", "somefile.yaml") + mock_chmod.assert_called_once_with(path, 0o644) + mock_move.assert_called_once_with(path, "somefile.yaml") @mock.patch("shutil.move") - @mock.patch("tempfile.NamedTemporaryFile") + @mock.patch("tempfile.mkstemp") + @mock.patch("io.open") + @mock.patch("os.close") @mock.patch("os.chmod") @mock.patch("os.path.exists") - def test_atomic_custom_permissions(self, mock_exists, mock_chmod, mock_tempfile, mock_move): + def test_atomic_custom_permissions(self, mock_exists, mock_chmod, mock_close, mock_open, mock_mkstemp, mock_move): """Tests that custom permissions may be set.""" # setup + fd = 0 + path = "tempfile.tmp" + mock_file = mock.MagicMock() - mock_file.name = "tempfile.tmp" - mock_tempfile.return_value = mock_file + mock_file.name = path + + mock_mkstemp.return_value = fd, path + mock_open.return_value = mock_file mock_exists.return_value = False # test - with octoprint.util.atomic_write("somefile.yaml", permissions=0o755) as f: + with octoprint.util.atomic_write("somefile.yaml", mode="wt", permissions=0o755) as f: f.write("test") # assert - mock_tempfile.assert_called_once_with(mode="w+b", prefix="tmp", suffix="", delete=False) + mock_mkstemp.assert_called_once_with(prefix="tmp", suffix="") + mock_close.assert_called_once_with(fd) + mock_open.assert_called_once_with(path, mode="wt", encoding="utf-8") mock_file.close.assert_called_once_with() - mock_chmod.assert_called_once_with("tempfile.tmp", 0o755) - mock_move.assert_called_once_with("tempfile.tmp", "somefile.yaml") + mock_chmod.assert_called_once_with(path, 0o755) + mock_move.assert_called_once_with(path, "somefile.yaml") @mock.patch("shutil.move") - @mock.patch("tempfile.NamedTemporaryFile") + @mock.patch("tempfile.mkstemp") + @mock.patch("io.open") + @mock.patch("os.close") @mock.patch("os.chmod") @mock.patch("os.path.exists") @mock.patch("os.stat") - def test_atomic_permissions_combined(self, mock_stat, mock_exists, mock_chmod, mock_tempfile, mock_move): + def test_atomic_permissions_combined(self, mock_stat, mock_exists, mock_chmod, mock_close, mock_open, mock_mkstemp, mock_move): """Tests that the permissions of an existing file are combined with the requested permissions.""" # setup + fd = 0 + path = "tempfile.tmp" + mock_file = mock.MagicMock() - mock_file.name = "tempfile.tmp" - mock_tempfile.return_value = mock_file + mock_file.name = path + + mock_mkstemp.return_value = fd, path + mock_open.return_value = mock_file mock_exists.return_value = True mock_stat_result = mock.MagicMock() @@ -229,27 +281,36 @@ class TestAtomicWrite(unittest.TestCase): mock_stat.return_value = mock_stat_result # test - with octoprint.util.atomic_write("somefile.yaml", permissions=0o755) as f: + with octoprint.util.atomic_write("somefile.yaml", mode="wt", permissions=0o755) as f: f.write("test") # assert - mock_tempfile.assert_called_once_with(mode="w+b", prefix="tmp", suffix="", delete=False) + mock_mkstemp.assert_called_once_with(prefix="tmp", suffix="") + mock_close.assert_called_once_with(fd) + mock_open.assert_called_once_with(path, mode="wt", encoding="utf-8") mock_file.close.assert_called_once_with() - mock_chmod.assert_called_once_with("tempfile.tmp", 0o777) # 0o755 | 0o666 - mock_move.assert_called_once_with("tempfile.tmp", "somefile.yaml") + mock_chmod.assert_called_once_with(path, 0o777) # 0o755 | 0o666 + mock_move.assert_called_once_with(path, "somefile.yaml") @mock.patch("shutil.move") - @mock.patch("tempfile.NamedTemporaryFile") + @mock.patch("tempfile.mkstemp") + @mock.patch("io.open") + @mock.patch("os.close") @mock.patch("os.chmod") @mock.patch("os.path.exists") @mock.patch("os.stat") - def test_atomic_permissions_limited(self, mock_stat, mock_exists, mock_chmod, mock_tempfile, mock_move): + def test_atomic_permissions_limited(self, mock_stat, mock_exists, mock_chmod, mock_close, mock_open, mock_mkstemp, mock_move): """Tests that max_permissions limit the combined file permissions.""" # setup + fd = 0 + path = "tempfile.tmp" + mock_file = mock.MagicMock() - mock_file.name = "tempfile.tmp" - mock_tempfile.return_value = mock_file + mock_file.name = path + + mock_mkstemp.return_value = fd, path + mock_open.return_value = mock_file mock_exists.return_value = True mock_stat_result = mock.MagicMock() @@ -257,14 +318,16 @@ class TestAtomicWrite(unittest.TestCase): mock_stat.return_value = mock_stat_result # test - with octoprint.util.atomic_write("somefile.yaml", permissions=0o600, max_permissions=0o666) as f: + with octoprint.util.atomic_write("somefile.yaml", mode="wt", permissions=0o600, max_permissions=0o666) as f: f.write("test") # assert - mock_tempfile.assert_called_once_with(mode="w+b", prefix="tmp", suffix="", delete=False) + mock_mkstemp.assert_called_once_with(prefix="tmp", suffix="") + mock_close.assert_called_once_with(fd) + mock_open.assert_called_once_with(path, mode="wt", encoding="utf-8") mock_file.close.assert_called_once_with() - mock_chmod.assert_called_once_with("tempfile.tmp", 0o644) # (0o600 | 0o755) & 0o666 = 0o755 & 0o666 - mock_move.assert_called_once_with("tempfile.tmp", "somefile.yaml") + mock_chmod.assert_called_once_with(path, 0o644) # (0o600 | 0o755) & 0o666 = 0o755 & 0o666 + mock_move.assert_called_once_with(path, "somefile.yaml") class TempDirTest(unittest.TestCase):