コード例 #1
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()]
コード例 #2
0
    def retrieve_logging_objects(self):
        """
        Creates an appropriate log printer and interactor according to the settings.
        """
        log_type = str(self.get("log_type", "console")).lower()
        log_level = LOG_LEVEL.from_str(str(self.get("log_level", "none")))

        if log_type == "console":
            self.log_printer = ConsolePrinter(log_level=log_level)
        else:
            try:
                # ConsolePrinter is the only printer which may not throw an exception (if we have no bugs though)
                # so well fallback to him if some other printer fails
                if log_type == "none":
                    self.log_printer = NullPrinter()
                else:
                    self.log_printer = FilePrinter(filename=log_type,
                                                   log_level=log_level)
            except:
                self.log_printer = ConsolePrinter(log_level=log_level)
                self.log_printer.log(
                    LOG_LEVEL.WARNING,
                    _("Failed to instantiate the logging method '{}'. Falling back "
                      "to console output.").format(log_type))

        # We currently only offer console interactor, so we'll ignore the output setting for now
        self.interactor = ConsoleInteractor.from_section(
            self, log_printer=self.log_printer)
コード例 #3
0
ファイル: Section.py プロジェクト: AhmedKamal1432/coala
    def retrieve_logging_objects(self):
        """
        Creates an appropriate log printer and interactor according to the
        settings.
        """
        log_type = str(self.get("log_type", "console")).lower()
        output_type = str(self.get("output", "console")).lower()
        str_log_level = str(self.get("log_level", "")).upper()
        log_level = LOG_LEVEL.str_dict.get(str_log_level, LOG_LEVEL.WARNING)

        if log_type == "console":
            self.log_printer = ConsolePrinter(log_level=log_level)
        else:
            try:
                # ConsolePrinter is the only printer which may not throw an
                # exception (if we have no bugs though) so well fallback to him
                # if some other printer fails
                if log_type == "none":
                    self.log_printer = NullPrinter()
                else:
                    self.log_printer = FilePrinter(filename=log_type,
                                                   log_level=log_level)
            except:
                self.log_printer = ConsolePrinter(log_level=log_level)
                self.log_printer.log(
                    LOG_LEVEL.WARNING,
                    _("Failed to instantiate the logging method '{}'. Falling "
                      "back to console output.").format(log_type))

        if output_type == "none":
            self.interactor = NullInteractor(log_printer=self.log_printer)
        else:
            self.interactor = ConsoleInteractor.from_section(
                self,
                log_printer=self.log_printer)
コード例 #4
0
    def retrieve_logging_objects(self):
        """
        Creates an appropriate log printer and interactor according to the
        settings.
        """
        log_type = str(self.get("log_type", "console")).lower()
        output_type = str(self.get("output", "console")).lower()
        str_log_level = str(self.get("log_level", "")).upper()
        log_level = LOG_LEVEL.str_dict.get(str_log_level, LOG_LEVEL.WARNING)

        if log_type == "console":
            self.log_printer = ConsolePrinter(log_level=log_level)
        else:
            try:
                # ConsolePrinter is the only printer which may not throw an
                # exception (if we have no bugs though) so well fallback to him
                # if some other printer fails
                if log_type == "none":
                    self.log_printer = NullPrinter()
                else:
                    self.log_printer = FilePrinter(filename=log_type,
                                                   log_level=log_level)
            except:
                self.log_printer = ConsolePrinter(log_level=log_level)
                self.log_printer.log(
                    LOG_LEVEL.WARNING,
                    _("Failed to instantiate the logging method '{}'. Falling "
                      "back to console output.").format(log_type))

        if output_type == "none":
            self.interactor = NullInteractor(log_printer=self.log_printer)
        else:
            self.interactor = ConsoleInteractor.from_section(
                self, log_printer=self.log_printer)
