示例#1
0
    def test_simulate_console_inputs(self):
        with simulate_console_inputs(0, 1, 2) as generator:
            self.assertEqual(input(), 0)
            self.assertEqual(generator.last_input, 0)
            generator.inputs.append(3)
            self.assertEqual(input(), 1)
            self.assertEqual(input(), 2)
            self.assertEqual(input(), 3)
            self.assertEqual(generator.last_input, 3)

        with simulate_console_inputs("test"), self.assertRaises(ValueError):
            self.assertEqual(input(), "test")
            input()
示例#2
0
    def test_simulate_console_inputs(self):
        with simulate_console_inputs(0, 1, 2) as generator:
            self.assertEqual(input(), 0)
            self.assertEqual(generator.last_input, 0)
            generator.inputs.append(3)
            self.assertEqual(input(), 1)
            self.assertEqual(input(), 2)
            self.assertEqual(input(), 3)
            self.assertEqual(generator.last_input, 3)

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

            class InvalidateTestAction(ResultAction):

                is_applicable = staticmethod(lambda *args: True)

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

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

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

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

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

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

            class InvalidateTestAction(ResultAction):

                is_applicable = staticmethod(lambda *args: True)

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

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

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

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

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

            ApplyPatchAction.is_applicable = old_applypatch_is_applicable
示例#5
0
    def test_require_settings(self):
        curr_section = Section("")
        self.assertRaises(TypeError, acquire_settings,
                          self.log_printer, 0, curr_section)

        with simulate_console_inputs(0, 1, 2) as generator:
            self.assertEqual(acquire_settings(self.log_printer,
                                              {"setting": ["help text",
                                                           "SomeBear"]},
                                              curr_section),
                             {"setting": 0})

            self.assertEqual(acquire_settings(self.log_printer,
                                              {"setting": ["help text",
                                                           "SomeBear",
                                                           "AnotherBear"]},
                                              curr_section),
                             {"setting": 1})

            self.assertEqual(acquire_settings(self.log_printer,
                                              {"setting": ["help text",
                                                           "SomeBear",
                                                           "AnotherBear",
                                                           "YetAnotherBear"]},
                                              curr_section),
                             {"setting": 2})

            self.assertEqual(generator.last_input, 2)
    def test_require_settings(self):
        curr_section = Section('')
        self.assertRaises(TypeError, acquire_settings,
                          self.log_printer, 0, curr_section)

        with simulate_console_inputs(0, 1, 2) as generator:
            self.assertEqual(acquire_settings(self.log_printer,
                                              {'setting': ['help text',
                                                           'SomeBear']},
                                              curr_section),
                             {'setting': 0})

            self.assertEqual(acquire_settings(self.log_printer,
                                              {'setting': ['help text',
                                                           'SomeBear',
                                                           'AnotherBear']},
                                              curr_section),
                             {'setting': 1})

            self.assertEqual(acquire_settings(self.log_printer,
                                              {'setting': ['help text',
                                                           'SomeBear',
                                                           'AnotherBear',
                                                           'YetAnotherBear']},
                                              curr_section),
                             {'setting': 2})

            self.assertEqual(generator.last_input, 2)
    def test_require_settings(self):
        self.assertRaises(TypeError, acquire_settings, self.log_printer, 0)
        self.assertEqual(acquire_settings(self.log_printer, {0: 0}), {})

        with simulate_console_inputs(0, 1, 2) as generator:
            self.assertEqual(
                acquire_settings(self.log_printer,
                                 {"setting": ["help text", "SomeBear"]}),
                {"setting": 0})

            self.assertEqual(
                acquire_settings(
                    self.log_printer,
                    {"setting": ["help text", "SomeBear", "AnotherBear"]}),
                {"setting": 1})

            self.assertEqual(
                acquire_settings(
                    self.log_printer, {
                        "setting": [
                            "help text", "SomeBear", "AnotherBear",
                            "YetAnotherBear"
                        ]
                    }), {"setting": 2})

            self.assertEqual(generator.last_input, 2)
