def test_apply(self):
        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\n"],
            "f_b": ["1\n", "3_changed\n"],
            "f_c": ["1\n", "2\n", "3\n"]
        }
        diff_dict = {"f_b": Diff()}
        diff_dict["f_b"].change_line(3, "3\n", "3_changed\n")

        section = Section("")
        section.append(Setting("editor", ""))
        uut = OpenEditorAction()
        subprocess.call = self.fake_edit
        diff_dict = uut.apply_from_section(
            Result("origin", "msg", "f_a"),
            file_dict,
            diff_dict,
            section)
        diff_dict = uut.apply_from_section(
            Result("origin", "msg", "f_b"),
            file_dict,
            diff_dict,
            section)

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

        self.assertEqual(file_dict, expected_file_dict)
Example #2
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", ""))
        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()
Example #3
0
    def test_apply(self):
        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\n"],
            "f_b": ["1\n", "3_changed\n"],
            "f_c": ["1\n", "2\n", "3\n"]
        }
        diff_dict = {"f_b": Diff()}
        diff_dict["f_b"].change_line(3, "3\n", "3_changed\n")

        section = Section("")
        section.append(Setting("editor", ""))
        uut = OpenEditorAction()
        os.system = self.fake_edit
        diff_dict = uut.apply_from_section(Result("origin", "msg", "f_a"),
                                           file_dict, diff_dict, section)
        diff_dict = uut.apply_from_section(Result("origin", "msg", "f_b"),
                                           file_dict, diff_dict, section)

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

        self.assertEqual(file_dict, expected_file_dict)
Example #4
0
 def test_is_applicable(self):
     result1 = Result("", "")
     result2 = Result.from_values("", "", "")
     invalid_result = ""
     self.assertFalse(OpenEditorAction.is_applicable(result1))
     self.assertTrue(OpenEditorAction.is_applicable(result2))
     self.assertFalse(OpenEditorAction.is_applicable(invalid_result))
Example #5
0
    def test_is_applicable(self):
        result1 = Result("", "")
        result2 = Result.from_values("", "", "")
        invalid_result = ""
        self.assertFalse(OpenEditorAction.is_applicable(result1, None, None))
        self.assertTrue(OpenEditorAction.is_applicable(result2, None, None))

        self.assertFalse(
            OpenEditorAction.is_applicable(invalid_result, None, None))
Example #6
0
    def test_subl(self):
        file_dict = {"f_a": []}
        section = Section("")
        section.append(Setting("editor", "subl"))
        uut = OpenEditorAction()
        os.system = self.fake_edit_subl
        diff_dict = uut.apply_from_section(Result("origin", "msg", "f_a"),
                                           file_dict, {}, section)
        file_dict["f_a"] = diff_dict["f_a"].apply(file_dict["f_a"])

        self.assertEqual(file_dict, file_dict)
Example #7
0
    def test_is_applicable(self):
        result1 = Result("", "")
        result2 = Result.from_values("", "", "")
        result3 = Result.from_values("", "", "file")
        invalid_result = ""
        self.assertFalse(OpenEditorAction.is_applicable(result1, None, {}))
        self.assertTrue(OpenEditorAction.is_applicable(result2, None, {}))
        # Check non-existent file
        self.assertFalse(OpenEditorAction.is_applicable(result3, None, {}))

        self.assertFalse(
            OpenEditorAction.is_applicable(invalid_result, None, {}))
    def test_subl(self):
        file_dict = {self.fa: []}
        section = Section('')
        section.append(Setting('editor', 'subl'))
        uut = OpenEditorAction()
        subprocess.call = self.fake_edit_subl
        diff_dict = uut.apply_from_section(
            Result.from_values('origin', 'msg', self.fa), file_dict, {},
            section)
        file_dict[self.fa] = diff_dict[self.fa].modified

        self.assertEqual(file_dict, file_dict)
Example #9
0
    def test_subl(self):
        file_dict = {self.fa: []}
        section = Section("")
        section.append(Setting("editor", "subl"))
        uut = OpenEditorAction()
        subprocess.call = self.fake_edit_subl
        diff_dict = uut.apply_from_section(
            Result.from_values("origin", "msg", self.fa), file_dict, {},
            section)
        file_dict[self.fa] = diff_dict[self.fa].modified

        self.assertEqual(file_dict, file_dict)
    def test_subl(self):
        file_dict = {self.fa: []}
        section = Section("")
        section.append(Setting("editor", "subl"))
        uut = OpenEditorAction()
        subprocess.call = self.fake_edit_subl
        diff_dict = uut.apply_from_section(
            Result.from_values("origin", "msg", self.fa),
            file_dict,
            {},
            section)
        file_dict[self.fa] = diff_dict[self.fa].modified

        self.assertEqual(file_dict, file_dict)
    def test_subl(self):
        file_dict = {"f_a": []}
        section = Section("")
        section.append(Setting("editor", "subl"))
        uut = OpenEditorAction()
        subprocess.call = self.fake_edit_subl
        diff_dict = uut.apply_from_section(
            Result("origin", "msg", "f_a"),
            file_dict,
            {},
            section)
        file_dict["f_a"] = diff_dict["f_a"].apply(file_dict["f_a"])

        self.assertEqual(file_dict, file_dict)
