예제 #1
0
class ESLintBearIgnoredFileTest(LocalBearTestHelper):

    def setUp(self):
        self.section = Section('')
        self.uut = ESLintBear(self.section, Queue())

    def test_lint_config_file(self):

        self.maxDiff = None
        config_filename = os.path.join(test_dir, '.eslintrc.js')

        self.section.append(Setting('eslint_config', config_filename))

        expected = Result.from_values(
            'ESLintBear',
            'File ignored by default.  Use a negated ignore pattern '
            '(like "--ignore-pattern \'!<relative/path/to/filename>\'") '
            'to override.',
            severity=RESULT_SEVERITY.NORMAL,
            file=config_filename,
            )

        Path(config_filename).touch()

        self.check_results(
            self.uut, ['{}'],
            [expected],
            create_tempfile=False,
            filename=config_filename,
        )
예제 #2
0
    def test_apply(self):
        # Initial file contents, *before* a patch was applied
        file_dict = {self.fa: ["1\n", "2\n", "3\n"], self.fb: ["1\n", "2\n", "3\n"], "f_c": ["1\n", "2\n", "3\n"]}

        # A patch that was applied for some reason to make things complicated
        diff_dict = {self.fb: Diff(file_dict[self.fb])}
        diff_dict[self.fb].change_line(3, "3\n", "3_changed\n")

        # File contents after the patch was applied, that's what's in the files
        current_file_dict = {
            filename: diff_dict[filename].modified if filename in diff_dict else file_dict[filename]
            for filename in (self.fa, self.fb)
        }
        for filename in current_file_dict:
            with open(filename, "w") as handle:
                handle.writelines(current_file_dict[filename])

        # End file contents after the patch and the OpenEditorAction was
        # applied
        expected_file_dict = {self.fa: ["1\n", "3\n"], self.fb: ["1\n", "3_changed\n"], "f_c": ["1\n", "2\n", "3\n"]}

        section = Section("")
        section.append(Setting("editor", ""))
        uut = OpenEditorAction()
        subprocess.call = self.fake_edit
        diff_dict = uut.apply_from_section(Result.from_values("origin", "msg", self.fa), file_dict, diff_dict, section)
        diff_dict = uut.apply_from_section(Result.from_values("origin", "msg", self.fb), file_dict, diff_dict, section)

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

        self.assertEqual(file_dict, expected_file_dict)
예제 #3
0
    def test_create_params_from_section_invalid(self):
        section = Section("name")
        section.append(Setting("bad_param", "value"))
        uut = FunctionMetadata.from_function(TestClass(5, 5).bad_function)

        with self.assertRaises(ValueError):
            uut.create_params_from_section(section)
예제 #4
0
    def test_apply(self):
        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\n"],
            "f_b": ["1\n", "3_changed\n"],
            "f_c": ["1\n", "2\n", "3\n"]
        }
        diff_dict = {"f_b": Diff()}
        diff_dict["f_b"].change_line(3, "3\n", "3_changed\n")

        section = Section("")
        section.append(Setting("editor", ""))
        uut = OpenEditorAction()
        subprocess.call = self.fake_edit
        diff_dict = uut.apply_from_section(
            Result("origin", "msg", "f_a"),
            file_dict,
            diff_dict,
            section)
        diff_dict = uut.apply_from_section(
            Result("origin", "msg", "f_b"),
            file_dict,
            diff_dict,
            section)

        for filename in diff_dict:
            file_dict[filename] = (
                diff_dict[filename].apply(file_dict[filename]))

        self.assertEqual(file_dict, expected_file_dict)
예제 #5
0
    def test_apply_section_filters(self):
        section_one = Section('apply')
        section_one.append(Setting('tags', 'save'))

        filtered = _apply_section_filter('section_tags', [], [section_one])

        self.assertEqual(filtered, [section_one])
예제 #6
0
class LanguageDefinitionTest(unittest.TestCase):
    def setUp(self):
        self.section = Section("any")
        self.section.append(Setting("language", "CPP"))

    def test_nonexistant_file(self):
        self.section.append(Setting("language", "bullshit"))

        with self.assertRaises(FileNotFoundError):
            LanguageDefinition.from_section(self.section)

    def test_loading(self):
        uut = LanguageDefinition.from_section(self.section)
        self.assertEqual(list(uut["extensions"]), [".c", ".cpp", ".h", ".hpp"])

    def test_key_contains(self):
        uut = LanguageDefinition.from_section(self.section)
        self.assertIn("extensions", uut)
        self.assertNotIn("randomstuff", uut)

    def test_external_coalang(self):
        with TemporaryDirectory() as directory:
            coalang_file = os.path.join(directory, "random_language.coalang")
            with open(coalang_file, "w") as file:
                file.write("extensions = .lol, .ROFL")
            uut = LanguageDefinition("random_language", coalang_dir=directory)
            self.assertIn("extensions", uut)
            self.assertEqual(list(uut["extensions"]), [".lol", ".ROFL"])
예제 #7
0
 def test_debug_run_with_no_return(self, runcall):
     section = Section('name')
     section.append(Setting('debug_bears', 'True'))
     my_bear = Bear(section, self.queue)
     args = ()
     kwargs = {}
     self.assertIsNone(my_bear.run_bear_from_section(args, kwargs))
