Example #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")
Example #2
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")
Example #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')
Example #4
0
    def test_output_file(self):
        with prepare_file(["#todo this is todo"], None) as (lines, filename):
            retval, output = execute_coala(
                coala_json.main, "coala-json", "-c", os.devnull, "-b", "LineCountTestBear", "-f", re.escape(filename)
            )
            exp_retval, exp_output = execute_coala(
                coala_json.main,
                "coala-json",
                "-c",
                os.devnull,
                "-b",
                "LineCountTestBear",
                "-f",
                re.escape(filename),
                "-o",
                "file.json",
            )

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

        output = json.loads(output)

        self.assertEqual(data["logs"][0]["log_level"], output["logs"][0]["log_level"])
        os.remove("file.json")
Example #5
0
 def test_tagging(self):
     with bear_test_module(), prepare_file(["\t#include <a>"], None) as (lines, filename):
         log_printer = LogPrinter(NullPrinter())
         execute_coala(
             coala_ci.main,
             "coala-ci",
             "default",
             "-c",
             self.coafile,
             "-f",
             re.escape(filename),
             "-b",
             "SpaceConsistencyTestBear",
             "-S",
             "tag=test_tag",
         )
         tag_path = get_tag_path("test_tag", self.unescaped_coafile, log_printer)
         self.assertTrue(os.path.exists(tag_path))
         execute_coala(
             coala_ci.main,
             "coala-ci",
             "default",
             "-c",
             self.coafile,
             "-f",
             re.escape(filename),
             "-b",
             "SpaceConsistencyTestBear",
             "-S",
             "dtag=test_tag",
         )
         self.assertFalse(os.path.exists(tag_path))
Example #6
0
 def test_find_issues(self):
     with bear_test_module(), prepare_file(["#fixme"], None) as (lines, filename):
         retval, output = execute_coala(
             coala_ci.main, "coala-ci", "-c", os.devnull, "-b", "LineCountTestBear", "-f", re.escape(filename)
         )
         self.assertIn("This file has 1 lines.", output, "The output should report count as 1 lines")
         self.assertNotEqual(retval, 0, "coala-ci was expected to return non-zero")
Example #7
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)
Example #8
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)
    def test_output_file(self):
        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",
                          "--nolaunch")

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

        self.assertEqual(update_file, noupdate_file)
Example #10
0
 def test_find_issues(self):
     with bear_test_module(), prepare_file(["#fixme"], None) as (lines, filename):
         retval, output = execute_coala(
             coala_json.main, "coala-json", "-c", os.devnull, "-b", "LineCountTestBear", "-f", re.escape(filename)
         )
         output = json.loads(output)
         self.assertEqual(output["results"]["default"][0]["message"], "This file has 1 lines.")
         self.assertNotEqual(retval, 0, "coala-json must return nonzero when " "results found")
Example #11
0
 def test_coala(self):
     with prepare_file(["#fixme"], None) as (lines, filename):
         bear = "LineCountBear"
         retval, output = execute_coala(coala.main, "coala", "-c",
                                        os.devnull, "--settings",
                                        "files=" + re.escape(filename),
                                        "bears=" + bear)
     self.assertIn("This file has 1 lines.", output,
                   "The output should report count as 1 lines")
Example #12
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')
Example #13
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")
Example #14
0
 def test_fix_patchable_issues(self):
     with prepare_file(["    #include <a>"], None) as (lines, filename):
         bear = "IndentBear"
         retval, output = execute_coala(
             coala_ci.main, "coala-ci", "-c", os.devnull, "--settings",
             "files=" + filename, "bears=" + bear, "autoapply=true",
             "default_actions=" + bear + ":ApplyPatchAction")
         self.assertEqual(
             retval, 5, "coala-ci must return exitcode 5 when it "
             "autofixes the code.")
Example #15
0
 def test_fix_patchable_issues(self):
     with prepare_file(["    #include <a>"], None) as (lines, filename):
         bear = "IndentBear"
         retval, output = execute_coala(
             coala_ci.main, "coala-ci", "-c", os.devnull, "--settings",
             "files=" + filename, "bears=" + bear, "autoapply=true",
             "default_actions=" + bear + ":ApplyPatchAction")
         self.assertEqual(retval,
                          5,
                          "coala-ci must return exitcode 5 when it "
                          "autofixes the code.")
Example #16
0
 def test_find_no_issues(self):
     with bear_test_module(), \
             prepare_file(["#include <a>"], None) as (lines, filename):
         retval, output = execute_coala(coala_ci.main, "coala-ci",
                                        '-c', os.devnull,
                                        '-f', re.escape(filename),
                                        '-b', 'SpaceConsistencyTestBear',
                                        "--settings", "use_spaces=True")
         self.assertIn("Executing section Default", output)
         self.assertEqual(retval, 0,
                          "coala-ci must return zero when successful")
