def setUp(self):
     self.section1 = Section("")
     self.section1.append(Setting('language', 'python3'))
     self.python_uut = AnnotationBear(self.section1, Queue())
     self.section2 = Section("")
     self.section2.append(Setting('language', 'c'))
     self.c_uut = AnnotationBear(self.section2, Queue())
    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)
    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)
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 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_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)
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"])
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_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()
Exemple #10
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))
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)
    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
    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)
    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)
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)
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)
Exemple #17
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)
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
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)
Exemple #20
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))
Exemple #21
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, [])
    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 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, [])
Exemple #24
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)
    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)
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)
Exemple #27
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}")
Exemple #28
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)
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")
    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])
Exemple #31
0
 def setUp(self):
     self.ib_check_prerequisites = URLBear.check_prerequisites
     self.section = Section('')
     URLBear.check_prerequisites = lambda *args: True
     self.uut = URLBear(self.section, Queue())
Exemple #32
0
 def test_extract_aspects_from_section_incorrect_language(self):
     section = Section('section')
     section.append(Setting('aspects', 'commitmessage'))
     section.append(Setting('language', 'not a language'))
     with self.assertRaises(AttributeError):
         extract_aspects_from_section(section)
Exemple #33
0
    def test_set_default_section(self):
        section = Section('section')

        section.set_default_section({})
        self.assertIsNone(section.defaults)

        sections = {'cli': Section('cli')}
        section.set_default_section(sections)
        self.assertEqual(section.defaults, sections['cli'])

        sections = {'all': Section('all'), 'all.python': Section('all.python')}
        sections['all.python'].set_default_section(sections)
        self.assertEqual(sections['all.python'].defaults, sections['all'])
        sections['all.python.codestyle'] = Section('all.python.codestyle')
        sections['all.python.codestyle'].set_default_section(sections)
        self.assertEqual(sections['all.python.codestyle'].defaults,
                         sections['all.python'])
        sections['all.c.codestyle'] = Section('all.c.codestyle')
        sections['all.c.codestyle'].set_default_section(sections)
        self.assertEqual(sections['all.c.codestyle'].defaults, sections['all'])