예제 #8
0
class ESLintBearIgnoredFileTest(LocalBearTestHelper):
    def setUp(self):
        self.section = Section('')
        self.uut = ESLintBear(self.section, Queue())

    def test_lint_config_file(self):

        self.maxDiff = None
        config_filename = os.path.join(test_dir, '.eslintrc.js')

        self.section.append(Setting('eslint_config', config_filename))

        expected = Result.from_values(
            'ESLintBear',
            'File ignored by default.  Use a negated ignore pattern '
            '(like "--ignore-pattern \'!<relative/path/to/filename>\'") '
            'to override.',
            severity=RESULT_SEVERITY.NORMAL,
            file=config_filename,
        )

        Path(config_filename).touch()

        self.check_results(
            self.uut,
            ['{}'],
            [expected],
            create_tempfile=False,
            filename=config_filename,
        )
    def test_get_config_directory(self):
        old_isfile = os.path.isfile
        old_isdir = os.path.isdir

        section = Section("default")

        # Without section
        config_dir = get_config_directory(None)
        self.assertEqual(config_dir, os.getcwd())

        # With section, but without "config"
        os.path.isfile = lambda *args: True
        config_dir = get_config_directory(section)
        self.assertEqual(config_dir, os.getcwd())

        os.path.isfile = lambda *args: False
        config_dir = get_config_directory(section)
        self.assertEqual(config_dir, None)

        # With "config" in section
        section.append(Setting("config", "/path/to/dir/config"))

        os.path.isdir = lambda *args: True
        config_dir = get_config_directory(section)
        self.assertEqual(config_dir, "/path/to/dir/config")

        os.path.isdir = lambda *args: False
        config_dir = get_config_directory(section)
        self.assertEqual(config_dir, "/path/to/dir")

        os.path.isdir = old_isdir
        os.path.isfile = old_isfile
예제 #10
0
 def test_custom_continue(self, do_continue):
     section = Section('name')
     section.append(Setting('debug_bears', 'True'))
     bear = Bear(section, self.queue)
     args = ()
     self.assertEqual(Debugger(bear).do_quit(args), 1)
     pdb.Pdb.do_continue.assert_called_once_with(args)
예제 #11
0
class CPPCheckBearTest(unittest.TestCase):
    def setUp(self):
        self.section = Section('cppcheck')
        self.file_dict = {}
        self.queue = Queue()
        self.test_files = ['good_file.cpp', 'bad_file.cpp', 'warn_file.cpp']

    def get_results(self, files_to_check):
        files = [get_absolute_test_path(file) for file in files_to_check]
        for filename in files:
            with open(filename, 'r', encoding='utf-8') as content:
                self.file_dict[filename] = tuple(content.readlines())
        self.uut = CPPCheckBear(self.file_dict, self.section, self.queue)
        return list(self.uut.run_bear_from_section([], {}))

    def test_results_complete(self):
        self.section.append(Setting('enable', 'unusedFunction'))
        results = self.get_results(self.test_files)
        messages = [result.message for result in results]
        self.assertEqual(len(messages), 2)
        self.assertRegex(messages[0], 'Array .+ out of bounds')
        self.assertRegex(messages[1], "function 'f1' .+ never used")

    def test_no_enable_entered(self):
        results = self.get_results(self.test_files)
        messages = [result.message for result in results]
        self.assertEqual(len(messages), 1)
        self.assertRegex(messages[0], 'Array .+ out of bounds')
        self.assertNotRegex(messages[0], 'function .+ never used')
class ApertiumLintBearTest(LocalBearTestHelper):
    def setUp(self):
        self.section = Section('test section')
        self.uut = ApertiumLintBear(self.section, Queue())
        test_files = os.path.join(os.path.dirname(__file__), 'test_files')
        self.good_file = os.path.join(test_files, 'apertium-go-od.en.dix')
        self.bad_file = os.path.join(test_files, 'apertium-ba-ad.en.dix')
        self.config_file = os.path.join(test_files, 'apertium_config.json')

    def test_run(self):
        self.section.append(Setting('apertiumlint_config', ''))
        self.check_validity(self.uut, [], self.good_file)

        self.section.append(Setting('apertiumlint_config', self.config_file))
        self.check_validity(self.uut, [], self.good_file)

        self.section.append(Setting('apertiumlint_config', ''))
        self.check_validity(self.uut, [], self.bad_file, valid=False)

        self.section.append(Setting('apertiumlint_config', self.config_file))
        self.check_validity(self.uut, [], self.bad_file, valid=False)

    def test_paradigm_names(self):
        self.section.append(Setting('paradigm_names', 'False'))
        self.check_validity(self.uut, [], self.bad_file)
예제 #13
0
class SectionFillingTest(unittest.TestCase):

    def setUp(self):
        self.log_printer = LogPrinter(ConsolePrinter())
        self.section = Section("test")
        self.section.append(Setting("key", "val"))

    def test_fill_settings(self):
        sections = {"test": self.section}
        with simulate_console_inputs() as generator:
            fill_settings(sections,
                          acquire_settings,
                          self.log_printer)
            self.assertEqual(generator.last_input, -1)

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

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

        self.assertEqual(bool(self.section["use_spaces"]), True)
        self.assertEqual(len(self.section.contents), 3)

    def test_fill_section(self):
        # Use the same value for both because order isn't predictable (uses
        # dict)
        with simulate_console_inputs(0, 0):
            new_section = fill_section(self.section,
                                       acquire_settings,
                                       self.log_printer,
                                       [LocalTestBear,
                                        GlobalTestBear])

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

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

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

    def test_dependency_resolving(self):
        sections = {"test": self.section}
        self.section['bears'] = "DependentBear"
        with simulate_console_inputs("True"), bear_test_module():
            fill_settings(sections, acquire_settings, self.log_printer)

        self.assertEqual(bool(self.section["use_spaces"]), True)
예제 #14
0
class CPPCheckBearTest(unittest.TestCase):

    def setUp(self):
        self.section = Section('cppcheck')
        self.file_dict = {}
        self.queue = Queue()
        self.test_files = ['good_file.cpp', 'bad_file.cpp', 'warn_file.cpp']

    def get_results(self, files_to_check):
        files = [get_absolute_test_path(file) for file in files_to_check]
        for filename in files:
            with open(filename, 'r', encoding='utf-8') as content:
                self.file_dict[filename] = tuple(content.readlines())
        self.uut = CPPCheckBear(self.file_dict,
                                self.section,
                                self.queue)
        return list(self.uut.run_bear_from_section([], {}))

    def test_results_complete(self):
        self.section.append(Setting('enable', 'unusedFunction'))
        results = self.get_results(self.test_files)
        messages = [result.message for result in results]
        self.assertEqual(len(messages), 2)
        self.assertRegex(messages[0], 'Array .+ out of bounds')
        self.assertRegex(messages[1], "function 'f1' .+ never used")

    def test_no_enable_entered(self):
        results = self.get_results(self.test_files)
        messages = [result.message for result in results]
        self.assertEqual(len(messages), 1)
        self.assertRegex(messages[0], 'Array .+ out of bounds')
        self.assertNotRegex(messages[0], 'function .+ never used')