Example #12
0
    def test_apply(self):
        # Initial file contents, *before* a patch was applied
        file_dict = {
            self.fa: ["1\n", "2\n", "3\n"],
            self.fb: ["1\n", "2\n", "3\n"],
            "f_c": ["1\n", "2\n", "3\n"]}

        # A patch that was applied for some reason to make things complicated
        diff_dict = {self.fb: Diff(file_dict[self.fb])}
        diff_dict[self.fb].change_line(3, "3\n", "3_changed\n")

        # File contents after the patch was applied, that's what's in the files
        current_file_dict = {
            filename: diff_dict[filename].modified
            if filename in diff_dict else file_dict[filename]
            for filename in (self.fa, self.fb)}
        for filename in current_file_dict:
            with open(filename, 'w') as handle:
                handle.writelines(current_file_dict[filename])

        # End file contents after the patch and the OpenEditorAction was
        # applied
        expected_file_dict = {
            self.fa: ["1\n", "3\n"],
            self.fb: ["1\n", "3_changed\n"],
            "f_c": ["1\n", "2\n", "3\n"]}

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

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

        self.assertEqual(file_dict, expected_file_dict)
Example #13
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]
Example #14
0
    def get_actions(self):
        """
        :return: All ResultAction classes applicable to this result.
        """
        from coalib.results.result_actions.OpenEditorAction import OpenEditorAction
        actions = []
        if self.file is not None:
            actions.append(OpenEditorAction())

        return actions
Example #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('[')
Example #16
0
    def test_print_result(self):
        self.uut.print = lambda x: x
        builtins.__dict__["input"] = lambda x: 0

        self.assertEqual(
            "|    |    | [{normal}] {bear}:".format(
                normal=RESULT_SEVERITY.__str__(RESULT_SEVERITY.NORMAL),
                bear="origin") + "\n|    |    | message",
            self.uut._print_result(Result("origin", "message")))

        self.uut.print_result(PatchResult("origin", "msg", {}), {})

        (testfile, testfile_path) = tempfile.mkstemp()
        os.close(testfile)
        file_dict = {
            testfile_path: ["1\n", "2\n", "3\n"],
            "f_b": ["1", "2", "3"]
        }
        diff = Diff()
        diff.delete_line(2)
        diff.change_line(3, "3\n", "3_changed\n")

        builtins.__dict__["input"] = lambda x: 1
        with self.assertRaises(ValueError):
            self.uut.print_result(
                PatchResult("origin", "msg", {testfile_path: diff}), file_dict)

        # To assure user can rechose if he didn't chose wisely
        input_generator = InputGenerator(["INVALID", -1, 1, 3])
        builtins.__dict__["input"] = input_generator.generate_input
        # To load current_section in ConsoleInteractor object
        self.uut.begin_section(Section(""))
        self.uut.print_result(
            PatchResult("origin", "msg", {testfile_path: diff}), file_dict)
        self.assertEqual(input_generator.current_input, 2)
        self.uut.finalize(file_dict)
        with open(testfile_path) as f:
            self.assertEqual(f.readlines(), ["1\n", "3_changed\n"])

        os.remove(testfile_path)
        os.remove(testfile_path + ".orig")

        name, section = self.uut._get_action_info(TestAction().get_metadata())
        self.assertEqual(str(section), " {param : 3}")
        self.assertEqual(name, "TestAction")

        # Check for asking the user for the paremeter just int the first time
        # Use OpenEditorAction thats need parameter (editor command)
        input_generator = InputGenerator([1, "test_editor", 1])
        builtins.__dict__[
            "input"] = input_generator.generate_input  # Choose open editor action
        PatchResult.get_actions = lambda self: [OpenEditorAction()]

        patch_result = PatchResult("origin", "msg", {testfile_path: diff})
        patch_result.file = "f_b"

        self.uut.print_result(patch_result, file_dict)
        self.assertEquals(input_generator.current_input,
                          1)  # Increase by 2 (-1 -> 1)

        # Increase by 1, It shoudn't ask for parameter again
        self.uut.print_result(patch_result, file_dict)
        self.assertEquals(input_generator.current_input, 2)
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):
Example #18
0
from coalib.results.RESULT_SEVERITY import (RESULT_SEVERITY,
                                            RESULT_SEVERITY_COLORS)
from coalib.settings.Setting import Setting

STR_GET_VAL_FOR_SETTING = ("Please enter a value for the setting \"{}\" ({}) "
                           "needed by {}: ")
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:"
FILE_NAME_COLOR = "blue"
FILE_LINES_COLOR = "blue"
HIGHLIGHTED_CODE_COLOR = 'red'
SUCCESS_COLOR = 'green'
CLI_ACTIONS = [
    OpenEditorAction(),
    ApplyPatchAction(),
    PrintDebugMessageAction(),
    ShowPatchAction()
]


def format_lines(lines, line_nr=""):
    return '\n'.join("|{:>4}| {}".format(line_nr, line)
                     for line in lines.rstrip("\n").split('\n'))


def print_section_beginning(console_printer, section):
    """
    Will be called after initialization current_section in
    begin_section()