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 9d2a6dae35)
This commit is contained in:
Alex Schultz 2017-02-15 14:08:50 -07:00 committed by Emilien Macchi
parent 0bbb86ebf9
commit 346461d51d
2 changed files with 10 additions and 3 deletions

View File

@ -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:

View File

@ -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')])