示例#8
0
    def test_print_result_no_input(self):
        with make_temp() as testfile_path:
            file_dict = {testfile_path: ["1\n", "2\n", "3\n"]}
            diff = Diff(file_dict[testfile_path])
            diff.delete_line(2)
            diff.change_line(3, "3\n", "3_changed\n")
            with simulate_console_inputs(1, 2, 3) as generator, retrieve_stdout() as stdout:
                ApplyPatchAction.is_applicable = staticmethod(lambda *args: True)
                print_results_no_input(
                    self.log_printer,
                    Section("someSection"),
                    [Result("origin", "message", diffs={testfile_path: diff})],
                    file_dict,
                    self.file_diff_dict,
                    color=False,
                )
                self.assertEqual(generator.last_input, -1)
                self.assertEqual(
                    stdout.getvalue(),
                    """
Project wide:
|    | [NORMAL] origin:
|    | message
""",
                )
示例#9
0
    def test_fill_section(self):
        # Use the same value for both because order isn't predictable (uses
        # dict)
        with simulate_console_inputs(0, 0):
            new_section = fill_section(self.section,
                                       acquire_settings,
                                       self.log_printer,
                                       [LocalTestBear,
                                        GlobalTestBear,
                                        "an inappropriate string object here"])

        self.assertEqual(int(new_section["local name"]), 0)
        self.assertEqual(int(new_section["global name"]), 0)
        self.assertEqual(new_section["key"].value, "val")
        self.assertEqual(len(new_section.contents), 3)

        # Shouldnt change anything the second time
        new_section = fill_section(self.section,
                                   acquire_settings,
                                   self.log_printer,
                                   [LocalTestBear, GlobalTestBear])

        self.assertTrue("local name" in new_section)
        self.assertTrue("global name" in new_section)
        self.assertEqual(new_section["key"].value, "val")
        self.assertEqual(len(new_section.contents), 3)
示例#10
0
    def test_dependency_resolving(self):
        sections = {"test": self.section}
        self.section['bears'] = "DependentBear"
        with simulate_console_inputs("True"), bear_test_module():
            fill_settings(sections, acquire_settings, self.log_printer)

        self.assertEqual(bool(self.section["use_spaces"]), True)
示例#11
0
    def test_caching_results(self):
        """
        A simple integration test to assert that results are not dropped
        when coala is ran multiple times with caching enabled.
        """
        with bear_test_module(), \
                prepare_file(["a=(5,6)"], None) as (lines, filename):
            with simulate_console_inputs("0"):
                retval, output = execute_coala(coala.main, "coala", "-c",
                                               os.devnull, "--disable-caching",
                                               "--flush-cache", "-f",
                                               re.escape(filename), "-b",
                                               "LineCountTestBear", "-L",
                                               "DEBUG")
                self.assertIn("This file has", output)

            # Due to the change in configuration from the removal of
            # ``--flush-cache`` this run will not be sufficient to
            # assert this behavior.
            retval, output = execute_coala(coala.main, "coala",
                                           "-c", os.devnull, "-f",
                                           re.escape(filename), "-b",
                                           "LineCountTestBear")
            self.assertIn("This file has", output)

            retval, output = execute_coala(coala.main, "coala",
                                           "-c", os.devnull, "-f",
                                           re.escape(filename), "-b",
                                           "LineCountTestBear")
            self.assertIn("This file has", output)
示例#12
0
    def test_dependency_resolving(self):
        sections = {"test": self.section}
        self.section['bears'] = "DependentBear"
        with simulate_console_inputs("True"), bear_test_module():
            fill_settings(sections, acquire_settings, self.log_printer)

        self.assertEqual(bool(self.section["use_spaces"]), True)