Example #17
0
 def test_coala(self):
     with prepare_file(["#fixme"], None) as (lines, filename):
         bear = "LineCountBear"
         retval, output = execute_coala(
                          coala.main,
                         "coala", "-c", os.devnull,
                         "--settings", "files=" + re.escape(filename),
                         "bears=" + bear)
     self.assertIn("This file has 1 lines.",
                   output,
                   "The output should report count as 1 lines")
Example #18
0
 def test_find_no_issues(self):
     with bear_test_module(), \
             prepare_file(["#include <a>"], None) as (lines, filename):
         retval, output = execute_coala(coala_ci.main, "coala-ci",
                                        '-c', os.devnull, '-f',
                                        re.escape(filename), '-b',
                                        'SpaceConsistencyTestBear',
                                        "--settings", "use_spaces=True")
         self.assertIn("Executing section Default", output)
         self.assertEqual(retval, 0,
                          "coala-ci must return zero when successful")
Example #19
0
    def check_results(self,
                      local_bear,
                      lines,
                      results,
                      filename=None,
                      check_order=False,
                      force_linebreaks=True,
                      create_tempfile=True,
                      tempfile_kwargs={}):
        """
        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. (string if single line
                                 or List of strings)
        :param results:          The expected result or 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().
        """
        if isinstance(lines, str):
            lines = [lines]
        if isinstance(results, Result):
            results = [results]

        assert isinstance(self, unittest.TestCase)
        self.assertIsInstance(local_bear,
                              LocalBear,
                              msg="The given bear is not a local bear.")
        self.assertIsInstance(lines,
                              list,
                              msg="The given lines are not a list.")
        self.assertIsInstance(results,
                              list,
                              msg="The given results are not a list.")

        with prepare_file(lines,
                          filename,
                          force_linebreaks=force_linebreaks,
                          create_tempfile=create_tempfile,
                          tempfile_kwargs=tempfile_kwargs) as (lines,
                                                               filename):

            bear_output = execute_bear(local_bear, filename, lines)
            msg = (
                "The local bear '{}' doesn't yield the right results. Or the"
                " order may be wrong.".format(local_bear.__class__.__name__))
            if not check_order:
                self.assertEqual(sorted(bear_output), sorted(results), msg=msg)
            else:
                self.assertEqual(bear_output, results, msg=msg)
Example #20
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")
Example #21
0
 def test_find_issues(self):
     with bear_test_module(), \
             prepare_file(["#fixme"], None) as (lines, filename):
         retval, output = execute_coala(coala_ci.main, "coala-ci", "-c",
                                        os.devnull, "-b",
                                        "LineCountTestBear", "-f",
                                        re.escape(filename))
         self.assertIn("This file has 1 lines.", output,
                       "The output should report count as 1 lines")
         self.assertNotEqual(retval, 0,
                             "coala-ci was expected to return non-zero")
Example #22
0
 def test_fix_patchable_issues(self):
     with bear_test_module(), \
             prepare_file(["\t#include <a>"], None) as (lines, filename):
         retval, output = execute_coala(
             coala_ci.main, "coala-ci", "-c", os.devnull, "-f",
             re.escape(filename), "-b", "SpaceConsistencyTestBear",
             "--settings", "autoapply=true", "use_spaces=True",
             "default_actions=SpaceConsistencyTestBear:ApplyPatchAction")
         self.assertIn("Applied 'ApplyPatchAction'", output)
         self.assertEqual(
             retval, 5, "coala-ci must return exitcode 5 when it "
             "autofixes the code.")
Example #23
0
 def test_find_no_issues(self):
     with bear_test_module(), \
             prepare_file(['#include <a>'], None) as (lines, filename):
         retval, output = execute_coala(coala.main, 'coala',
                                        '--non-interactive',
                                        '-c', os.devnull,
                                        '-f', re.escape(filename),
                                        '-b', 'SpaceConsistencyTestBear',
                                        '--settings', 'use_spaces=True')
         self.assertIn('Executing section Default', output)
         self.assertEqual(retval, 0,
                          'coala-ci must return zero when successful')
    def check_results(self,
                      local_bear,
                      lines,
                      results,
                      filename=None,
                      check_order=False,
                      force_linebreaks=True,
                      create_tempfile=True,
                      tempfile_kwargs={}):
        """
        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. (string if single line
                                 or List of strings)
        :param results:          The expected result or 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().
        """
        if isinstance(lines, str):
            lines = [lines]
        if isinstance(results, Result):
            results = [results]

        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.")

        with prepare_file(lines,
                          filename,
                          force_linebreaks=force_linebreaks,
                          create_tempfile=create_tempfile,
                          tempfile_kwargs=tempfile_kwargs) as (lines, filename):

            bear_output = execute_bear(local_bear, filename, lines)
            msg = ("The local bear '{}' doesn't yield the right results. Or the"
                   " order may be wrong.".format(local_bear.__class__.__name__))
            if not check_order:
                self.assertEqual(sorted(bear_output), sorted(results), msg=msg)
            else:
                self.assertEqual(bear_output, results, msg=msg)
