Exemplo n.º 1
0
    def test_print_results_sorting(self):
        with retrieve_stdout() as stdout:
            print_results(self.log_printer,
                          Section(""),
                          [Result.from_values("SpaceConsistencyBear",
                                              "Trailing whitespace found",
                                              file="file",
                                              line=5),
                           Result.from_values("SpaceConsistencyBear",
                                              "Trailing whitespace found",
                                              file="file",
                                              line=2)],
                          {"file": ["test line\n",
                                    "line 2\n",
                                    "line 3\n",
                                    "line 4\n",
                                    "line 5\n"]},
                          {},
                          color=False)

            self.assertEqual("""
file
|   2| line 2
|    | [{}] SpaceConsistencyBear:
|    | Trailing whitespace found

file
|   5| line 5
|    | [{}] SpaceConsistencyBear:
|    | Trailing whitespace found
""".format(RESULT_SEVERITY.__str__(RESULT_SEVERITY.NORMAL),
           RESULT_SEVERITY.__str__(RESULT_SEVERITY.NORMAL)),
                             stdout.getvalue())
Exemplo n.º 2
0
 def test_str_conversion(self):
     self.assertEqual("INFO",
                      RESULT_SEVERITY.__str__(RESULT_SEVERITY.INFO))
     self.assertEqual("NORMAL",
                      RESULT_SEVERITY.__str__(RESULT_SEVERITY.NORMAL))
     self.assertEqual("MAJOR",
                      RESULT_SEVERITY.__str__(RESULT_SEVERITY.MAJOR))
Exemplo n.º 3
0
    def test_print_results_sorting(self):
        with retrieve_stdout() as stdout:
            print_results(self.log_printer,
                          Section(""),
                          [Result("SpaceConsistencyBear",
                                  "Trailing whitespace found",
                                  "proj/white",
                                  line_nr=5),
                           Result("SpaceConsistencyBear",
                                  "Trailing whitespace found",
                                  "proj/white",
                                  line_nr=2)],
                          {"proj/white": ["test line\n",
                                          "line 2\n",
                                          "line 3\n",
                                          "line 4\n",
                                          "line 5\n"]},
                          {},
                          color=False)

            self.assertEqual("""\n\nproj/white
|   1|   1| test line
|   2|   2| line 2
|    |    | [{}] SpaceConsistencyBear:
|    |    | Trailing whitespace found
|   3|   3| line 3
|   4|   4| line 4
|   5|   5| line 5
|    |    | [{}] SpaceConsistencyBear:
|    |    | Trailing whitespace found
""".format(RESULT_SEVERITY.__str__(RESULT_SEVERITY.NORMAL),
           RESULT_SEVERITY.__str__(RESULT_SEVERITY.NORMAL)),
                             stdout.getvalue())
Exemplo n.º 4
0
 def test_str_conversion(self):
     self.assertEqual(_("INFO"),
                      RESULT_SEVERITY.__str__(RESULT_SEVERITY.INFO))
     self.assertEqual(_("NORMAL"),
                      RESULT_SEVERITY.__str__(RESULT_SEVERITY.NORMAL))
     self.assertEqual(_("MAJOR"),
                      RESULT_SEVERITY.__str__(RESULT_SEVERITY.MAJOR))
Exemplo n.º 5
0
 def test_str_conversion(self):
     self.assertEqual('INFO',
                      RESULT_SEVERITY.__str__(RESULT_SEVERITY.INFO))
     self.assertEqual('NORMAL',
                      RESULT_SEVERITY.__str__(RESULT_SEVERITY.NORMAL))
     self.assertEqual('MAJOR',
                      RESULT_SEVERITY.__str__(RESULT_SEVERITY.MAJOR))
Exemplo n.º 6
0
    def test_print_results_multiple_ranges(self):
        affected_code = (SourceRange.from_values("some_file", 5, end_line=7),
                         SourceRange.from_values("another_file", 1, 3, 1, 5),
                         SourceRange.from_values("another_file", 3, 3, 3, 5))
        with retrieve_stdout() as stdout:
            print_results(
                self.log_printer,
                Section(""),
                [Result("ClangCloneDetectionBear",
                        "Clone Found",
                        affected_code)],
                {"some_file": ["line "+str(i+1)+"\n" for i in range(10)],
                 "another_file": ["line "+str(i+1)+"\n" for i in range(10)]},
                {},
                color=False)
            self.assertEqual("""
another_file
|   1| line 1

another_file
|   3| line 3

some_file
|   5| line 5
|   6| line 6
|   7| line 7
|    | [{}] ClangCloneDetectionBear:
|    | Clone Found
""".format(RESULT_SEVERITY.__str__(RESULT_SEVERITY.NORMAL)),
                         stdout.getvalue())