예제 #15
0
class ProcessingTest_PrintResult(unittest.TestCase):
    def setUp(self):
        self.section = Section("name")
        self.log_printer = LogPrinter(ConsolePrinter(), log_level=0)
        self.console_printer = ConsolePrinter()

    def test_autoapply_override(self):
        """
        Tests that the default_actions aren't automatically applied when the
        autoapply setting overrides that.
        """

        self.section.append(Setting("default_actions", "somebear: PrintDebugMessageAction"))

        # Verify that it would apply the action, i.e. remove the result
        results = [5, HiddenResult("origin", []), Result("somebear", "message", debug_msg="debug")]
        retval, newres = print_result(
            results,
            {},
            0,
            lambda *args: None,
            self.section,
            self.log_printer,
            {},
            [],
            console_printer=self.console_printer,
        )
        self.assertEqual(newres, [])
class ValidateAndInjectLanguageTest(unittest.TestCase):

    def setUp(self):
        self.section = Section('language section')
        self.section.append(Setting('language', 'python'))
        self.sections = {'language section': self.section}
        self.language = Language['python']

    def test__set_section_language(self):
        _set_section_language(self.sections)
        self.assertIsInstance(self.section.language, Language)
        self.assertEqual(str(self.language), str(self.section.language))

    def test__set_section_language_no_language(self):
        self.section['language'] = ''
        _set_section_language(self.sections)
        self.assertIsNone(self.section.language)

    def test__set_section_language_wrong_language(self):
        self.section['language'] = 'INVALID_LANGUAGE'

        logger = logging.getLogger()
        with self.assertLogs(logger, 'WARNING') as cm:
            _set_section_language(self.sections)
            self.assertRegex(
                cm.output[0],
                'Section `language section` contain invalid language setting. '
                '\'Language `INVALID_LANGUAGE` is not a valid language name or '
                'not recognized by coala.\'')
            self.assertIsNone(self.section.language)
예제 #17
0
class coalaDeleteOrigTest(unittest.TestCase):

    def setUp(self):
        self.section = Section("default")
        self.section.append(Setting("config", '/path/to/file'))

    @unittest.mock.patch('os.getcwd')
    def test_nonexistent_coafile(self, mocked_getcwd):
        mocked_getcwd.return_value = None
        retval = coala_delete_orig.main()
        self.assertEqual(retval, 255)

    @unittest.mock.patch('coalib.parsing.Globbing.glob')
    def test_remove_exception(self, mock_glob):
        # Non existent file
        mock_glob.return_value = ["non_existent_file"]
        with retrieve_stdout() as stdout:
            retval = coala_delete_orig.main(section=self.section)
            output = stdout.getvalue()
            self.assertEqual(retval, 0)
            self.assertIn("Couldn't delete", output)

        # Directory instead of file
        with tempfile.TemporaryDirectory() as filename, \
                retrieve_stdout() as stdout:
            mock_glob.return_value = [filename]
            retval = coala_delete_orig.main(section=self.section)
            output = stdout.getvalue()
            self.assertEqual(retval, 0)
            self.assertIn("Couldn't delete", output)
예제 #18
0
class CPDBearTest(unittest.TestCase):
    def setUp(self):
        self.base_test_path = os.path.abspath(
            os.path.join(os.path.dirname(__file__),
                         'code_duplication_samples'))

        self.section = Section('default')
        self.section.append(Setting('language', 'java'))
        self.queue = Queue()

    def test_good_file(self):
        good_file = os.path.join(self.base_test_path, 'good_code.java')

        with open(good_file) as file:
            good_filelines = file.readlines()

        self.uut = CPDBear({good_file: good_filelines}, self.section,
                           self.queue)

        result = list(self.uut.run_bear_from_section([], {}))

        self.assertEqual(result, [])

    def test_bad_file(self):

        bad_file = os.path.join(self.base_test_path, 'bad_code.java')

        with open(bad_file) as file:
            bad_filelines = file.readlines()

        self.uut = CPDBear({bad_file: bad_filelines}, self.section, self.queue)

        result = list(self.uut.run_bear_from_section([], {}))

        self.assertNotEqual(result, [])
예제 #19
0
    def test_config_failure_wrong_indent_size(self):
        section = Section("name")
        section.append(Setting('indent_size', 3))
        bear = DartLintBear(section, Queue())

        with self.assertRaises(AssertionError):
            self.check_validity(bear, [], good_file)
예제 #20
0
class JSONFormatBearTest(LocalBearTestHelper):

    def setUp(self):
        self.section = Section('name')
        self.uut = JSONFormatBear(self.section, Queue())

    def test_valid(self):
        self.assertLinesValid(self.uut, ['{',
                                         '    "a": 5,',
                                         '    "b": 5',
                                         '}'])
        self.assertLinesValid(self.uut, ['{',
                                         '    "b": 5,',
                                         '    "a": 5',
                                         '}'])

    def test_invalid(self):
        self.assertLinesInvalid(self.uut, [""])
        self.assertLinesInvalid(self.uut, ["random stuff"])
        self.assertLinesInvalid(self.uut, ['{"a":5,"b":5}'])

    def test_sorting(self):
        self.section.append(Setting("json_sort", "true"))
        self.assertLinesInvalid(self.uut, ['{',
                                           '    "b": 5,',
                                           '    "a": 5',
                                           '}'])

    def test_indent(self):
        test_code = ['{', '   "b": 5,', '   "a": 5', '}']
        self.assertLinesInvalid(self.uut, test_code)

        self.section.append(Setting("tab_width", "3"))
        self.assertLinesValid(self.uut, test_code)
    def test_validate_use_spaces(self):
        section = Section('name')
        section.append(Setting('use_spaces', True))
        bear = HappinessLintBear(section, Queue())

        with self.assertRaisesRegex(ValueError, self.USE_SPACE_ERR_MSG):
            bear.run(bad_file, use_spaces=True)
