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

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

            self.assertEqual(file_dict, expected_file_dict)
    def test_gather_configuration(self):
        args = (lambda *args: True, self.log_printer)

        # Passing the default coafile name only triggers a warning.
        gather_configuration(*args, arg_list=["-c abcdefghi/invalid/.coafile"])

        # Using a bad filename explicitly exits coala.
        with self.assertRaises(SystemExit):
            gather_configuration(
                *args, arg_list=["-S", "test=5", "-c", "some_bad_filename"])

        with make_temp() as temporary:
            sections, local_bears, global_bears, targets = (
                gather_configuration(*args,
                                     arg_list=[
                                         "-S", "test=5", "-c",
                                         escape(temporary, "\\"), "-s"
                                     ]))

        self.assertEqual(
            str(sections["default"]),
            "Default {config : " + repr(temporary) + ", save : "
            "'True', test : '5'}")

        with make_temp() as temporary:
            sections, local_bears, global_bears, targets = (
                gather_configuration(*args,
                                     arg_list=[
                                         "-S test=5",
                                         "-c " + escape(temporary, "\\"),
                                         "-b LineCountBear -s"
                                     ]))

        self.assertEqual(len(local_bears["default"]), 0)
 def test_apply_orig_option(self):
     uut = ApplyPatchAction()
     with make_temp() as f_a, make_temp() as f_b:
         file_dict = {
             f_a: ["1\n", "2\n", "3\n"],
             f_b: ["1\n", "2\n", "3\n"]
             }
         expected_file_dict = {
             f_a: ["1\n", "2\n", "3_changed\n"],
             f_b: ["1\n", "2\n", "3_changed\n"]
             }
         file_diff_dict = {}
         diff = Diff(file_dict[f_a])
         diff.change_line(3, "3\n", "3_changed\n")
         uut.apply(Result("origin", "msg", diffs={f_a: diff}),
                   file_dict,
                   file_diff_dict,
                   no_orig=True)
         diff = Diff(file_dict[f_b])
         diff.change_line(3, "3\n", "3_changed\n")
         uut.apply(Result("origin", "msg", diffs={f_b: diff}),
                   file_dict,
                   file_diff_dict,
                   no_orig=False)
         self.assertFalse(isfile(f_a+".orig"))
         self.assertTrue(isfile(f_b+".orig"))
    def test_gather_configuration(self):
        args = (lambda *args: True, self.log_printer)

        # Passing the default coafile name only triggers a warning.
        gather_configuration(*args, arg_list=["-c abcdefghi/invalid/.coafile"])

        # Using a bad filename explicitly exits coala.
        with self.assertRaises(SystemExit):
            gather_configuration(
                *args,
                arg_list=["-S", "test=5", "-c", "some_bad_filename"])

        with make_temp() as temporary:
            sections, local_bears, global_bears, targets = (
                gather_configuration(
                    *args,
                    arg_list=["-S",
                              "test=5",
                              "-c",
                              escape(temporary, "\\"),
                              "-s"]))

        self.assertEqual(str(sections["default"]),
                         "Default {config : " +
                         repr(temporary) + ", save : 'True', test : '5'}")

        with make_temp() as temporary:
            sections, local_bears, global_bears, targets = (
                gather_configuration(*args,
                                     arg_list=["-S test=5",
                                               "-c " + escape(temporary, "\\"),
                                               "-b LineCountBear -s"]))

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

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

            self.assertEqual(file_dict, expected_file_dict)
    def test_make_temp(self):
        with make_temp() as f_a:
            self.assertTrue(os.path.isfile(f_a))
            self.assertTrue(os.path.basename(f_a).startswith("tmp"))

        with make_temp(suffix=".orig", prefix="pre") as f_b:
            self.assertTrue(f_b.endswith(".orig"))
            self.assertTrue(os.path.basename(f_b).startswith("pre"))
    def test_make_temp(self):
        with make_temp() as f_a:
            self.assertTrue(os.path.isfile(f_a))
            self.assertTrue(os.path.basename(f_a).startswith("tmp"))

        with make_temp(suffix=".orig", prefix="pre") as f_b:
            self.assertTrue(f_b.endswith(".orig"))
            self.assertTrue(os.path.basename(f_b).startswith("pre"))
    def test_make_temp(self):
        with make_temp() as f_a:
            self.assertTrue(os.path.isfile(f_a))
            self.assertTrue(os.path.basename(f_a).startswith('tmp'))
        self.assertFalse(os.path.isfile(f_a))

        with make_temp(suffix='.orig', prefix='pre') as f_b:
            self.assertTrue(f_b.endswith('.orig'))
            self.assertTrue(os.path.basename(f_b).startswith('pre'))
