Пример #1
0
def test_aggregate_options_when_isolated(optmanager):
    """Verify we aggregate options and config values appropriately."""
    arguments = [
        "flake8",
        "--select",
        "E11,E34,E402,W,F",
        "--exclude",
        "tests/*",
    ]
    config_finder = config.ConfigFileFinder("flake8", ignore_config_files=True)
    optmanager.extend_default_ignore(["E8"])
    options, args = aggregator.aggregate_options(optmanager, config_finder,
                                                 arguments)

    assert options.select == ["E11", "E34", "E402", "W", "F"]
    assert sorted(options.ignore) == [
        "E121",
        "E123",
        "E126",
        "E226",
        "E24",
        "E704",
        "E8",
        "W503",
        "W504",
    ]
    assert options.exclude == [os.path.abspath("tests/*")]
Пример #2
0
def test_aggregate_options_when_isolated(optmanager):
    """Verify we aggregate options and config values appropriately."""
    arguments = [
        'flake8', '--isolated', '--select', 'E11,E34,E402,W,F', '--exclude',
        'tests/*'
    ]
    config_finder = config.ConfigFileFinder('flake8', arguments, [])
    optmanager.extend_default_ignore(['E8'])
    options, args = aggregator.aggregate_options(optmanager, config_finder,
                                                 arguments)

    assert options.isolated is True
    assert options.select == ['E11', 'E34', 'E402', 'W', 'F']
    assert sorted(options.ignore) == [
        'E121',
        'E123',
        'E126',
        'E226',
        'E24',
        'E704',
        'E8',
        'W503',
        'W504',
    ]
    assert options.exclude == [os.path.abspath('tests/*')]
Пример #3
0
def test_is_configured_by(filename, is_configured_by, optmanager,
                          config_finder):
    """Verify the behaviour of the is_configured_by method."""
    parsed_config, _ = config.ConfigFileFinder('flake8')._read_config(filename)
    parser = config.MergedConfigParser(optmanager, config_finder)

    assert parser.is_configured_by(parsed_config) is is_configured_by
Пример #4
0
def test_cli_config():
    """Verify opening and reading the file specified via the cli."""
    cli_filepath = CLI_SPECIFIED_FILEPATH
    finder = config.ConfigFileFinder('flake8', None, [])

    parsed_config = finder.cli_config(cli_filepath)
    assert parsed_config.has_section('flake8')
Пример #5
0
def get_style_guide(argv=None):
    # this is a fork of flake8.api.legacy.get_style_guide
    # to allow passing command line argument
    application = Application()
    if hasattr(application, 'parse_preliminary_options'):
        prelim_opts, remaining_args = application.parse_preliminary_options(
            argv)
        from flake8 import configure_logging
        configure_logging(prelim_opts.verbose, prelim_opts.output_file)
        from flake8.options import config
        config_finder = config.ConfigFileFinder(
            application.program,
            prelim_opts.append_config,
            config_file=prelim_opts.config,
            ignore_config_files=prelim_opts.isolated)
        application.find_plugins(config_finder)
        application.register_plugin_options()
        application.parse_configuration_and_cli(config_finder, remaining_args)
    else:
        application.parse_preliminary_options_and_args([])
        application.make_config_finder()
        application.find_plugins()
        application.register_plugin_options()
        application.parse_configuration_and_cli(argv)
    application.make_formatter()
    application.make_guide()
    application.make_file_checker_manager()
    return StyleGuide(application)
Пример #6
0
    def initialize(self, argv: List[str]) -> None:
        """Initialize the application to be run.

        This finds the plugins, registers their options, and parses the
        command-line arguments.
        """
        # NOTE(sigmavirus24): When updating this, make sure you also update
        # our legacy API calls to these same methods.
        prelim_opts, remaining_args = self.parse_preliminary_options(argv)
        flake8.configure_logging(prelim_opts.verbose, prelim_opts.output_file)
        config_finder = config.ConfigFileFinder(
            self.program,
            prelim_opts.append_config,
            config_file=prelim_opts.config,
            ignore_config_files=prelim_opts.isolated,
        )
        self.find_plugins(config_finder)
        self.register_plugin_options()
        self.parse_configuration_and_cli(
            config_finder,
            remaining_args,
        )
        self.make_formatter()
        self.make_guide()
        self.make_file_checker_manager()
