コード例 #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)
コード例 #2
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)
コード例 #3
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)
コード例 #4
0
    def test_apply(self):
        uut = ShowAppliedPatchesAction()

        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']
            }

            with make_temp() as testfile_path:
                file_diff_dict = {}
                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')
                result = Result('origin', 'msg', diffs={f_a: diff},
                                applied_actions={'ApplyPatchAction': [Result(
                                    'origin', 'message',
                                    diffs={testfile_path: diff}),
                                    file_dict, file_diff_dict, Section('')]})

                self.assertTrue(uut.apply(result,
                                          file_dict,
                                          file_diff_dict))
コード例 #5
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['cli']), "cli {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['cli']), 0)
コード例 #6
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["cli"]),
            "cli {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["cli"]), 0)
コード例 #7
0
    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'))
コード例 #8
0
    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'))
コード例 #9
0
    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"))
コード例 #10
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())
コード例 #11
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())
コード例 #12
0
ファイル: Linter.py プロジェクト: Eoghan-Murphy/coala
        def _create_config(cls, filename=None, file=None, **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 being linted. ``None`` for project
                scope.
            :param file:
                The content of the file being linted. ``None`` for project
                scope.
            :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
コード例 #13
0
    def test_is_applicable(self):

        with self.assertRaises(TypeError) as context:
            IgnoreResultAction.is_applicable('str', {}, {})

        self.assertEqual(
            IgnoreResultAction.is_applicable(
                Result.from_values('origin', 'msg', "file doesn't exist", 2),
                {},
                {}
            ),
            "The result is associated with source code that doesn't "
            'seem to exist.'
        )

        self.assertEqual(
            IgnoreResultAction.is_applicable(
                Result('', ''),
                {},
                {}
            ),
            'The result is not associated with any source code.'
        )

        with make_temp() as f_a:
            self.assertTrue(IgnoreResultAction.is_applicable(
                Result.from_values('origin', 'msg', f_a, 2), {}, {}))
コード例 #14
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()
コード例 #15
0
        def _create_config(cls, filename=None, file=None, **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 being linted. ``None`` for project
                scope.
            :param file:
                The content of the file being linted. ``None`` for project
                scope.
            :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
コード例 #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.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()
コード例 #17
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,
                                       self.console_printer)
                self.assertEqual(generator.last_input, -1)
                self.assertEqual(stdout.getvalue(),
                                 """
Project wide:

**** origin [Section: someSection] ****

!    ! [Severity: NORMAL]
!    ! {}\n""".format(highlight_text(self.no_color,
                                     'message', style=BackgroundMessageStyle)))
コード例 #18
0
    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())
コード例 #19
0
 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), {}, {}))
コード例 #20
0
    def test_proxymap_resolve_creates_binary(self):
        with make_temp() as filename:
            data = bytearray([120, 3, 255, 0, 100])

            with open(filename, 'wb') as file:
                file.write(data)

            proxy = self.empty_proxymap().resolve(filename, binary=True)
            self.assertEqual(proxy.lines(), (data, ))
コード例 #21
0
ファイル: FileProxyTest.py プロジェクト: Anmolbansal1/coala
    def test_proxymap_resolve_creates_binary(self):
        with make_temp() as filename:
            data = bytearray([120, 3, 255, 0, 100])

            with open(filename, 'wb') as file:
                file.write(data)

            proxy = self.empty_proxymap().resolve(filename, binary=True)
            self.assertEqual(proxy.lines(), (data,))
コード例 #22
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["cli"], sections["test"].defaults)
コード例 #23
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(), '')
コード例 #24
0
 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), {}, {}))
コード例 #25
0
    def test_acquire_actions_and_apply_single(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('a', 'n') as generator:
                with retrieve_stdout() as sio:
                    ApplyPatchAction.is_applicable = staticmethod(
                        lambda *args: True)
                    acquire_actions_and_apply(self.console_printer,
                                              Section(''),
                                              self.file_diff_dict,
                                              Result(
                                                  'origin',
                                                  'message',
                                                  diffs={testfile_path: diff}),
                                              file_dict,
                                              apply_single=True)
                    self.assertEqual(generator.last_input, -1)
                    self.assertIn('', sio.getvalue())

            class InvalidateTestAction(ResultAction):

                is_applicable = staticmethod(lambda *args: True)

                def apply(*args, **kwargs):
                    ApplyPatchAction.is_applicable = staticmethod(
                        lambda *args: 'ApplyPatchAction cannot be applied.')

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

            with simulate_console_inputs('a') as generator:
                with retrieve_stdout() as sio:
                    acquire_actions_and_apply(self.console_printer,
                                              Section(''),
                                              self.file_diff_dict,
                                              Result(
                                                  'origin',
                                                  'message',
                                                  diffs={testfile_path: diff}),
                                              file_dict,
                                              cli_actions=cli_actions,
                                              apply_single=True)
                    self.assertEqual(generator.last_input, -1)

                    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), 0)

            ApplyPatchAction.is_applicable = old_applypatch_is_applicable