Example #25
0
 def test_line_count(self):
     with bear_test_module(), \
             prepare_file(["#fixme"], None) as (lines, filename):
         retval, output = execute_coala(coala_format.main, "coala-format",
                                        "-c", os.devnull,
                                        "-f", re.escape(filename),
                                        "-b", "LineCountTestBear")
         self.assertRegex(output, r'msg:This file has [0-9]+ lines.',
                          "coala-format output for line count should "
                          "not be empty")
         self.assertEqual(retval, 1,
                          "coala-format must return exitcode 1 when it "
                          "yields results")
Example #26
0
 def test_find_issues(self):
     with bear_test_module(), \
             prepare_file(['#fixme'], None) as (lines, filename):
         retval, output = execute_coala(coala.main, 'coala',
                                        '--non-interactive',
                                        '-c', os.devnull,
                                        '-b', 'LineCountTestBear',
                                        '-f', re.escape(filename))
         self.assertIn('This file has 1 lines.',
                       output,
                       'The output should report count as 1 lines')
         self.assertNotEqual(retval, 0,
                             'coala-ci was expected to return non-zero')
Example #27
0
 def test_show_patch(self):
     with bear_test_module(), \
          prepare_file(["\t#include <a>"], None) as (lines, filename):
         retval, output = execute_coala(
             coala_ci.main, "coala-ci",
             "-c", os.devnull,
             "-f", re.escape(filename),
             "-b", "SpaceConsistencyTestBear",
             "--settings", "use_spaces=True")
         self.assertIn("Applied 'ShowPatchAction'", output)
         self.assertEqual(retval, 5,
                          "coala-ci must return exitcode 5 when it "
                          "autofixes the code.")
Example #28
0
    def test_stdin_input(self):
        with prepare_file(["abcd", "efgh"], None) as (lines, filename):
            # Use more which is a command that can take stdin and show it.
            # This is available in windows and unix.
            self.uut.executable = "more"
            self.uut.use_stdin = True
            self.uut.use_stderr = False
            self.uut.process_output = lambda output, filename, file: output

            out = self.uut.lint(file=lines)
            # Some implementations of `more` add an extra newline at the end.
            self.assertTrue(("abcd\n", "efgh\n") == out
                            or ("abcd\n", "efgh\n", "\n") == out)
Example #29
0
 def test_line_count(self):
     with bear_test_module(), \
             prepare_file(["#fixme"], None) as (lines, filename):
         retval, output = execute_coala(coala_format.main, "coala-format",
                                        "-c", os.devnull,
                                        "-f", re.escape(filename),
                                        "-b", "LineCountTestBear")
         self.assertRegex(output, r'msg:This file has [0-9]+ lines.',
                          "coala-format output for line count should "
                          "not be empty")
         self.assertEqual(retval, 1,
                          "coala-format must return exitcode 1 when it "
                          "yields results")
Example #30
0
 def test_find_issues(self):
     with bear_test_module(), \
             prepare_file(["#fixme"], None) as (lines, filename):
         retval, output = execute_coala(coala_json.main, "coala-json", "-c",
                                        os.devnull, "-b",
                                        "LineCountTestBear", "-f",
                                        re.escape(filename))
         output = json.loads(output)
         self.assertEqual(output["results"]["default"][0]["message"],
                          "This file has 1 lines.")
         self.assertNotEqual(
             retval, 0, "coala-json must return nonzero when "
             "results found")
Example #31
0
 def test_find_issues(self):
     with bear_test_module(), \
             prepare_file(['#fixme'], None) as (lines, filename):
         retval, output = execute_coala(coala.main, 'coala', '--json', '-c',
                                        os.devnull, '-b',
                                        'LineCountTestBear', '-f',
                                        re.escape(filename))
         output = json.loads(output)
         self.assertEqual(output['results']['default'][0]['message'],
                          'This file has 1 lines.')
         self.assertNotEqual(
             retval, 0, 'coala-json must return nonzero when '
             'results found')