Beispiel #9
0
 def test_coala_delete_orig(self):
     with TemporaryDirectory() as tempdir,\
          NamedTemporaryFile(suffix='.orig',
                             dir=tempdir,
                             delete=False) as orig_file,\
          make_temp(suffix='.coafile', prefix='', dir=tempdir) as coafile,\
          make_temp(dir=tempdir) as unrelated_file:
         orig_file.close()
         execute_coala_ci(("-c", re.escape(coafile)))
         self.assertFalse(os.path.isfile(orig_file.name))
         self.assertTrue(os.path.isfile(unrelated_file))
Beispiel #10
0
 def test_coala_delete_orig(self):
     with TemporaryDirectory() as tempdir,\
          NamedTemporaryFile(suffix='.orig',
                             dir=tempdir,
                             delete=False) as orig_file,\
          make_temp(suffix='.coafile', prefix='', dir=tempdir) as coafile,\
          make_temp(dir=tempdir) as unrelated_file:
         orig_file.close()
         execute_coala(coala_ci.main, "coala-ci", "-c", re.escape(coafile))
         self.assertFalse(os.path.isfile(orig_file.name))
         self.assertTrue(os.path.isfile(unrelated_file))
Beispiel #11
0
    def test_coala_delete_orig(self):
        with TemporaryDirectory() as tempdir,\
             NamedTemporaryFile(suffix='.orig',
                                dir=tempdir,
                                delete=False) as orig_file,\
             make_temp(suffix='.coafile', prefix='', dir=tempdir) as coafile,\
             make_temp(dir=tempdir) as unrelated_file:
            orig_file.close()

            execute_coala(coala_ci.main, "coala-ci", "-S",
                          "project_dir=" + os.path.dirname(coafile))
            self.assertFalse(os.path.isfile(orig_file.name))
            self.assertTrue(os.path.isfile(unrelated_file))
Beispiel #12
0
    def test_coala_delete_orig(self):
        with TemporaryDirectory() as tempdir,\
             NamedTemporaryFile(suffix='.orig',
                                dir=tempdir,
                                delete=False) as orig_file,\
             make_temp(suffix='.coafile', prefix='', dir=tempdir) as coafile,\
             make_temp(dir=tempdir) as unrelated_file:
            orig_file.close()
            with open(coafile, mode="w") as file:
                file.write("files = something\n")

            execute_coala(coala_ci.main, "coala-ci",
                          "-c", re.escape(coafile))
            self.assertFalse(os.path.isfile(orig_file.name))
            self.assertTrue(os.path.isfile(unrelated_file))
    def test_apply(self):
        uut = ApplyPatchAction()
        with make_temp() as f_a, make_temp() as f_b, make_temp() as f_c:

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

            file_diff_dict = {}

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

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

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

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

            self.assertEqual(file_dict, expected_file_dict)
            with open(f_a) as fa:
                self.assertEqual(file_dict[f_a], fa.readlines())
            with open(f_b) as fb:
                self.assertEqual(file_dict[f_b], fb.readlines())
            with open(f_c) as fc:
                # File c is unchanged and should be untouched
                self.assertEqual([], fc.readlines())