示例#13
0
    def test_caching_results(self):
        """
        A simple integration test to assert that results are not dropped
        when coala is ran multiple times with caching enabled.
        """
        with bear_test_module(), \
                prepare_file(['a=(5,6)'], None) as (lines, filename):
            with simulate_console_inputs('0'):
                retval, output = execute_coala(coala.main, 'coala', '-c',
                                               os.devnull, '--disable-caching',
                                               '--flush-cache', '-f',
                                               re.escape(filename), '-b',
                                               'LineCountTestBear', '-L',
                                               'DEBUG')
                self.assertIn('This file has', output)

            # Due to the change in configuration from the removal of
            # ``--flush-cache`` this run will not be sufficient to
            # assert this behavior.
            retval, output = execute_coala(coala.main, 'coala',
                                           '-c', os.devnull, '-f',
                                           re.escape(filename), '-b',
                                           'LineCountTestBear')
            self.assertIn('This file has', output)

            retval, output = execute_coala(coala.main, 'coala',
                                           '-c', os.devnull, '-f',
                                           re.escape(filename), '-b',
                                           'LineCountTestBear')
            self.assertIn('This file has', output)
示例#14
0
    def test_fill_section(self):
        # Use the same value for both because order isn't predictable (uses
        # dict)
        with simulate_console_inputs(0, 0):
            new_section = fill_section(self.section,
                                       acquire_settings,
                                       self.log_printer,
                                       [LocalTestBear,
                                        GlobalTestBear,
                                        "an inappropriate string object here"])

        self.assertEqual(int(new_section["local name"]), 0)
        self.assertEqual(int(new_section["global name"]), 0)
        self.assertEqual(new_section["key"].value, "val")
        self.assertEqual(len(new_section.contents), 3)

        # Shouldnt change anything the second time
        new_section = fill_section(self.section,
                                   acquire_settings,
                                   self.log_printer,
                                   [LocalTestBear, GlobalTestBear])

        self.assertTrue("local name" in new_section)
        self.assertTrue("global name" in new_section)
        self.assertEqual(new_section["key"].value, "val")
        self.assertEqual(len(new_section.contents), 3)
示例#15
0
    def test_dependency_resolving(self):
        sections = {'test': self.section}
        self.section['bears'] = 'DependentBear'
        with simulate_console_inputs('True'), bear_test_module():
            fill_settings(sections, acquire_settings, self.log_printer)

        self.assertEqual(bool(self.section['use_spaces']), True)
示例#16
0
    def test_fill_settings(self):
        sections = {"test": self.section}
        with simulate_console_inputs() as generator:
            fill_settings(sections, acquire_settings, self.log_printer)
            self.assertEqual(generator.last_input, -1)

        self.section.append(Setting("bears", "SpaceConsistencyTestBear"))

        with simulate_console_inputs("True"), bear_test_module():
            local_bears, global_bears = fill_settings(sections,
                                                      acquire_settings,
                                                      self.log_printer)
            self.assertEqual(len(local_bears["test"]), 1)
            self.assertEqual(len(global_bears["test"]), 0)

        self.assertEqual(bool(self.section["use_spaces"]), True)
        self.assertEqual(len(self.section.contents), 3)
示例#17
0
    def test_default_input(self):
        action = TestAction()
        args = [self.console_printer, Section(''),
                [action.get_metadata()], {'TestAction': action},
                set(), Result('origin', 'message'), {}, {}]

        with simulate_console_inputs('') as generator:
            self.assertFalse(ask_for_action_and_apply(*args))
示例#18
0
    def test_default_input(self):
        action = TestAction()
        args = [self.console_printer, Section(""),
                [action.get_metadata()], {'TestAction': action},
                set(), Result("origin", "message"), {}, {}]

        with simulate_console_inputs("") as generator:
            self.assertFalse(ask_for_action_and_apply(*args))