class KeywordBearDiffTest(unittest.TestCase):
    def setUp(self):
        self.section = Section('')
        self.section.append(Setting('language', 'python3'))
        self.section.append(Setting('keywords', 'TODO'))
        self.uut = KeywordBear(self.section, Queue())

        self.annotation_bear_result_type = namedtuple('result', ['contents'])
        self.dep_results = {
            'AnnotationBear': HiddenResult('AnnotationBear', {'comments': ()})
        }

    def test_empty_keyword(self):
        text = ['a == b']

        with execute_bear(self.uut,
                          filename='F',
                          file=text,
                          dependency_results=self.dep_results) as result:
            self.assertEqual(result, [])

    def test_keyword_in_comment(self):
        dep_results = {'AnnotationBear': {}}
        text = ['# todo 123']
        with execute_bear(self.uut,
                          filename='F',
                          file=text,
                          dependency_results=dep_results) as result:
            self.assertEqual(result[0].diffs, {})
            self.assertEqual(result[0].affected_code[0].start.line, 1)
            self.assertEqual(len(result), 1)

        dep_results = {
            'AnnotationBear': HiddenResult('AnnotationBear', {'comments': 123})
        }
        with execute_bear(self.uut,
                          filename='F',
                          file=text,
                          dependency_results=dep_results) as result:
            self.assertEqual(result[0].diffs, {})
            self.assertEqual(result[0].affected_code[0].start.line, 1)
            self.assertEqual(len(result), 1)

        dep_results = {'AnnotationBear': HiddenResult('AnnotationBear', 123)}
        with execute_bear(self.uut,
                          filename='F',
                          file=text,
                          dependency_results=dep_results) as result:
            self.assertEqual(result[0].diffs, {})
            self.assertEqual(result[0].affected_code[0].start.line, 1)
            self.assertEqual(len(result), 1)

    def test_keyword_not_in_comment(self):
        text = ['# comment 123\n', 'a = "TODO"\n']
        comments = [SourceRange.from_values('F', 1, 1, 1, 40)]
        dep_results = {
            'AnnotationBear':
            [self.annotation_bear_result_type({'comments': comments})]
        }

        with execute_bear(self.uut,
                          filename='F',
                          file=text,
                          dependency_results=dep_results) as result:
            self.assertEqual(len(result[0].diffs), 0)

    def test_keyword_diff(self):
        text = ['# todo 123\n']
        comments = [SourceRange.from_values('F', 1, 1, 1, 10)]
        dep_results = {
            'AnnotationBear':
            [self.annotation_bear_result_type({'comments': comments})]
        }

        with execute_bear(self.uut,
                          filename='F',
                          file=text,
                          dependency_results=dep_results) as result:
            self.assertEqual(
                result[0].diffs['F'].unified_diff, '--- \n'
                '+++ \n'
                '@@ -1 +0,0 @@\n'
                '-# todo 123\n')

        text = ['test = 55 # todo 123\n']
        comments = [SourceRange.from_values('F', 1, 11, 1, 23)]
        dep_results = {
            'AnnotationBear':
            [self.annotation_bear_result_type({'comments': comments})]
        }
        with execute_bear(self.uut,
                          filename='F',
                          file=text,
                          dependency_results=dep_results) as result:
            self.assertEqual(
                result[0].diffs['F'].unified_diff, '--- \n'
                '+++ \n'
                '@@ -1 +1 @@\n'
                '-test = 55 # todo 123\n'
                '+test = 55\n')

    def test_keyword_outside_of_comment(self):
        text = ['todo = 123\n']
        with execute_bear(self.uut,
                          filename='F',
                          file=text,
                          dependency_results=self.dep_results) as result:
            self.assertEqual(result[0].diffs, {})

    def test_keyword_between_code(self):
        self.section.append(Setting('language', 'c'))
        self.section.append(Setting('keywords', 'todo'))

        text = ['int a=0; /* TODO: Test */ int b=1;\n']

        comments = [SourceRange.from_values('F', 1, 10, 1, 25)]
        dep_results = {
            'AnnotationBear':
            [self.annotation_bear_result_type({'comments': comments})]
        }

        with execute_bear(self.uut,
                          filename='F',
                          file=text,
                          dependency_results=dep_results) as result:
            self.assertEqual(
                result[0].diffs['F'].unified_diff, '--- \n'
                '+++ \n'
                '@@ -1 +1 @@\n'
                '-int a=0; /* TODO: Test */ int b=1;\n'
                '+int a=0; int b=1;\n')

        text = ['int a = 0; /* TODO test\n', 'another test\n', '*/\n']
        comments = [SourceRange.from_values('F', 1, 12, 3, 2)]
        dep_results = {
            'AnnotationBear':
            [self.annotation_bear_result_type({'comments': comments})]
        }

        with execute_bear(self.uut,
                          filename='F',
                          file=text,
                          dependency_results=dep_results) as result:
            self.assertEqual(
                result[0].diffs['F'].unified_diff, '--- \n'
                '+++ \n'
                '@@ -1,3 +1,3 @@\n'
                '-int a = 0; /* TODO test\n'
                '+int a = 0; /*\n'
                ' another test\n'
                ' */\n')

        text = ['/* TODO\n', 'test\n', '*/\n']
        comments = [SourceRange.from_values('F', 1, 1, 3, 2)]
        dep_results = {
            'AnnotationBear':
            [self.annotation_bear_result_type({'comments': comments})]
        }

        with execute_bear(self.uut,
                          filename='F',
                          file=text,
                          dependency_results=dep_results) as result:
            self.assertEqual(
                result[0].diffs['F'].unified_diff, '--- \n'
                '+++ \n'
                '@@ -1,3 +1,3 @@\n'
                '-/* TODO\n'
                '+/*\n'
                ' test\n'
                ' */\n')

    def test_keyword_regex(self):
        text = [
            '# add two given values and result the result\n', 'def add(a, b):',
            '    return a+b\n', '               \n', 'print(add(2, 3))\n'
        ]

        regex_keyword = 'r.s.l.'

        with execute_bear(self.uut,
                          filename='F',
                          file=text,
                          regex_keyword=regex_keyword,
                          dependency_results=self.dep_results) as result:
            self.assertEqual(
                result[0].message, 'The line contains the keyword'
                " 'result' which resulted in a"
                ' match with given regex.')

        text = ['# bla bla bla', 'Issue #123', 'bla bla bla']

        regex_keyword = '[iI]ssue #[1-9][0-9]*'

        with execute_bear(self.uut,
                          filename='F',
                          file=text,
                          regex_keyword=regex_keyword,
                          dependency_results=self.dep_results) as result:
            self.assertEqual(
                result[0].message, 'The line contains the keyword'
                " 'Issue #123' which resulted "
                'in a match with given regex.')

    def test_wrong_language(self):
        self.section.append(Setting('language', 'anything'))
        logger = logging.getLogger()
        annotation_bear_result_type = namedtuple('result', 'contents')
        dep_results = {
            'AnnotationBear': [
                annotation_bear_result_type(
                    'coalang specification for anything not found.')
            ]
        }

        text = ['# todo 123']

        with self.assertLogs(logger, 'ERROR') as log:
            with execute_bear(self.uut,
                              filename='F',
                              file=text,
                              dependency_results=dep_results) as result:
                self.assertEqual(len(result), 1)
                self.assertEqual(result[0].diffs, {})
                self.assertEqual(result[0].affected_code[0].start.line, 1)
                self.assertEqual(len(log.output), 1)
                self.assertIn(
                    log.output[0], 'ERROR:root:coalang specification'
                    ' for anything not found.')

    def test_empty_keywords_list(self):
        self.section.append(Setting('keywords', ''))

        text = ['bears = KeywordBear\n']

        with execute_bear(self.uut,
                          filename='F',
                          file=text,
                          dependency_results=self.dep_results) as result:
            self.assertEqual(len(result), 0)
 def setUp(self):
     self.uut = PyCommentedCodeBear(Section('name'), Queue())
Exemple #36
0
 def test_construction(self):
     uut = Section(Constants.COMPLEX_TEST_STRING, None)
     uut = Section(Constants.COMPLEX_TEST_STRING, uut)
     self.assertRaises(TypeError, Section, "irrelevant", 5)
     self.assertRaises(ValueError, uut.__init__, "name", uut)
Exemple #37
0
 def setUp(self):
     self.section = Section('TEST_SECTION')
