示例#1
0
    def test_prepare_file(self):
        with prepare_file(['line1', 'line2\n'],
                          '/file/name',
                          force_linebreaks=True,
                          create_tempfile=True) as (lines, filename):
            self.assertEqual(filename, '/file/name')
            self.assertEqual(lines, ['line1\n', 'line2\n'])

        with prepare_file(['line1', 'line2\n'],
                          None,
                          force_linebreaks=False,
                          create_tempfile=True) as (lines, filename):
            self.assertTrue(os.path.isfile(filename))
            self.assertEqual(lines, ['line1', 'line2\n'])

        with prepare_file(['line1', 'line2\n'],
                          None,
                          tempfile_kwargs={
                              'suffix': '.test',
                              'prefix': 'test_'
                          },
                          force_linebreaks=False,
                          create_tempfile=True) as (lines, filename):
            self.assertTrue(os.path.isfile(filename))
            basename = os.path.basename(filename)
            self.assertTrue(basename.endswith('.test'))
            self.assertTrue(basename.startswith('test_'))

        with prepare_file(['line1', 'line2\n'],
                          None,
                          force_linebreaks=False,
                          create_tempfile=False) as (lines, filename):
            self.assertEqual(filename, 'dummy_file_name')
    def test_prepare_file(self):
        with prepare_file(['line1', 'line2\n'],
                          "/file/name",
                          force_linebreaks=True,
                          create_tempfile=True) as (lines, filename):
            self.assertEqual(filename, '/file/name')
            self.assertEqual(lines, ['line1\n', 'line2\n'])

        with prepare_file(['line1', 'line2\n'],
                          None,
                          force_linebreaks=False,
                          create_tempfile=True) as (lines, filename):
            self.assertTrue(os.path.isfile(filename))
            self.assertEqual(lines, ['line1', 'line2\n'])

        with prepare_file(['line1', 'line2\n'],
                          None,
                          tempfile_kwargs={"suffix": ".test",
                                           "prefix": "test_"},
                          force_linebreaks=False,
                          create_tempfile=True) as (lines, filename):
            self.assertTrue(os.path.isfile(filename))
            basename = os.path.basename(filename)
            self.assertTrue(basename.endswith(".test"))
            self.assertTrue(basename.startswith("test_"))

        with prepare_file(['line1', 'line2\n'],
                          None,
                          force_linebreaks=False,
                          create_tempfile=False) as (lines, filename):
            self.assertEqual(filename, "dummy_file_name")
示例#3
0
    def test_prepare_file(self):
        with prepare_file(['line1', 'line2\n'],
                          '/file/name',
                          force_linebreaks=True,
                          create_tempfile=True) as (lines, filename):
            self.assertEqual(filename, '/file/name')
            self.assertEqual(lines, ['line1\n', 'line2\n'])

        with prepare_file(['line1', 'line2\n'],
                          None,
                          force_linebreaks=False,
                          create_tempfile=True) as (lines, filename):
            self.assertTrue(os.path.isfile(filename))
            self.assertEqual(lines, ['line1', 'line2\n'])

        with prepare_file(['line1', 'line2\n'],
                          None,
                          tempfile_kwargs={'suffix': '.test',
                                           'prefix': 'test_'},
                          force_linebreaks=False,
                          create_tempfile=True) as (lines, filename):
            self.assertTrue(os.path.isfile(filename))
            basename = os.path.basename(filename)
            self.assertTrue(basename.endswith('.test'))
            self.assertTrue(basename.startswith('test_'))

        with prepare_file(['line1', 'line2\n'],
                          None,
                          force_linebreaks=False,
                          create_tempfile=False) as (lines, filename):
            self.assertEqual(filename, 'dummy_file_name')
