Merge pull request #37452 from rallytime/fix-31135

file.line with mode=replace on an empty file should return False, not stacktrace
This commit is contained in:
Mike Place 2016-11-06 14:55:11 +13:00 committed by GitHub
commit be93710fee
2 changed files with 33 additions and 3 deletions

View file

@ -1513,9 +1513,13 @@ def line(path, content, match=None, mode=None, location=None,
body = os.linesep.join([line for line in body.split(os.linesep) if line.find(match) < 0])
elif mode == 'replace':
body = os.linesep.join([(_get_line_indent(line, content, indent)
if (line.find(match) > -1 and not line == content) else line)
for line in body.split(os.linesep)])
if os.stat(path).st_size == 0:
log.warning('Cannot find text to replace. File \'{0}\' is empty.'.format(path))
body = ''
else:
body = os.linesep.join([(_get_line_indent(file_line, content, indent)
if (file_line.find(match) > -1 and not file_line == content) else file_line)
for file_line in body.split(os.linesep)])
elif mode == 'insert':
if not location and not before and not after:
raise CommandExecutionError('On insert must be defined either "location" or "before/after" conditions.')

View file

@ -643,6 +643,32 @@ class FileModuleTestCase(TestCase):
saltenv='base')
self.assertEqual(ret, 'This is a templated file.')
def test_replace_line_in_empty_file(self):
'''
Tests that when calling file.line with ``mode=replace``,
the function doesn't stack trace if the file is empty.
Should return ``False``.
See Issue #31135.
'''
# Create an empty temporary named file
empty_file = tempfile.NamedTemporaryFile(delete=False,
mode='w+')
# Assert that the file was created and is empty
self.assertEqual(os.stat(empty_file.name).st_size, 0)
# Now call the function on the empty file and assert
# the return is False instead of stack-tracing
self.assertFalse(filemod.line(empty_file.name,
content='foo',
match='bar',
mode='replace'))
# Close and remove the file
empty_file.close()
os.remove(empty_file.name)
if __name__ == '__main__':
from integration import run_tests