예제 #1
0
    def test_acquire_actions_and_apply_single(self):
        with make_temp() as testfile_path:
            file_dict = {testfile_path: ['1\n', '2\n', '3\n']}
            diff = Diff(file_dict[testfile_path])
            diff.delete_line(2)
            diff.change_line(3, '3\n', '3_changed\n')
            with simulate_console_inputs('a', 'n') as generator:
                with retrieve_stdout() as sio:
                    ApplyPatchAction.is_applicable = staticmethod(
                        lambda *args: True)
                    acquire_actions_and_apply(self.console_printer,
                                              Section(''),
                                              self.file_diff_dict,
                                              Result(
                                                  'origin',
                                                  'message',
                                                  diffs={testfile_path: diff}),
                                              file_dict,
                                              apply_single=True)
                    self.assertEqual(generator.last_input, -1)
                    self.assertIn('', sio.getvalue())

            class InvalidateTestAction(ResultAction):

                is_applicable = staticmethod(lambda *args: True)

                def apply(*args, **kwargs):
                    ApplyPatchAction.is_applicable = staticmethod(
                        lambda *args: 'ApplyPatchAction cannot be applied.')

            old_applypatch_is_applicable = ApplyPatchAction.is_applicable
            ApplyPatchAction.is_applicable = staticmethod(lambda *args: True)
            cli_actions = [ApplyPatchAction(), InvalidateTestAction()]

            with simulate_console_inputs('a') as generator:
                with retrieve_stdout() as sio:
                    acquire_actions_and_apply(self.console_printer,
                                              Section(''),
                                              self.file_diff_dict,
                                              Result(
                                                  'origin',
                                                  'message',
                                                  diffs={testfile_path: diff}),
                                              file_dict,
                                              cli_actions=cli_actions,
                                              apply_single=True)
                    self.assertEqual(generator.last_input, -1)

                    action_fail = 'Failed to execute the action'
                    self.assertNotIn(action_fail, sio.getvalue())

                    apply_path_desc = ApplyPatchAction().get_metadata().desc
                    self.assertEqual(sio.getvalue().count(apply_path_desc), 0)

            ApplyPatchAction.is_applicable = old_applypatch_is_applicable
예제 #2
0
    def test_acquire_actions_and_apply(self):
        with make_temp() as testfile_path:
            file_dict = {testfile_path: ["1\n", "2\n", "3\n"]}
            diff = Diff(file_dict[testfile_path])
            diff.delete_line(2)
            diff.change_line(3, "3\n", "3_changed\n")
            with simulate_console_inputs(1, 0) as generator, \
                    retrieve_stdout() as sio:
                ApplyPatchAction.is_applicable = staticmethod(
                        lambda *args: True)
                acquire_actions_and_apply(self.console_printer,
                                          self.log_printer,
                                          Section(""),
                                          self.file_diff_dict,
                                          Result("origin", "message", diffs={
                                           testfile_path: diff}),
                                          file_dict)
                self.assertEqual(generator.last_input, 1)
                self.assertIn(ApplyPatchAction.SUCCESS_MESSAGE, sio.getvalue())

            class InvalidateTestAction(ResultAction):

                is_applicable = staticmethod(lambda *args: True)

                def apply(*args, **kwargs):
                    ApplyPatchAction.is_applicable = staticmethod(
                        lambda *args: False)

            old_applypatch_is_applicable = ApplyPatchAction.is_applicable
            ApplyPatchAction.is_applicable = staticmethod(lambda *args: True)
            cli_actions = [ApplyPatchAction(), InvalidateTestAction()]

            with simulate_console_inputs(2, 1, 0) as generator, \
                    retrieve_stdout() as sio:
                acquire_actions_and_apply(self.console_printer,
                                          self.log_printer,
                                          Section(""),
                                          self.file_diff_dict,
                                          Result("origin", "message",
                                                 diffs={testfile_path: diff}),
                                          file_dict,
                                          cli_actions=cli_actions)
                self.assertEqual(generator.last_input, 2)

                action_fail = "Failed to execute the action"
                self.assertNotIn(action_fail, sio.getvalue())

                apply_path_desc = ApplyPatchAction().get_metadata().desc
                self.assertEqual(sio.getvalue().count(apply_path_desc), 1)

            ApplyPatchAction.is_applicable = old_applypatch_is_applicable