Exemplo n.º 7
0
def print_results_formatted(log_printer,
                            section,
                            result_list,
                            *args):
    format_str = str(section.get(
        "format_str",
        "id:{id}:origin:{origin}:file:{file}:line:{line}:column:"
        "{column}:end_line:{end_line}:end_column:{end_column}:severity:"
        "{severity}:severity_str:{severity_str}:message:{message}"))
    for result in result_list:
        severity_str = RESULT_SEVERITY.__str__(result.severity)
        try:
            if len(result.affected_code) == 0:
                print(format_str.format(file=None,
                                        line=None,
                                        end_line=None,
                                        column=None,
                                        end_column=None,
                                        severity_str=severity_str,
                                        **result.__dict__))
                continue

            for range in result.affected_code:
                print(format_str.format(file=range.start.file,
                                        line=range.start.line,
                                        end_line=range.end.line,
                                        column=range.start.column,
                                        end_column=range.end.column,
                                        severity_str=severity_str,
                                        **result.__dict__))
        except KeyError as exception:
            log_printer.log_exception(
                "Unable to print the result with the given format string.",
                exception)
    def apply(self,
              result,
              original_file_dict,
              file_diff_dict):
        """
        Show Applied (P)atches
        """
        console_printer = ConsolePrinter()
        applied_actions = result.get_applied_actions()
        show_patch_action = ShowPatchAction()
        RESULT_INDEX = 0
        FILE_DICT_INDEX = 1
        FILE_DIFF_DICT_INDEX = 2
        SECTION_INDEX = 3

        for key, val in applied_actions.items():
            this_result = val[RESULT_INDEX]
            this_section = val[SECTION_INDEX]
            color_res = RESULT_SEVERITY_COLORS[this_result.severity]
            console_printer.print('\n**** {bear} [Section: {section}] ***'
                                  '*\n**** Action Applied: {action} ****\n'
                                  .format(bear=this_result.origin,
                                          section=this_section.name,
                                          action=key),
                                  color=color_res)
            console_printer.print(format_lines('[Severity: {sev}]'.format(
                sev=RESULT_SEVERITY.__str__(this_result.severity)), '!'),
                  color=color_res)
            show_patch_action.apply_from_section(val[RESULT_INDEX],
                                                 val[FILE_DICT_INDEX],
                                                 val[FILE_DIFF_DICT_INDEX],
                                                 val[SECTION_INDEX])
            console_printer.print(
                '\n**************\n', color=color_res)
        return True
Exemplo n.º 9
0
def print_results_formatted(log_printer,
                            section,
                            result_list,
                            *args):
    """
    Prints results through the format string from the format setting done by
    user.

    :param log_printer:    Printer responsible for logging the messages.
    :param section:        The section to which the results belong.
    :param result_list:    List of Result objects containing the corresponding
                           results.
    """
    global _warn_deprecated_format_str
    default_format = ('id:{id}:origin:{origin}:file:{file}:line:{line}:'
                      'column:{column}:end_line:{end_line}:end_column:'
                      '{end_column}:severity:{severity}:severity_str:'
                      '{severity_str}:message:{message}')
    if 'format_str' in section:
        format_str = str(section.get('format_str', default_format))
        if _warn_deprecated_format_str:
            log_printer.warn('The setting "format_str" has been deprecated.'
                             ' Please use "format" instead')
            _warn_deprecated_format_str = False
    else:
        format_str = str(section.get('format', default_format))

    if format_str == 'True':
        format_str = default_format

    for result in result_list:
        severity_str = RESULT_SEVERITY.__str__(result.severity)
        format_args = vars(result)
        try:
            if len(result.affected_code) == 0:
                format_args['affected_code'] = None
                print(format_str.format(file=None,
                                        line=None,
                                        end_line=None,
                                        column=None,
                                        end_column=None,
                                        severity_str=severity_str,
                                        message=result.message,
                                        **format_args))
                continue

            for range in result.affected_code:
                format_args['affected_code'] = range
                print(format_str.format(file=range.start.file,
                                        line=range.start.line,
                                        end_line=range.end.line,
                                        column=range.start.column,
                                        end_column=range.end.column,
                                        severity_str=severity_str,
                                        message=result.message,
                                        **format_args))
        except KeyError as exception:
            log_printer.log_exception(
                'Unable to print the result with the given format string.',
                exception)
Exemplo n.º 10
0
    def apply(self, result, original_file_dict, file_diff_dict):
        """
        Show Applied (P)atches
        """
        console_printer = ConsolePrinter()
        applied_actions = result.get_applied_actions()
        show_patch_action = ShowPatchAction()
        RESULT_INDEX = 0
        FILE_DICT_INDEX = 1
        FILE_DIFF_DICT_INDEX = 2
        SECTION_INDEX = 3

        for key, val in applied_actions.items():
            this_result = val[RESULT_INDEX]
            this_section = val[SECTION_INDEX]
            color_res = RESULT_SEVERITY_COLORS[this_result.severity]
            console_printer.print(
                '\n**** {bear} [Section: {section}] ***'
                '*\n**** Action Applied: {action} ****\n'.format(
                    bear=this_result.origin,
                    section=this_section.name,
                    action=key),
                color=color_res)
            console_printer.print(format_lines(
                '[Severity: {sev}]'.format(
                    sev=RESULT_SEVERITY.__str__(this_result.severity)), '!'),
                                  color=color_res)
            show_patch_action.apply_from_section(val[RESULT_INDEX],
                                                 val[FILE_DICT_INDEX],
                                                 val[FILE_DIFF_DICT_INDEX],
                                                 val[SECTION_INDEX])
            console_printer.print('\n**************\n', color=color_res)
        return True