예제 #22
0
    def test_config_failure_use_spaces(self):
        section = Section("name")
        section.append(Setting('use_spaces', False))
        bear = DartLintBear(section, Queue())

        with self.assertRaises(AssertionError):
            self.check_validity(bear, [], good_file)
예제 #23
0
class coalaDeleteOrigTest(unittest.TestCase):
    def setUp(self):
        self.section = Section("default")
        self.section.append(Setting("config", '/path/to/file'))

    @unittest.mock.patch('os.getcwd')
    def test_nonexistent_coafile(self, mocked_getcwd):
        mocked_getcwd.return_value = None
        retval = coala_delete_orig.main()
        self.assertEqual(retval, 255)

    @unittest.mock.patch('coalib.parsing.Globbing.glob')
    def test_remove_exception(self, mock_glob):
        # Non existent file
        mock_glob.return_value = ["non_existent_file"]
        with retrieve_stdout() as stdout:
            retval = coala_delete_orig.main(section=self.section)
            output = stdout.getvalue()
            self.assertEqual(retval, 0)
            self.assertIn("Couldn't delete", output)

        # Directory instead of file
        with tempfile.TemporaryDirectory() as filename, \
                retrieve_stdout() as stdout:
            mock_glob.return_value = [filename]
            retval = coala_delete_orig.main(section=self.section)
            output = stdout.getvalue()
            self.assertEqual(retval, 0)
            self.assertIn("Couldn't delete", output)
예제 #24
0
class coalaDeleteOrigTest(unittest.TestCase):
    def setUp(self):
        self.section = Section("default")
        self.section.append(Setting("config", '/path/to/file'))

    def test_nonexistent_coafile(self):
        old_getcwd = os.getcwd
        os.getcwd = lambda *args: None
        with retrieve_stdout() as stdout:
            retval = coala_delete_orig.main()
            self.assertIn("Can only delete .orig files if ", stdout.getvalue())
            self.assertEqual(retval, 255)
        os.getcwd = old_getcwd

    def test_remove_exception(self):
        old_glob = Globbing.glob

        # Non existent file
        with retrieve_stdout() as stdout:
            Globbing.glob = lambda *args: ["non_existent_file"]
            retval = coala_delete_orig.main(section=self.section)
            output = stdout.getvalue()
            self.assertEqual(retval, 0)
            self.assertIn("Couldn't delete", output)

        # Directory instead of file
        with tempfile.TemporaryDirectory() as filename, \
                retrieve_stdout() as stdout:
            Globbing.glob = lambda *args: [filename]
            retval = coala_delete_orig.main(section=self.section)
            output = stdout.getvalue()
            self.assertEqual(retval, 0)
            self.assertIn("Couldn't delete", output)

        Globbing.glob = old_glob
예제 #25
0
class ProcessingTest_PrintResult(unittest.TestCase):
    def setUp(self):
        self.section = Section('name')
        self.log_printer = LogPrinter(ConsolePrinter(), log_level=0)
        self.console_printer = ConsolePrinter()

    def test_autoapply_override(self):
        """
        Tests that the default_actions aren't automatically applied when the
        autoapply setting overrides that.
        """

        self.section.append(
            Setting('default_actions', 'somebear: PrintDebugMessageAction'))

        # Verify that it would apply the action, i.e. remove the result
        results = [
            5,
            HiddenResult('origin', []),
            Result('somebear', 'message', debug_msg='debug')
        ]
        retval, newres = print_result(results, {},
                                      0,
                                      lambda *args: None,
                                      self.section,
                                      self.log_printer, {}, [],
                                      console_printer=self.console_printer)
        self.assertEqual(newres, [])
예제 #26
0
    def test_update(self):
        cli = Section("cli", None)
        conf = Section("conf", None)

        self.assertRaises(TypeError, cli.update, 4)

        cli.append(Setting("key1", "value11"))
        cli.append(Setting("key2", "value12"))
        conf.append(Setting("key1", "value21"))
        conf.append(Setting("key3", "value23"))

        # Values are overwritten, new keys appended
        self.assertEqual(str(conf.copy().update(cli)),
                         "conf {key1 : 'value11', key3 : 'value23', "
                         "key2 : 'value12'}")

        cli.defaults = Section("clidef", None)
        cli.defaults.append(Setting("def1", "dval1"))

        self.assertEqual(str(conf.copy().update(cli).defaults),
                         "clidef {def1 : 'dval1'}")

        conf.defaults = Section("confdef", None)
        conf.defaults.append(Setting("def2", "dval2"))

        self.assertEqual(str(conf.copy().update(cli).defaults),
                         "confdef {def2 : 'dval2', def1 : 'dval1'}")
예제 #27
0
class ProcessingTest_PrintResult(unittest.TestCase):

    def setUp(self):
        self.section = Section('name')
        self.log_printer = LogPrinter(ConsolePrinter(), log_level=0)

    def test_autoapply_override(self):
        """
        Tests that the default_actions aren't automatically applied when the
        autoapply setting overrides that.
        """
        self.section.append(Setting('default_actions',
                                    'somebear: PrintDebugMessageAction'))

        # Verify that it would apply the action, i.e. remove the result
        results = [5, HiddenResult('origin', []),
                   Result('somebear', 'message', debug_msg='debug')]
        retval, newres = print_result(results, {}, 0, lambda *args: None,
                                      self.section, self.log_printer, {}, [])
        self.assertEqual(newres, [])

        # Override and verify that result is unprocessed, i.e. not gone
        self.section.append(Setting('autoapply', 'false'))
        retval, newres = print_result(results, {}, 0, lambda *args: None,
                                      self.section, self.log_printer, {}, [])
        self.assertNotEqual(newres, [])