예제 #3
0
    def test_apply_rename(self):
        uut = ApplyPatchAction()
        with make_temp() as f_a:
            file_dict = {f_a: ['1\n', '2\n', '3\n']}
            expected_file_dict = {
                f_a + '.renamed': ['1\n', '2_changed\n', '3_changed\n']
            }
            file_diff_dict = {}
            diff = Diff(file_dict[f_a], rename=f_a + '.renamed')
            diff.change_line(3, '3\n', '3_changed\n')
            uut.apply(Result('origin', 'msg', diffs={f_a: diff}), file_dict,
                      file_diff_dict)
            self.assertTrue(isfile(f_a + '.orig'))
            self.assertTrue(isfile(f_a + '.renamed'))
            self.assertFalse(isfile(f_a))

            diff = Diff(file_dict[f_a])
            diff.change_line(2, '2\n', '2_changed\n')
            uut.apply(Result('origin', 'msg', diffs={f_a: diff}), file_dict,
                      file_diff_dict)
            self.assertFalse(isfile(f_a + '.renamed.orig'))

            file_dict = {f_a + '.renamed': open(f_a + '.renamed').readlines()}

            self.assertEqual(file_dict, expected_file_dict)
            # Recreate file so that context manager make_temp() can delete it
            open(f_a, 'w').close()
예제 #4
0
    def test_apply_rename(self):
        # Initial file contents, *before* a patch was applied
        file_dict = {self.fa: ['1\n', '2\n', '3\n']}

        # A patch that was applied for some reason to make things complicated
        file_diff_dict = {}
        diff = Diff(file_dict[self.fa], rename=self.fa + '.renamed')
        diff.change_line(3, '3\n', '3_changed\n')
        ApplyPatchAction().apply(
            Result('origin', 'msg', diffs={self.fa: diff}), file_dict,
            file_diff_dict)
        # End file contents after the patch and the OpenEditorAction was
        # applied
        expected_file_dict = {self.fa: ['1\n', '3_changed\n']}

        section = Section('')
        section.append(Setting('editor', 'vim'))
        uut = OpenEditorAction()
        subprocess.call = self.fake_edit
        diff_dict = uut.apply_from_section(
            Result.from_values('origin', 'msg', self.fa), file_dict,
            file_diff_dict, section)

        for filename in diff_dict:
            file_dict[filename] = (file_diff_dict[filename].modified)

        self.assertEqual(file_dict, expected_file_dict)
        open(self.fa, 'w').close()
예제 #5
0
    def test_apply_orig_option(self):
        uut = ApplyPatchAction()
        with make_temp() as f_a, make_temp() as f_b:
            file_dict = {
                f_a: ["1\n", "2\n", "3\n"],
                f_b: ["1\n", "2\n", "3\n"]
                }
            expected_file_dict = {
                f_a: ["1\n", "2\n", "3_changed\n"],
                f_b: ["1\n", "2\n", "3_changed\n"]
                }
            file_diff_dict = {}
            diff = Diff(file_dict[f_a])
            diff.change_line(3, "3\n", "3_changed\n")
            uut.apply(Result("origin", "msg", diffs={f_a: diff}),
                      file_dict,
                      file_diff_dict,
                      no_orig=True)
            diff = Diff(file_dict[f_b])
            diff.change_line(3, "3\n", "3_changed\n")
            uut.apply(Result("origin", "msg", diffs={f_b: diff}),
                      file_dict,
                      file_diff_dict,
                      no_orig=False)
            self.assertFalse(isfile(f_a+".orig"))
            self.assertTrue(isfile(f_b+".orig"))

            for filename in file_diff_dict:
                file_dict[filename] = file_diff_dict[filename].modified

            self.assertEqual(file_dict, expected_file_dict)
예제 #6
0
    def test_apply_rename(self):
        uut = ApplyPatchAction()
        with make_temp() as f_a:
            file_dict = {f_a: ["1\n", "2\n", "3\n"]}
            expected_file_dict = {f_a+".renamed":
                                      ["1\n", "2_changed\n", "3_changed\n"]}
            file_diff_dict = {}
            diff = Diff(file_dict[f_a], rename=f_a+".renamed")
            diff.change_line(3, "3\n", "3_changed\n")
            uut.apply(Result("origin", "msg", diffs={f_a: diff}),
                      file_dict,
                      file_diff_dict)
            self.assertTrue(isfile(f_a+".orig"))
            self.assertTrue(isfile(f_a+".renamed"))
            self.assertFalse(isfile(f_a))

            diff = Diff(file_dict[f_a])
            diff.change_line(2, "2\n", "2_changed\n")
            uut.apply(Result("origin", "msg", diffs={f_a: diff}),
                      file_dict,
                      file_diff_dict)
            self.assertFalse(isfile(f_a+".renamed.orig"))

            file_dict = {f_a+".renamed": open(f_a+".renamed").readlines()}

            self.assertEqual(file_dict, expected_file_dict)
            # Recreate file so that context manager make_temp() can delete it
            open(f_a, 'w').close()