Пример #7
0
 def make_config_finder(self):
     """Make our ConfigFileFinder based on preliminary opts and args."""
     if self.config_finder is None:
         self.config_finder = config.ConfigFileFinder(
             self.option_manager.program_name,
             self.prelim_args,
             self.prelim_opts.append_config,
         )
Пример #8
0
def test_generate_possible_local_files(cwd, expected):
    """Verify generation of all possible config paths."""
    finder = config.ConfigFileFinder("flake8")

    with mock.patch.object(os, "getcwd", return_value=cwd):
        config_files = list(finder.generate_possible_local_files())

    assert config_files == expected
Пример #9
0
 def make_config_finder(self):
     """Make our ConfigFileFinder based on preliminary opts and args."""
     if self.config_finder is None:
         extra_config_files = utils.normalize_paths(
             self.prelim_opts.append_config)
         self.config_finder = config.ConfigFileFinder(
             self.option_manager.program_name, self.prelim_args,
             extra_config_files)
Пример #10
0
def test_cli_config_double_read():
    """Second request for CLI config is cached."""
    finder = config.ConfigFileFinder('flake8', None, [])

    parsed_config = finder.cli_config(CLI_SPECIFIED_FILEPATH)
    boom = Exception("second request for CLI config not cached")
    with mock.patch.object(finder, '_read_config', side_effect=boom):
        parsed_config_2 = finder.cli_config(CLI_SPECIFIED_FILEPATH)

    assert parsed_config is parsed_config_2
Пример #11
0
def test_local_configs_double_read():
    """Second request for local configs is cached."""
    finder = config.ConfigFileFinder('flake8', None, [])

    first_read = finder.local_configs()
    boom = Exception("second request for local configs not cached")
    with mock.patch.object(finder, '_read_config', side_effect=boom):
        second_read = finder.local_configs()

    assert first_read is second_read
Пример #12
0
def test_get_local_plugins():
    """Verify get_local_plugins returns expected plugins."""
    config_fixture_path = 'tests/fixtures/config_files/local-plugin.ini'
    config_finder = config.ConfigFileFinder('flake8')

    with mock.patch.object(config_finder, 'local_config_files') as localcfs:
        localcfs.return_value = [config_fixture_path]
        local_plugins = config.get_local_plugins(config_finder)

    assert local_plugins.extension == ['XE = test_plugins:ExtensionTestPlugin']
    assert local_plugins.report == ['XR = test_plugins:ReportTestPlugin']
Пример #13
0
    def make_config_finder(self, append_config, args):
        # type: (List[str], List[str]) -> None
        """Make our ConfigFileFinder based on preliminary opts and args.

        :param list append_config:
            List of configuration files to be parsed for configuration.
        :param list args:
            The list of file arguments passed from the CLI.
        """
        if self.config_finder is None:
            self.config_finder = config.ConfigFileFinder(
                self.option_manager.program_name, args, append_config)
Пример #14
0
def test_aggregate_options_with_config(optmanager):
    """Verify we aggregate options and config values appropriately."""
    arguments = ['flake8', '--select',
                 'E11,E34,E402,W,F', '--exclude', 'tests/*']
    config_finder = config.ConfigFileFinder(
        'flake8',
        config_file=CLI_SPECIFIED_CONFIG)
    options, args = aggregator.aggregate_options(
        optmanager, config_finder, arguments)

    assert options.select == ['E11', 'E34', 'E402', 'W', 'F']
    assert options.ignore == ['E123', 'W234', 'E111']
    assert options.exclude == [os.path.abspath('tests/*')]