Exemple #38
0
 def test_get_config_dir(self):
     section = Section('default')
     section.append(Setting('files', '**', '/path/to/dir/config'))
     uut = TestBear(section, None)
     self.assertEqual(uut.get_config_dir(), abspath('/path/to/dir'))
Exemple #39
0
class BearTest(unittest.TestCase):

    def setUp(self):
        self.queue = multiprocessing.Queue()
        self.settings = Section('test_settings')
        self.uut = TestBear(self.settings, self.queue)

    def test_simple_api(self):
        self.assertRaises(TypeError, TestBear, self.settings, 2)
        self.assertRaises(TypeError, TestBear, None, self.queue)
        self.assertRaises(NotImplementedError, self.uut.kind)

        base = Bear(self.settings, None)
        self.assertRaises(NotImplementedError, base.run)
        self.assertEqual(base.get_non_optional_settings(), {})

    def test_message_queue(self):
        self.uut.execute()
        self.check_message(LOG_LEVEL.DEBUG,
                           'Running bear TestBear...')
        self.check_message(LOG_LEVEL.DEBUG, 'set=up')
        self.check_message(LOG_LEVEL.ERROR, 'teardown')

    def test_bad_bear(self):
        self.uut = BadTestBear(self.settings, self.queue)
        self.uut.execute()
        self.check_message(LOG_LEVEL.DEBUG)
        self.check_message(LOG_LEVEL.WARNING,
                           'Bear BadTestBear failed to run. Take a look at '
                           'debug messages (`-V`) for further '
                           'information.')
        # debug message contains custom content, dont test this here
        self.queue.get()

    def test_inconvertible(self):
        self.uut = TypedTestBear(self.settings, self.queue)
        self.settings.append(Setting('something', '5'))
        self.uut.execute()
        self.check_message(LOG_LEVEL.DEBUG)
        self.assertTrue(self.uut.was_executed)

        self.settings.append(Setting('something', 'nonsense'))
        self.uut.was_executed = False
        self.uut.execute()
        self.check_message(LOG_LEVEL.DEBUG)
        self.check_message(LOG_LEVEL.WARNING)
        self.assertTrue(self.queue.empty())
        self.assertFalse(self.uut.was_executed)

    def check_message(self, log_level, message=None):
        msg = self.queue.get()
        self.assertIsInstance(msg, LogMessage)
        if message:
            self.assertEqual(msg.message, message)

        self.assertEqual(msg.log_level, log_level, msg)

    def test_no_queue(self):
        uut = TestBear(self.settings, None)
        uut.execute()  # No exceptions

    def test_dependencies(self):
        self.assertEqual(Bear.BEAR_DEPS, set())
        self.assertEqual(Bear.missing_dependencies([]), set())
        self.assertEqual(Bear.missing_dependencies([BadTestBear]), set())

        self.assertEqual(TestBear.missing_dependencies([]), {BadTestBear})
        self.assertEqual(TestBear.missing_dependencies([BadTestBear]), set())
        self.assertEqual(TestBear.missing_dependencies([TestBear]),
                         {BadTestBear})
        self.assertEqual(TestBear.missing_dependencies([TestBear,
                                                        BadTestBear]),
                         set())

    def test_check_prerequisites(self):
        uut = BearWithPrerequisites(self.settings, self.queue, True)
        uut.execute()
        self.check_message(LOG_LEVEL.DEBUG)
        self.assertTrue(self.queue.empty())
        self.assertTrue(uut.was_executed)

        self.assertRaisesRegex(RuntimeError,
                               'The bear BearWithPrerequisites does not '
                               'fulfill all requirements\\.',
                               BearWithPrerequisites,
                               self.settings,
                               self.queue,
                               False)

        self.check_message(LOG_LEVEL.ERROR,
                           'The bear BearWithPrerequisites does not fulfill '
                           'all requirements.')
        self.assertTrue(self.queue.empty())

        self.assertRaisesRegex(RuntimeError,
                               'The bear BearWithPrerequisites does not '
                               'fulfill all requirements\\. Just because '
                               'I want to\\.',
                               BearWithPrerequisites,
                               self.settings,
                               self.queue,
                               'Just because I want to.')

        self.check_message(LOG_LEVEL.ERROR,
                           'The bear BearWithPrerequisites does not fulfill '
                           'all requirements. Just because I want to.')
        self.assertTrue(self.queue.empty())

    def test_get_config_dir(self):
        section = Section('default')
        section.append(Setting('files', '**', '/path/to/dir/config'))
        uut = TestBear(section, None)
        self.assertEqual(uut.get_config_dir(), abspath('/path/to/dir'))

    def test_new_result(self):
        bear = Bear(self.settings, None)
        result = bear.new_result('test message', '/tmp/testy')
        expected = Result.from_values(bear, 'test message', '/tmp/testy')
        self.assertEqual(result, expected)

    def test_download_cached_file(self):
        url = 'https://google.com'
        filename = 'google.html'
        uut = TestBear(self.settings, None)
        self.assertFalse(isfile(join(uut.data_dir, filename)))
        expected_filename = join(uut.data_dir, filename)
        result_filename = uut.download_cached_file(url, filename)
        self.assertEqual(result_filename, expected_filename)
        expected_time = getmtime(join(uut.data_dir, filename))
        result_filename = uut.download_cached_file(url, filename)
        self.assertEqual(result_filename, expected_filename)
        result_time = getmtime(join(uut.data_dir, filename))
        self.assertEqual(result_time, expected_time)