Exemplo n.º 11
0
def print_result(console_printer,
                 section,
                 file_diff_dict,
                 result,
                 file_dict,
                 interactive=True):
    """
    Prints the result to console.

    :param console_printer: Object to print messages on the console.
    :param section:         Name of section to which the result belongs.
    :param file_diff_dict:  Dictionary containing filenames as keys and Diff
                            objects as values.
    :param result:          A derivative of Result.
    :param file_dict:       A dictionary containing all files with filename as
                            key.
    :param interactive:     Variable to check whether or not to
                            offer the user actions interactively.
    """
    no_color = not console_printer.print_colored
    if not isinstance(result, Result):
        logging.warning('One of the results can not be printed since it is '
                        'not a valid derivative of the coala result '
                        'class.')
        return

    if hasattr(section, 'name'):
        console_printer.print(
            '\n**** {bear} [Section: {section}] ****\n'.format(
                bear=result.origin, section=section.name),
            color=RESULT_SEVERITY_COLORS[result.severity])
    else:
        console_printer.print(
            '\n**** {bear} [Section: {section}] ****\n'.format(
                bear=result.origin, section='<empty>'),
            color=RESULT_SEVERITY_COLORS[result.severity])
    console_printer.print(format_lines(
        '[Severity: {sev}]'.format(
            sev=RESULT_SEVERITY.__str__(result.severity)), '!'),
                          color=RESULT_SEVERITY_COLORS[result.severity])
    lexer = TextLexer()
    result.message = highlight_text(no_color, result.message, lexer,
                                    BackgroundMessageStyle)
    console_printer.print(format_lines(result.message, symbol='!'))

    if interactive:
        cli_actions = CLI_ACTIONS
        show_patch_action = ShowPatchAction()
        if show_patch_action.is_applicable(result, file_dict,
                                           file_diff_dict) is True:
            diff_size = sum(len(diff) for diff in result.diffs.values())
            if diff_size <= DIFF_EXCERPT_MAX_SIZE:
                show_patch_action.apply_from_section(result, file_dict,
                                                     file_diff_dict, section)
                cli_actions = tuple(action for action in cli_actions
                                    if not isinstance(action, ShowPatchAction))
            else:
                print_diffs_info(result.diffs, console_printer)
        acquire_actions_and_apply(console_printer, section, file_diff_dict,
                                  result, file_dict, cli_actions)
Exemplo n.º 12
0
def print_result(console_printer,
                 log_printer,
                 section,
                 file_diff_dict,
                 result,
                 file_dict,
                 interactive=True):
    """
    Prints the result to console.

    :param console_printer: Object to print messages on the console.
    :param log_printer:     Printer responsible for logging the messages.
    :param section:         Name of section to which the result belongs.
    :param file_diff_dict:  Dictionary containing filenames as keys and Diff
                            objects as values.
    :param result:          A derivative of Result.
    :param file_dict:       A dictionary containing all files with filename as
                            key.
    :interactive:           Variable to check wether or not to
                            offer the user actions interactively.
    """
    if not isinstance(result, Result):
        log_printer.warn("One of the results can not be printed since it is "
                         "not a valid derivative of the coala result "
                         "class.")
        return

    console_printer.print(format_lines("[{sev}] {bear}:".format(
        sev=RESULT_SEVERITY.__str__(result.severity), bear=result.origin)),
                          color=RESULT_SEVERITY_COLORS[result.severity])
    console_printer.print(format_lines(result.message), delimiter="\n")

    if interactive:
        acquire_actions_and_apply(console_printer, log_printer, section,
                                  file_diff_dict, result, file_dict)
Exemplo n.º 13
0
def print_results_formatted(log_printer,
                            section,
                            result_list,
                            *args):
    format_str = str(section.get(
        "format_str",
        "id:{id}:origin:{origin}:file:{file}:line:{line}:column:"
        "{column}:end_line:{end_line}:end_column:{end_column}:severity:"
        "{severity}:severity_str:{severity_str}:message:{message}"))
    for result in result_list:
        severity_str = RESULT_SEVERITY.__str__(result.severity)
        try:
            if len(result.affected_code) == 0:
                print(format_str.format(file=None,
                                        line=None,
                                        end_line=None,
                                        column=None,
                                        end_column=None,
                                        severity_str=severity_str,
                                        **result.__dict__))
                continue

            for range in result.affected_code:
                print(format_str.format(file=range.start.file,
                                        line=range.start.line,
                                        end_line=range.end.line,
                                        column=range.start.column,
                                        end_column=range.end.column,
                                        severity_str=severity_str,
                                        **result.__dict__))
        except KeyError as exception:
            log_printer.log_exception(
                "Unable to print the result with the given format string.",
                exception)
Exemplo n.º 14
0
    def test_print_result(self):
        self.uut.print = lambda x: x
        self.assertEqual("|    |    | [{normal}] {bear}:".format(normal=RESULT_SEVERITY.__str__(RESULT_SEVERITY.NORMAL),
                                                                 bear="origin") + "\n|    |    | message",
                         self.uut._print_result(Result("origin", "message")))

        builtins.__dict__["input"] = lambda x: 0
        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"] = self.generate_input  # To assure user can rechose if he didn't chose wisely
        self.uut.print_result(PatchResult("origin", "msg", {testfile_path: diff}), file_dict)
        self.assertEqual(self.curr, 1)
        self.uut.finalize(file_dict)
        with open(testfile_path) as f:
            self.assertEqual(f.readlines(), ["1\n", "3_changed\n"])

        os.remove(testfile_path)

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

        builtins.__dict__["input"] = lambda x: x