Example #32
0
    def test_stdin_input(self):
        with prepare_file(["abcd", "efgh"], None) as (lines, filename):
            # Use more which is a command that can take stdin and show it.
            # This is available in windows and unix.
            self.uut.executable = "more"
            self.uut.use_stdin = True
            self.uut.use_stderr = False
            self.uut.process_output = lambda output, filename, file: output

            out = self.uut.lint(file=lines)
            # Some implementations of `more` add an extra newline at the end.
            self.assertTrue(("abcd\n", "efgh\n") == out or
                            ("abcd\n", "efgh\n", "\n") == out)
Example #33
0
 def test_show_patch(self):
     with bear_test_module(), \
          prepare_file(["\t#include <a>"], None) as (lines, filename):
         retval, output = execute_coala(
             coala_ci.main, "coala-ci",
             "-c", os.devnull,
             "-f", re.escape(filename),
             "-b", "SpaceConsistencyTestBear",
             "--settings", "use_spaces=True")
         self.assertIn("Line contains ", output)  # Result message is shown
         self.assertIn("Applied 'ShowPatchAction'", output)
         self.assertEqual(retval, 5,
                          "coala-ci must return exitcode 5 when it "
                          "autofixes the code.")
Example #34
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.")

        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:
            msg = ("The local bear '{}' doesn't yield the right results. Or "
                   "the order may be wrong."
                   .format(local_bear.__class__.__name__))
            if not check_order:
                self.assertEqual(sorted(bear_output), sorted(results), msg=msg)
            else:
                self.assertEqual(bear_output, results, msg=msg)
Example #35
0
 def test_line_count(self):
     with bear_test_module(), \
             prepare_file(['#fixme'], None) as (lines, filename):
         retval, output = execute_coala(coala.main, 'coala', '--format',
                                        '-c', os.devnull, '-f',
                                        re.escape(filename), '-b',
                                        'LineCountTestBear')
         self.assertRegex(
             output, r'message:This file has [0-9]+ lines.',
             'coala-format output for line count should '
             'not be empty')
         self.assertEqual(
             retval, 1, 'coala-format must return exitcode 1 when it '
             'yields results')
Example #36
0
    def check_validity(
        self,
        local_bear,
        lines,
        filename=None,
        valid=True,
        force_linebreaks=True,
        create_tempfile=True,
        tempfile_kwargs={},
    ):
        """
        Asserts that a check of the given lines with the given local bear
        either yields or does not yield any results.

        :param local_bear:       The local bear to check with.
        :param lines:            The lines to check. (string if single line
                                 or List of strings)
        :param filename:         The filename, if it matters.
        :param valid:            Whether the lines are valid or not.
        :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().
        """
        if isinstance(lines, str):
            lines = [lines]

        assert isinstance(self, unittest.TestCase)
        self.assertIsInstance(local_bear, LocalBear, msg="The given bear is not a local bear.")
        self.assertIsInstance(lines, list, msg="The given lines are not a list.")

        with prepare_file(
            lines,
            filename,
            force_linebreaks=force_linebreaks,
            create_tempfile=create_tempfile,
            tempfile_kwargs=tempfile_kwargs,
        ) as (lines, filename):

            bear_output = execute_bear(local_bear, filename, lines)
            if valid:
                msg = "The local bear '{}' yields a result although it " "shouldn't.".format(
                    local_bear.__class__.__name__
                )
                self.assertEqual(bear_output, [], msg=msg)
            else:
                msg = "The local bear '{}' yields no result although it " "should.".format(
                    local_bear.__class__.__name__
                )
                self.assertNotEqual(len(bear_output), 0, msg=msg)
Example #37
0
 def test_show_patch(self):
     with bear_test_module(), \
          prepare_file(['\t#include <a>'], None) as (lines, filename):
         retval, output = execute_coala(
             coala.main, 'coala', '--non-interactive',
             '-c', os.devnull,
             '-f', re.escape(filename),
             '-b', 'SpaceConsistencyTestBear',
             '--settings', 'use_spaces=True')
         self.assertIn('Line contains ', output)  # Result message is shown
         self.assertIn("Applied 'ShowPatchAction'", output)
         self.assertEqual(retval, 5,
                          'coala-ci must return exitcode 5 when it '
                          'autofixes the code.')