コード例 #26
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['cli'], sections['test'].defaults)
コード例 #27
0
    def test_fileproxy_binary_file(self):
        with make_temp() as filename:
            data = bytearray([120, 3, 255, 0, 100])

            with open(filename, 'wb') as file:
                file.write(data)

            proxy = FileProxy.from_file(filename, None, binary=True)
            self.assertEqual(proxy.filename, os.path.normcase(filename))
            self.assertEqual(proxy.contents(), data)
            self.assertEqual(proxy.lines(), (data, ))
コード例 #28
0
ファイル: FileProxyTest.py プロジェクト: Anmolbansal1/coala
    def test_fileproxy_binary_file(self):
        with make_temp() as filename:
            data = bytearray([120, 3, 255, 0, 100])

            with open(filename, 'wb') as file:
                file.write(data)

            proxy = FileProxy.from_file(filename, None, binary=True)
            self.assertEqual(proxy.filename, os.path.normcase(filename))
            self.assertEqual(proxy.contents(), data)
            self.assertEqual(proxy.lines(), (data,))
コード例 #29
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')
コード例 #30
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['cli'],
                         sections['test'].defaults)
コード例 #31
0
    def test_acquire_actions_and_apply_single(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('a', 'n') as generator:
                with retrieve_stdout() as sio:
                    ApplyPatchAction.is_applicable = staticmethod(
                        lambda *args: True)
                    acquire_actions_and_apply(self.console_printer,
                                              Section(''),
                                              self.file_diff_dict,
                                              Result(
                                                  'origin', 'message',
                                                  diffs={testfile_path: diff}),
                                              file_dict, apply_single=True)
                    self.assertEqual(generator.last_input, -1)
                    self.assertIn('', sio.getvalue())

            class InvalidateTestAction(ResultAction):

                is_applicable = staticmethod(lambda *args: True)

                def apply(*args, **kwargs):
                    ApplyPatchAction.is_applicable = staticmethod(
                        lambda *args: 'ApplyPatchAction cannot be applied.')

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

            with simulate_console_inputs('a') as generator:
                with retrieve_stdout() as sio:
                    acquire_actions_and_apply(self.console_printer,
                                              Section(''),
                                              self.file_diff_dict,
                                              Result(
                                                  'origin', 'message',
                                                  diffs={testfile_path: diff}),
                                              file_dict,
                                              cli_actions=cli_actions,
                                              apply_single=True)
                    self.assertEqual(generator.last_input, -1)

                    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), 0)

            ApplyPatchAction.is_applicable = old_applypatch_is_applicable
コード例 #32
0
    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'))
コード例 #33
0
    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'))
コード例 #34
0
    def test_is_applicable(self):
        prior_ignore = ('IgnoreResultAction')
        associated_result = Result.from_values('origin', 'msg',
                                               "file doesn't exist", 2)

        with self.assertRaises(TypeError) as context:
            IgnoreResultAction.is_applicable('str', {}, {})
        with self.assertRaises(TypeError) as context:
            IgnoreResultAction.is_applicable('str', {}, {}, prior_ignore)

        self.assertEqual(
            IgnoreResultAction.is_applicable(associated_result, {}, {}),
            "The result is associated with source code that doesn't "
            'seem to exist.')

        self.assertEqual(
            IgnoreResultAction.is_applicable(
                associated_result,
                {},
                {},
                prior_ignore),
            'An ignore comment was already added for this result.')

        self.assertEqual(
            IgnoreResultAction.is_applicable(
                Result('', ''),
                {},
                {},
                prior_ignore),
            'An ignore comment was already added for this result.')

        self.assertEqual(
            IgnoreResultAction.is_applicable(
                Result('', ''),
                {},
                {}
            ),
            'The result is not associated with any source code.'
        )

        with make_temp() as f_a:
            result = Result.from_values('origin', 'msg', f_a, 2)
            self.assertTrue(IgnoreResultAction.is_applicable(result, {}, {}))
            self.assertEqual(
                IgnoreResultAction.is_applicable(
                    result,
                    {},
                    {},
                    prior_ignore),
                'An ignore comment was already added for this result.')
コード例 #35
0
    def test_apply(self):
        uut = ShowAppliedPatchesAction()

        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']
            }

            with make_temp() as testfile_path:
                file_diff_dict = {}
                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')
                result = Result('origin',
                                'msg',
                                diffs={f_a: diff},
                                applied_actions={
                                    'ApplyPatchAction': [
                                        Result('origin',
                                               'message',
                                               diffs={testfile_path: diff}),
                                        file_dict, file_diff_dict,
                                        Section('')
                                    ]
                                })

                self.assertTrue(uut.apply(result, file_dict, file_diff_dict))
