From 346461d51d35eeadb6fc5dc97b4e4992e027d2d8 Mon Sep 17 00:00:00 2001 From: Alex Schultz Date: Wed, 15 Feb 2017 14:08:50 -0700 Subject: [PATCH] Open log in utf-8 to prevent UnicodeEncodeError In python2 opens files as ascii by default, we were getting errors when trying to write out unicode to log files. This change pulls in the codecs module for python2 to support writing unicode out to files. In python3, all strings are unicode so there is no issues when writing them out to a file. Change-Id: Id740253a0e6143cfcdd4f7fe2b5460d9f64fa01e Closes-Bug: #1665114 (cherry picked from commit 9d2a6dae35de3987aded8d4611040d7130d6dc91) --- tripleo_common/image/image_builder.py | 7 ++++++- tripleo_common/tests/image/test_image_builder.py | 6 ++++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/tripleo_common/image/image_builder.py b/tripleo_common/image/image_builder.py index 1778d6d2e..010561993 100644 --- a/tripleo_common/image/image_builder.py +++ b/tripleo_common/image/image_builder.py @@ -23,6 +23,11 @@ import sys from tripleo_common.image.exception import ImageBuilderException +if sys.version_info[0] < 3: + import codecs + _open = open + open = codecs.open + @six.add_metaclass(abc.ABCMeta) class ImageBuilder(object): @@ -116,7 +121,7 @@ class DibImageBuilder(ImageBuilder): process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) - with open(log_file, 'w') as f: + with open(log_file, 'w', encoding='utf-8') as f: while True: line = process.stdout.readline() try: diff --git a/tripleo_common/tests/image/test_image_builder.py b/tripleo_common/tests/image/test_image_builder.py index b5239a343..0b661fe23 100644 --- a/tripleo_common/tests/image/test_image_builder.py +++ b/tripleo_common/tests/image/test_image_builder.py @@ -66,7 +66,8 @@ class TestDibImageBuilder(base.TestCase): 'element1', 'element2'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) - mock_open.assert_called_once_with('image/path.log', 'w') + mock_open.assert_called_once_with( + 'image/path.log', 'w', encoding='utf-8') self.assertEqual([mock.call(u'foo\n'), mock.call(u'bar\n')], mock_file.write.mock_calls) @@ -101,7 +102,8 @@ class TestDibImageBuilder(base.TestCase): 'element1', 'element2'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) - mock_open.assert_called_once_with('image/path.log', 'w') + mock_open.assert_called_once_with( + 'image/path.log', 'w', encoding='utf-8') self.assertEqual([mock.call(u'error\n')], mock_file.write.mock_calls) self.builder.logger.info.assert_has_calls([mock.call(u'error')])