예제 #28
0
    def test_apply_rename(self):
        # Initial file contents, *before* a patch was applied
        file_dict = {
            self.fa: ["1\n", "2\n", "3\n"]}

        # A patch that was applied for some reason to make things complicated
        file_diff_dict = {}
        diff = Diff(file_dict[self.fa], rename=self.fa+".renamed")
        diff.change_line(3, "3\n", "3_changed\n")
        ApplyPatchAction().apply(
            Result("origin", "msg", diffs={self.fa: diff}),
            file_dict,
            file_diff_dict)
        # End file contents after the patch and the OpenEditorAction was
        # applied
        expected_file_dict = {
            self.fa: ["1\n", "3_changed\n"]}

        section = Section("")
        section.append(Setting("editor", ""))
        uut = OpenEditorAction()
        subprocess.call = self.fake_edit
        diff_dict = uut.apply_from_section(
            Result.from_values("origin", "msg", self.fa),
            file_dict,
            file_diff_dict,
            section)

        for filename in diff_dict:
            file_dict[filename] = (
                file_diff_dict[filename].modified)

        self.assertEqual(file_dict, expected_file_dict)
        open(self.fa, 'w').close()
예제 #29
0
    def test_extract_aspects_from_section(self):
        section = Section('section')
        section.append(Setting(
            'aspects',
            'spelling, commitmessage, methodsmell'))
        # Custom taste for ColonExistence
        section.append(Setting('commitmessage:shortlog_colon', 'false'))
        section.language = Language['py 3.4']

        aspects = extract_aspects_from_section(section)
        spelling_instance = Root.Spelling('py 3.4')
        colon_existence_instance = (
            Root.Metadata.CommitMessage.Shortlog.ColonExistence(
                'py 3.4', shortlog_colon=False))
        method_smell_instance = Root.Smell.MethodSmell('py 3.4')
        trailing_period_instance = (
            Root.Metadata.CommitMessage.Shortlog.TrailingPeriod('py 3.4'))

        self.assertIsInstance(aspects, AspectList)
        self.assertEqual(aspects.get('spelling'), spelling_instance)
        self.assertEqual(aspects.get('colonexistence'),
                         colon_existence_instance)
        self.assertEqual(aspects.get('methodsmell'), method_smell_instance)
        self.assertEqual(aspects.get('TrailingPeriod'),
                         trailing_period_instance)
    def test_get_config_directory(self):
        old_isfile = os.path.isfile
        old_isdir = os.path.isdir

        section = Section("default")

        # Without section
        config_dir = get_config_directory(None)
        self.assertEqual(config_dir, os.getcwd())

        # With section, but without "config"
        os.path.isfile = lambda *args: True
        config_dir = get_config_directory(section)
        self.assertEqual(config_dir, os.getcwd())

        os.path.isfile = lambda *args: False
        config_dir = get_config_directory(section)
        self.assertEqual(config_dir, None)

        # With "config" in section
        section.append(Setting("config", "/path/to/dir/config"))

        os.path.isdir = lambda *args: True
        config_dir = get_config_directory(section)
        self.assertEqual(config_dir, "/path/to/dir/config")

        os.path.isdir = lambda *args: False
        config_dir = get_config_directory(section)
        self.assertEqual(config_dir, "/path/to/dir")

        os.path.isdir = old_isdir
        os.path.isfile = old_isfile
예제 #31
0
 def test_string_conversion(self):
     uut = Section("name")
     self.assertEqual(str(uut), "name {}")
     uut.append(Setting("key", "value"))
     self.assertEqual(str(uut), "name {key : value}")
     uut.append(Setting("another_key", "another_value"))
     self.assertEqual(str(uut), "name {key : value, another_key : another_value}")
예제 #32
0
    def test_update(self):
        cli = Section('cli', None)
        conf = Section('conf', None)

        self.assertRaises(TypeError, cli.update, 4)

        cli.append(Setting('key1', 'value11'))
        cli.append(Setting('key2', 'value12'))
        conf.append(Setting('key1', 'value21'))
        conf.append(Setting('key3', 'value23'))

        # Values are overwritten, new keys appended
        self.assertEqual(str(conf.copy().update(cli)),
                         "conf {key1 : 'value11', key3 : 'value23', "
                         "key2 : 'value12'}")

        cli.defaults = Section('clidef', None)
        cli.defaults.append(Setting('def1', 'dval1'))

        self.assertEqual(str(conf.copy().update(cli).defaults),
                         "clidef {def1 : 'dval1'}")

        conf.defaults = Section('confdef', None)
        conf.defaults.append(Setting('def2', 'dval2'))

        self.assertEqual(str(conf.copy().update(cli).defaults),
                         "confdef {def2 : 'dval2', def1 : 'dval1'}")
class ValidateAndInjectLanguageTest(unittest.TestCase):

    def setUp(self):
        self.section = Section('language section')
        self.section.append(Setting('language', 'python'))
        self.sections = {'language section': self.section}
        self.language = Language['python']

    def test__set_section_language(self):
        _set_section_language(self.sections)
        self.assertIsInstance(self.section.language, Language)
        self.assertEqual(str(self.language), str(self.section.language))

    def test__set_section_language_no_language(self):
        self.section['language'] = ''
        _set_section_language(self.sections)
        self.assertIsNone(self.section.language)

    def test__set_section_language_wrong_language(self):
        self.section['language'] = 'INVALID_LANGUAGE'

        logger = logging.getLogger()
        with self.assertLogs(logger, 'WARNING') as cm:
            _set_section_language(self.sections)
            self.assertRegex(
                cm.output[0],
                'Section `language section` contain invalid language setting. '
                '\'Language `INVALID_LANGUAGE` is not a valid language name or '
                'not recognized by coala.\'')
            self.assertIsNone(self.section.language)