예제 #7
0
    def test_apply(self):
        uut = ApplyPatchAction()
        file_dict = {
            "f_a": ["1", "2", "3"],
            "f_b": ["1", "2", "3"],
            "f_c": ["1", "2", "3"]
        }
        expected_file_dict = {
            "f_a": ["1", "3_changed"],
            "f_b": ["1", "2", "3_changed"],
            "f_c": ["1", "2", "3"]
        }

        file_diff_dict = {}

        diff = Diff()
        diff.delete_line(2)
        uut.apply_from_section(PatchResult("origin", "msg", {"f_a": diff}),
                               file_dict, file_diff_dict, Section("t"))

        diff = Diff()
        diff.change_line(3, "3", "3_changed")
        uut.apply_from_section(PatchResult("origin", "msg", {"f_a": diff}),
                               file_dict, file_diff_dict, Section("t"))

        diff = Diff()
        diff.change_line(3, "3", "3_changed")
        uut.apply(PatchResult("origin", "msg", {"f_b": diff}), file_dict,
                  file_diff_dict)

        for filename in file_diff_dict:
            file_dict[filename] = file_diff_dict[filename].apply(
                file_dict[filename])

        self.assertEqual(file_dict, expected_file_dict)
예제 #8
0
    def test_ask_for_actions_and_apply2(self):
        failed_actions = set()
        action = ApplyPatchAction()
        action2 = ChainPatchAction()
        args = [
            self.console_printer,
            Section(''), [action.get_metadata(),
                          action2.get_metadata()], {
                              'ApplyPatchAction': action,
                              'ChainPatchAction': action2
                          }, failed_actions,
            Result('origin', 'message'), {}, {}, {}
        ]

        with simulate_console_inputs('c', 'a') as generator:
            ask_for_action_and_apply(*args)
            self.assertEqual(generator.last_input, 1)
            self.assertIn('ApplyPatchAction', failed_actions)

        with simulate_console_inputs('c', 'n') as generator:
            ask_for_action_and_apply(*args)
            self.assertEqual(generator.last_input, 1)
            self.assertNotIn('ChainPatchAction', failed_actions)

        with simulate_console_inputs('c', 'x') as generator:
            ask_for_action_and_apply(*args)
            self.assertEqual(generator.last_input, 0)
            self.assertNotIn('ChainPatchAction', failed_actions)

        with simulate_console_inputs('c', 'o') as generator:
            ask_for_action_and_apply(*args)
            self.assertEqual(generator.last_input, 0)
            self.assertNotIn('ChainPatchAction', failed_actions)
예제 #9
0
    def test_apply_orig_option(self):
        uut = ApplyPatchAction()
        with make_temp() as f_a, make_temp() as f_b:
            file_dict = {
                f_a: ['1\n', '2\n', '3\n'],
                f_b: ['1\n', '2\n', '3\n']
            }
            expected_file_dict = {
                f_a: ['1\n', '2\n', '3_changed\n'],
                f_b: ['1\n', '2\n', '3_changed\n']
            }
            file_diff_dict = {}
            diff = Diff(file_dict[f_a])
            diff.change_line(3, '3\n', '3_changed\n')
            uut.apply(Result('origin', 'msg', diffs={f_a: diff}),
                      file_dict,
                      file_diff_dict,
                      no_orig=True)
            diff = Diff(file_dict[f_b])
            diff.change_line(3, '3\n', '3_changed\n')
            uut.apply(Result('origin', 'msg', diffs={f_b: diff}),
                      file_dict,
                      file_diff_dict,
                      no_orig=False)
            self.assertFalse(isfile(f_a + '.orig'))
            self.assertTrue(isfile(f_b + '.orig'))

            for filename in file_diff_dict:
                file_dict[filename] = file_diff_dict[filename].modified

            self.assertEqual(file_dict, expected_file_dict)