Exemplo n.º 15
0
def print_results_formatted(log_printer, section, result_list, *args):
    """
    Prints results through the format string from the format setting done by
    user.

    :param log_printer:    Printer responsible for logging the messages.
    :param section:        The section to which the results belong.
    :param result_list:    List of Result objects containing the corresponding
                           results.
    """
    global _warn_deprecated_format_str
    default_format = ('id:{id}:origin:{origin}:file:{file}:line:{line}:'
                      'column:{column}:end_line:{end_line}:end_column:'
                      '{end_column}:severity:{severity}:severity_str:'
                      '{severity_str}:message:{message}')
    if 'format_str' in section:
        format_str = str(section.get('format_str', default_format))
        if _warn_deprecated_format_str:
            log_printer.warn('The setting "format_str" has been deprecated.'
                             ' Please use "format" instead')
            _warn_deprecated_format_str = False
    else:
        format_str = str(section.get('format', default_format))

    if format_str == 'True':
        format_str = default_format

    for result in result_list:
        severity_str = RESULT_SEVERITY.__str__(result.severity)
        format_args = vars(result)
        try:
            if len(result.affected_code) == 0:
                format_args['affected_code'] = None
                print(
                    format_str.format(file=None,
                                      line=None,
                                      end_line=None,
                                      column=None,
                                      end_column=None,
                                      severity_str=severity_str,
                                      message=result.message,
                                      **format_args))
                continue

            for range in result.affected_code:
                format_args['affected_code'] = range
                print(
                    format_str.format(file=range.start.file,
                                      line=range.start.line,
                                      end_line=range.end.line,
                                      column=range.start.column,
                                      end_column=range.end.column,
                                      severity_str=severity_str,
                                      message=result.message,
                                      **format_args))
        except KeyError as exception:
            log_printer.log_exception(
                'Unable to print the result with the given format string.',
                exception)
Exemplo n.º 16
0
    def _print_result(self, result):
        message_string_list = "[{sev}] {bear}:\n{msg}".format(
            sev=RESULT_SEVERITY.__str__(result.severity),
            bear=result.origin,
            msg=result.message).split("\n")

        return self.print("\n".join(
            [self._format_line(line) for line in message_string_list]))
Exemplo n.º 17
0
def print_result(console_printer,
                 log_printer,
                 section,
                 file_diff_dict,
                 result,
                 file_dict,
                 interactive=True):
    """
    Prints the result to console.

    :param console_printer: Object to print messages on the console.
    :param log_printer:     Printer responsible for logging the messages.
    :param section:         Name of section to which the result belongs.
    :param file_diff_dict:  Dictionary containing filenames as keys and Diff
                            objects as values.
    :param result:          A derivative of Result.
    :param file_dict:       A dictionary containing all files with filename as
                            key.
    :interactive:           Variable to check wether or not to
                            offer the user actions interactively.
    """
    if not isinstance(result, Result):
        log_printer.warn("One of the results can not be printed since it is "
                         "not a valid derivative of the coala result "
                         "class.")
        return

    console_printer.print(format_lines("[{sev}] {bear}:".format(
        sev=RESULT_SEVERITY.__str__(result.severity), bear=result.origin)),
        color=RESULT_SEVERITY_COLORS[result.severity])
    lexer = TextLexer()
    result.message = highlight_text(result.message, lexer,
                                    BackgroundMessageStyle)
    console_printer.print(format_lines(result.message))

    if interactive:
        cli_actions = CLI_ACTIONS
        show_patch_action = ShowPatchAction()
        if show_patch_action.is_applicable(result, file_dict, file_diff_dict):
            diff_size = sum(len(diff) for diff in result.diffs.values())
            if diff_size <= DIFF_EXCERPT_MAX_SIZE:
                show_patch_action.apply_from_section(result,
                                                     file_dict,
                                                     file_diff_dict,
                                                     section)
                cli_actions = tuple(action for action in cli_actions
                                    if not isinstance(action, ShowPatchAction))
            else:
                print_diffs_info(result.diffs, console_printer)
        acquire_actions_and_apply(console_printer,
                                  log_printer,
                                  section,
                                  file_diff_dict,
                                  result,
                                  file_dict,
                                  cli_actions)
Exemplo n.º 18
0
def print_result(console_printer,
                 log_printer,
                 section,
                 file_diff_dict,
                 result,
                 file_dict):
    """
    Prints the result to console.

    :param console_printer: Object to print messages on the console.
    :param log_printer:     Printer responsible for logging the messages.
    :param section:         Name of section to which the result belongs.
    :param file_diff_dict:  Dictionary containing filenames as keys and Diff
                            objects as values.
    :param result:          A derivative of Result.
    :param file_dict:       A dictionary containing all files with filename as
                            key.
    """
    if not isinstance(result, Result):
        log_printer.warn(_("One of the results can not be printed since it is "
                           "not a valid derivative of the coala result "
                           "class."))
        return

    console_printer.print(format_line("[{sev}] {bear}:".format(
        sev=RESULT_SEVERITY.__str__(result.severity), bear=result.origin)),
        color=RESULT_SEVERITY_COLORS[result.severity])
    console_printer.print(
        *[format_line(line) for line in result.message.split("\n")],
        delimiter="\n")

    actions = []
    for action in CLI_ACTIONS:
        if action.is_applicable(result):
            actions.append(action)

    if actions == []:
        return

    action_dict = {}
    metadata_list = []
    for action in actions:
        metadata = action.get_metadata()
        action_dict[metadata.name] = action
        metadata_list.append(metadata)

    # User can always choose no action which is guaranteed to succeed
    while not apply_action(log_printer,
                           console_printer,
                           section,
                           metadata_list,
                           action_dict,
                           result,
                           file_diff_dict,
                           file_dict):
        pass