Exemple #40
0
 def setUp(self):
     self.section = Section('name')
     self.log_printer = LogPrinter(ConsolePrinter(), log_level=0)
     self.console_printer = ConsolePrinter()
Exemple #41
0
class KeywordBearDiffTest(unittest.TestCase):
    def setUp(self):
        self.section = Section("")
        self.section.append(Setting('language', 'python3'))
        self.section.append(Setting('keywords', 'TODO'))
        self.uut = KeywordBear(self.section, Queue())

        self.annotation_bear_result_type = namedtuple('result', ['contents'])
        self.dep_results = {
            'AnnotationBear': HiddenResult('AnnotationBear', {'comments': ()})
        }

    def test_empty_keyword(self):
        text = ['a == b']

        with execute_bear(self.uut,
                          "F",
                          text,
                          dependency_results=self.dep_results) as result:
            self.assertEqual(result, [])

    def test_keyword_in_comment(self):
        dep_results = {'AnnotationBear': {}}
        text = ['# todo 123']
        with execute_bear(self.uut, "F", text,
                          dependency_results=dep_results) as result:
            self.assertEqual(result[0].diffs, {})
            self.assertEqual(result[0].affected_code[0].start.line, 1)
            self.assertEqual(len(result), 1)

        dep_results = {
            'AnnotationBear': HiddenResult('AnnotationBear', {'comments': 123})
        }
        with execute_bear(self.uut, "F", text,
                          dependency_results=dep_results) as result:
            self.assertEqual(result[0].diffs, {})
            self.assertEqual(result[0].affected_code[0].start.line, 1)
            self.assertEqual(len(result), 1)

        dep_results = {'AnnotationBear': HiddenResult('AnnotationBear', 123)}
        with execute_bear(self.uut, "F", text,
                          dependency_results=dep_results) as result:
            self.assertEqual(result[0].diffs, {})
            self.assertEqual(result[0].affected_code[0].start.line, 1)
            self.assertEqual(len(result), 1)

    def test_keyword_not_in_comment(self):
        text = ['# comment 123\n', 'a = "TODO"\n']
        comments = [SourceRange.from_values("F", 1, 1, 1, 40)]
        dep_results = {
            'AnnotationBear':
            [self.annotation_bear_result_type({'comments': comments})]
        }

        with execute_bear(self.uut, "F", text,
                          dependency_results=dep_results) as result:
            self.assertEqual(len(result[0].diffs), 0)

    def test_keyword_diff(self):
        text = ['# todo 123\n']
        comments = [SourceRange.from_values("F", 1, 1, 1, 10)]
        dep_results = {
            'AnnotationBear':
            [self.annotation_bear_result_type({'comments': comments})]
        }

        with execute_bear(self.uut, "F", text,
                          dependency_results=dep_results) as result:
            self.assertEqual(
                result[0].diffs['F'].unified_diff, '--- \n'
                '+++ \n'
                '@@ -1 +0,0 @@\n'
                '-# todo 123\n')

        text = ['test = 55 # todo 123\n']
        comments = [SourceRange.from_values("F", 1, 11, 1, 23)]
        dep_results = {
            'AnnotationBear':
            [self.annotation_bear_result_type({'comments': comments})]
        }
        with execute_bear(self.uut, "F", text,
                          dependency_results=dep_results) as result:
            self.assertEqual(
                result[0].diffs['F'].unified_diff, '--- \n'
                '+++ \n'
                '@@ -1 +1 @@\n'
                '-test = 55 # todo 123\n'
                '+test = 55\n')

    def test_keyword_outside_of_comment(self):
        text = ['todo = 123\n']
        with execute_bear(self.uut,
                          "F",
                          text,
                          dependency_results=self.dep_results) as result:
            self.assertEquals(result[0].diffs, {})

    def test_keyword_between_code(self):
        self.section.append(Setting('language', 'c'))
        self.section.append(Setting('keywords', 'todo'))

        text = ['int a=0; /* TODO: Test */ int b=1;\n']

        comments = [SourceRange.from_values("F", 1, 10, 1, 25)]
        dep_results = {
            'AnnotationBear':
            [self.annotation_bear_result_type({'comments': comments})]
        }

        with execute_bear(self.uut, "F", text,
                          dependency_results=dep_results) as result:
            self.assertEqual(
                result[0].diffs['F'].unified_diff, '--- \n'
                '+++ \n'
                '@@ -1 +1 @@\n'
                '-int a=0; /* TODO: Test */ int b=1;\n'
                '+int a=0; int b=1;\n')

        text = ['int a = 0; /* TODO test\n', 'another test\n', '*/\n']
        comments = [SourceRange.from_values("F", 1, 12, 3, 2)]
        dep_results = {
            'AnnotationBear':
            [self.annotation_bear_result_type({'comments': comments})]
        }

        with execute_bear(self.uut, "F", text,
                          dependency_results=dep_results) as result:
            self.assertEqual(
                result[0].diffs['F'].unified_diff, '--- \n'
                '+++ \n'
                '@@ -1,3 +1,3 @@\n'
                '-int a = 0; /* TODO test\n'
                '+int a = 0; /*\n'
                ' another test\n'
                ' */\n')

        text = ['/* TODO\n', 'test\n', '*/\n']
        comments = [SourceRange.from_values("F", 1, 1, 3, 2)]
        dep_results = {
            'AnnotationBear':
            [self.annotation_bear_result_type({'comments': comments})]
        }

        with execute_bear(self.uut, "F", text,
                          dependency_results=dep_results) as result:
            self.assertEqual(
                result[0].diffs['F'].unified_diff, '--- \n'
                '+++ \n'
                '@@ -1,3 +1,3 @@\n'
                '-/* TODO\n'
                '+/*\n'
                ' test\n'
                ' */\n')