예제 #10
0
def provide_all_actions():
    return [DoNothingAction().get_metadata().desc,
            ShowPatchAction().get_metadata().desc,
            ApplyPatchAction().get_metadata().desc,
            IgnoreResultAction().get_metadata().desc,
            OpenEditorAction().get_metadata().desc,
            PrintAspectAction().get_metadata().desc,
            PrintDebugMessageAction().get_metadata().desc,
            PrintMoreInfoAction().get_metadata().desc]
예제 #11
0
    def setUp(self):
        self._input = builtins.__dict__["input"]
        builtins.__dict__["input"] = lambda x: x
        self.uut = ConsoleInteractor()

        # All those tests assume that Result has no actions and PatchResult has
        # one. This makes this test independent from the real number of actions
        # applicable to those results.
        Result.get_actions = lambda self: []
        PatchResult.get_actions = lambda self: [ApplyPatchAction()]
예제 #12
0
    def test_apply(self):
        uut = ApplyPatchAction()
        fh_a, f_a = mkstemp()
        fh_b, f_b = mkstemp()
        fh_c, f_c = mkstemp()
        os.close(fh_a)
        os.close(fh_b)
        os.close(fh_c)

        file_dict = {
            f_a: ["1\n", "2\n", "3\n"],
            f_b: ["1\n", "2\n", "3\n"],
            f_c: ["1\n", "2\n", "3\n"]
        }
        expected_file_dict = {
            f_a: ["1\n", "3_changed\n"],
            f_b: ["1\n", "2\n", "3_changed\n"],
            f_c: ["1\n", "2\n", "3\n"]
        }

        file_diff_dict = {}

        diff = Diff(file_dict[f_a])
        diff.delete_line(2)
        uut.apply_from_section(Result("origin", "msg", diffs={f_a: diff}),
                               file_dict, file_diff_dict, Section("t"))

        diff = Diff(file_dict[f_a])
        diff.change_line(3, "3\n", "3_changed\n")
        uut.apply_from_section(Result("origin", "msg", diffs={f_a: diff}),
                               file_dict, file_diff_dict, Section("t"))

        diff = Diff(file_dict[f_b])
        diff.change_line(3, "3\n", "3_changed\n")
        uut.apply(Result("origin", "msg", diffs={f_b: diff}), file_dict,
                  file_diff_dict)

        for filename in file_diff_dict:
            file_dict[filename] = file_diff_dict[filename].modified

        self.assertEqual(file_dict, expected_file_dict)
        with open(f_a) as fa:
            self.assertEqual(file_dict[f_a], fa.readlines())
        with open(f_b) as fb:
            self.assertEqual(file_dict[f_b], fb.readlines())
        with open(f_c) as fc:
            # File c is unchanged and should be untouched
            self.assertEqual([], fc.readlines())

        os.remove(f_a)
        os.remove(f_b)
        os.remove(f_c)
예제 #13
0
    def test_apply(self):
        uut = ApplyPatchAction()
        with make_temp() as f_a, make_temp() as f_b, make_temp() as f_c:

            file_dict = {
                f_a: ['1\n', '2\n', '3\n'],
                f_b: ['1\n', '2\n', '3\n'],
                f_c: ['1\n', '2\n', '3\n']
            }
            expected_file_dict = {
                f_a: ['1\n', '3_changed\n'],
                f_b: ['1\n', '2\n', '3_changed\n'],
                f_c: ['1\n', '2\n', '3\n']
            }

            file_diff_dict = {}

            diff = Diff(file_dict[f_a])
            diff.delete_line(2)
            uut.apply_from_section(Result('origin', 'msg', diffs={f_a: diff}),
                                   file_dict,
                                   file_diff_dict,
                                   Section('t'))

            diff = Diff(file_dict[f_a])
            diff.change_line(3, '3\n', '3_changed\n')
            uut.apply_from_section(Result('origin', 'msg', diffs={f_a: diff}),
                                   file_dict,
                                   file_diff_dict,
                                   Section('t'))

            diff = Diff(file_dict[f_b])
            diff.change_line(3, '3\n', '3_changed\n')
            uut.apply(Result('origin', 'msg', diffs={f_b: diff}),
                      file_dict,
                      file_diff_dict)

            for filename in file_diff_dict:
                file_dict[filename] = file_diff_dict[filename].modified

            self.assertEqual(file_dict, expected_file_dict)
            with open(f_a) as fa:
                self.assertEqual(file_dict[f_a], fa.readlines())
            with open(f_b) as fb:
                self.assertEqual(file_dict[f_b], fb.readlines())
            with open(f_c) as fc:
                # File c is unchanged and should be untouched
                self.assertEqual([], fc.readlines())