コード例 #36
0
ファイル: CachingTest.py プロジェクト: zuphilip/coala
    def test_get_file_dict_unicode_error(self):
        with make_temp() as filename:
            with open(filename, 'wb') as file:
                file.write(bytearray([120, 3, 255, 0, 100]))

            self.cache.set_proxymap(FileProxyMap())
            file_dict = self.cache.get_file_dict([filename])

            self.assertEqual(len(file_dict), 0)

            self.cache.set_proxymap(FileProxyMap())
            file_dict = self.cache.get_file_dict([filename],
                                                 allow_raw_files=True)

            self.assertEqual(len(file_dict), 1)
            self.assertIn(filename, file_dict)
コード例 #37
0
ファイル: CachingTest.py プロジェクト: Anmolbansal1/coala
    def test_get_file_dict_unicode_error(self):
        with make_temp() as filename:
            with open(filename, 'wb') as file:
                file.write(bytearray([120, 3, 255, 0, 100]))

            self.cache.set_proxymap(FileProxyMap())
            file_dict = self.cache.get_file_dict([filename])

            self.assertEqual(len(file_dict), 0)

            self.cache.set_proxymap(FileProxyMap())
            file_dict = self.cache.get_file_dict([filename],
                                                 allow_raw_files=True)

            self.assertEqual(len(file_dict), 1)
            self.assertIn(filename, file_dict)
コード例 #38
0
    def test_ignore_jinja2(self):
        uut = IgnoreResultAction()
        with make_temp() as f_a:
            file_dict = {
                f_a: ['1\n', '2\n']
            }

            file_diff_dict = {}

            # Test ignore comment in jinja2
            uut.apply(Result.from_values('else', 'msg', f_a, 1),
                      file_dict, file_diff_dict, 'jinja2')
            self.assertEqual(
                file_diff_dict[f_a].modified,
                ['1  {# Ignore else #}\n', '2\n'])
            with open(f_a, 'r') as f:
                self.assertEqual(file_diff_dict[f_a].modified, f.readlines())
コード例 #39
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()
    def test_is_applicable(self):

        with self.assertRaises(TypeError) as context:
            IgnoreResultAction.is_applicable('str', {}, {})

        self.assertEqual(
            IgnoreResultAction.is_applicable(
                Result.from_values('origin', 'msg', "file doesn't exist", 2),
                {}, {}),
            "The result is associated with source code that doesn't "
            'seem to exist.')

        self.assertEqual(
            IgnoreResultAction.is_applicable(Result('', ''), {}, {}),
            'The result is not associated with any source code.')

        with make_temp() as f_a:
            self.assertTrue(
                IgnoreResultAction.is_applicable(
                    Result.from_values('origin', 'msg', f_a, 2), {}, {}))
コード例 #41
0
    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, 'css')
            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())

            import logging
            logger = logging.getLogger()

            with unittest.mock.patch('subprocess.call'):
                with self.assertLogs(logger, 'WARNING') as log:
                    uut.apply(Result.from_values('else', 'msg', f_a, 1),
                              file_dict, file_diff_dict, 'dothraki')

                    self.assertEqual(1, len(log.output))
                    self.assertIn(
                        'coala does not support Ignore in "dothraki".',
                        log.output[0]
                    )
コード例 #42
0
    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, 'css')
            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())

            import logging
            logger = logging.getLogger()

            with unittest.mock.patch('subprocess.call'):
                with self.assertLogs(logger, 'WARNING') as log:
                    uut.apply(Result.from_values('else', 'msg', f_a, 1),
                              file_dict, file_diff_dict, 'dothraki')

                    self.assertEqual(1, len(log.output))
                    self.assertIn(
                        'coala does not support Ignore in "dothraki".',
                        log.output[0]
                    )
コード例 #43
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()
コード例 #44
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 = "tests.misc.BuildManPageTest:test_arg_parser"
            uut.parser = '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))
コード例 #45
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 = "tests.misc.BuildManPageTest:test_arg_parser"
            uut.parser = '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))
コード例 #46
0
ファイル: ConsoleInteractionTest.py プロジェクト: icoz/coala
    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,
                                       self.console_printer)
                self.assertEqual(generator.last_input, -1)
                self.assertEqual(stdout.getvalue(),
                                 """
Project wide:
|    | [NORMAL] origin:
|    | {}\n""".format(highlight_text(self.no_color,
                                     'message', style=BackgroundMessageStyle)))
コード例 #47
0
    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())
コード例 #48
0
    def test_print_result(self):
        print_result(self.console_printer,
                     None,
                     self.file_diff_dict,
                     'illegal value',
                     {})

        with simulate_console_inputs(0):
            print_result(self.console_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,
                             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,
                         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,
                         curr_section,
                         self.file_diff_dict,
                         patch_result,
                         file_dict)
            self.assertEqual(generator.last_input, 4)