Exemple #42
0
class ProcessingTest_AutoapplyActions(unittest.TestCase):

    def setUp(self):
        self.log_queue = queue.Queue()
        self.log_printer = ProcessingTestLogPrinter(self.log_queue)

        self.resultY = Result('YBear', 'msg1')
        self.resultZ = Result('ZBear', 'msg2')
        self.results = [self.resultY, self.resultZ]
        self.section = Section('A')

    def test_no_default_actions(self):
        ret = autoapply_actions(self.results,
                                {},
                                {},
                                self.section,
                                self.log_printer)
        self.assertEqual(ret, self.results)
        self.assertTrue(self.log_queue.empty())

    def test_with_invalid_action(self):
        self.section.append(Setting('default_actions',
                                    'XBear: nonSENSE_action'))
        ret = autoapply_actions(self.results,
                                {},
                                {},
                                self.section,
                                self.log_printer)
        self.assertEqual(ret, self.results)
        self.assertEqual(self.log_queue.get().message,
                         "Selected default action 'nonSENSE_action' for bear "
                         "'XBear' does not exist. Ignoring action.")
        self.assertTrue(self.log_queue.empty())

    def test_without_default_action_and_unapplicable(self):
        # Use a result where no default action is supplied for and another one
        # where the action is not applicable.
        old_is_applicable = ApplyPatchAction.is_applicable
        ApplyPatchAction.is_applicable = lambda *args: False

        self.section.append(Setting(
            'default_actions',
            'NoBear: ApplyPatchAction, YBear: ApplyPatchAction'))
        ret = autoapply_actions(self.results,
                                {},
                                {},
                                self.section,
                                self.log_printer)
        self.assertEqual(ret, self.results)
        self.assertEqual(self.log_queue.get().message,
                         "Selected default action 'ApplyPatchAction' for bear "
                         "'YBear' is not applicable. Action not applied.")
        self.assertTrue(self.log_queue.empty())

        ApplyPatchAction.is_applicable = old_is_applicable

    def test_applicable_action(self):
        # Use a result whose action can be successfully applied.
        log_printer = self.log_printer

        class TestAction(ResultAction):

            def apply(self, *args, **kwargs):
                log_printer.debug('ACTION APPLIED SUCCESSFULLY.')

        ACTIONS.append(TestAction)

        self.section.append(Setting('default_actions', 'Z*: TestAction'))
        ret = autoapply_actions(self.results,
                                {},
                                {},
                                self.section,
                                log_printer)
        self.assertEqual(ret, [self.resultY])
        self.assertEqual(self.log_queue.get().message,
                         'ACTION APPLIED SUCCESSFULLY.')
        self.assertEqual(self.log_queue.get().message,
                         "Applied 'TestAction' "
                         "on the whole project from 'ZBear'.")
        self.assertTrue(self.log_queue.empty())

        ACTIONS.pop()

    def test_failing_action(self):
        class FailingTestAction(ResultAction):

            def apply(self, *args, **kwargs):
                raise RuntimeError("YEAH THAT'S A FAILING BEAR")

        ACTIONS.append(FailingTestAction)

        self.section.append(Setting('default_actions',
                                    'YBear: FailingTestAction'))
        ret = autoapply_actions(self.results,
                                {},
                                {},
                                self.section,
                                self.log_printer)
        self.assertEqual(ret, self.results)
        self.assertEqual(self.log_queue.get().message,
                         "Failed to execute action 'FailingTestAction'"
                         " with error: YEAH THAT'S A FAILING BEAR.")
        self.assertIn("YEAH THAT'S A FAILING BEAR",
                      self.log_queue.get().message)
        self.assertEqual(self.log_queue.get().message,
                         '-> for result ' + repr(self.resultY) + '.')
        self.assertTrue(self.log_queue.empty())

        ACTIONS.pop()