Пример #15
0
def test_aggregate_options_with_config(optmanager):
    """Verify we aggregate options and config values appropriately."""
    arguments = [
        "flake8",
        "--select",
        "E11,E34,E402,W,F",
        "--exclude",
        "tests/*",
    ]
    config_finder = config.ConfigFileFinder("flake8",
                                            config_file=CLI_SPECIFIED_CONFIG)
    options, args = aggregator.aggregate_options(optmanager, config_finder,
                                                 arguments)

    assert options.select == ["E11", "E34", "E402", "W", "F"]
    assert options.ignore == ["E123", "W234", "E111"]
    assert options.exclude == [os.path.abspath("tests/*")]
Пример #16
0
def check_file(path, flake8ignore, maxlength, maxcomplexity, showshource,
               statistics):
    """Run flake8 over a single file, and return the number of failures."""
    args = []
    if maxlength:
        args += ['--max-line-length', maxlength]
    if maxcomplexity:
        args += ['--max-complexity', maxcomplexity]
    if showshource:
        args += ['--show-source']
    if statistics:
        args += ['--statistics']
    app = application.Application()
    if not hasattr(app, 'parse_preliminary_options_and_args'):  # flake8 >= 3.8
        prelim_opts, remaining_args = app.parse_preliminary_options(args)
        config_finder = config.ConfigFileFinder(
            app.program,
            prelim_opts.append_config,
            config_file=prelim_opts.config,
            ignore_config_files=prelim_opts.isolated,
        )
        app.find_plugins(config_finder)
        app.register_plugin_options()
        app.parse_configuration_and_cli(config_finder, remaining_args)
    else:
        app.parse_preliminary_options_and_args(args)
        app.make_config_finder()
        app.find_plugins()
        app.register_plugin_options()
        app.parse_configuration_and_cli(args)
    if flake8ignore:
        app.options.ignore = flake8ignore
    app.make_formatter()  # fix this
    if hasattr(app, 'make_notifier'):
        # removed in flake8 3.7+
        app.make_notifier()
    app.make_guide()
    app.make_file_checker_manager()
    app.run_checks([str(path)])
    app.formatter.start()
    app.report_errors()
    app.formatter.stop()
    return app.result_count
Пример #17
0
def read_configs(ctx: click.Context, param: click.Parameter,
                 value: Optional[str]) -> Optional[str]:
    """Read configs through the config param's callback hook."""
    # Use black's `read_pyproject_toml` for the default
    result = black.read_pyproject_toml(ctx, param, value)
    # Use flake8's config file parsing to load setup.cfg, tox.ini, and .blue
    # The parsing looks both in the project and user directories.
    finder = flake8_config.ConfigFileFinder('blue')
    manager = flake8_manager.OptionManager('blue', '0')
    parser = MergedConfigParser(manager, finder)
    config = parser.parse()
    # Merge the configs into Click's `default_map`.
    default_map: Dict[str, Any] = {}
    default_map.update(ctx.default_map or {})
    for key, value in config.items():
        key = key.replace('--', '').replace('-', '_')
        default_map[key] = value
    ctx.default_map = default_map
    return result
Пример #18
0
def get_style_guide(**kwargs):
    r"""Provision a StyleGuide for use.

    :param \*\*kwargs:
        Keyword arguments that provide some options for the StyleGuide.
    :returns:
        An initialized StyleGuide
    :rtype:
        :class:`StyleGuide`
    """
    application = app.Application()
    prelim_opts, remaining_args = application.parse_preliminary_options([])
    flake8.configure_logging(prelim_opts.verbose, prelim_opts.output_file)
    config_finder = config.ConfigFileFinder(
        application.program,
        prelim_opts.append_config,
        config_file=prelim_opts.config,
        ignore_config_files=prelim_opts.isolated,
    )

    application.find_plugins(config_finder)
    application.register_plugin_options()
    application.parse_configuration_and_cli(
        config_finder,
        remaining_args,
    )
    # We basically want application.initialize to be called but with these
    # options set instead before we make our formatter, notifier, internal
    # style guide and file checker manager.
    options = application.options
    for key, value in kwargs.items():
        try:
            getattr(options, key)
            setattr(options, key, value)
        except AttributeError:
            LOG.error('Could not update option "%s"', key)
    application.make_formatter()
    application.make_guide()
    application.make_file_checker_manager()
    return StyleGuide(application)