示例#4
0
    def test_noupdate(self, mock_browser, mock_subprocess_call,
                      mock_server_close, mock_serve_forever):
        """
        Test that when JSON configs are already generated, coala-html
        with 'noupdate' option will run successfully and not update existing
        configuration. Also, we mock the expensive http calls and instantiating
        the server by mocking the corresponding method calls.
        """
        mock_serve_forever.side_effect = KeyboardInterrupt
        mock_subprocess_call.return_value = 0  # To mock the `bower install`
        update_file = ""
        noupdate_file = ""
        with prepare_file(["#todo this is todo"], None) as (lines, filename):
            execute_coala(coala_html.main, "coala-html", "-c",
                          os.devnull, "-b", "LineCountBear", "-f",
                          re.escape(filename), "--nolaunch")

            with open(self.result_file, 'r') as fp:
                update_file = fp.read()

            execute_coala(coala_html.main, "coala-html", "-c",
                          os.devnull, "-b", "LineCountBear", "-f",
                          re.escape(filename), "--noupdate")

            with open(self.result_file, 'r') as fp:
                noupdate_file = fp.read()

        self.assertEqual(update_file, noupdate_file)
        self.assertTrue(mock_browser.called)
        self.assertTrue(mock_serve_forever.called)
        self.assertTrue(mock_server_close.called)
 def test_bad_assertComparableObjectsEqual(self):
     with self.assertRaises(AssertionError) as cm:
         self.uut = LineCountTestBear(Section('name'), Queue())
         file_content = 'a\nb\nc'
         with prepare_file(file_content.splitlines(), filename=None,
                           create_tempfile=True) as (file, fname):
             self.check_results(self.uut,
                                file_content.splitlines(),
                                [Result.from_values(
                                 origin='LineCountTestBea',
                                 message='This file has 2 lines.',
                                 severity=RESULT_SEVERITY.INFO,
                                 file=fname)],
                                filename=fname,
                                create_tempfile=False)
     self.assertEqual('\'LineCountTestBear\' != \'LineCountTestBea\'\n'
                      '- LineCountTestBear\n'
                      '?                 -\n'
                      '+ LineCountTestBea\n'
                      ' : origin mismatch.\n\n'
                      '\'This file has 3 lines.\' != \'This file has 2 '
                      'lines.\'\n'
                      '- This file has 3 lines.\n'
                      '?               ^\n'
                      '+ This file has 2 lines.\n'
                      '?               ^\n'
                      ' : message_base mismatch.\n\n',
                      str(cm.exception))
示例#6
0
    def test_coala_no_unexpected_warnings(self):
        with bear_test_module(), \
                prepare_file(['#fixme'], None) as (lines, filename):
            retval, stdout, stderr = execute_coala(coala.main, 'coala')
            errors = filter(bool, stderr.split('\n'))
            errors = list(errors)

            unexpected = errors.copy()

            expected = [
                err for err in unexpected
                if "Implicit 'Default' section inheritance" in err
            ]
            self.assertNotEqual([], expected)
            # Filter them out
            unexpected = [err for err in unexpected if err not in expected]

            # These errors depend on the state of the host, so ignore them
            ignored = [
                err for err in unexpected
                if re.search("No bears matching '.*' were found", err)
            ]

            # Filter them out
            unexpected = [err for err in unexpected if err not in ignored]

            self.assertEqual([], unexpected)
            self.assertEqual(
                retval, 0, 'coala must return zero when there are no errors;'
                ' errors={errors}'.format(errors=list(errors)))
示例#7
0
def get_results(local_bear,
                lines,
                filename=None,
                force_linebreaks=True,
                create_tempfile=True,
                tempfile_kwargs={},
                settings={}):
    if local_bear.BEAR_DEPS:
        # Get results of bear's dependencies first
        deps_results = dict()
        for bear in local_bear.BEAR_DEPS:
            uut = bear(local_bear.section, queue.Queue())
            deps_results[bear.name] = get_results(uut,
                                                  lines,
                                                  filename,
                                                  force_linebreaks,
                                                  create_tempfile,
                                                  tempfile_kwargs,
                                                  settings)
    else:
        deps_results = None

    with prepare_file(lines, filename,
                      force_linebreaks=force_linebreaks,
                      create_tempfile=create_tempfile,
                      tempfile_kwargs=tempfile_kwargs) as (file, fname), \
        execute_bear(local_bear, fname, file, dependency_results=deps_results,
                     **local_bear.get_metadata().filter_parameters(settings)
                     ) as bear_output:
        return bear_output
示例#8
0
    def test_profiler_dependency(self, debug=False):
        with bear_test_module():
            with prepare_file(['#fixme  '], None) as (lines, filename):
                results = run_coala(console_printer=ConsolePrinter(),
                                    log_printer=LogPrinter(),
                                    arg_list=(
                                        '-c',
                                        os.devnull,
                                        '-f',
                                        filename,
                                        '-b',
                                        'DependentBear',
                                        '-S',
                                        'use_spaces=yeah',
                                        '--profile',
                                        'profiled_bears',
                                    ),
                                    autoapply=False,
                                    debug=debug)
                cli_result = results[0]['cli']
                self.assertEqual(len(cli_result), 1)

        profiled_files = os.listdir('profiled_bears')
        self.assertEqual(len(profiled_files), 1)
        self.assertEqual(profiled_files[0],
                         'cli_SpaceConsistencyTestBear.prof')
        shutil.rmtree('profiled_bears')