示例#19
0
    def test_fill_settings(self):
        sections = {'test': self.section}
        with simulate_console_inputs() as generator:
            fill_settings(sections, acquire_settings, self.log_printer)
            self.assertEqual(generator.last_input, -1)

        self.section.append(Setting('bears', 'SpaceConsistencyTestBear'))

        with simulate_console_inputs('True'), bear_test_module():
            local_bears, global_bears = fill_settings(sections,
                                                      acquire_settings,
                                                      self.log_printer)
            self.assertEqual(len(local_bears['test']), 1)
            self.assertEqual(len(global_bears['test']), 0)

        self.assertEqual(bool(self.section['use_spaces']), True)
        self.assertEqual(len(self.section.contents), 3)
示例#20
0
 def test_simulate_console_inputs(self):
     with simulate_console_inputs(0, 1, 2) as generator:
         self.assertEqual(input(), 0)
         self.assertEqual(generator.last_input, 0)
         generator.inputs.append(3)
         self.assertEqual(input(), 1)
         self.assertEqual(input(), 2)
         self.assertEqual(input(), 3)
         self.assertEqual(generator.last_input, 3)
示例#21
0
    def test_fill_settings(self):
        sections = {"test": self.section}
        with simulate_console_inputs() as generator:
            fill_settings(sections,
                          acquire_settings,
                          self.log_printer)
            self.assertEqual(generator.last_input, -1)

        self.section.append(Setting("bears", "SpaceConsistencyBear"))

        with simulate_console_inputs("True"):
            local_bears, global_bears = fill_settings(sections,
                                                      acquire_settings,
                                                      self.log_printer)
            self.assertEqual(len(local_bears["test"]), 1)
            self.assertEqual(len(global_bears["test"]), 0)

        self.assertEqual(bool(self.section["use_spaces"]), True)
        self.assertEqual(len(self.section.contents), 3)
 def test_acquire_actions_and_apply(self):
     with make_temp() as testfile_path:
         file_dict = {testfile_path: ["1\n", "2\n", "3\n"]}
         diff = Diff(file_dict[testfile_path])
         diff.delete_line(2)
         diff.change_line(3, "3\n", "3_changed\n")
         with simulate_console_inputs(1, 0) as generator, \
                 retrieve_stdout() as sio:
             ApplyPatchAction.is_applicable = staticmethod(
                 lambda *args: True)
             acquire_actions_and_apply(
                 self.console_printer, self.log_printer, Section(""),
                 self.file_diff_dict,
                 Result("origin", "message", diffs={testfile_path:
                                                    diff}), file_dict)
             self.assertEqual(generator.last_input, 1)
             self.assertIn(ApplyPatchAction.success_message, sio.getvalue())
示例#23
0
 def test_acquire_actions_and_apply(self):
     with make_temp() as testfile_path:
         file_dict = {testfile_path: ["1\n", "2\n", "3\n"]}
         diff = Diff(file_dict[testfile_path])
         diff.delete_line(2)
         diff.change_line(3, "3\n", "3_changed\n")
         with simulate_console_inputs(1, 0) as generator:
             ApplyPatchAction.is_applicable = staticmethod(
                     lambda *args: True)
             acquire_actions_and_apply(self.console_printer,
                                       self.log_printer,
                                       Section(""),
                                       self.file_diff_dict,
                                       Result("origin", "message", diffs={
                                        testfile_path: diff}),
                                       file_dict)
             self.assertEqual(generator.last_input, 1)
示例#24
0
    def test_ask_for_actions_and_apply(self):
        failed_actions = set()
        action = TestAction()
        args = [self.log_printer, self.console_printer, Section(""),
                [action.get_metadata()], {'TestAction': action},
                failed_actions, Result("origin", "message"), {}, {}]

        with simulate_console_inputs(1, 'param1', 1, 'param2') as generator:
            action.apply = unittest.mock.Mock(side_effect=AssertionError)
            ask_for_action_and_apply(*args)
            self.assertEqual(generator.last_input, 1)
            self.assertIn('TestAction', failed_actions)

            action.apply = lambda *args, **kwargs: {}
            ask_for_action_and_apply(*args)
            self.assertEqual(generator.last_input, 3)
            self.assertNotIn('TestAction', failed_actions)