예제 #14
0
    def test_apply_delete(self):
        uut = ApplyPatchAction()
        with make_temp() as f_a:
            file_dict = {f_a: ['1\n', '2\n', '3\n']}
            file_diff_dict = {}
            diff = Diff(file_dict[f_a], delete=True)
            uut.apply(Result('origin', 'msg', diffs={f_a: diff}), file_dict,
                      file_diff_dict)
            self.assertFalse(isfile(f_a))
            self.assertTrue(isfile(f_a + '.orig'))
            os.remove(f_a + '.orig')

            diff = Diff(file_dict[f_a])
            diff.change_line(3, '3\n', '3_changed\n')
            uut.apply(Result('origin', 'msg', diffs={f_a: diff}), file_dict,
                      file_diff_dict)
            self.assertFalse(isfile(f_a + '.orig'))
            # Recreate file so that context manager make_temp() can delete it
            open(f_a, 'w').close()
예제 #15
0
STR_LINE_DOESNT_EXIST = ('The line belonging to the following result '
                         'cannot be printed because it refers to a line '
                         "that doesn't seem to exist in the given file.")
STR_PROJECT_WIDE = 'Project wide:'
STR_ENTER_NUMBER = ('Enter number (Ctrl-'
                    f"{'Z' if platform.system() == 'Windows' else 'D'} "
                    'to exit): ')
STR_INVALID_OPTION = '*** Invalid Option: ({}) ***\n'
WARNING_COLOR = 'red'
FILE_NAME_COLOR = 'blue'
FILE_LINES_COLOR = 'blue'
CAPABILITY_COLOR = 'green'
HIGHLIGHTED_CODE_COLOR = 'red'
SUCCESS_COLOR = 'green'
REQUIRED_SETTINGS_COLOR = 'green'
CLI_ACTIONS = (OpenEditorAction(), ApplyPatchAction(),
               PrintDebugMessageAction(), PrintMoreInfoAction(),
               ShowPatchAction(), IgnoreResultAction(),
               ShowAppliedPatchesAction(), GeneratePatchesAction())
DIFF_EXCERPT_MAX_SIZE = 4


def color_letter(console_printer, line):
    x = line.find('(')
    if x == -1:
        letter = ''
        y = x + 1
    else:
        letter = line[x + 1]
        y = x + 2
    warn = line.rfind('[')
STR_GET_VAL_FOR_SETTING = ('Please enter a value for the setting \"{}\" ({}) '
                           'needed by {} for section \"{}\": ')
STR_LINE_DOESNT_EXIST = ('The line belonging to the following result '
                         'cannot be printed because it refers to a line '
                         "that doesn't seem to exist in the given file.")
STR_PROJECT_WIDE = 'Project wide:'
STR_ENTER_NUMBER = 'Enter number (Ctrl-{} to exit): '.format(
    'Z' if platform.system() == 'Windows' else 'D')
FILE_NAME_COLOR = 'blue'
FILE_LINES_COLOR = 'blue'
CAPABILITY_COLOR = 'green'
HIGHLIGHTED_CODE_COLOR = 'red'
SUCCESS_COLOR = 'green'
REQUIRED_SETTINGS_COLOR = 'green'
CLI_ACTIONS = (OpenEditorAction(),
               ApplyPatchAction(),
               PrintDebugMessageAction(),
               PrintMoreInfoAction(),
               ShowPatchAction(),
               IgnoreResultAction(),
               ShowAppliedPatchesAction(),
               GeneratePatchesAction())
DIFF_EXCERPT_MAX_SIZE = 4


def color_letter(console_printer, line):
    x = -1
    y = -1
    letter = ''
    for i, l in enumerate(line, 0):
        if line[i] == '(':
예제 #17
0
 def get_actions():
     return [ApplyPatchAction()]
예제 #18
0
파일: PatchResult.py 프로젝트: B-Rich/coala
    def get_actions(self):
        actions = Result.get_actions(self)
        actions.extend([ApplyPatchAction()])

        return actions