示例#9
0
 def test_fileproxy_init(self):
     with prepare_file([], None) as (_, file):
         url = os.path.normcase(os.getcwd())
         fileproxy = FileProxy(file, url, 'coala')
         self.assertEqual(fileproxy.version, -1)
         self.assertEqual(fileproxy.contents(), 'coala')
         self.assertEqual(fileproxy.workspace, url)
    def test_redirect_threshold(self):
        long_url_redirect = """
        https://bitbucket.org/api/301
        https://bitbucket.org/api/302
        """.splitlines()

        short_url_redirect = """
        http://httpbin.org/status/301
        """.splitlines()

        with requests_mock.Mocker() as m:
            m.add_matcher(custom_matcher)

            self.check_validity(self.uut, long_url_redirect,
                                settings={'follow_redirects': 'true'})

            with prepare_file(short_url_redirect, None,
                              create_tempfile=False) as (lines, _):
                diff = Diff(lines)
                diff.modify_line(2,
                                 '        http://httpbin.org/get\n')

            self.check_results(
                self.uut,
                short_url_redirect,
                [Result.from_values(
                    'InvalidLinkBear',
                    'This link redirects to http://httpbin.org/get',
                    severity=RESULT_SEVERITY.NORMAL,
                    line=2,
                    file='short_url_redirect_text',
                    diffs={'short_url_redirect_text': diff},
                )],
                settings={'follow_redirects': 'true'},
                filename='short_url_redirect_text')
示例#11
0
    def test_caching_results(self):
        """
        A simple integration test to assert that results are not dropped
        when coala is ran multiple times with caching enabled.
        """
        with bear_test_module(), \
                prepare_file(['a=(5,6)'], None) as (lines, filename):
            with simulate_console_inputs('0'):
                retval, output = execute_coala(coala.main, 'coala', '-c',
                                               os.devnull, '--disable-caching',
                                               '--flush-cache', '-f',
                                               re.escape(filename), '-b',
                                               'LineCountTestBear', '-L',
                                               'DEBUG')
                self.assertIn('This file has', output)

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

            retval, output = execute_coala(coala.main, 'coala',
                                           '-c', os.devnull, '-f',
                                           re.escape(filename), '-b',
                                           'LineCountTestBear')
            self.assertIn('This file has', output)
示例#12
0
    def test_output_file(self):
        with prepare_file(['#todo this is todo'], None) as (lines, filename):
            retval, output = execute_coala(coala.main,
                                           'coala',
                                           '--json',
                                           '-c',
                                           os.devnull,
                                           '-b',
                                           'LineCountTestBear',
                                           '-f',
                                           re.escape(filename),
                                           '--log-json',
                                           stdout_only=True)
            execute_coala(coala.main, 'coala', '--json', '-c',
                          os.devnull, '-b', 'LineCountTestBear', '-f',
                          re.escape(filename), '-o', 'file.json', '--log-json')

        with open('file.json') as fp:
            data = json.load(fp)

        output = json.loads(output)
        # Remove 'time' key from both as we cant compare them
        for log_index in range(len(data['logs'])):
            del data['logs'][log_index]['timestamp']
            del output['logs'][log_index]['timestamp']

        self.assertEqual(data, output)
        os.remove('file.json')
示例#13
0
    def test_run_coala_no_autoapply(self, debug=False):
        with bear_test_module():
            with prepare_file(['#fixme  '], None) as (lines, filename):
                self.assertEqual(
                    1,
                    len(run_coala(
                        console_printer=ConsolePrinter(),
                        log_printer=LogPrinter(),
                        arg_list=(
                            '-c', os.devnull,
                            '-f', filename,
                            '-b', 'SpaceConsistencyTestBear',
                            '--apply-patches',
                            '-S', 'use_spaces=yeah'
                        ),
                        autoapply=False,
                        debug=debug
                    )[0]['cli'])
                )

                self.assertEqual(
                    0,
                    len(run_coala(
                        console_printer=ConsolePrinter(),
                        log_printer=LogPrinter(),
                        arg_list=(
                            '-c', os.devnull,
                            '-f', filename,
                            '-b', 'SpaceConsistencyTestBear',
                            '--apply-patches',
                            '-S', 'use_spaces=yeah'
                        ),
                        debug=debug
                    )[0]['cli'])
                )
示例#14
0
 def test_html_in_markdown(self):
     content = html_file.splitlines()
     with prepare_file(content, None) as (file, fname):
         with execute_bear(self.uut, fname, file) as results:
             self.assertEqual(results[0].message,
                              'Do not use HTML in markdown')
             self.assertEqual(results[0].severity, RESULT_SEVERITY.NORMAL)