예제 #34
0
    def test_update(self):
        cli = Section("cli", None)
        conf = Section("conf", None)

        self.assertRaises(TypeError, cli.update, 4)

        cli.append(Setting("key1", "value11"))
        cli.append(Setting("key2", "value12"))
        conf.append(Setting("key1", "value21"))
        conf.append(Setting("key3", "value23"))

        # Values are overwritten, new keys appended
        self.assertEqual(str(conf.copy().update(cli)),
                         "conf {key1 : 'value11', key3 : 'value23', "
                         "key2 : 'value12'}")

        cli.defaults = Section("clidef", None)
        cli.defaults.append(Setting("def1", "dval1"))

        self.assertEqual(str(conf.copy().update(cli).defaults),
                         "clidef {def1 : 'dval1'}")

        conf.defaults = Section("confdef", None)
        conf.defaults.append(Setting("def2", "dval2"))

        self.assertEqual(str(conf.copy().update(cli).defaults),
                         "confdef {def2 : 'dval2', def1 : 'dval1'}")
예제 #35
0
    def test_config_failure_wrong_indent_size(self):
        section = Section('name')
        section.append(Setting('indent_size', 3))
        bear = DartLintBear(section, Queue())

        with self.assertRaisesRegex(AssertionError, self.DART_VALUE_ERROR_RE):
            self.check_validity(bear, [], good_file)
예제 #36
0
 def test_debug_run_with_no_return(self, runcall):
     section = Section('name')
     section.append(Setting('debug_bears', 'True'))
     my_bear = Bear(section, self.queue)
     args = ()
     kwargs = {}
     self.assertIsNone(my_bear.run_bear_from_section(args, kwargs))
예제 #37
0
    def test_apply_rename(self):
        # Initial file contents, *before* a patch was applied
        file_dict = {self.fa: ['1\n', '2\n', '3\n']}

        # A patch that was applied for some reason to make things complicated
        file_diff_dict = {}
        diff = Diff(file_dict[self.fa], rename=self.fa + '.renamed')
        diff.change_line(3, '3\n', '3_changed\n')
        ApplyPatchAction().apply(
            Result('origin', 'msg', diffs={self.fa: diff}), file_dict,
            file_diff_dict)
        # End file contents after the patch and the OpenEditorAction was
        # applied
        expected_file_dict = {self.fa: ['1\n', '3_changed\n']}

        section = Section('')
        section.append(Setting('editor', 'vim'))
        uut = OpenEditorAction()
        subprocess.call = self.fake_edit
        diff_dict = uut.apply_from_section(
            Result.from_values('origin', 'msg', self.fa), file_dict,
            file_diff_dict, section)

        for filename in diff_dict:
            file_dict[filename] = (file_diff_dict[filename].modified)

        self.assertEqual(file_dict, expected_file_dict)
        open(self.fa, 'w').close()
예제 #38
0
class SectionFillingTest(unittest.TestCase):

    def setUp(self):
        self.log_printer = LogPrinter(ConsolePrinter())
        self.section = Section('test')
        self.section.append(Setting('key', 'val'))

    def test_fill_settings(self):
        sections = {'test': self.section}
        with simulate_console_inputs() as generator:
            fill_settings(sections,
                          acquire_settings,
                          self.log_printer)
            self.assertEqual(generator.last_input, -1)

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

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

        self.assertEqual(bool(self.section['use_spaces']), True)
        self.assertEqual(len(self.section.contents), 3)

    def test_fill_section(self):
        # Use the same value for both because order isn't predictable (uses
        # dict)
        with simulate_console_inputs(0, 0):
            new_section = fill_section(self.section,
                                       acquire_settings,
                                       self.log_printer,
                                       [LocalTestBear,
                                        GlobalTestBear])

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

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

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

    def test_dependency_resolving(self):
        sections = {'test': self.section}
        self.section['bears'] = 'DependentBear'
        with simulate_console_inputs('True'), bear_test_module():
            fill_settings(sections, acquire_settings, self.log_printer)

        self.assertEqual(bool(self.section['use_spaces']), True)
예제 #39
0
    class LocalBearTest(LocalBearTestHelper):

        def setUp(self):
            self.section = Section('name')
            self.uut = bear(self.section,
                            queue.Queue())
            for name, value in settings.items():
                self.section.append(Setting(name, value))

        def test_valid_files(self):
            self.assertIsInstance(valid_files, (list, tuple))
            for file in valid_files:
                self.check_validity(self.uut,
                                    file.splitlines(keepends=True),
                                    filename,
                                    valid=True,
                                    force_linebreaks=force_linebreaks,
                                    create_tempfile=create_tempfile,
                                    tempfile_kwargs=tempfile_kwargs)

        def test_invalid_files(self):
            self.assertIsInstance(invalid_files, (list, tuple))
            for file in invalid_files:
                self.check_validity(self.uut,
                                    file.splitlines(keepends=True),
                                    filename,
                                    valid=False,
                                    force_linebreaks=force_linebreaks,
                                    create_tempfile=create_tempfile,
                                    tempfile_kwargs=tempfile_kwargs)
예제 #40
0
    def test_create_params_from_section_invalid(self):
        section = Section("name")
        section.append(Setting("bad_param", "value"))
        uut = FunctionMetadata.from_function(TestClass(5, 5).bad_function)

        with self.assertRaises(ValueError):
            uut.create_params_from_section(section)
class ApertiumLintBearTest(LocalBearTestHelper):

    def setUp(self):
        self.section = Section('test section')
        self.uut = ApertiumLintBear(self.section, Queue())
        test_files = os.path.join(os.path.dirname(__file__), 'test_files')
        self.good_file = os.path.join(test_files, 'apertium-go-od.en.dix')
        self.bad_file = os.path.join(test_files, 'apertium-ba-ad.en.dix')
        self.config_file = os.path.join(test_files, 'apertium_config.json')

    def test_run(self):
        self.section.append(Setting('apertiumlint_config', ''))
        self.check_validity(self.uut, [], self.good_file)

        self.section.append(Setting('apertiumlint_config', self.config_file))
        self.check_validity(self.uut, [], self.good_file)

        self.section.append(Setting('apertiumlint_config', ''))
        self.check_invalidity(self.uut, [], self.bad_file)

        self.section.append(Setting('apertiumlint_config', self.config_file))
        self.check_invalidity(self.uut, [], self.bad_file)

    def test_paradigm_names(self):
        self.section.append(Setting('paradigm_names', 'False'))
        self.check_validity(self.uut, [], self.bad_file)
