def test_replace_append_if_not_found(self):
        args = {
                'pattern': '#*baz=(?P<value>.*)',
                'repl': 'baz=\\g<value>',
                'append_if_not_found': True,
        }
        base = 'foo=1\nbar=2'
        expected = '{base}\n{repl}\n'.format(base=base, **args)
        # File ending with a newline, no match
        with tempfile.NamedTemporaryFile(mode='w+') as tfile:
            tfile.write(base + '\n')
            tfile.flush()
            filemod.replace(tfile.name, **args)
            with salt.utils.fopen(tfile.name) as tfile2:
                self.assertEqual(tfile2.read(), expected)
        # File not ending with a newline, no match
        with tempfile.NamedTemporaryFile('w+') as tfile:
            tfile.write(base)
            tfile.flush()
            filemod.replace(tfile.name, **args)
            with salt.utils.fopen(tfile.name) as tfile2:
                self.assertEqual(tfile2.read(), expected)
        # A newline should not be added in empty files
        with tempfile.NamedTemporaryFile('w+') as tfile:
            filemod.replace(tfile.name, **args)
            with salt.utils.fopen(tfile.name) as tfile2:
                self.assertEqual(tfile2.read(), args['repl'] + '\n')
        # Using not_found_content, rather than repl
        with tempfile.NamedTemporaryFile('w+') as tfile:
            args['not_found_content'] = 'baz=3'
            expected = '{base}\n{not_found_content}\n'.format(base=base, **args)
            tfile.write(base)
            tfile.flush()
            filemod.replace(tfile.name, **args)
            with salt.utils.fopen(tfile.name) as tfile2:
                self.assertEqual(tfile2.read(), expected)
        # not appending if matches
        with tempfile.NamedTemporaryFile('w+') as tfile:
            base = 'foo=1\n#baz=42\nbar=2\n'
            expected = 'foo=1\nbaz=42\nbar=2\n'
            tfile.write(base)
            tfile.flush()
            filemod.replace(tfile.name, **args)
            with salt.utils.fopen(tfile.name) as tfile2:
                self.assertEqual(tfile2.read(), expected)
Check that file.replace append_if_not_found works
dataset/ETHPy150Open saltstack/salt/tests/unit/modules/file_test.py/FileReplaceTestCase.test_replace_append_if_not_found