示例#15
0
    def test_file_cache_proxy_integration(self, debug=False):
        with bear_test_module(), \
                prepare_file(['disk-copy\n'], None) as (_, filename):

            memory_data = 'in-memory\n'
            proxy = FileProxy(filename, None, memory_data)
            proxymap = FileProxyMap([proxy])
            self.cache.set_proxymap(proxymap)

            results, exitcode, file_dicts = run_coala(
                console_printer=ConsolePrinter(),
                log_printer=LogPrinter(),
                arg_list=(
                    '-c',
                    os.devnull,
                    '-f',
                    filename,
                    '-b',
                    'TestBear',
                ),
                autoapply=False,
                debug=debug,
                cache=self.cache)

            self.assertEqual(exitcode, 0)
            self.assertEqual(len(results), 1)

            # run_coala() output's name is always lower case
            self.assertEqual(file_dicts['cli'][filename.lower()],
                             (memory_data, ))
示例#16
0
 def test_find_no_issues(self, debug=False):
     with bear_test_module():
         with prepare_file(['#include <a>'], None) as (lines, filename):
             retval, stdout, stderr = execute_coala(
                 coala.main,
                 'coala',
                 '--non-interactive',
                 '-c',
                 os.devnull,
                 '-f',
                 filename,
                 '-b',
                 'SpaceConsistencyTestBear',
                 '--settings',
                 'use_spaces=True',
                 debug=debug)
             self.assertEqual('Executing section cli...\n', stdout)
             if not debug:
                 self.assertFalse(stderr)
             else:
                 # in debug mode, log_level is also set to DEBUG, causing
                 # stderr output
                 self.assertTrue(stderr)
             self.assertEqual(retval, 0,
                              'coala must return zero when successful')
示例#17
0
 def test_bad_assertComparableObjectsEqual(self):
     with self.assertRaises(AssertionError) as cm:
         self.uut = LineCountTestBear(Section('name'), Queue())
         file_content = 'a\nb\nc'
         with prepare_file(file_content.splitlines(),
                           filename=None,
                           create_tempfile=True) as (file, fname):
             self.check_results(
                 self.uut,
                 file_content.splitlines(), [
                     Result.from_values(origin='LineCountTestBea',
                                        message='This file has 2 lines.',
                                        severity=RESULT_SEVERITY.INFO,
                                        file=fname)
                 ],
                 filename=fname,
                 create_tempfile=False)
     self.assertEqual(
         '\'LineCountTestBear\' != \'LineCountTestBea\'\n'
         '- LineCountTestBear\n'
         '?                 -\n'
         '+ LineCountTestBea\n'
         ' : origin mismatch.\n\n'
         '\'This file has 3 lines.\' != \'This file has 2 '
         'lines.\'\n'
         '- This file has 3 lines.\n'
         '?               ^\n'
         '+ This file has 2 lines.\n'
         '?               ^\n'
         ' : message_base mismatch.\n\n', str(cm.exception))
示例#18
0
    def test_section_ordering(self, debug=False):
        with bear_test_module():
            with prepare_file(['#include <a>'], None) as (lines, filename):
                retval, stdout, stderr = execute_coala(
                        coala.main, 'coala', 'b', 'a',
                        '--non-interactive', '-S',
                        'a.bears=SpaceConsistencyTestBear',
                        'a.files={}'.format(filename),
                        'a.use_spaces=True',
                        'b.bears=SpaceConsistencyTestBear',
                        'b.files={}'.format(filename),
                        'b.use_spaces=True',
                        '-c', os.devnull,
                        debug=debug)
                stdout_list = stdout.splitlines(True)
                self.assertEqual('Executing section b...\n', stdout_list[0])
                self.assertEqual('Executing section a...\n', stdout_list[1])

                retval, stdout, stderr = execute_coala(
                        coala.main, 'coala', 'a', 'b',
                        '--non-interactive', '-S',
                        'a.bears=SpaceConsistencyTestBear',
                        'a.files={}'.format(filename),
                        'a.use_spaces=True',
                        'b.bears=SpaceConsistencyTestBear',
                        'b.files={}'.format(filename),
                        'b.use_spaces=True',
                        '-c', os.devnull,
                        debug=debug)
                stdout_list = stdout.splitlines(True)
                self.assertEqual('Executing section a...\n', stdout_list[0])
                self.assertEqual('Executing section b...\n', stdout_list[1])