示例#25
0
    def test_ask_for_actions_and_apply(self):
        failed_actions = set()
        action = TestAction()
        args = [self.log_printer, self.console_printer, Section(""),
                [action.get_metadata()], {'TestAction': action},
                failed_actions, Result("origin", "message"), {}, {}]

        with simulate_console_inputs(1, 'param1', 1, 'param2') as generator:
            action.apply = lambda *args, **kwargs: raise_error(AssertionError)
            ask_for_action_and_apply(*args)
            self.assertEqual(generator.last_input, 1)
            self.assertIn('TestAction', failed_actions)

            action.apply = lambda *args, **kwargs: {}
            ask_for_action_and_apply(*args)
            self.assertEqual(generator.last_input, 3)
            self.assertNotIn('TestAction', failed_actions)
示例#26
0
    def test_caching_multi_results(self):
        """
        Integration test to assert that results are not dropped when coala is
        ran multiple times with caching enabled and one section yields a result
        and second one doesn't.
        """
        filename = 'tests/misc/test_caching_multi_results/'
        with bear_test_module():
            with simulate_console_inputs('0'):
                retval, output = execute_coala(coala.main, 'coala', '-c',
                                               filename + '.coafile', '-f',
                                               filename + 'test.py')
                self.assertIn('This file has', output)

            retval, output = execute_coala(coala.main, 'coala', '-c',
                                           filename + '.coafile', '-f',
                                           filename + 'test.py')
            self.assertIn('This file has', output)
    def test_get_project_files(self):
        orig_cwd = os.getcwd()
        os.chdir(os.path.dirname(os.path.realpath(__file__)))
        os.makedirs("file_globs_testfiles", exist_ok=True)
        os.chdir("file_globs_testfiles")

        os.makedirs("src", exist_ok=True)
        os.makedirs("ignore_dir", exist_ok=True)
        open(os.path.join("src", "file.c"), "w").close()
        open("root.c", "w").close()
        open(os.path.join("ignore_dir", "src.c"), "w").close()
        open(os.path.join("ignore_dir", "src.js"), "w").close()

        with suppress_stdout(), simulate_console_inputs("**.c", "ignore_dir/**"):
            res = get_project_files(self.log_printer, self.printer, os.getcwd())
            self.assertIn(os.path.join(os.getcwd(), "src", "file.c"), res)
            self.assertIn(os.path.join(os.getcwd(), "root.c"), res)
            self.assertNotIn(os.path.join(os.getcwd(), "ignore_dir/src.c"), res)
            self.assertNotIn(os.path.join(os.getcwd(), "ignore_dir/src.js"), res)

        os.chdir(orig_cwd)
示例#28
0
    def test_caching_results(self):
        """
        A simple integration test to assert that results are not dropped
        when coala is ran multiple times with caching enabled.
        """
        with bear_test_module(), \
                prepare_file(["a=(5,6)"], None) as (lines, filename):
            with simulate_console_inputs("0"):
                retval, output = execute_coala(
                    coala.main,
                    "coala",
                    "-c", os.devnull,
                    "--flush-cache",
                    "--changed-files",
                    "-f", re.escape(filename),
                    "-b", "LineCountTestBear",
                    "-L", "DEBUG")
                self.assertIn("This file has", output)

            # Due to the change in configuration from the removal of
            # ``--flush-cache`` this run will not be sufficient to
            # assert this behavior.
            retval, output = execute_coala(
                coala.main,
                "coala",
                "-c", os.devnull,
                "--changed-files",
                "-f", re.escape(filename),
                "-b", "LineCountTestBear")
            self.assertIn("This file has", output)

            retval, output = execute_coala(
                coala.main,
                "coala",
                "-c", os.devnull,
                "--changed-files",
                "-f", re.escape(filename),
                "-b", "LineCountTestBear")
            self.assertIn("This file has", output)
