Unless we're using py2 and Windows, ensure we're writing out a string when using file.line.

This commit is contained in:
Gareth J. Greenaway 2018-06-15 11:38:31 -07:00
parent 0e3f846836
commit 5a9ef0d1ae
No known key found for this signature in database
GPG Key ID: 10B62F8A7CAD7A41
2 changed files with 29 additions and 1 deletions

View File

@ -2039,7 +2039,12 @@ def line(path, content=None, match=None, mode=None, location=None,
fh_ = None
try:
# Make sure we match the file mode from salt.utils.files.fopen
mode = 'wb' if six.PY2 and salt.utils.platform.is_windows() else 'w'
if six.PY2 and salt.utils.platform.is_windows():
mode = 'wb'
body = salt.utils.stringutils.to_bytes(body)
else:
mode = 'w'
body = salt.utils.stringutils.to_str(body)
fh_ = salt.utils.atomicfile.atomic_open(path, mode)
fh_.write(body)
finally:

View File

@ -1063,6 +1063,29 @@ class FilemodLineTests(TestCase, LoaderModuleMockMixin):
self.assertEqual(atomic_opener().write.call_args_list[0][0][0],
file_modified)
@patch('os.path.realpath', MagicMock())
@patch('os.path.isfile', MagicMock(return_value=True))
@patch('os.stat', MagicMock())
def test_line_insert_multi_line_content_after_unicode(self):
'''
Test for file.line for insertion after specific line with Unicode
See issue #48113
:return:
'''
file_content = ("This is a line\nThis is another line")
file_modified = salt.utils.stringutils.to_str("This is a line\nThis is another line\nThis is a line with unicode Ŷ")
cfg_content = "This is a line with unicode Ŷ"
for after_line in ['This is another line']:
files_fopen = mock_open(read_data=file_content)
with patch('salt.utils.files.fopen', files_fopen):
atomic_opener = mock_open()
with patch('salt.utils.atomicfile.atomic_open', atomic_opener):
filemod.line('foo', content=cfg_content, after=after_line, mode='insert', indent=False)
self.assertEqual(len(atomic_opener().write.call_args_list), 1)
self.assertEqual(atomic_opener().write.call_args_list[0][0][0],
file_modified)
@patch('os.path.realpath', MagicMock())
@patch('os.path.isfile', MagicMock(return_value=True))
@patch('os.stat', MagicMock())