示例#19
0
    def test_file_cache_proxy_integration(self, debug=False):
        with bear_test_module():
            with prepare_file(['disk-copy\n'], None) as (_, filename):

                memory_data = 'in-memory\n'
                proxy = FileProxy(filename, None, memory_data)
                proxymap = FileProxyMap([proxy])
                self.cache.set_proxymap(proxymap)

                results, exitcode, file_dicts = run_coala(
                    console_printer=ConsolePrinter(),
                    log_printer=LogPrinter(),
                    arg_list=(
                        '-c', os.devnull,
                        '-f', filename,
                        '-b', 'TestBear',
                    ),
                    autoapply=False,
                    debug=debug,
                    cache=self.cache
                )

                self.assertEqual(exitcode, 0)
                self.assertEqual(len(results), 1)

                # run_coala() output's name is always lower case
                self.assertEqual(file_dicts['cli'][filename.lower()],
                                 (memory_data,))
示例#20
0
 def test_without_simplify(self):
     content = in_file1.splitlines()
     with prepare_file(content, None) as (file, fname):
         with execute_bear(self.uut, fname, file) as results:
             fdict = {fname: file}
             results[0].apply(fdict)
             self.assertEqual(''.join(fdict[fname]), out_file1)
示例#21
0
    def test_coala_no_unexpected_warnings(self):
        with bear_test_module():
            with prepare_file(['#fixme'], None) as (lines, filename):
                retval, stdout, stderr = execute_coala(
                    coala.main, 'coala')
                errors = filter(bool, stderr.split('\n'))
                errors = list(errors)

                unexpected = errors.copy()

                expected = [
                    err for err in unexpected
                    if "Implicit 'Default' section inheritance" in err]
                self.assertNotEqual([], expected)
                # Filter them out
                unexpected = [err for err in unexpected
                              if err not in expected]

                # These errors depend on the state of the host, so ignore them
                ignored = [
                    err for err in unexpected
                    if re.search("No bears matching '.*' were found", err)]

                # Filter them out
                unexpected = [err for err in unexpected if err not in ignored]

                self.assertEqual([], unexpected)
                self.assertEqual(
                    retval, 0,
                    'coala must return zero when there are no errors;'
                    ' errors={errors}'.format(errors=list(errors)))
示例#22
0
    def test_run_coala_no_autoapply(self, debug=False):
        with bear_test_module(), \
                prepare_file(['#fixme  '], None) as (lines, filename):
            self.assertEqual(
                1,
                len(
                    run_coala(console_printer=ConsolePrinter(),
                              log_printer=LogPrinter(),
                              arg_list=('-c', os.devnull, '-f', filename, '-b',
                                        'SpaceConsistencyTestBear',
                                        '--apply-patches', '-S',
                                        'use_spaces=yeah'),
                              autoapply=False,
                              debug=debug)[0]['cli']))

            self.assertEqual(
                0,
                len(
                    run_coala(console_printer=ConsolePrinter(),
                              log_printer=LogPrinter(),
                              arg_list=('-c', os.devnull, '-f', filename, '-b',
                                        'SpaceConsistencyTestBear',
                                        '--apply-patches', '-S',
                                        'use_spaces=yeah'),
                              debug=debug)[0]['cli']))
示例#23
0
 def test_fileproxy_init(self):
     with prepare_file([], None) as (_, file):
         url = os.path.normcase(os.getcwd())
         fileproxy = FileProxy(file, url, 'coala')
         self.assertEqual(fileproxy.version, -1)
         self.assertEqual(fileproxy.contents(), 'coala')
         self.assertEqual(fileproxy.workspace, url)
示例#24
0
def get_results(local_bear,
                lines,
                filename=None,
                force_linebreaks=True,
                create_tempfile=True,
                tempfile_kwargs={},
                settings={}):
    if local_bear.BEAR_DEPS:
        # Get results of bear's dependencies first
        deps_results = dict()
        for bear in local_bear.BEAR_DEPS:
            uut = bear(local_bear.section, queue.Queue())
            deps_results[bear.name] = get_results(uut,
                                                  lines,
                                                  filename,
                                                  force_linebreaks,
                                                  create_tempfile,
                                                  tempfile_kwargs,
                                                  settings)
    else:
        deps_results = None

    with prepare_file(lines, filename,
                      force_linebreaks=force_linebreaks,
                      create_tempfile=create_tempfile,
                      tempfile_kwargs=tempfile_kwargs) as (file, fname), \
        execute_bear(local_bear, fname, file, dependency_results=deps_results,
                     **local_bear.get_metadata().filter_parameters(settings)
                     ) as bear_output:
        return bear_output
 def test_html_in_markdown(self):
     content = html_file.splitlines()
     with prepare_file(content, None) as (file, fname):
         with execute_bear(self.uut, fname, file) as results:
             self.assertEqual(results[0].message,
                              'Do not use HTML in markdown')
             self.assertEqual(results[0].severity, RESULT_SEVERITY.NORMAL)