Exemplo n.º 19
0
def print_result(console_printer,
                 log_printer,
                 section,
                 file_diff_dict,
                 result,
                 file_dict,
                 interactive=True):
    """
    Prints the result to console.

    :param console_printer: Object to print messages on the console.
    :param log_printer:     Printer responsible for logging the messages.
    :param section:         Name of section to which the result belongs.
    :param file_diff_dict:  Dictionary containing filenames as keys and Diff
                            objects as values.
    :param result:          A derivative of Result.
    :param file_dict:       A dictionary containing all files with filename as
                            key.
    :interactive:           Variable to check wether or not to
                            offer the user actions interactively.
    """
    if not isinstance(result, Result):
        log_printer.warn("One of the results can not be printed since it is "
                         "not a valid derivative of the coala result "
                         "class.")
        return

    console_printer.print(format_lines("[{sev}] {bear}:".format(
        sev=RESULT_SEVERITY.__str__(result.severity), bear=result.origin)),
        color=RESULT_SEVERITY_COLORS[result.severity])
    lexer = TextLexer()
    result.message = highlight_text(result.message, lexer,
                                    BackgroundMessageStyle)
    console_printer.print(format_lines(result.message))

    if interactive:
        cli_actions = CLI_ACTIONS
        show_patch_action = ShowPatchAction()
        if show_patch_action.is_applicable(result, file_dict, file_diff_dict):
            diff_size = sum(len(diff) for diff in result.diffs.values())
            if diff_size <= DIFF_EXCERPT_MAX_SIZE:
                show_patch_action.apply_from_section(result,
                                                     file_dict,
                                                     file_diff_dict,
                                                     section)
                cli_actions = tuple(action for action in cli_actions
                                    if not isinstance(action, ShowPatchAction))
            else:
                print_diffs_info(result.diffs, console_printer)
        acquire_actions_and_apply(console_printer,
                                  log_printer,
                                  section,
                                  file_diff_dict,
                                  result,
                                  file_dict,
                                  cli_actions)
Exemplo n.º 20
0
 def test_print_results_project_wide(self):
     with retrieve_stdout() as stdout:
         print_results(self.log_printer,
                       Section(""),
                       [Result("origin", "message")],
                       {},
                       {},
                       color=False)
         self.assertEqual(
             "\n\n{}\n|    |    | [{}] origin:\n|    |    | message"
             "\n".format(STR_PROJECT_WIDE,
                         RESULT_SEVERITY.__str__(RESULT_SEVERITY.NORMAL)),
             stdout.getvalue())
Exemplo n.º 21
0
 def test_print_results_without_line(self):
     with retrieve_stdout() as stdout:
         print_results(
             self.log_printer,
             Section(""),
             [Result.from_values("t", "msg", file="file")],
             {"file": []},
             {},
             color=False)
         self.assertEqual(
             "\nfile\n"
             "|    | [{}] t:\n"
             "|    | msg\n".format(
                 RESULT_SEVERITY.__str__(RESULT_SEVERITY.NORMAL)),
             stdout.getvalue())
Exemplo n.º 22
0
def print_result(console_printer, log_printer, section, file_diff_dict, result,
                 file_dict):
    """
    Prints the result to console.

    :param console_printer: Object to print messages on the console.
    :param log_printer:     Printer responsible for logging the messages.
    :param section:         Name of section to which the result belongs.
    :param file_diff_dict:  Dictionary containing filenames as keys and Diff
                            objects as values.
    :param result:          A derivative of Result.
    :param file_dict:       A dictionary containing all files with filename as
                            key.
    """
    if not isinstance(result, Result):
        log_printer.warn("One of the results can not be printed since it is "
                         "not a valid derivative of the coala result "
                         "class.")
        return

    console_printer.print(format_lines("[{sev}] {bear}:".format(
        sev=RESULT_SEVERITY.__str__(result.severity), bear=result.origin)),
                          color=RESULT_SEVERITY_COLORS[result.severity])
    console_printer.print(format_lines(result.message), delimiter="\n")

    actions = []
    for action in CLI_ACTIONS:
        if action.is_applicable(result, file_dict, file_diff_dict):
            actions.append(action)

    if actions == []:
        return

    action_dict = {}
    metadata_list = []
    for action in actions:
        metadata = action.get_metadata()
        action_dict[metadata.name] = action
        metadata_list.append(metadata)

    # User can always choose no action which is guaranteed to succeed
    while ask_for_action_and_apply(log_printer, console_printer, section,
                                   metadata_list, action_dict, result,
                                   file_diff_dict, file_dict):
        pass