Example #38
0
 def test_tagging(self):
     with bear_test_module(), \
             prepare_file(["\t#include <a>"], None) as (lines, filename):
         log_printer = LogPrinter(NullPrinter())
         execute_coala(coala_ci.main, "coala-ci", "default", "-c",
                       self.coafile, "-f", re.escape(filename), "-b",
                       "SpaceConsistencyTestBear", "-S", "tag=test_tag")
         tag_path = get_tag_path("test_tag", self.unescaped_coafile,
                                 log_printer)
         self.assertTrue(os.path.exists(tag_path))
         execute_coala(coala_ci.main, "coala-ci", "default", "-c",
                       self.coafile, "-f", re.escape(filename), "-b",
                       "SpaceConsistencyTestBear", "-S", "dtag=test_tag")
         self.assertFalse(os.path.exists(tag_path))
Example #39
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.')

        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:
            msg = ("The local bear '{}' doesn't yield the right results. Or "
                   'the order may be wrong.'
                   .format(local_bear.__class__.__name__))
            if not check_order:
                self.assertEqual(sorted(bear_output), sorted(results), msg=msg)
            else:
                self.assertEqual(bear_output, results, msg=msg)
Example #40
0
    def check_validity(self,
                       local_bear,
                       lines,
                       filename=None,
                       valid=True,
                       force_linebreaks=True,
                       create_tempfile=True,
                       tempfile_kwargs={}):
        """
        Asserts that a check of the given lines with the given local bear
        either yields or does not yield any results.

        :param local_bear:       The local bear to check with.
        :param lines:            The lines to check. (string if single line
                                 or List of strings)
        :param filename:         The filename, if it matters.
        :param valid:            Whether the lines are valid or not.
        :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().
        """
        if isinstance(lines, str):
            lines = [lines]

        assert isinstance(self, unittest.TestCase)
        self.assertIsInstance(local_bear,
                              LocalBear,
                              msg="The given bear is not a local bear.")
        self.assertIsInstance(lines,
                              list,
                              msg="The given lines are not a list.")

        with prepare_file(lines,
                          filename,
                          force_linebreaks=force_linebreaks,
                          create_tempfile=create_tempfile,
                          tempfile_kwargs=tempfile_kwargs) as (lines,
                                                               filename):

            bear_output = execute_bear(local_bear, filename, lines)
            if valid:
                msg = ("The local bear '{}' yields a result although it "
                       "shouldn't.".format(local_bear.__class__.__name__))
                self.assertEqual(bear_output, [], msg=msg)
            else:
                msg = ("The local bear '{}' yields no result although it "
                       "should.".format(local_bear.__class__.__name__))
                self.assertNotEqual(len(bear_output), 0, msg=msg)
Example #41
0
 def test_find_issues(self):
     with prepare_file(["#todo this is todo"], None) as (lines, filename):
         bear = "KeywordBear"
         retval, output = execute_coala(coala_ci.main, "coala-ci", "-c",
                                        os.devnull, "-S",
                                        "ci_keywords=#TODO",
                                        "cs_keywords=#todo",
                                        "bears=" + bear,
                                        "-f", re.escape(filename))
         self.assertIn("The line contains the keyword `#todo`.",
                       output, "coala-ci output should match the keyword\
                       #todo")
         self.assertNotEqual(retval,
                             0, "coala-ci must return nonzero when "
                             "matching `#todo` keyword")
Example #42
0
 def test_find_issues(self):
     with prepare_file(["#todo this is todo"], None) as (lines, filename):
         bear = "KeywordBear"
         retval, output = execute_coala(coala_json.main, "coala-json", "-c",
                                        os.devnull, "-S",
                                        "ci_keywords=#TODO",
                                        "cs_keywords=#todo",
                                        "bears=" + bear,
                                        "-f", re.escape(filename))
         output = json.loads(output)
         self.assertEqual(output["results"]["default"][0]["message"],
                          "The line contains the keyword `#todo`.",
                          "coala-json output should match the keyword #todo")
         self.assertNotEqual(retval,
                             0, "coala-json must return nonzero when "
                             "matching `#todo` keyword")
Example #43
0
 def test_find_issues(self):
     with prepare_file(["#todo this is todo"], None) as (lines, filename):
         bear = "KeywordBear"
         retval, output = execute_coala(coala_ci.main, "coala-ci", "-c",
                                        os.devnull, "-S",
                                        "ci_keywords=#TODO",
                                        "cs_keywords=#todo",
                                        "bears=" + bear, "-f",
                                        re.escape(filename))
         self.assertIn(
             "The line contains the keyword `#todo`.", output,
             "coala-ci output should match the keyword\
                       #todo")
         self.assertNotEqual(
             retval, 0, "coala-ci must return nonzero when "
             "matching `#todo` keyword")