コード例 #5
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()]
コード例 #6
0
    def __init__(self,
                 name,
                 defaults=None,
                 interactor=ConsoleInteractor(),
                 log_printer=ConsolePrinter()):
        if defaults is not None and not isinstance(defaults, Section):
            raise TypeError("defaults has to be a Section object or None.")
        if defaults is self:
            raise ValueError("defaults may not be self for non-recursivity.")
        if not isinstance(interactor, Interactor):
            raise TypeError(
                "The interactor parameter has to be of type Interactor.")
        if not isinstance(log_printer, LogPrinter):
            raise TypeError(
                "The log_printer parameter has to be of type LogPrinter.")

        self.name = str(name)
        self.defaults = defaults
        self.contents = OrderedDict()
        self.interactor = interactor
        self.log_printer = log_printer
コード例 #7
0
 def test_from_section(self):
     section = Section("test")
     ConsoleInteractor.from_section(section)
     section.append(Setting("output", "stderr"))
     ConsoleInteractor.from_section(section)
コード例 #8
0
class ConsoleInteractorTestCase(unittest.TestCase):
    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()]

    def tearDown(self):
        builtins.__dict__["input"] = self._input

    def test_require_settings(self):
        self.assertRaises(TypeError, self.uut.acquire_settings, 0)
        self.assertEqual(self.uut.acquire_settings({0: 0}), {})

        self.assertEqual(
            self.uut.acquire_settings({"setting": ["help text", "SomeBear"]}),
            {
                "setting":
                self.uut.STR_GET_VAL_FOR_SETTING.format(
                    "setting", "help text", "SomeBear")
            })

        self.assertEqual(
            self.uut.acquire_settings(
                {"setting": ["help text", "SomeBear", "AnotherBear"]}), {
                    "setting":
                    self.uut.STR_GET_VAL_FOR_SETTING.format(
                        "setting", "help text",
                        "SomeBear" + _(" and ") + "AnotherBear")
                })

        self.assertEqual(
            self.uut.acquire_settings({
                "setting":
                ["help text", "SomeBear", "AnotherBear", "YetAnotherBear"]
            }), {
                "setting":
                self.uut.STR_GET_VAL_FOR_SETTING.format(
                    "setting", "help text",
                    "SomeBear, AnotherBear" + _(" and ") + "YetAnotherBear")
            })

    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)

    def test_static_functions(self):
        q = queue.Queue()
        # 0:-1 to strip of the trailing newline character
        self.uut._print = lambda string: q.put(string[0:-1])
        self.uut.begin_section(Section("name"))
        self.assertEqual(
            q.get(timeout=0),
            _("Executing section "
              "{name}...").format(name="name"))

        self.uut.did_nothing()
        self.assertEqual(
            q.get(timeout=0),
            _("No existent section was targeted or enabled. "
              "Nothing to do."))

    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)], {})

    def test_from_section(self):
        section = Section("test")
        ConsoleInteractor.from_section(section)
        section.append(Setting("output", "stderr"))
        ConsoleInteractor.from_section(section)

    @staticmethod
    def get_str_from_queue(q):
        result = ""
        try:
            while True:
                result += q.get(timeout=0)
        except queue.Empty:
            pass

        return result