Пример #19
0
def get_flake8_style_guide(argv):
    # This is a modified version of flake8.legacy.get_style_guide() in which we pass argv through
    # to parse_configuration_and_cli(), as opposed to a dict of flake8 options.
    # Since we are using config files and a mix plugins, it is not trivial to determine the
    # appropriate options to pass into the standard flake8.legacy.get_style_guide();
    # passing argv gets it to determine the options for us.
    application = flake8_app.Application()
    if hasattr(application, 'parse_preliminary_options'):
        prelim_opts, remaining_args = application.parse_preliminary_options(
            argv)
        flake8.configure_logging(prelim_opts.verbose, prelim_opts.output_file)
        from flake8.options import config
        config_finder = config.ConfigFileFinder(
            application.program,
            prelim_opts.append_config,
            config_file=prelim_opts.config,
            ignore_config_files=prelim_opts.isolated)
        application.find_plugins(config_finder)
        application.register_plugin_options()
        application.parse_configuration_and_cli(config_finder, remaining_args)
    else:
        application.parse_preliminary_options_and_args([])
        flake8.configure_logging(application.prelim_opts.verbose,
                                 application.prelim_opts.output_file)
        application.make_config_finder()
        application.find_plugins()
        application.register_plugin_options()
        application.parse_configuration_and_cli(argv)
    application.make_formatter()
    try:
        # needed in older flake8 versions to populate the listener
        application.make_notifier()
    except AttributeError:
        pass
    application.make_guide()
    application.make_file_checker_manager()
    return StyleGuide(application)
Пример #20
0
def test_config_file_default_value():
    """Verify the default 'config_file' attribute value."""
    finder = config.ConfigFileFinder("flake8")
    assert finder.config_file is None
Пример #21
0
def config_finder():
    """Generate a simple ConfigFileFinder."""
    return config.ConfigFileFinder('flake8', [], [])
Пример #22
0
def test_generate_possible_local_files(args, expected):
    """Verify generation of all possible config paths."""
    finder = config.ConfigFileFinder('flake8', args, [])

    assert (list(finder.generate_possible_local_files()) ==
            expected)
Пример #23
0
def test_setting_config_file_value():
    """Verify the 'config_file' attribute matches constructed value."""
    config_file_value = "flake8.ini"
    finder = config.ConfigFileFinder("flake8", config_file=config_file_value)
    assert finder.config_file == config_file_value
Пример #24
0
def test_windows_detection(platform, is_windows):
    """Verify we detect Windows to the best of our knowledge."""
    with mock.patch.object(sys, 'platform', platform):
        finder = config.ConfigFileFinder('flake8', None, [])
    assert finder.is_windows is is_windows
Пример #25
0
def test_uses_default_args():
    """Show that we default the args value."""
    finder = config.ConfigFileFinder('flake8', None, [])
    assert finder.parent == os.path.abspath('.')
Пример #26
0
def test_read_config_catches_broken_config_files(files):
    """Verify that we do not allow the exception to bubble up."""
    _, parsed = config.ConfigFileFinder('flake8')._read_config(*files)
    assert BROKEN_CONFIG_PATH not in parsed
Пример #27
0
def test_local_configs():
    """Verify we return a ConfigParser."""
    finder = config.ConfigFileFinder('flake8', None, [])

    assert isinstance(finder.local_configs(), configparser.RawConfigParser)
Пример #28
0
def test_local_config_files(args, extra_config_files, expected):
    """Verify discovery of local config files."""
    finder = config.ConfigFileFinder('flake8', args, extra_config_files)

    assert list(finder.local_config_files()) == expected
Пример #29
0
def test_ignore_config_files_default_value():
    """Verify the default 'ignore_config_files' attribute value."""
    finder = config.ConfigFileFinder("flake8")
    assert finder.ignore_config_files is False
Пример #30
0
def test_setting_ignore_config_files_value(ignore_config_files_arg):
    """Verify the 'ignore_config_files' attribute matches constructed value."""
    finder = config.ConfigFileFinder(
        "flake8", ignore_config_files=ignore_config_files_arg)
    assert finder.ignore_config_files is ignore_config_files_arg