Example #44
0
 def test_find_issues(self):
     with prepare_file(["#todo this is todo"], None) as (lines, filename):
         bear = "KeywordBear"
         retval, output = execute_coala(coala_json.main, "coala-json", "-c",
                                        os.devnull, "-S",
                                        "ci_keywords=#TODO",
                                        "cs_keywords=#todo",
                                        "bears=" + bear, "-f",
                                        re.escape(filename))
         output = json.loads(output)
         self.assertEqual(
             output["results"]["default"][0]["message"],
             "The line contains the keyword `#todo`.",
             "coala-json output should match the keyword #todo")
         self.assertNotEqual(
             retval, 0, "coala-json must return nonzero when "
             "matching `#todo` keyword")
Example #45
0
    def test_output_file(self):
        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", "--nolaunch")

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

        self.assertEqual(update_file, noupdate_file)
Example #46
0
    def test_output_file(self):
        with prepare_file(["#todo this is todo"], None) as (lines, filename):
            retval, output = execute_coala(coala_json.main, "coala-json",
                                           "-c", os.devnull,
                                           "-b", "LineCountTestBear",
                                           "-f", re.escape(filename),
                                           stdout_only=True)
            execute_coala(coala_json.main, "coala-json", "-c", os.devnull,
                          "-b", "LineCountTestBear", "-f", re.escape(filename),
                          "-o", "file.json")

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

        output = json.loads(output)

        self.assertEqual(data, output)
        os.remove('file.json')
Example #47
0
    def test_output_file(self):
        with prepare_file(["#todo this is todo"], None) as (lines, filename):
            retval, output = execute_coala(coala_json.main, "coala-json", "-c",
                                           os.devnull, "-b",
                                           "LineCountTestBear", "-f",
                                           re.escape(filename))
            exp_retval, exp_output = execute_coala(coala_json.main,
                                                   "coala-json", "-c",
                                                   os.devnull, "-b",
                                                   "LineCountTestBear", "-f",
                                                   re.escape(filename), "-o",
                                                   "file.json")

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

        output = json.loads(output)

        self.assertEqual(data['logs'][0]['log_level'],
                         output['logs'][0]['log_level'])
        os.remove('file.json')
Example #48
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)
Example #49
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,
                    "--flush-cache",
                    "--changed-files",
                    "-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,
                "--changed-files",
                "-f", re.escape(filename),
                "-b", "LineCountTestBear")
            self.assertIn("This file has", output)

            retval, output = execute_coala(
                coala.main,
                "coala",
                "-c", os.devnull,
                "--changed-files",
                "-f", re.escape(filename),
                "-b", "LineCountTestBear")
            self.assertIn("This file has", output)
Example #50
0
 def test_discarded_note(self):
     source = dedent("""
         def f() -> None:
             1 + "a"
     """).splitlines()
     prepared = prepare_file(source, filename=None, create_tempfile=True)
     with prepared as (file, fname):
         results = [
             Result.from_values(
                 message=(
                     'Unsupported operand types for + ("int" and "str")'),
                 file=fname,
                 line=3,
                 origin=self.uut,
                 severity=RESULT_SEVERITY.MAJOR,
             )
         ]
         self.check_results(self.uut,
                            source,
                            results=results,
                            filename=fname,
                            create_tempfile=False)