Beispiel #14
0
    def test_apply(self):
        uut = ApplyPatchAction()
        with make_temp() as f_a, make_temp() as f_b, make_temp() as f_c:

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

            file_diff_dict = {}

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

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

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

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

            self.assertEqual(file_dict, expected_file_dict)
            with open(f_a) as fa:
                self.assertEqual(file_dict[f_a], fa.readlines())
            with open(f_b) as fb:
                self.assertEqual(file_dict[f_b], fb.readlines())
            with open(f_c) as fc:
                # File c is unchanged and should be untouched
                self.assertEqual([], fc.readlines())
    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
""",
                )
Beispiel #16
0
    def test_apply_rename(self):
        uut = ApplyPatchAction()
        with make_temp() as f_a:
            file_dict = {f_a: ["1\n", "2\n", "3\n"]}
            expected_file_dict = {f_a+".renamed":
                                      ["1\n", "2_changed\n", "3_changed\n"]}
            file_diff_dict = {}
            diff = Diff(file_dict[f_a], rename=f_a+".renamed")
            diff.change_line(3, "3\n", "3_changed\n")
            uut.apply(Result("origin", "msg", diffs={f_a: diff}),
                      file_dict,
                      file_diff_dict)
            self.assertTrue(isfile(f_a+".orig"))
            self.assertTrue(isfile(f_a+".renamed"))
            self.assertFalse(isfile(f_a))

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

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

            self.assertEqual(file_dict, expected_file_dict)
            # Recreate file so that context manager make_temp() can delete it
            open(f_a, 'w').close()
Beispiel #17
0
    def test_apply_rename(self):
        uut = ApplyPatchAction()
        with make_temp() as f_a:
            file_dict = {f_a: ["1\n", "2\n", "3\n"]}
            expected_file_dict = {f_a+".renamed":
                                      ["1\n", "2_changed\n", "3_changed\n"]}
            file_diff_dict = {}
            diff = Diff(file_dict[f_a], rename=f_a+".renamed")
            diff.change_line(3, "3\n", "3_changed\n")
            uut.apply(Result("origin", "msg", diffs={f_a: diff}),
                      file_dict,
                      file_diff_dict)
            self.assertTrue(isfile(f_a+".orig"))
            self.assertTrue(isfile(f_a+".renamed"))
            self.assertFalse(isfile(f_a))

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

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

            self.assertEqual(file_dict, expected_file_dict)
            # Recreate file so that context manager make_temp() can delete it
            open(f_a, 'w').close()
Beispiel #18
0
    def test_apply_rename(self):
        uut = ApplyPatchAction()
        with make_temp() as f_a:
            file_dict = {f_a: ['1\n', '2\n', '3\n']}
            expected_file_dict = {
                f_a + '.renamed': ['1\n', '2_changed\n', '3_changed\n']
            }
            file_diff_dict = {}
            diff = Diff(file_dict[f_a], rename=f_a + '.renamed')
            diff.change_line(3, '3\n', '3_changed\n')
            uut.apply(Result('origin', 'msg', diffs={f_a: diff}), file_dict,
                      file_diff_dict)
            self.assertTrue(isfile(f_a + '.orig'))
            self.assertTrue(isfile(f_a + '.renamed'))
            self.assertFalse(isfile(f_a))

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

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

            self.assertEqual(file_dict, expected_file_dict)
            # Recreate file so that context manager make_temp() can delete it
            open(f_a, 'w').close()
Beispiel #19
0
 def test_temp_file_existence(self):
     """
     Test that the temporary file created exists only within the with
     statement context and not outside it
     """
     with make_temp() as temporary:
         self.assertTrue(os.path.isfile(temporary))
     self.assertFalse(os.path.isfile(temporary))
Beispiel #20
0
 def test_temp_file_existence(self):
     """
     Test that the temporary file created exists only within the with
     statement context and not outside it
     """
     with make_temp() as temporary:
         self.assertTrue(os.path.isfile(temporary))
     self.assertFalse(os.path.isfile(temporary))
    def test_merge_defaults(self):
        with make_temp() as temporary:
            sections, local_bears, global_bears, targets = gather_configuration(
                lambda *args: True,
                self.log_printer,
                arg_list=["-S", "value=1", "test.value=2", "-c", escape(temporary, "\\")],
            )

        self.assertEqual(sections["default"], sections["test"].defaults)
 def test_is_applicable(self):
     self.assertFalse(IgnoreResultAction.is_applicable('str', {}, {}))
     self.assertFalse(
         IgnoreResultAction.is_applicable(
             Result.from_values('origin', 'msg', "file doesn't exist", 2),
             {}, {}))
     with make_temp() as f_a:
         self.assertTrue(
             IgnoreResultAction.is_applicable(
                 Result.from_values('origin', 'msg', f_a, 2), {}, {}))
Beispiel #23
0
 def test_coala_delete_orig(self):
     with TemporaryDirectory() as tempdir, NamedTemporaryFile(
         suffix=".orig", dir=tempdir, delete=False
     ) as orig_file, make_temp(suffix=".coafile", prefix="", dir=tempdir) as coafile, make_temp(
         dir=tempdir
     ) as unrelated_file:
         orig_file.close()
         execute_coala(coala_ci.main, "coala-ci", "-c", re.escape(coafile))
         self.assertFalse(os.path.isfile(orig_file.name))
         self.assertTrue(os.path.isfile(unrelated_file))
 def test_print_affected_files(self):
     with retrieve_stdout() as stdout, \
             make_temp() as some_file:
         file_dict = {some_file: ['1\n', '2\n', '3\n']}
         affected_code = (SourceRange.from_values(some_file), )
         print_affected_files(
             self.console_printer, self.log_printer,
             Result('origin', 'message', affected_code=affected_code),
             file_dict)
         self.assertEqual(stdout.getvalue(),
                          '\n' + relpath(some_file) + '\n')
Beispiel #25
0
    def test_merge_defaults(self):
        with make_temp() as temporary:
            sections, local_bears, global_bears, targets = (
                gather_configuration(lambda *args: True,
                                     self.log_printer,
                                     arg_list=[
                                         '-S', 'value=1', 'test.value=2', '-c',
                                         escape(temporary, '\\')
                                     ] + self.min_args))

        self.assertEqual(sections['default'], sections['test'].defaults)
    def test_merge_defaults(self):
        with make_temp() as temporary:
            sections, local_bears, global_bears, targets = (
                gather_configuration(lambda *args: True,
                                     self.log_printer,
                                     arg_list=[
                                         "-S", "value=1", "test.value=2", "-c",
                                         escape(temporary, "\\")
                                     ]))

        self.assertEqual(sections["default"], sections["test"].defaults)
Beispiel #27
0
 def test_print_affected_files(self):
     with retrieve_stdout() as stdout, \
             make_temp() as some_file:
         file_dict = {some_file: ["1\n", "2\n", "3\n"]}
         affected_code = (SourceRange.from_values(some_file), )
         print_affected_files(
             self.console_printer, self.log_printer,
             Result("origin", "message", affected_code=affected_code),
             file_dict)
         self.assertEqual(stdout.getvalue(),
                          "\n" + relpath(some_file) + "\n")
    def test_build(self):
        dist = Distribution()
        uut = BuildDbusService(dist)
        self.assertRaises(DistutilsOptionError, uut.finalize_options)
        with make_temp() as uut.output:
            uut.finalize_options()

            uut.run()
            with open(uut.output) as file:
                result = file.read(1000)

            self.assertEqual(result, "[D-BUS Service]\nNames=" + Constants.BUS_NAME + "\nExec=coala-dbus")
 def test_print_affected_files(self):
     with retrieve_stdout() as stdout, \
             make_temp() as some_file:
         file_dict = {some_file: ["1\n", "2\n", "3\n"]}
         affected_code = (SourceRange.from_values(some_file),)
         print_affected_files(self.console_printer,
                              self.log_printer,
                              Result("origin",
                                     "message",
                                     affected_code=affected_code),
                              file_dict)
         self.assertEqual(stdout.getvalue(),
                          "\n"+relpath(some_file)+"\n")
Beispiel #30
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
    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
    def test_build(self):
        dist = Distribution()
        uut = BuildDbusService(dist)
        self.assertRaises(DistutilsOptionError, uut.finalize_options)
        with make_temp() as uut.output:
            uut.finalize_options()

            uut.run()
            with open(uut.output) as file:
                result = file.read(1000)

            self.assertEqual(
                result, "[D-BUS Service]\nNames=" + Constants.BUS_NAME +
                "\nExec=coala-dbus")
    def test_no_orig(self):
        uut = IgnoreResultAction()
        with make_temp() as f_a:
            file_dict = {f_a: ['1\n', '2\n', '3\n']}

            file_diff_dict = {}

            # Apply an initial patch
            uut.apply(Result.from_values('origin', 'msg', f_a, 2),
                      file_dict,
                      file_diff_dict,
                      'c',
                      no_orig=True)
            self.assertFalse(exists(f_a + '.orig'))
Beispiel #34
0
    def test_gather_configuration(self):
        args = (lambda *args: True, self.log_printer)

        # Using incomplete settings (e.g. an invalid coafile) will error
        with self.assertRaises(SystemExit):
            gather_configuration(*args,
                                 arg_list=["-c abcdefghi/invalid/.coafile"])

        # Using a bad filename explicitly exits coala.
        with self.assertRaises(SystemExit):
            gather_configuration(
                *args, arg_list=["-S", "test=5", "-c", "some_bad_filename"])

        with make_temp() as temporary:
            sections, local_bears, global_bears, targets = (
                gather_configuration(*args,
                                     arg_list=[
                                         "-S", "test=5", "-c",
                                         escape(temporary, "\\"), "-s"
                                     ] + self.min_args))

        self.assertEqual(
            str(sections["default"]),
            "Default {bears : 'JavaTestBear', config : " + repr(temporary) +
            ", files : '*.java', save : 'True', test : '5'}")

        with make_temp() as temporary:
            sections, local_bears, global_bears, targets = (
                gather_configuration(*args,
                                     arg_list=[
                                         "-S test=5", "-f *.java",
                                         "-c " + escape(temporary, "\\"),
                                         "-b LineCountBear -s"
                                     ]))

        self.assertEqual(len(local_bears["default"]), 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)
 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())
Beispiel #37
0
    def test_apply_delete(self):
        uut = ApplyPatchAction()
        with make_temp() as f_a:
            file_dict = {f_a: ['1\n', '2\n', '3\n']}
            file_diff_dict = {}
            diff = Diff(file_dict[f_a], delete=True)
            uut.apply(Result('origin', 'msg', diffs={f_a: diff}), file_dict,
                      file_diff_dict)
            self.assertFalse(isfile(f_a))
            self.assertTrue(isfile(f_a + '.orig'))
            os.remove(f_a + '.orig')

            diff = Diff(file_dict[f_a])
            diff.change_line(3, '3\n', '3_changed\n')
            uut.apply(Result('origin', 'msg', diffs={f_a: diff}), file_dict,
                      file_diff_dict)
            self.assertFalse(isfile(f_a + '.orig'))
            # Recreate file so that context manager make_temp() can delete it
            open(f_a, 'w').close()
Beispiel #38
0
    def test_apply_delete(self):
        uut = ApplyPatchAction()
        with make_temp() as f_a:
            file_dict = {f_a: ["1\n", "2\n", "3\n"]}
            file_diff_dict = {}
            diff = Diff(file_dict[f_a], delete=True)
            uut.apply(Result("origin", "msg", diffs={f_a: diff}),
                      file_dict,
                      file_diff_dict)
            self.assertFalse(isfile(f_a))
            self.assertTrue(isfile(f_a+".orig"))
            os.remove(f_a+".orig")

            diff = Diff(file_dict[f_a])
            diff.change_line(3, "3\n", "3_changed\n")
            uut.apply(Result("origin", "msg", diffs={f_a: diff}),
                      file_dict,
                      file_diff_dict)
            self.assertFalse(isfile(f_a+".orig"))
            # Recreate file so that context manager make_temp() can delete it
            open(f_a, 'w').close()
Beispiel #39
0
        def _create_config(cls, filename, file, **kwargs):
            """
            Provides a context-manager that creates the config file if the
            user provides one and cleans it up when done with linting.

            :param filename:
                The filename of the file.
            :param file:
                The file contents.
            :param kwargs:
                Section settings passed from ``run()``.
            :return:
                A context-manager handling the config-file.
            """
            content = cls.generate_config(filename, file, **kwargs)
            if content is None:
                yield None
            else:
                with make_temp(suffix=options['config_suffix']) as config_file:
                    with open(config_file, mode='w') as fl:
                        fl.write(content)
                    yield config_file
Beispiel #40
0
    def test_finalize_options(self):
        dist = Distribution()
        uut = BuildManPage(dist)
        self.assertRaises(DistutilsOptionError, uut.finalize_options)
        with make_temp() as uut.output:
            self.assertRaises(DistutilsOptionError, uut.finalize_options)
            uut.parser = "coalib.tests.misc.BuildManPageTest:test_arg_parser"

            uut.finalize_options()
            self.assertIsInstance(uut._parser, argparse.ArgumentParser)

            uut.run()
            with open(uut.output) as file:
                result = file.read(1000)

            today = datetime.date.today().strftime('%Y\\-%m\\-%d')
            self.assertEqual(result,
                             """.TH {0} 1 {1}