Exemplo n.º 23
0
def print_results_formatted(log_printer, section, result_list, *args):
    global _warn_deprecated_format_str
    default_format = ('id:{id}:origin:{origin}:file:{file}:line:{line}:'
                      'column:{column}:end_line:{end_line}:end_column:'
                      '{end_column}:severity:{severity}:severity_str:'
                      '{severity_str}:message:{message}')
    if 'format_str' in section:
        format_str = str(section.get('format_str', default_format))
        if _warn_deprecated_format_str:
            log_printer.warn('The setting "format_str" has been deprecated.'
                             ' Please use "format" instead')
            _warn_deprecated_format_str = False
    else:
        format_str = str(section.get('format', default_format))

    if format_str == 'True':
        format_str = default_format

    for result in result_list:
        severity_str = RESULT_SEVERITY.__str__(result.severity)
        try:
            if len(result.affected_code) == 0:
                print(
                    format_str.format(file=None,
                                      line=None,
                                      end_line=None,
                                      column=None,
                                      end_column=None,
                                      severity_str=severity_str,
                                      **result.__dict__))
                continue

            for range in result.affected_code:
                print(
                    format_str.format(file=range.start.file,
                                      line=range.start.line,
                                      end_line=range.end.line,
                                      column=range.start.column,
                                      end_column=range.end.column,
                                      severity_str=severity_str,
                                      **result.__dict__))
        except KeyError as exception:
            log_printer.log_exception(
                'Unable to print the result with the given format string.',
                exception)
Exemplo n.º 24
0
def print_result(console_printer,
                 log_printer,
                 section,
                 file_diff_dict,
                 result,
                 file_dict,
                 interactive=True):
    """
    Prints the result to console.

    :param console_printer: Object to print messages on the console.
    :param log_printer:     Printer responsible for logging the messages.
    :param section:         Name of section to which the result belongs.
    :param file_diff_dict:  Dictionary containing filenames as keys and Diff
                            objects as values.
    :param result:          A derivative of Result.
    :param file_dict:       A dictionary containing all files with filename as
                            key.
    :interactive:           Variable to check wether or not to
                            offer the user actions interactively.
    """
    if not isinstance(result, Result):
        log_printer.warn("One of the results can not be printed since it is "
                         "not a valid derivative of the coala result "
                         "class.")
        return

    console_printer.print(format_lines("[{sev}] {bear}:".format(
        sev=RESULT_SEVERITY.__str__(result.severity), bear=result.origin)),
        color=RESULT_SEVERITY_COLORS[result.severity])
    console_printer.print(format_lines(result.message), delimiter="\n")

    if interactive:
        acquire_actions_and_apply(console_printer,
                                  log_printer,
                                  section,
                                  file_diff_dict,
                                  result,
                                  file_dict)
Exemplo n.º 25
0
    def test_print_results_missing_line(self):
        # Line isn't in dict[file], shouldn't print but also shouldn't throw.
        # This can occur if filter writers are doing nonsense.
        with retrieve_stdout() as stdout:
            print_results(
                self.log_printer,
                Section(""),
                [Result("t", "msg", "file", line_nr=5)],
                {"file": []},
                {},
                color=False)
            self.assertEqual("""\n\nfile\n|    |    | {}\n|    |    | [{}] t:
|    |    | msg\n""".format(STR_LINE_DOESNT_EXIST,
                            RESULT_SEVERITY.__str__(RESULT_SEVERITY.NORMAL)),
                             stdout.getvalue())

        self.assertRaises(AssertionError,
                          print_results,
                          self.log_printer,
                          Section(""),
                          [Result("t", "msg", None, line_nr=5)],
                          {},
                          {})
Exemplo n.º 26
0
 def test_print_results_missing_line(self):
     with retrieve_stdout() as stdout:
         print_results(
             self.log_printer,
             Section(""),
             [Result.from_values("t", "msg", file="file", line=5),
              Result.from_values("t", "msg", file="file", line=6)],
             {"file": ["line " + str(i+1) for i in range(5)]},
             {},
             color=False)
         # "NORMAL" but translated to test system language
         NORMAL = RESULT_SEVERITY.__str__(RESULT_SEVERITY.NORMAL)
         self.assertEqual("\n"
                          "file\n"
                          "|   5| line 5\n"
                          "|    | [{sev}] t:\n"
                          "|    | msg\n"
                          "\n"
                          "file\n"
                          "|    | {}\n"
                          "|    | [{sev}] t:\n"
                          "|    | msg\n".format(STR_LINE_DOESNT_EXIST,
                                                sev=NORMAL),
                          stdout.getvalue())