Exemple #43
0
    def test_process_queues(self):
        ctrlq = queue.Queue()

        # Append custom controlling sequences.

        # Simulated process 1
        ctrlq.put((CONTROL_ELEMENT.LOCAL, 1))
        ctrlq.put((CONTROL_ELEMENT.LOCAL_FINISHED, None))
        ctrlq.put((CONTROL_ELEMENT.GLOBAL, 1))

        # Simulated process 2
        ctrlq.put((CONTROL_ELEMENT.LOCAL, 2))

        # Simulated process 1
        ctrlq.put((CONTROL_ELEMENT.GLOBAL_FINISHED, None))

        # Simulated process 2
        ctrlq.put((CONTROL_ELEMENT.LOCAL_FINISHED, None))
        ctrlq.put((CONTROL_ELEMENT.GLOBAL, 1))
        ctrlq.put((CONTROL_ELEMENT.GLOBAL_FINISHED, None))

        first_local = Result.from_values('o', 'The first result.', file='f')
        second_local = Result.from_values('ABear',
                                          'The second result.',
                                          file='f',
                                          line=1)
        third_local = Result.from_values('ABear',
                                         'The second result.',
                                         file='f',
                                         line=4)
        fourth_local = Result.from_values('ABear',
                                          'Another result.',
                                          file='f',
                                          line=7)
        first_global = Result('o', 'The one and only global result.')
        section = Section('')
        section.append(Setting('min_severity', 'normal'))
        process_queues(
            [DummyProcess(control_queue=ctrlq) for i in range(3)],
            ctrlq,
            {1: [first_local,
                 second_local,
                 third_local,
                 # The following are to be ignored
                 Result('o', 'm', severity=RESULT_SEVERITY.INFO),
                 Result.from_values('ABear', 'u', 'f', 2, 1),
                 Result.from_values('ABear', 'u', 'f', 3, 1)],
             2: [fourth_local,
                 # The following are to be ignored
                 HiddenResult('t', 'c'),
                 Result.from_values('ABear', 'u', 'f', 5, 1),
                 Result.from_values('ABear', 'u', 'f', 6, 1)]},
            {1: [first_global]},
            {'f': ['first line  # stop ignoring, invalid ignore range\n',
                   'second line  # ignore all\n',
                   'third line\n',
                   "fourth line  # gnore shouldn't trigger without i!\n",
                   '# Start ignoring ABear, BBear and CBear\n',
                   '# Stop ignoring\n',
                   'seventh']},
            lambda *args: self.queue.put(args[2]),
            section,
            None,
            self.log_printer,
            self.console_printer)

        self.assertEqual(self.queue.get(timeout=0), ([first_local,
                                                      second_local,
                                                      third_local]))
        self.assertEqual(self.queue.get(timeout=0), ([fourth_local]))
        self.assertEqual(self.queue.get(timeout=0), ([first_global]))
        self.assertEqual(self.queue.get(timeout=0), ([first_global]))
class PyLintBearTest(LocalBearTestHelper):
    def setUp(self):
        self.section = Section('test section')
        self.uut = PyLintBear(self.section, Queue())
        self.test_file = os.path.join(os.path.dirname(__file__), 'test_files',
                                      'pylint_test.py')
        self.rc_file = os.path.join(os.path.dirname(__file__), 'test_files',
                                    'pylint_config')

    def test_run(self):
        self.section.append(Setting('pylint_disable', ''))
        self.check_invalidity(
            self.uut,
            [],  # Doesn't matter, pylint will parse the file
            self.test_file)

        # This is a special case because there's only one result yielded.
        # This was a bug once where the last result got ignored.
        self.section.append(Setting('pylint_disable', 'E0211,W0611,C0111'))
        self.check_invalidity(self.uut, [], self.test_file)

        self.section.append(
            Setting('pylint_disable', 'E0211,W0611,C0111,W0311'))
        self.check_validity(self.uut, [], self.test_file)

        self.section.append(Setting('pylint_disable', 'all'))
        self.check_validity(self.uut, [], self.test_file)

        self.section.append(Setting('pylint_enable', 'C0111'))
        self.check_invalidity(self.uut, [], self.test_file)

        self.section.append(Setting('pylint_cli_options', '--disable=all'))
        self.check_validity(self.uut, [], self.test_file)

    def test_rcfile(self):
        self.section.append(Setting('pylint_rcfile', re.escape(self.rc_file)))
        self.check_validity(self.uut, [], self.test_file)
Exemple #45
0
 def test_bear_dirs_empty(self):
     section = Section("section", None)
     self.assertEqual(len(section.bear_dirs()), 1)
Exemple #46
0
 def setUp(self):
     self.queue = multiprocessing.Queue()
     self.settings = Section('test_settings')
     self.uut = TestBear(self.settings, self.queue)
Exemple #47
0
 def test_append(self):
     uut = Section(Constants.COMPLEX_TEST_STRING, None)
     self.assertRaises(TypeError, uut.append, 5)
     uut.append(Setting(5, 5, 5))
     self.assertEqual(str(uut.get("5 ")), "5")
     self.assertEqual(int(uut.get("nonexistent", 5)), 5)
 def setUp(self):
     self.section = Section('')
 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))
Exemple #50
0
 def setUp(self):
     self.section = Section("test section")
     self.uut = SpaceConsistencyBear(self.section, Queue())
Exemple #51
0
 def setUp(self):
     self.uut = HTTPoliceLintBear(Section('name'), Queue())