示例#26
0
    def check_results(self,
                      local_bear,
                      lines,
                      results,
                      filename=None,
                      check_order=False,
                      force_linebreaks=True,
                      create_tempfile=True,
                      tempfile_kwargs={},
                      settings={}):
        """
        Asserts that a check of the given lines with the given local bear does
        yield exactly the given results.

        :param local_bear:       The local bear to check with.
        :param lines:            The lines to check. (List of strings)
        :param results:          The expected list of results.
        :param filename:         The filename, if it matters.
        :param force_linebreaks: Whether to append newlines at each line
                                 if needed. (Bears expect a \\n for every line)
        :param create_tempfile:  Whether to save lines in tempfile if needed.
        :param tempfile_kwargs:  Kwargs passed to tempfile.mkstemp().
        :param settings:         A dictionary of keys and values (both strings)
                                 from which settings will be created that will
                                 be made available for the tested bear.
        """
        assert isinstance(self, unittest.TestCase)
        self.assertIsInstance(local_bear,
                              LocalBear,
                              msg='The given bear is not a local bear.')
        self.assertIsInstance(lines,
                              (list, tuple),
                              msg='The given lines are not a list.')
        self.assertIsInstance(results,
                              list,
                              msg='The given results are not a list.')

        if results in [[], ()]:
            msg = ("The local bear '{}' yields a result although it "
                   "shouldn't.".format(local_bear.__class__.__name__))
            check_order = True
        else:
            msg = ("The local bear '{}' doesn't yield the right results."
                   .format(local_bear.__class__.__name__))
            if check_order:
                msg += ' Or the order may be wrong.'

        with prepare_file(lines, filename,
                          force_linebreaks=force_linebreaks,
                          create_tempfile=create_tempfile,
                          tempfile_kwargs=tempfile_kwargs) as (file, fname), \
                execute_bear(local_bear, fname, file,
                             **settings) as bear_output:
            if not check_order:
                self.assertEqual(sorted(bear_output), sorted(results), msg=msg)
            else:
                self.assertEqual(bear_output, results, msg=msg)

            return bear_output
示例#27
0
 def test_invalid_message(self):
     content = test_file3.splitlines()
     self.section.append(Setting('max_line_length', '10'))
     with prepare_file(content, None) as (file, fname):
         with execute_bear(self.uut, fname, file) as results:
             self.assertEqual(results[0].message,
                              'Line must be at most 10 characters')
             self.assertEqual(results[0].severity, RESULT_SEVERITY.NORMAL)
示例#28
0
 def test_invalid_link(self):
     content = test_file4.splitlines()
     self.section.append(Setting('check_links', True))
     with prepare_file(content, None) as (file, fname):
         with execute_bear(self.uut, fname, file) as results:
             self.assertEqual(results[0].message,
                              'Link to unknown heading: `world`')
             self.assertEqual(results[0].severity, RESULT_SEVERITY.NORMAL)
 def test_first_heading_level(self):
     content = first_heading_level_file.splitlines()
     self.section.append(Setting('first_heading_level', 2))
     with prepare_file(content, None) as (file, fname):
         with execute_bear(self.uut, fname, file) as results:
             self.assertEqual(results[0].message,
                              'First heading level should be `2`')
             self.assertEqual(results[0].severity, RESULT_SEVERITY.NORMAL)
示例#30
0
    def test_fileproxy_str(self):
        with prepare_file([], None) as (_, file):
            empty_fileproxy = FileProxy(file)

            gen_str = '<FileProxy {}, {}>'.format(empty_fileproxy.filename,
                                                  empty_fileproxy.version)

            self.assertEqual(gen_str, str(empty_fileproxy))
示例#31
0
    def test_fileproxy_from_file(self):
        with prepare_file(['coala\n'], None) as (_, file):
            fileproxy = FileProxy.from_file(file, None)

            self.assertEqual(fileproxy.version, -1)
            self.assertEqual(fileproxy.workspace, None)
            self.assertEqual(fileproxy.contents(), 'coala\n')
            self.assertEqual(fileproxy.filename, os.path.normcase(file))
示例#32
0
    def test_get_file_dict_with_proxy_map(self):
        with prepare_file([], None) as (_, file):
            proxy = FileProxy(file, None, 'coala\n')
            proxymap = FileProxyMap([proxy])
            self.cache.set_proxymap(proxymap)

            file_dict = self.cache.get_file_dict([file])
            self.assertEqual(file_dict, {file: ('coala\n', )})