示例#29
0
    def test_fill_section(self):
        # Use the same value for both because order isn't predictable (uses
        # dict)
        with simulate_console_inputs(0, 0):
            new_section = fill_section(self.section, acquire_settings,
                                       self.log_printer,
                                       [LocalTestBear, GlobalTestBear])

        self.assertEqual(int(new_section['local name']), 0)
        self.assertEqual(int(new_section['global name']), 0)
        self.assertEqual(new_section['key'].value, 'val')
        self.assertEqual(len(new_section.contents), 3)

        # Shouldnt change anything the second time
        new_section = fill_section(self.section, acquire_settings,
                                   self.log_printer,
                                   [LocalTestBear, GlobalTestBear])

        self.assertTrue('local name' in new_section)
        self.assertTrue('global name' in new_section)
        self.assertEqual(new_section['key'].value, 'val')
        self.assertEqual(len(new_section.contents), 3)
示例#30
0
    def test_caching_multi_results(self):
        """
        Integration test to assert that results are not dropped when coala is
        ran multiple times with caching enabled and one section yields a result
        and second one doesn't.
        """
        filename = "tests/misc/test_caching_multi_results/"
        with bear_test_module():
            with simulate_console_inputs("0"):
                retval, output = execute_coala(
                   coala.main,
                   "coala",
                   "-c", filename + ".coafile",
                   "-f", filename + "test.py")
                self.assertIn("This file has", output)

            retval, output = execute_coala(
               coala.main,
               "coala",
               "-c", filename + ".coafile",
               "-f", filename + "test.py")
            self.assertIn("This file has", output)
示例#31
0
    def test_print_result_no_input(self):
        with make_temp() as testfile_path:
            file_dict = {testfile_path: ["1\n", "2\n", "3\n"]}
            diff = Diff(file_dict[testfile_path])
            diff.delete_line(2)
            diff.change_line(3, "3\n", "3_changed\n")
            with simulate_console_inputs(1, 2, 3) as generator, \
                    retrieve_stdout() as stdout:
                ApplyPatchAction.is_applicable = staticmethod(
                    lambda *args: True)
                print_results_no_input(
                    self.log_printer,
                    Section("someSection"),
                    [Result("origin", "message", diffs={testfile_path: diff})],
                    file_dict,
                    self.file_diff_dict,
                    color=False)
                self.assertEqual(generator.last_input, -1)
                self.assertEqual(
                    stdout.getvalue(), """
Project wide:
|    | [NORMAL] origin:
|    | {}\n""".format(highlight_text("message", style=BackgroundMessageStyle)))
示例#32
0
    def test_get_project_files(self):
        orig_cwd = os.getcwd()
        os.chdir(os.path.dirname(os.path.realpath(__file__)))
        os.makedirs("file_globs_testfiles", exist_ok=True)
        os.chdir("file_globs_testfiles")

        os.makedirs("src", exist_ok=True)
        os.makedirs("ignore_dir", exist_ok=True)
        open(os.path.join("src", "file.c"), "w").close()
        open("root.c", "w").close()
        open(os.path.join("ignore_dir", "src.c"), "w").close()
        open(os.path.join("ignore_dir", "src.js"), "w").close()

        with suppress_stdout(), simulate_console_inputs("ignore_dir/**"):
            res, _ = get_project_files(self.log_printer, self.printer,
                                       os.getcwd())
            self.assertIn(os.path.join(os.getcwd(), "src", "file.c"), res)
            self.assertIn(os.path.join(os.getcwd(), "root.c"), res)
            self.assertNotIn(os.path.join(os.getcwd(), "ignore_dir/src.c"),
                             res)
            self.assertNotIn(os.path.join(os.getcwd(), "ignore_dir/src.js"),
                             res)

        os.chdir(orig_cwd)