class GitCommitBearTest(unittest.TestCase):

    @staticmethod
    def run_git_command(*args, stdin=None):
        run_shell_command(" ".join(("git",) + args), stdin)

    @staticmethod
    def git_commit(msg):
        # Use stdin mode from git, since -m on Windows cmd does not support
        # multiline messages.
        GitCommitBearTest.run_git_command("commit",
                                          "--allow-empty",
                                          "--allow-empty-message",
                                          "--file=-",
                                          stdin=msg)

    def run_uut(self, *args, **kwargs):
        """
        Runs the unit-under-test (via `self.uut.run()`) and collects the
        messages of the yielded results as a list.

        :param args:   Positional arguments to forward to the run function.
        :param kwargs: Keyword arguments to forward to the run function.
        :return:       A list of the message strings.
        """
        return list(result.message for result in self.uut.run(*args, **kwargs))

    def setUp(self):
        self.msg_queue = Queue()
        self.section = Section("")
        self.uut = GitCommitBear(None, self.section, self.msg_queue)

        self._old_cwd = os.getcwd()
        self.gitdir = mkdtemp()
        os.chdir(self.gitdir)
        self.run_git_command("init")
        self.run_git_command("config", "user.email [email protected]")
        self.run_git_command("config", "user.name coala")

    @staticmethod
    def _windows_rmtree_remove_readonly(func, path, excinfo):
        os.chmod(path, stat.S_IWRITE)
        func(path)

    def tearDown(self):
        os.chdir(self._old_cwd)
        if platform.system() == "Windows":
            onerror = self._windows_rmtree_remove_readonly
        else:
            onerror = None
        shutil.rmtree(self.gitdir, onerror=onerror)

    def test_check_prerequisites(self):
        _shutil_which = shutil.which
        try:
            shutil.which = lambda *args, **kwargs: None
            self.assertEqual(GitCommitBear.check_prerequisites(),
                             "git is not installed.")

            shutil.which = lambda *args, **kwargs: "path/to/git"
            self.assertTrue(GitCommitBear.check_prerequisites())
        finally:
            shutil.which = _shutil_which

    def test_git_failure(self):
        # In this case use a reference to a non-existing commit, so just try
        # to log all commits on a newly created repository.
        self.assertEqual(self.run_uut(), [])

        git_error = self.msg_queue.get().message
        self.assertEqual(git_error[:4], "git:")

        self.assertTrue(self.msg_queue.empty())

    def test_empty_message(self):
        self.git_commit("")

        self.assertEqual(self.run_uut(),
                         ["HEAD commit has no message."])
        self.assertTrue(self.msg_queue.empty())

        self.assertEqual(self.run_uut(allow_empty_commit_message=True),
                         [])
        self.assertTrue(self.msg_queue.empty())

    def test_shortlog_checks(self):
        self.git_commit("Commits messages that nearly exceeds default limit")

        self.assertEqual(self.run_uut(), [])
        self.assertTrue(self.msg_queue.empty())

        self.assertEqual(self.run_uut(shortlog_length=17),
                         ["Shortlog of HEAD commit is too long."])
        self.assertTrue(self.msg_queue.empty())

        self.git_commit("A shortlog that is too long is not good for history")
        self.assertEqual(self.run_uut(),
                         ["Shortlog of HEAD commit is too long."])
        self.assertTrue(self.msg_queue.empty())

    def test_body_checks(self):
        self.git_commit(
            "Commits message with a body\n\n"
            "nearly exceeding the default length of a body, but not quite. "
            "haaaaaaands")

        self.assertEqual(self.run_uut(), [])
        self.assertTrue(self.msg_queue.empty())

        self.git_commit("Shortlog only")

        self.assertEqual(self.run_uut(), [])
        self.assertTrue(self.msg_queue.empty())

        # Force a body.
        self.git_commit("Shortlog only ...")
        self.assertEqual(self.run_uut(force_body=True),
                         ["No commit message body at HEAD."])
        self.assertTrue(self.msg_queue.empty())

        # Miss a newline between shortlog and body.
        self.git_commit("Shortlog\nOops, body too early")
        self.assertEqual(self.run_uut(),
                         ["No newline between shortlog and body at HEAD."])
        self.assertTrue(self.msg_queue.empty())

        # And now too long lines.
        self.git_commit("Shortlog\n\n"
                        "This line is ok.\n"
                        "This line is by far too long (in this case).\n"
                        "This one too, blablablablablablablablabla.")
        self.assertEqual(self.run_uut(body_line_length=41),
                         ["Body of HEAD commit contains too long lines."])
        self.assertTrue(self.msg_queue.empty())

    def test_different_path(self):
        no_git_dir = mkdtemp()
        self.git_commit("A shortlog that is too long is not good for history")
        os.chdir(no_git_dir)
        # When section doesn't have a config setting
        self.assertEqual(self.run_uut(), [])
        git_error = self.msg_queue.get().message
        self.assertEqual(git_error[:4], "git:")
        # when section does have a config setting
        self.section.append(Setting("config", re.escape(self.gitdir)))
        self.assertEqual(self.run_uut(),
                         ["Shortlog of HEAD commit is too long."])
        self.assertEqual(get_config_directory(self.section),
                         self.gitdir)
        os.chdir(self.gitdir)
        os.rmdir(no_git_dir)
Exemple #53
0
 def setUp(self):
     self.section = Section("any")
     self.section.append(Setting("language", "CPP"))
Exemple #54
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'}")
Exemple #55
0
    def test_iter(self):
        defaults = Section('default', None)
        uut = Section('name', defaults)
        uut.append(Setting(5, 5))
        uut.add_or_create_setting(Setting('TEsT', 4))
        defaults.append(Setting('tEsT', 1))
        defaults.append(Setting(' great   ', 3))
        defaults.append(Setting(' great   ', 3), custom_key='custom')
        uut.add_or_create_setting(Setting('custom', 4, to_append=True))
        uut.add_or_create_setting(Setting(' NEW   ', 'val'))
        uut.add_or_create_setting(Setting(' NEW   ', 'vl'),
                                  allow_appending=False)
        uut.add_or_create_setting(Setting('new', 'val'),
                                  custom_key='teSt ',
                                  allow_appending=True)
        self.assertEqual(list(uut), ['5', 'test', 'custom', 'new', 'great'])

        for index in uut:
            t = uut[index]
            self.assertNotEqual(t, None)

        self.assertIn('teST', defaults)
        self.assertIn('       GREAT', defaults)
        self.assertNotIn('       GrEAT !', defaults)
        self.assertNotIn('', defaults)
        self.assertEqual(str(uut['test']), '4\nval')
        self.assertEqual(str(uut['custom']), '3, 4')
        self.assertEqual(int(uut['GREAT ']), 3)
        self.assertRaises(IndexError, uut.__getitem__, 'doesnotexist')
        self.assertRaises(IndexError, uut.__getitem__, 'great', True)
        self.assertRaises(IndexError, uut.__getitem__, ' ')