コード例 #9
0
class ConsoleInteractorTestCase(unittest.TestCase):
    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()]

    def tearDown(self):
        builtins.__dict__["input"] = self._input

    def test_require_settings(self):
        self.assertRaises(TypeError, self.uut.acquire_settings, 0)
        self.assertEqual(self.uut.acquire_settings({0: 0}), {})

        self.assertEqual(self.uut.acquire_settings({"setting": ["help text",
                                                                "SomeBear"]}),
                         {"setting": self.uut.STR_GET_VAL_FOR_SETTING.format(
                             "setting",
                             "help text",
                             "SomeBear")})

        self.assertEqual(self.uut.acquire_settings({"setting":
                                                        ["help text",
                                                         "SomeBear",
                                                         "AnotherBear"]}),
                         {"setting": self.uut.STR_GET_VAL_FOR_SETTING.format(
                             "setting",
                             "help text",
                             "SomeBear" + _(" and ") + "AnotherBear")})

        self.assertEqual(self.uut.acquire_settings({"setting":
                                                        ["help text",
                                                         "SomeBear",
                                                         "AnotherBear",
                                                         "YetAnotherBear"]}),
                         {"setting": self.uut.STR_GET_VAL_FOR_SETTING.format(
                             "setting",
                             "help text",
                             "SomeBear, AnotherBear" + _(" and ") +
                             "YetAnotherBear")})

    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)

    def test_static_functions(self):
        q = queue.Queue()
        # 0:-1 to strip of the trailing newline character
        self.uut._print = lambda string: q.put(string[0:-1])
        self.uut.begin_section(Section("name"))
        self.assertEqual(q.get(timeout=0), _("Executing section "
                                             "{name}...").format(name="name"))

        self.uut.did_nothing()
        self.assertEqual(q.get(timeout=0),
                         _("No existent section was targeted or enabled. "
                           "Nothing to do."))

    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)],
                          {})

    def test_from_section(self):
        section = Section("test")
        ConsoleInteractor.from_section(section)
        section.append(Setting("output", "stderr"))
        ConsoleInteractor.from_section(section)

    @staticmethod
    def get_str_from_queue(q):
        result = ""
        try:
            while True:
                result += q.get(timeout=0)
        except queue.Empty:
            pass

        return result
コード例 #10
0
 def test_from_section(self):
     section = Section("test")
     ConsoleInteractor.from_section(section)
     section.append(Setting("output", "stderr"))
     ConsoleInteractor.from_section(section)
コード例 #11
0
 def setUp(self):
     self.uut = ConsoleInteractor()
コード例 #12
0
class ConsoleInteractorTestCase(unittest.TestCase):
    def setUp(self):
        self.uut = ConsoleInteractor()

    def test_require_settings(self):
        self.assertRaises(TypeError, self.uut.acquire_settings, 0)
        self.assertEqual(self.uut.acquire_settings({0: 0}), {})

        self.assertEqual(self.uut.acquire_settings({"setting": ["help text", "SomeBear"]}),
                         {"setting": self.uut.STR_GET_VAL_FOR_SETTING.format("setting", "help text", "SomeBear")})

        self.assertEqual(self.uut.acquire_settings({"setting": ["help text", "SomeBear", "AnotherBear"]}),
                         {"setting": self.uut.STR_GET_VAL_FOR_SETTING.format("setting",
                                                                             "help text",
                                                                             "SomeBear" + _(" and ") + "AnotherBear")})

        self.assertEqual(self.uut.acquire_settings({"setting": ["help text",
                                                                "SomeBear",
                                                                "AnotherBear",
                                                                "YetAnotherBear"]}),
                         {"setting": self.uut.STR_GET_VAL_FOR_SETTING.format("setting",
                                                                             "help text",
                                                                             "SomeBear, AnotherBear" + _(" and ") +
                                                                             "YetAnotherBear")})

    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


    curr = -5

    @staticmethod
    def generate_input(x):
        ConsoleInteractorTestCase.curr += 2
        if ConsoleInteractorTestCase.curr == -3:
            return "INVALID"

        return ConsoleInteractorTestCase.curr

    def test_print_results(self):
        self.assertRaises(TypeError, self.uut.print_results, 5, {})
        self.assertRaises(TypeError, self.uut.print_results, [], 5)
        q = queue.Queue()
        self.uut._print = lambda string: q.put(string)

        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|    .    | \n|    .    | \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)], {})

    def test_from_section(self):
        section = Section("test")
        ConsoleInteractor.from_section(section)
        section.append(Setting("output", "stderr"))
        ConsoleInteractor.from_section(section)

    @staticmethod
    def get_str_from_queue(q):
        result = ""
        try:
            while True:
                result += q.get(timeout=0)
        except queue.Empty:
            pass

        return result