.SH NAME
{0}
.SH SYNOPSIS
 \\fB{0}\\fR [-h] [-a A] arg1


.SH DESCRIPTION
UNKNOWN
.SH OPTIONS
  arg1

  \\fB-h\\fR, \\fB--help\\fR
                        show this help message and exit
  \\fB-a\\fR \\fIA\\fR
.SH LICENSE
 UNKNOWN
.SH MAINTAINER(S)
 UNKNOWN
.SH SEE ALSO
 Online documentation: UNKNOWN""".format(app_name, today))
    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)))
Beispiel #42
0
        def _create_config(cls, filename, file, **kwargs):
            """
            Provides a context-manager that creates the config file if the
            user provides one and cleans it up when done with linting.

            :param filename:
                The filename of the file.
            :param file:
                The file contents.
            :param kwargs:
                Section settings passed from ``run()``.
            :return:
                A context-manager handling the config-file.
            """
            content = cls.generate_config(filename, file, **kwargs)
            if content is None:
                yield None
            else:
                with make_temp(
                        suffix=options["config_suffix"]) as config_file:
                    with open(config_file, mode="w") as fl:
                        fl.write(content)
                    yield config_file
    def test_ignore(self):
        uut = IgnoreResultAction()
        with make_temp() as f_a:
            file_dict = {f_a: ['1\n', '2\n', '3\n']}

            file_diff_dict = {}

            # Apply an initial patch
            uut.apply(Result.from_values('origin', 'msg', f_a, 2), file_dict,
                      file_diff_dict, 'c')
            self.assertEqual(file_diff_dict[f_a].modified,
                             ['1\n', '2  // Ignore origin\n', '3\n'])
            with open(f_a, 'r') as f:
                self.assertEqual(file_diff_dict[f_a].modified, f.readlines())
            self.assertTrue(exists(f_a + '.orig'))

            # Apply a second patch, old patch has to stay!
            uut.apply(Result.from_values('else', 'msg', f_a, 1), file_dict,
                      file_diff_dict, 'c')
            self.assertEqual(
                file_diff_dict[f_a].modified,
                ['1  // Ignore else\n', '2  // Ignore origin\n', '3\n'])
            with open(f_a, 'r') as f:
                self.assertEqual(file_diff_dict[f_a].modified, f.readlines())
    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,
                         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)