Exemplo n.º 27
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)
Exemplo n.º 28
0
    def test_print_results(self):
        q = queue.Queue()
        self.uut._print = lambda string: q.put(string)

        self.assertRaises(TypeError, self.uut.print_results, 5, {})
        self.assertRaises(TypeError, self.uut.print_results, [], 5)

        self.uut.print_results([], {})
        self.assertRaises(queue.Empty, q.get, timeout=0)

        self.uut.print_results([Result("origin", "message")], {})
        self.assertEqual(
            "\n\n{}\n|    |    | [{}] origin:\n|    |    | "
            "message\n".format(self.uut.STR_PROJECT_WIDE,
                               RESULT_SEVERITY.__str__(
                                   RESULT_SEVERITY.NORMAL)),
            self.get_str_from_queue(q))

        self.uut.print_results([
            Result("SpaceConsistencyBear",
                   "Trailing whitespace found",
                   "proj/white",
                   line_nr=2)
        ], {"proj/white": ["test line\n", "line 2\n", "line 3\n"]})
        self.assertEqual(
            """\n\nproj/white
|   1|   1| test line\n|   2|   2| line 2
|    |    | [{}] SpaceConsistencyBear:
|    |    | Trailing whitespace found
""".format(RESULT_SEVERITY.__str__(RESULT_SEVERITY.NORMAL)),
            self.get_str_from_queue(q))

        self.uut.print_results(
            [
                Result("SpaceConsistencyBear",
                       "Trailing whitespace found",
                       "proj/white",
                       line_nr=5)
            ], {
                "proj/white": [
                    "test line\n", "line 2\n", "line 3\n", "line 4\n",
                    "line 5\n"
                ]
            })
        self.assertEqual(
            """\n\nproj/white
| ...| ...| \n|   2|   2| line 2
|   3|   3| line 3
|   4|   4| line 4
|   5|   5| line 5
|    |    | [{}] SpaceConsistencyBear:
|    |    | Trailing whitespace found
""".format(RESULT_SEVERITY.__str__(RESULT_SEVERITY.NORMAL)),
            self.get_str_from_queue(q))

        # Check sorting and multi result output
        self.uut.print_results(
            [
                Result("SpaceConsistencyBear",
                       "Trailing whitespace found",
                       "proj/white",
                       line_nr=5),
                Result("SpaceConsistencyBear",
                       "Trailing whitespace found",
                       "proj/white",
                       line_nr=2)
            ], {
                "proj/white": [
                    "test line\n", "line 2\n", "line 3\n", "line 4\n",
                    "line 5\n"
                ]
            })

        self.assertEqual(
            """\n\nproj/white
|   1|   1| test line
|   2|   2| line 2
|    |    | [{}] SpaceConsistencyBear:
|    |    | Trailing whitespace found
|   3|   3| line 3
|   4|   4| line 4
|   5|   5| line 5
|    |    | [{}] SpaceConsistencyBear:
|    |    | Trailing whitespace found
""".format(RESULT_SEVERITY.__str__(RESULT_SEVERITY.NORMAL),
           RESULT_SEVERITY.__str__(RESULT_SEVERITY.NORMAL)),
            self.get_str_from_queue(q))

        # File isn't in dict, shouldn't print but also shouldn't throw. This
        # can occur if filter writers are doing nonsense. If this happens twice
        # the same should happen (whitebox testing: this is a potential bug.)
        self.uut.log_printer = NullPrinter()
        self.uut.print_results([
            Result("t", "msg", "file", line_nr=5),
            Result("t", "msg", "file", line_nr=5)
        ], {})
        self.assertEqual("", self.get_str_from_queue(q))

        # Line isn't in dict[file], shouldn't print but also shouldn't throw.
        # This can occur if filter writers are doing nonsense.
        self.uut.print_results([Result("t", "msg", "file", line_nr=5)],
                               {"file": []})
        self.assertEqual(
            """\n\nfile\n|    |    | {}\n|    |    | [{}] t:
|    |    | msg\n""".format(self.uut.STR_LINE_DOESNT_EXIST,
                            RESULT_SEVERITY.__str__(RESULT_SEVERITY.NORMAL)),
            self.get_str_from_queue(q))

        self.assertRaises(AssertionError, self.uut.print_results,
                          [Result("t", "msg", None, line_nr=5)], {})
Exemplo n.º 29
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)
Exemplo n.º 30
0
def print_result(console_printer,
                 section,
                 file_diff_dict,
                 result,
                 file_dict,
                 interactive=True,
                 apply_single=False):
    """
    Prints the result to console.

    :param console_printer: Object to print messages on the console.
    :param section:         Name of section to which the result belongs.
    :param file_diff_dict:  Dictionary containing filenames as keys and Diff
                            objects as values.
    :param result:          A derivative of Result.
    :param file_dict:       A dictionary containing all files with filename as
                            key.
    :param apply_single:    The action that should be applied for all results.
                            If it's not selected, has a value of False.
    :param interactive:     Variable to check whether or not to
                            offer the user actions interactively.
    """
    no_color = not console_printer.print_colored
    if not isinstance(result, Result):
        logging.warning('One of the results can not be printed since it is '
                        'not a valid derivative of the coala result '
                        'class.')
        return

    if hasattr(section, 'name'):
        console_printer.print('**** {bear} [Section: {section} | Severity: '
                              '{severity}] ****'
                              .format(bear=result.origin,
                                      section=section.name,
                                      severity=RESULT_SEVERITY.__str__(
                                          result.severity)),
                              color=RESULT_SEVERITY_COLORS[result.severity])
    else:
        console_printer.print('**** {bear} [Section {section} | Severity '
                              '{severity}] ****'
                              .format(bear=result.origin, section='<empty>',
                                      severity=RESULT_SEVERITY.__str__(
                                          result.severity)),
                              color=RESULT_SEVERITY_COLORS[result.severity])
    lexer = TextLexer()
    result.message = highlight_text(no_color, result.message,
                                    BackgroundMessageStyle, lexer)
    console_printer.print(format_lines(result.message, symbol='!'))

    if interactive:
        cli_actions = CLI_ACTIONS
        show_patch_action = ShowPatchAction()
        if show_patch_action.is_applicable(
                result, file_dict, file_diff_dict) is True:
            diff_size = sum(len(diff) for diff in result.diffs.values())
            if diff_size <= DIFF_EXCERPT_MAX_SIZE:
                show_patch_action.apply_from_section(result,
                                                     file_dict,
                                                     file_diff_dict,
                                                     section)
                cli_actions = tuple(action for action in cli_actions
                                    if not isinstance(action, ShowPatchAction))
            else:
                print_diffs_info(result.diffs, console_printer)
        acquire_actions_and_apply(console_printer,
                                  section,
                                  file_diff_dict,
                                  result,
                                  file_dict,
                                  cli_actions,
                                  apply_single=apply_single)