Example #51
0
    def run(self, filename, file,
            max_line_length: int=79,
            indent_size: int=SpacingHelper.DEFAULT_TAB_WIDTH,
            allow_multiline_lambdas: bool=False,
            blank_line_before_nested_class_or_def: bool=False,
            continuation_tab_width: int=SpacingHelper.DEFAULT_TAB_WIDTH,
            dedent_closing_brackets: bool=False,
            indent_dictionary_value: bool=False,
            coalesce_brackets: bool=False,
            join_multiple_lines: bool=True,
            spaces_around_power_operator: bool=True,
            spaces_before_comment: int=2,
            space_between_ending_comma_and_closing_bracket: bool=False,
            split_arguments_when_comma_terminated: bool=False,
            split_before_bitwise_operator: bool=False,
            split_before_first_argument: bool=False,
            split_before_logical_operator: bool=False,
            split_before_named_assigns: bool=True,
            use_spaces: bool=True,
            based_on_style: str='pep8',
            prefer_line_break_after_opening_bracket: bool=True):
        """
        :param max_line_length:
            Maximum number of characters for a line.
        :param indent_size:
            Number of spaces per indentation level.
        :param allow_multiline_lambdas:
            Allows lambdas to be formatted on more than one line.
        :param blank_line_before_nested_class_or_def:
            Inserts a blank line before a ``def`` or ``class`` immediately
            nested within another ``def`` or ``class``.
        :param continuation_tab_width:
            Indent width used for line continuations.
        :param dedent_closing_brackets:
            Puts closing brackets on a separate line, dedented, if the
            bracketed expression can't fit in a single line. Applies to all
            kinds of brackets, including function definitions and calls.
        :param indent_dictionary_value:
            Indents the dictionary value if it cannot fit on the same line as
            the dictionary key.
        :param coalesce_brackets:
            Prevents splitting consecutive brackets. Only relevant when
            ``dedent_closing_brackets`` is set.
            Example:
            If ``True``,

            ```
            call_func_that_takes_a_dict(
                {
                    'key1': 'value1',
                    'key2': 'value2',
                }
            )
            ```
            would reformat to:
            ```
            call_func_that_takes_a_dict({
                'key1': 'value1',
                'key2': 'value2',
            })
            ```
        :param join_multiple_lines:
            Joins short lines into one line.
        :param spaces_around_power_operator:
            Set to ``True`` to prefer using spaces around ``**``.
        :param spaces_before_comment:
            The number of spaces required before a trailing comment.
        :param space_between_ending_comma_and_closing_bracket:
            Inserts a space between the ending comma and closing bracket of a
            list, etc.
        :param split_arguments_when_comma_terminated:
            Splits before arguments if the argument list is terminated by a
            comma.
        :param split_before_bitwise_operator:
            Set to ``True`` to prefer splitting before ``&``, ``|`` or ``^``
            rather than after.
        :param split_before_first_argument:
            If an argument / parameter list is going to be split, then split
            before the first argument.
        :param split_before_logical_operator:
            Set to ``True`` to prefer splitting before ``and`` or ``or`` rather
            than after.
        :param split_before_named_assigns:
            Splits named assignments into individual lines.
        :param use_spaces:
            Uses spaces for indentation.
        :param based_on_style:
            The formatting style to be used as reference.
        :param prefer_line_break_after_opening_bracket:
            If True, splitting right after a open bracket will not be
            preferred.
        """
        if not file:
            # Yapf cannot handle zero-byte files well, and adds a redundent
            # newline into the file. To avoid this, we don't parse zero-byte
            # files as they cannot have anything to format either.
            return

        options = """
[style]
indent_width = {indent_size}
column_limit = {max_line_length}
allow_multiline_lambdas = {allow_multiline_lambdas}
continuation_indent_width = {continuation_tab_width}
dedent_closing_brackets = {dedent_closing_brackets}
indent_dictionary_value = {indent_dictionary_value}
join_multiple_lines = {join_multiple_lines}
spaces_around_power_operator = {spaces_around_power_operator}
spaces_before_comment = {spaces_before_comment}
coalesce_brackets = {coalesce_brackets}
split_before_bitwise_operator = {split_before_bitwise_operator}
split_before_first_argument = {split_before_first_argument}
split_before_logical_operator = {split_before_logical_operator}
split_before_named_assigns = {split_before_named_assigns}
based_on_style = {based_on_style}
blank_line_before_nested_class_or_def = {blank_line_before_nested_class_or_def}
split_arguments_when_comma_terminated = {split_arguments_when_comma_terminated}
space_between_ending_comma_and_closing_bracket= \
{space_between_ending_comma_and_closing_bracket}
"""
        options += 'use_tabs = ' + str(not use_spaces) + "\n"
        options += ('split_penalty_after_opening_bracket = ' +
                    ('30' if prefer_line_break_after_opening_bracket
                     else '0') + "\n")
        options = options.format(**locals())

        try:
            with prepare_file(options.splitlines(keepends=True),
                              None) as (file_, fname):
                corrected = FormatFile(filename,
                                       style_config=fname,
                                       verify=False)[0].splitlines(True)
        except SyntaxError as err:
            if isinstance(err, IndentationError):
                error_type = "indentation errors (" + err.args[0] + ')'
            else:
                error_type = "syntax errors"
            yield Result.from_values(
                self,
                "The code cannot be parsed due to {0}.".format(error_type),
                filename, line=err.lineno, column=err.offset)
            return
        diffs = Diff.from_string_arrays(file, corrected).split_diff()
        for diff in diffs:
            yield Result(self,
                         "The code does not comply with the settings "
                         "provided.",
                         affected_code=(diff.range(filename),),
                         diffs={filename: diff})