示例#33
0
    def test_fileproxy_str(self):
        with prepare_file([], None) as (_, file):
            empty_fileproxy = FileProxy(file)

            gen_str = (f'<FileProxy {empty_fileproxy.filename}, '
                       f'{empty_fileproxy.version}>')

            self.assertEqual(gen_str, str(empty_fileproxy))
示例#34
0
 def test_blockquote_indentation(self):
     content = blockquote_indentation_file.splitlines()
     with prepare_file(content, None) as (file, fname):
         with execute_bear(self.uut, fname, file) as results:
             self.assertEqual(results[0].message,
                              'Remove 1 space between blockquote and '
                              'content')
             self.assertEqual(results[0].severity, RESULT_SEVERITY.NORMAL)
 def test_invalid_link(self):
     content = test_file4.splitlines()
     self.section.append(Setting('check_links', True))
     with prepare_file(content, None) as (file, fname):
         with execute_bear(self.uut, fname, file) as results:
             self.assertEqual(results[0].message,
                              'Link to unknown heading: `world`')
             self.assertEqual(results[0].severity, RESULT_SEVERITY.NORMAL)
示例#36
0
 def test_duplicate_headings(self):
     content = duplicate_heading_file.splitlines()
     with prepare_file(content, None) as (file, fname):
         with execute_bear(self.uut, fname, file) as results:
             self.assertEqual(results[0].message,
                              'Do not use headings with similar content '
                              'per section (3:1)')
             self.assertEqual(results[0].severity, RESULT_SEVERITY.NORMAL)
示例#37
0
 def test_first_heading_level(self):
     content = first_heading_level_file.splitlines()
     self.section.append(Setting('first_heading_level', 2))
     with prepare_file(content, None) as (file, fname):
         with execute_bear(self.uut, fname, file) as results:
             self.assertEqual(results[0].message,
                              'First heading level should be `2`')
             self.assertEqual(results[0].severity, RESULT_SEVERITY.NORMAL)
 def test_invalid_message(self):
     content = test_file3.splitlines()
     self.section.append(Setting('max_line_length', '10'))
     with prepare_file(content, None) as (file, fname):
         with execute_bear(self.uut, fname, file) as results:
             self.assertEqual(results[0].message,
                              'Line must be at most 10 characters')
             self.assertEqual(results[0].severity, RESULT_SEVERITY.NORMAL)
示例#39
0
 def test_checkbox_content_indentation(self):
     content = checkbox_content_indentation_file.splitlines()
     with prepare_file(content, None) as (file, fname):
         with execute_bear(self.uut, fname, file) as results:
             self.assertEqual(results[0].message,
                              'Checkboxes should be followed by a single '
                              'character')
             self.assertEqual(results[0].severity, RESULT_SEVERITY.NORMAL)
示例#40
0
 def prep_file():
     with prepare_file(dedent(file).splitlines(True),
                       None,
                       tempfile_kwargs={'suffix': '.py'
                                        }) as lines_filename:
         lines, filename = lines_filename
         self.file_dict[filename] = file
         yield
示例#41
0
    def test_get_file_dict_with_proxy_map(self):
        with prepare_file([], None) as (_, file):
            proxy = FileProxy(file, None, 'coala\n')
            proxymap = FileProxyMap([proxy])
            self.cache.set_proxymap(proxymap)

            file_dict = self.cache.get_file_dict([file])
            self.assertEqual(file_dict, {file: ('coala\n',)})
示例#42
0
    def test_fileproxy_from_file(self):
        with prepare_file(['coala\n'], None) as (_, file):
            fileproxy = FileProxy.from_file(file, None)

            self.assertEqual(fileproxy.version, -1)
            self.assertEqual(fileproxy.workspace, None)
            self.assertEqual(fileproxy.contents(), 'coala\n')
            self.assertEqual(fileproxy.filename, os.path.normcase(file))
示例#43
0
    def test_fileproxy_str(self):
        with prepare_file([], None) as (_, file):
            empty_fileproxy = FileProxy(file)

            gen_str = '<FileProxy {}, {}>'.format(
                empty_fileproxy.filename, empty_fileproxy.version)

            self.assertEqual(gen_str, str(empty_fileproxy))
 def test_heading_level_increment(self):
     content = heading_level_increment_file.splitlines()
     self.section.append(Setting('enforce_heading_level_increment', True))
     with prepare_file(content, None) as (file, fname):
         with execute_bear(self.uut, fname, file) as results:
             self.assertEqual(results[0].message,
                              'Heading levels should increment by one '
                              'level at a time')
             self.assertEqual(results[0].severity, RESULT_SEVERITY.NORMAL)