예제 #42
0
class JSHintBearTest(LocalBearTestHelper):

    def setUp(self):
        self.section = Section("test section")
        self.uut = JSHintBear(self.section, Queue())
        self.test_file1 = os.path.join(os.path.dirname(__file__),
                                       "test_files",
                                       "jshint_test1.js")
        self.test_file2 = os.path.join(os.path.dirname(__file__),
                                       "test_files",
                                       "jshint_test2.js")
        self.conf_file = os.path.join(os.path.dirname(__file__),
                                      "test_files",
                                      "jshint_config.js")

    def test_run(self):
        # Test a file with errors and warnings
        self.assertLinesInvalid(
            self.uut,
            [],
            self.test_file2)

        # Test a file with a warning which can be changed using a config
        self.assertLinesInvalid(
            self.uut,
            [],
            self.test_file1)

        # Test if warning disappears
        self.section.append(Setting("jshint_config", self.conf_file))
        self.assertLinesValid(
            self.uut,
            [],
            self.test_file1)
예제 #43
0
class coalaDeleteOrigTest(unittest.TestCase):

    def setUp(self):
        self.section = Section("default")
        self.section.append(Setting("config", '/path/to/file'))

    def test_nonexistent_coafile(self):
        old_getcwd = os.getcwd
        os.getcwd = lambda *args: None
        retval = coala_delete_orig.main()
        self.assertEqual(retval, 255)
        os.getcwd = old_getcwd

    def test_remove_exception(self):
        old_glob = Globbing.glob

        # Non existent file
        with retrieve_stdout() as stdout:
            Globbing.glob = lambda *args: ["non_existent_file"]
            retval = coala_delete_orig.main(section=self.section)
            output = stdout.getvalue()
            self.assertEqual(retval, 0)
            self.assertIn("Couldn't delete", output)

        # Directory instead of file
        with tempfile.TemporaryDirectory() as filename, \
                retrieve_stdout() as stdout:
            Globbing.glob = lambda *args: [filename]
            retval = coala_delete_orig.main(section=self.section)
            output = stdout.getvalue()
            self.assertEqual(retval, 0)
            self.assertIn("Couldn't delete", output)

        Globbing.glob = old_glob
예제 #44
0
class MapAmbiguousSettingToAspectTest(unittest.TestCase):

    EXPECTED = {'remove_unreachable_code': False,
                'minimum_clone_tokens': 10,
                'use_spaces': True,
                }

    def setUp(self):
        self.section = Section('aspect section')
        self.bear = RunDecoratedBear(self.section, None)

    def test_mapping(self):
        self.section.aspects = AspectList([
            get_aspect('Indentation')('py', indent_type='tab'),
        ])
        result = self.bear.execute()
        expected = self.EXPECTED.copy()
        expected['use_spaces'] = False
        self.assertEqual(expected, dict(result))

    def test_setting_priority(self):
        self.section.aspects = AspectList([
            get_aspect('Indentation')('py', indent_type='tab'),
        ])
        self.section.append(Setting('use_spaces', True))
        result = self.bear.execute()
        expected = self.EXPECTED.copy()
        self.assertEqual(expected, dict(result))
예제 #45
0
    class LocalBearTest(LocalBearTestHelper):

        def setUp(self):
            self.section = Section('name')
            self.uut = bear(self.section,
                            queue.Queue())
            for name, value in settings.items():
                self.section.append(Setting(name, value))

        def test_valid_files(self):
            self.assertIsInstance(valid_files, (list, tuple))
            for file in valid_files:
                self.check_validity(self.uut,
                                    file,
                                    filename,
                                    valid=True,
                                    force_linebreaks=force_linebreaks,
                                    create_tempfile=create_tempfile,
                                    tempfile_kwargs=tempfile_kwargs)

        def test_invalid_files(self):
            self.assertIsInstance(invalid_files, (list, tuple))
            for file in invalid_files:
                self.check_validity(self.uut,
                                    file,
                                    filename,
                                    valid=False,
                                    force_linebreaks=force_linebreaks,
                                    create_tempfile=create_tempfile,
                                    tempfile_kwargs=tempfile_kwargs)
예제 #46
0
class DoNothingActionTest(unittest.TestCase):

    def setUp(self):
        self.uut = DoNothingAction()
        self.file_dict = {'a': ['a\n', 'b\n', 'c\n'], 'b': ['old_first\n']}
        self.diff_dict = {'a': Diff(self.file_dict['a']),
                          'b': Diff(self.file_dict['b'])}
        self.diff_dict['a'].add_lines(1, ['test\n'])
        self.diff_dict['a'].delete_line(3)
        self.diff_dict['b'].add_lines(0, ['first\n'])

        self.test_result = Result('origin', 'message', diffs=self.diff_dict)
        self.section = Section('name')
        self.section.append(Setting('colored', 'false'))

    def test_is_applicable(self):
        diff = Diff([], rename='new_name')
        result = Result('', '', diffs={'f': diff})

        self.assertTrue(self.uut.is_applicable(result, {}, {'f': diff}))

    def test_apply(self):
        with retrieve_stdout() as stdout:
            self.assertEqual(self.uut.apply(self.test_result,
                                            self.file_dict,
                                            {}), None)
예제 #47
0
 def test_custom_continue(self, do_continue):
     section = Section('name')
     section.append(Setting('debug_bears', 'True'))
     bear = Bear(section, self.queue)
     args = ()
     self.assertEqual(Debugger(bear).do_quit(args), 1)
     pdb.Pdb.do_continue.assert_called_once_with(args)
예제 #48
0
    def test_config_failure_use_spaces(self):
        section = Section('name')
        section.append(Setting('use_spaces', False))
        bear = DartLintBear(section, Queue())

        with self.assertRaisesRegex(AssertionError, self.DART_VALUE_ERROR_RE):
            self.check_validity(bear, [], good_file)