Example #52
0
""".split("\n")


test_file2 = """
function () {
}()
""".split("\n")


config_file = """
{
  "lastsemic": true,
  "maxlen": 80
}
""".split("\n")


JSHintBear1Test = verify_local_bear(JSHintBear,
                                    valid_files=(),
                                    invalid_files=(test_file1, test_file2))


with prepare_file(config_file,
                  filename=None,
                  force_linebreaks=True,
                  create_tempfile=True) as (conf_lines, conf_file):
    JSHintBear2Test = verify_local_bear(JSHintBear,
                                        valid_files=(test_file1),
                                        invalid_files=(),
                                        settings={"jshint_config": conf_file})
Example #53
0
    def run(self, filename, file,
            max_line_length: int=79,
            tab_width: int=SpacingHelper.DEFAULT_TAB_WIDTH,
            allow_multiline_lambdas: bool=False,
            blank_line_before_nested_class_or_def: bool=False,
            continuation_tab_width: int=SpacingHelper.DEFAULT_TAB_WIDTH,
            dedent_closing_brackets: bool=False,
            indent_dictionary_value: bool=False,
            join_multiple_lines: bool=True,
            spaces_around_power_operator: bool=True,
            spaces_before_comment: int=2,
            space_between_ending_comma_and_closing_bracket: bool=False,
            split_arguments_when_comma_terminated: bool=False,
            split_before_bitwise_operator: bool=False,
            split_before_first_argument: bool=False,
            split_before_logical_operator: bool=False,
            split_before_named_assigns: bool=True,
            use_spaces: bool=True,
            based_on_style: str='pep8'):
        """
        :param max_line_length:
            Maximum number of characters for a line.
        :param tab_width:
            Number of spaces per indent level.
        :param allow_multiline_lambdas:
            Allows lambdas to be formatted on more than one line.
        :param blank_line_before_nested_class_or_def:
            Inserts a blank line before a ``def`` or ``class`` immediately
            nested within another ``def`` or ``class``.
        :param continuation_tab_width:
            Indent width used for line continuations.
        :param dedent_closing_brackets:
            Puts closing brackets on a separate line, dedented, if the
            bracketed expression can't fit in a single line. Applies to all
            kinds of brackets, including function definitions and calls.
        :param indent_dictionary_value:
            Indents the dictionary value if it cannot fit on the same line as
            the dictionary key.
        :param join_multiple_lines:
            Joins short lines into one line.
        :param spaces_around_power_operator:
            Set to ``True`` to prefer using spaces around ``**``.
        :param spaces_before_comment:
            The number of spaces required before a trailing comment.
        :param space_between_ending_comma_and_closing_bracket:
            Inserts a space between the ending comma and closing bracket of a
            list, etc.
        :param split_arguments_when_comma_terminated:
            Splits before arguments if the argument list is terminated by a
            comma.
        :param split_before_bitwise_operator:
            Set to ``True`` to prefer splitting before ``&``, ``|`` or ``^``
            rather than after.
        :param split_before_first_argument:
            If an argument / parameter list is going to be split, then split
            before the first argument.
        :param split_before_logical_operator:
            Set to ``True`` to prefer splitting before ``and`` or ``or`` rather
            than after.
        :param split_before_named_assigns:
            Splits named assignments into individual lines.
        :param use_spaces:
            Uses spaces for indentation.
        :param based_on_style:
            The formatting style to be used as reference.
        """

        options = """
[style]
indent_width = {tab_width}
column_limit = {max_line_length}
allow_multiline_lambdas = {allow_multiline_lambdas}
continuation_indent_width = {continuation_tab_width}
dedent_closing_brackets = {dedent_closing_brackets}
indent_dictionary_value = {indent_dictionary_value}
join_multiple_lines = {join_multiple_lines}
spaces_around_power_operator = {spaces_around_power_operator}
spaces_before_comment = {spaces_before_comment}
split_before_bitwise_operator = {split_before_bitwise_operator}
split_before_first_argument = {split_before_first_argument}
split_before_logical_operator = {split_before_logical_operator}
split_before_named_assigns = {split_before_named_assigns}
based_on_style = {based_on_style}
blank_line_before_nested_class_or_def = {blank_line_before_nested_class_or_def}
split_arguments_when_comma_terminated = {split_arguments_when_comma_terminated}
space_between_ending_comma_and_closing_bracket= \
{space_between_ending_comma_and_closing_bracket}
"""
        options += 'use_tabs = ' + str(not use_spaces)
        options = options.format(**locals())

        with prepare_file(options.splitlines(keepends=True),
                          None) as (file_, fname):
            corrected = FormatFile(filename,
                                   style_config=fname)[0].splitlines(True)
        diffs = Diff.from_string_arrays(file, corrected).split_diff()
        for diff in diffs:
            yield Result(self,
                         "The code does not comply with the settings "
                         "provided.",
                         affected_code=(diff.range(filename),),
                         diffs={filename: diff})
Example #54
0
 def test_json(self):
     with prepare_file([""], None) as (_, filename):
         uut = SourcePosition(filename, 1)
         self.assertEqual(uut.__json__(use_relpath=True)
                          ['file'], relpath(filename))