Exemplo n.º 31
0
 def test_str_conversion(self):
     self.assertEqual('INFO', RESULT_SEVERITY.__str__(RESULT_SEVERITY.INFO))
     self.assertEqual('NORMAL',
                      RESULT_SEVERITY.__str__(RESULT_SEVERITY.NORMAL))
     self.assertEqual('MAJOR',
                      RESULT_SEVERITY.__str__(RESULT_SEVERITY.MAJOR))
Exemplo n.º 32
0
    def test_print_results(self):
        q = queue.Queue()
        self.uut._print = lambda string: q.put(string)

        self.assertRaises(TypeError, self.uut.print_results, 5, {})
        self.assertRaises(TypeError, self.uut.print_results, [], 5)

        self.uut.print_results([], {})
        self.assertRaises(queue.Empty, q.get, timeout=0)

        self.uut.print_results([Result("origin", "message")], {})
        self.assertEqual("\n\n{}\n|    |    | [{}] origin:\n|    |    | "
                         "message\n".format(
                             self.uut.STR_PROJECT_WIDE,
                             RESULT_SEVERITY.__str__(RESULT_SEVERITY.NORMAL)),
                         self.get_str_from_queue(q))

        self.uut.print_results([Result("SpaceConsistencyBear",
                                       "Trailing whitespace found",
                                       "proj/white",
                                       line_nr=2)],
                               {"proj/white": ["test line\n",
                                               "line 2\n",
                                               "line 3\n"]})
        self.assertEqual("""\n\nproj/white
|   1|   1| test line\n|   2|   2| line 2
|    |    | [{}] SpaceConsistencyBear:
|    |    | Trailing whitespace found
""".format(RESULT_SEVERITY.__str__(RESULT_SEVERITY.NORMAL)),
                         self.get_str_from_queue(q))

        self.uut.print_results([Result("SpaceConsistencyBear",
                                       "Trailing whitespace found",
                                       "proj/white",
                                       line_nr=5)],
                               {"proj/white": ["test line\n",
                                               "line 2\n",
                                               "line 3\n",
                                               "line 4\n",
                                               "line 5\n"]})
        self.assertEqual("""\n\nproj/white
| ...| ...| \n|   2|   2| line 2
|   3|   3| line 3
|   4|   4| line 4
|   5|   5| line 5
|    |    | [{}] SpaceConsistencyBear:
|    |    | Trailing whitespace found
""".format(RESULT_SEVERITY.__str__(RESULT_SEVERITY.NORMAL)),
                         self.get_str_from_queue(q))

        # Check sorting and multi result output
        self.uut.print_results([Result("SpaceConsistencyBear",
                                       "Trailing whitespace found",
                                       "proj/white",
                                       line_nr=5),
                                Result("SpaceConsistencyBear",
                                       "Trailing whitespace found",
                                       "proj/white",
                                       line_nr=2)],
                               {"proj/white": ["test line\n",
                                               "line 2\n",
                                               "line 3\n",
                                               "line 4\n",
                                               "line 5\n"]})

        self.assertEqual("""\n\nproj/white
|   1|   1| test line
|   2|   2| line 2
|    |    | [{}] SpaceConsistencyBear:
|    |    | Trailing whitespace found
|   3|   3| line 3
|   4|   4| line 4
|   5|   5| line 5
|    |    | [{}] SpaceConsistencyBear:
|    |    | Trailing whitespace found
""".format(RESULT_SEVERITY.__str__(RESULT_SEVERITY.NORMAL),
           RESULT_SEVERITY.__str__(RESULT_SEVERITY.NORMAL)),
                         self.get_str_from_queue(q))

        # File isn't in dict, shouldn't print but also shouldn't throw. This
        # can occur if filter writers are doing nonsense. If this happens twice
        # the same should happen (whitebox testing: this is a potential bug.)
        self.uut.log_printer = NullPrinter()
        self.uut.print_results([Result("t", "msg", "file", line_nr=5),
                                Result("t", "msg", "file", line_nr=5)], {})
        self.assertEqual("", self.get_str_from_queue(q))

        # Line isn't in dict[file], shouldn't print but also shouldn't throw.
        # This can occur if filter writers are doing nonsense.
        self.uut.print_results([Result("t", "msg", "file", line_nr=5)],
                               {"file": []})
        self.assertEqual("""\n\nfile\n|    |    | {}\n|    |    | [{}] t:
|    |    | msg\n""".format(self.uut.STR_LINE_DOESNT_EXIST,
                            RESULT_SEVERITY.__str__(RESULT_SEVERITY.NORMAL)),
                         self.get_str_from_queue(q))

        self.assertRaises(AssertionError,
                          self.uut.print_results,
                          [Result("t", "msg", None, line_nr=5)],
                          {})