示例#45
0
    def test_fileproxy_relative_name(self):
        with prepare_file(['coala'], None) as (_, file):
            relative_url = os.path.relpath(file, __file__)

            with self.assertRaises(ValueError) as context:
                FileProxy(relative_url)

            self.assertEqual('expecting absolute filename',
                             str(context.exception))
示例#46
0
 def test_coala(self):
     with bear_test_module(), \
             prepare_file(['#fixme'], None) as (lines, filename):
         retval, output = execute_coala(coala.main, 'coala',
                                        '-c', os.devnull, '-f',
                                        re.escape(filename), '-b',
                                        'LineCountTestBear')
         self.assertIn('This file has 1 lines.', output,
                       'The output should report count as 1 lines')
示例#47
0
 def test_good_function(self):
     prepared = prepare_file(good_file_function.splitlines(),
                             filename=None,
                             create_tempfile=True)
     with prepared as (file, fname):
         self.check_results(self.uut,
                            good_file_function.splitlines(), [],
                            filename=fname,
                            create_tempfile=False)
 def test_warning(self):
     content = test_file.splitlines()
     with prepare_file(content, None) as (file, fname):
         with execute_bear(self.uut, fname, file) as results:
             self.assertEqual(results[6].message, 'comment not indented'
                              ' like content (comments-indentation)')
             self.assertEqual(results[6].affected_code[0].start.line, 11)
             self.assertEqual(results[6].affected_code[0].end.line, 11)
             self.assertEqual(results[6].severity, RESULT_SEVERITY.NORMAL)
 def prep_file():
     with prepare_file(
         dedent(file).splitlines(True),
         None,
         tempfile_kwargs={'suffix': '.py'}
     ) as lines_filename:
         lines, filename = lines_filename
         self.file_dict[filename] = file
         yield
示例#50
0
    def test_fileproxy_relative_name(self):
        with prepare_file(['coala'], None) as (_, file):
            relative_url = os.path.relpath(file, __file__)

            with self.assertRaises(ValueError) as context:
                FileProxy(relative_url)

            self.assertEqual('expecting absolute filename',
                             str(context.exception))
示例#51
0
    def test_proxymap_resolve_not_finds_soft(self):
        with prepare_file(['coala\n'], None) as (_, file):
            missing_file = file + 'coala'
            proxy = self.empty_proxymap().resolve(
                missing_file, None, hard_sync=False)

            normcased = os.path.normcase(missing_file)
            self.assertEqual(proxy.filename, normcased)
            self.assertEqual(proxy.contents(), '')
示例#52
0
    def test_proxymap_resolve_create_soft_relative_name(self):
        with prepare_file([], None) as (_, file):
            relative_url = os.path.relpath(file, __file__)

            with self.assertRaises(ValueError) as context:
                self.empty_proxymap().resolve(relative_url, hard_sync=False)

            self.assertEqual('expecting absolute filename',
                             str(context.exception))
 def test_line_length(self):
     content = long_line.splitlines()
     with prepare_file(content, None) as (file, fname):
         with execute_bear(self.uut, fname, file) as results:
             result = results[0]
             self.assertEqual(result.message,
                              'E501 line too long (106 > 30 characters)')
             self.assertEqual(result.origin, 'PycodestyleBear (E501)')
             self.assertEqual(result.aspect, LineLength('py'))
 def test_error(self):
     content = test_file.splitlines()
     with prepare_file(content, None) as (file, fname):
         with execute_bear(self.uut, fname, file) as results:
             self.assertEqual(results[0].message, 'too many blank lines'
                              ' (1 > 0) (empty-lines)')
             self.assertEqual(results[0].affected_code[0].start.line, 1)
             self.assertEqual(results[0].affected_code[0].end.line, 1)
             self.assertEqual(results[0].severity, RESULT_SEVERITY.MAJOR)
 def test_bad_max_line_length(self):
     self.section.append(Setting('max_line_length', 50))
     content = bad_max_line_length.splitlines()
     with prepare_file(content, None) as (file, fname):
         with execute_bear(self.uut, fname, file) as results:
             self.assertEqual(results[0].message, 'line too long '
                              '(52 > 50 characters) (line-length)')
             self.assertEqual(results[0].affected_code[0].start.line, 2)
             self.assertEqual(results[0].affected_code[0].end.line, 2)
             self.assertEqual(results[0].severity, RESULT_SEVERITY.MAJOR)
示例#56
0
    def test_proxymap_get(self):
        proxymap = self.empty_proxymap()

        with prepare_file([], None) as (_, file):
            assert proxymap.get(file) is None

        proxy = self.random_proxy()
        proxymap.add(proxy)

        self.assertEqual(proxymap.get(proxy.filename), proxy)