示例#33
0
    def test_print_result(self):
        print_result(self.console_printer, self.log_printer, None,
                     self.file_diff_dict, "illegal value", {})

        with simulate_console_inputs(0):
            print_result(self.console_printer, self.log_printer,
                         self.section, self.file_diff_dict,
                         Result("origin", "msg", diffs={}), {})

        with make_temp() as testfile_path:
            file_dict = {
                testfile_path: ["1\n", "2\n", "3\n"],
                "f_b": ["1", "2", "3"]
            }
            diff = Diff(file_dict[testfile_path])
            diff.delete_line(2)
            diff.change_line(3, "3\n", "3_changed\n")

            ApplyPatchAction.is_applicable = staticmethod(lambda *args: True)

            # Interaction must be closed by the user with `0` if it's not a
            # param
            with simulate_console_inputs("INVALID", -1, 1, 0,
                                         3) as input_generator:
                curr_section = Section("")
                print_section_beginning(self.console_printer, curr_section)
                print_result(
                    self.console_printer, self.log_printer, curr_section,
                    self.file_diff_dict,
                    Result("origin", "msg", diffs={testfile_path:
                                                   diff}), file_dict)
                self.assertEqual(input_generator.last_input, 3)

                self.file_diff_dict.clear()

                with open(testfile_path) as f:
                    self.assertEqual(f.readlines(), ["1\n", "3_changed\n"])

                os.remove(testfile_path + ".orig")

                name, section = get_action_info(curr_section,
                                                TestAction().get_metadata(),
                                                failed_actions=set())
                self.assertEqual(input_generator.last_input, 4)
                self.assertEqual(str(section), " {param : '3'}")
                self.assertEqual(name, "TestAction")

        # Check if the user is asked for the parameter only the first time.
        # Use OpenEditorAction that needs this parameter (editor command).
        with simulate_console_inputs(1, "test_editor", 0, 1, 0) as generator:
            OpenEditorAction.is_applicable = staticmethod(lambda *args: True)

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

            print_result(self.console_printer, self.log_printer, curr_section,
                         self.file_diff_dict, patch_result, file_dict)
            # choose action, choose editor, choose no action (-1 -> 2)
            self.assertEqual(generator.last_input, 2)

            # It shoudn't ask for parameter again
            print_result(self.console_printer, self.log_printer, curr_section,
                         self.file_diff_dict, patch_result, file_dict)
            self.assertEqual(generator.last_input, 4)
    def test_print_result(self):
        print_result(self.console_printer,
                     self.log_printer,
                     None,
                     self.file_diff_dict,
                     "illegal value",
                     {})

        with simulate_console_inputs(0):
            print_result(self.console_printer,
                         self.log_printer,
                         None,
                         self.file_diff_dict,
                         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")

        with simulate_console_inputs(1), self.assertRaises(ValueError):
            ApplyPatchAction.is_applicable = staticmethod(lambda result: True)
            print_result(self.console_printer,
                         self.log_printer,
                         None,
                         self.file_diff_dict,
                         PatchResult("origin", "msg", {testfile_path: diff}),
                         file_dict)

        # To assure user can rechose if he didn't chose wisely
        with simulate_console_inputs("INVALID", -1, 1, 3) as input_generator:
            curr_section = Section("")
            print_section_beginning(self.console_printer, curr_section)
            print_result(self.console_printer,
                         self.log_printer,
                         curr_section,
                         self.file_diff_dict,
                         PatchResult("origin", "msg", {testfile_path: diff}),
                         file_dict)
            self.assertEqual(input_generator.last_input, 2)
            finalize(self.file_diff_dict, file_dict)
            # Check that the next section does not use the same file_diff_dict
            self.assertEqual(len(self.file_diff_dict), 0)

            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 = get_action_info(curr_section,
                                            TestAction().get_metadata())
            self.assertEqual(input_generator.last_input, 3)
            self.assertEqual(str(section), " {param : 3}")
            self.assertEqual(name, "TestAction")

        # Check if the user is asked for the parameter only the first time.
        # Use OpenEditorAction that needs this parameter (editor command).
        with simulate_console_inputs(1, "test_editor", 0, 1, 0) as generator:
            OpenEditorAction.is_applicable = staticmethod(lambda result: True)

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

            print_result(self.console_printer,
                         self.log_printer,
                         curr_section,
                         self.file_diff_dict,
                         patch_result,
                         file_dict)
            # choose action, choose editor, choose no action (-1 -> 2)
            self.assertEqual(generator.last_input, 2)

            # It shoudn't ask for parameter again
            print_result(self.console_printer,
                         self.log_printer,
                         curr_section,
                         self.file_diff_dict,
                         patch_result,
                         file_dict)
            self.assertEqual(generator.last_input, 4)
示例#35
0
    def test_print_result(self):
        print_result(self.console_printer,
                     self.log_printer,
                     None,
                     self.file_diff_dict,
                     "illegal value",
                     {})

        with simulate_console_inputs(0):
            print_result(self.console_printer,
                         self.log_printer,
                         None,
                         self.file_diff_dict,
                         Result("origin", "msg", diffs={}),
                         {})

        with make_temp() as testfile_path:
            file_dict = {
                testfile_path: ["1\n", "2\n", "3\n"],
                "f_b": ["1", "2", "3"]
            }
            diff = Diff(file_dict[testfile_path])
            diff.delete_line(2)
            diff.change_line(3, "3\n", "3_changed\n")

            with simulate_console_inputs(1), self.assertRaises(ValueError):
                ApplyPatchAction.is_applicable = staticmethod(
                    lambda *args: True)
                print_result(self.console_printer,
                             self.log_printer,
                             None,
                             self.file_diff_dict,
                             Result("origin", "msg", diffs={
                                    testfile_path: diff}),
                             file_dict)

            # Interaction must be closed by the user with `0` if it's not a
            # param
            with simulate_console_inputs("INVALID",
                                         -1,
                                         1,
                                         0,
                                         3) as input_generator:
                curr_section = Section("")
                print_section_beginning(self.console_printer, curr_section)
                print_result(self.console_printer,
                             self.log_printer,
                             curr_section,
                             self.file_diff_dict,
                             Result("origin", "msg", diffs={
                                    testfile_path: diff}),
                             file_dict)
                self.assertEqual(input_generator.last_input, 3)

                self.file_diff_dict.clear()

                with open(testfile_path) as f:
                    self.assertEqual(f.readlines(), ["1\n", "3_changed\n"])

                os.remove(testfile_path + ".orig")

                name, section = get_action_info(curr_section,
                                                TestAction().get_metadata())
                self.assertEqual(input_generator.last_input, 4)
                self.assertEqual(str(section), " {param : '3'}")
                self.assertEqual(name, "TestAction")

        # Check if the user is asked for the parameter only the first time.
        # Use OpenEditorAction that needs this parameter (editor command).
        with simulate_console_inputs(1, "test_editor", 0, 1, 0) as generator:
            OpenEditorAction.is_applicable = staticmethod(lambda *args: True)

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

            print_result(self.console_printer,
                         self.log_printer,
                         curr_section,
                         self.file_diff_dict,
                         patch_result,
                         file_dict)
            # choose action, choose editor, choose no action (-1 -> 2)
            self.assertEqual(generator.last_input, 2)

            # It shoudn't ask for parameter again
            print_result(self.console_printer,
                         self.log_printer,
                         curr_section,
                         self.file_diff_dict,
                         patch_result,
                         file_dict)
            self.assertEqual(generator.last_input, 4)