예제 #49
0
class ShowPatchActionTest(unittest.TestCase):

    def setUp(self):
        self.uut = ShowPatchAction()
        self.file_dict = {"a": ["a\n", "b\n", "c\n"], "b": ["old_first\n"]}
        diff_dict = {"a": Diff(self.file_dict['a']),
                     "b": Diff(self.file_dict['b'])}
        diff_dict["a"].add_lines(1, ["test\n"])
        diff_dict["a"].delete_line(3)
        diff_dict["b"].add_lines(0, ["first\n"])

        self.test_result = Result("origin", "message", diffs=diff_dict)
        self.section = Section("name")
        self.section.append(Setting("colored", "false"))

    def test_is_applicable(self):
        self.assertFalse(self.uut.is_applicable(1, None, None))
        self.assertFalse(self.uut.is_applicable(Result("o", "m"), None, None))
        self.assertTrue(self.uut.is_applicable(self.test_result, None, None))

    def test_apply(self):
        with retrieve_stdout() as stdout:
            self.assertEqual(self.uut.apply_from_section(self.test_result,
                                                         self.file_dict,
                                                         {},
                                                         self.section),
                             {})
            self.assertEqual(stdout.getvalue(),
                             "|----|    | a\n"
                             "|    |++++| a\n"
                             "|   1|   1| a\n"
                             "|    |   2|+test\n"
                             "|   2|   3| b\n"
                             "|   3|    |-c\n"
                             "|----|    | b\n"
                             "|    |++++| b\n"
                             "|    |   1|+first\n"
                             "|   1|   2| old_first\n")

    def test_apply_with_previous_patches(self):
        with retrieve_stdout() as stdout:
            previous_diffs = {"a": Diff(self.file_dict['a'])}
            previous_diffs["a"].change_line(2, "b\n", "b_changed\n")
            self.assertEqual(self.uut.apply_from_section(self.test_result,
                                                         self.file_dict,
                                                         previous_diffs,
                                                         self.section),
                             previous_diffs)
            self.assertEqual(stdout.getvalue(),
                             "|----|    | a\n"
                             "|    |++++| a\n"
                             "|   1|   1| a\n"
                             "|    |   2|+test\n"
                             "|   2|   3| b_changed\n"
                             "|   3|    |-c\n"
                             "|----|    | b\n"
                             "|    |++++| b\n"
                             "|    |   1|+first\n"
                             "|   1|   2| old_first\n")
예제 #50
0
파일: SectionTest.py 프로젝트: yland/coala
 def test_string_conversion(self):
     uut = Section("name")
     self.assertEqual(str(uut), "name {}")
     uut.append(Setting("key", "value"))
     self.assertEqual(str(uut), "name {key : 'value'}")
     uut.append(Setting("another_key", "another_value"))
     self.assertEqual(str(uut),
                      "name {key : 'value', another_key : 'another_value'}")
예제 #51
0
 def test_profiler_with_debugger(self):
     section = Section('name')
     section.append(Setting('debug_bears', 'tRuE'))
     section.append(Setting('profile', 'tRuE'))
     with self.assertRaisesRegex(
             ValueError,
             'Cannot run debugger and profiler at the same time.'):
         Bear(section, self.queue)
예제 #52
0
 def test_profiler_with_false_setting(self, profile_run):
     args = ()
     kwargs = {}
     section = Section('name')
     section.append(Setting('profile', '0'))
     bear = TestThreeBear(section, self.queue)
     self.assertIsNone(bear.run_bear_from_section(args, kwargs))
     assert not profile_run.called
예제 #53
0
 def test_string_conversion(self):
     uut = Section('name')
     self.assertEqual(str(uut), 'name {}')
     uut.append(Setting('key', 'value'))
     self.assertEqual(str(uut), "name {key : 'value'}")
     uut.append(Setting('another_key', 'another_value'))
     self.assertEqual(
         str(uut), "name {key : 'value', another_key : 'another_value'}")
예제 #54
0
    def test_section_tags_filter_no_tags(self):
        filter = available_filters['section_tags']

        section = Section('sample')
        section.append(Setting('tags', 'save'))

        flag = filter(section, [])
        self.assertTrue(flag)
예제 #55
0
 def test_bear_dirs(self):
     section = Section('section', None)
     empty_bear_dirs_len = len(section.bear_dirs())
     section.append(Setting('bear_dirs', 'test1, test2 (1)'))
     self.assertEqual(len(section.bear_dirs()), empty_bear_dirs_len + 2)
     # Verify if bear directories are properly escaped
     root = get_config_directory(section)
     path = os.path.join(glob_escape(root), glob_escape('test2 (1)'), '**')
     self.assertIn(path, section.bear_dirs())
예제 #56
0
파일: SectionTest.py 프로젝트: mani87/coala
 def test_extract_aspects_from_section_no_language(self):
     section = Section('section')
     section.append(Setting('aspects', 'commitmessage'))
     with self.assertRaisesRegex(
             AttributeError,
             'Language was not found in configuration file. '
             'Usage of aspect-based configuration must include '
             'language information.'):
         extract_aspects_from_section(section)
예제 #57
0
class LanguageDefinitionTest(unittest.TestCase):
    def setUp(self):
        self.section = Section('any')
        self.section.append(Setting('language', 'CPP'))

    def test_key_contains(self):
        uut = LanguageDefinition.from_section(self.section)
        self.assertIn('extensions', uut)
        self.assertNotIn('randomstuff', uut)
예제 #58
0
 def test_normal_running(self):
     with tempfile.TemporaryDirectory() as directory:
         temporary = tempfile.mkstemp(suffix='.orig', dir=directory)
         os.close(temporary[0])
         section = Section('')
         section.append(Setting('project_dir', PathArg(directory)))
         retval = coala_delete_orig.main(section=section)
         self.assertEqual(retval, 0)
         self.assertFalse(os.path.isfile(temporary[1]))