Exemple #56
0
    def test_iter(self):
        defaults = Section("default", None)
        uut = Section("name", defaults)
        uut.append(Setting(5, 5, 5))
        uut.add_or_create_setting(Setting("TEsT", 4, 5))
        defaults.append(Setting("tEsT", 1, 3))
        defaults.append(Setting(" great   ", 3, 8))
        defaults.append(Setting(" great   ", 3, 8), custom_key="custom")
        uut.add_or_create_setting(Setting(" NEW   ", "val", 8))
        uut.add_or_create_setting(Setting(" NEW   ", "vl", 8),
                                  allow_appending=False)
        uut.add_or_create_setting(Setting("new", "val", 9),
                                  custom_key="teSt ",
                                  allow_appending=True)
        self.assertEqual(list(uut), ["5", "test", "new", "great", "custom"])

        for index in uut:
            t = uut[index]
            self.assertNotEqual(t, None)

        self.assertIn("teST", defaults)
        self.assertIn("       GREAT", defaults)
        self.assertNotIn("       GrEAT !", defaults)
        self.assertNotIn("", defaults)
        self.assertEqual(str(uut['test']), "4\nval")
        self.assertEqual(int(uut["GREAT "]), 3)
        self.assertRaises(IndexError, uut.__getitem__, "doesnotexist")
        self.assertRaises(IndexError, uut.__getitem__, "great", True)
        self.assertRaises(IndexError, uut.__getitem__, " ")
Exemple #57
0
 def test_extract_aspects_from_section_no_aspects(self):
     section = Section('section')
     self.assertIsNone(extract_aspects_from_section(section))
Exemple #58
0
 def test_bear_dirs(self):
     section = Section("section", None)
     section.append(Setting("bear_dirs", "test1, test2"))
     self.assertEqual(len(section.bear_dirs()), 3)
Exemple #59
0
 def setUp(self):
     self.section = Section('test section')
     self.uut = FilenameBear(self.section, Queue())
class ShowPatchActionTest(unittest.TestCase):

    def setUp(self):
        self.uut = ShowPatchAction()
        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})

        # Two renames donot result in any change
        self.assertEqual(
            self.uut.is_applicable(result, {}, {'f': diff}),
            'The given patches do not change anything anymore.'
        )

        with self.assertRaises(TypeError):
            self.uut.is_applicable(1, None, None)

        self.assertEqual(
            self.uut.is_applicable(Result('o', 'm'), None, None),
            'This result has no patch attached.')

        self.assertTrue(self.uut.is_applicable(self.test_result, {}, {}))

        self.assertIn(
            'Two or more patches conflict with each other: ',
            self.uut.is_applicable(self.test_result, {}, self.diff_dict))

    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_renaming_only(self):
        with retrieve_stdout() as stdout:
            test_result = Result('origin', 'message',
                                 diffs={'a': Diff([], rename='b')})
            file_dict = {'a': []}
            self.assertEqual(self.uut.apply_from_section(test_result,
                                                         file_dict,
                                                         {},
                                                         self.section),
                             {})
            self.assertEqual(stdout.getvalue(),
                             '|----|    | ' + join('a', 'a') + '\n'
                             '|    |++++| ' + join('b', 'b') + '\n')

    def test_apply_empty(self):
        with retrieve_stdout() as stdout:
            test_result = Result('origin', 'message',
                                 diffs={'a': Diff([])})
            file_dict = {'a': []}
            self.assertEqual(self.uut.apply_from_section(test_result,
                                                         file_dict,
                                                         {},
                                                         self.section),
                             {})
            self.assertEqual(stdout.getvalue(), '')

    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')

    def test_apply_with_rename(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')

            diff_dict = {'a': Diff(self.file_dict['a'], rename='a.rename'),
                         'b': Diff(self.file_dict['b'], delete=True)}
            diff_dict['a'].add_lines(1, ['test\n'])
            diff_dict['a'].delete_line(3)
            diff_dict['b'].add_lines(0, ['first\n'])

            test_result = Result('origin', 'message', diffs=diff_dict)

            self.assertEqual(self.uut.apply_from_section(test_result,
                                                         self.file_dict,
                                                         previous_diffs,
                                                         self.section),
                             previous_diffs)
            self.assertEqual(stdout.getvalue(),
                             '|----|    | a\n'
                             '|    |++++| a.rename\n'
                             '|   1|   1| a\n'
                             '|    |   2|+test\n'
                             '|   2|   3| b_changed\n'
                             '|   3|    |-c\n'
                             '|----|    | b\n'
                             '|    |++++| /dev/null\n'
                             '|   1|    |-old_first\n')