Exemple #1
0
def test_del_section():
    updater = ConfigUpdater()
    updater.read_string(test2_cfg_in)
    del updater["section2"]
    assert str(updater) == test2_cfg_out
    with pytest.raises(KeyError):
        del updater["section2"]
def test_get_option():
    updater = ConfigUpdater()
    updater.read_string(test1_cfg_in)
    option = updater["default"]["key"]
    assert option.value == "1"
    with pytest.raises(KeyError):
        updater["default"]["wrong_key"]
def test_validate_format(setup_cfg_path):
    updater = ConfigUpdater(allow_no_value=False)
    updater.read(setup_cfg_path)
    updater.validate_format()
    updater.set('metadata', 'author')
    with pytest.raises(ParsingError):
        updater.validate_format()
Exemple #4
0
 def cleartext(self, value):
     self.config = ConfigUpdater()
     self.config.read_string(value)
     self.set_members(self.get_members())
     s = io.StringIO()
     self.config.write(s)
     self._cleartext = s.getvalue()
Exemple #5
0
def test_section_setitem():
    cfg = ConfigUpdater()
    cfg.optionxform = str.upper
    cfg.read_string("[section1]\nOTHERKEY = 0")

    assert "KEY" not in cfg["section1"]
    cfg["section1"]["key"] = "value"
    assert "KEY" in cfg["section1"]
    assert cfg["section1"]["KEY"].value == "value"

    cfg["section1"]["key"] = "42"
    assert cfg["section1"]["KEY"].value == "42"
    assert cfg["section1"]["key"].value == "42"

    other = ConfigUpdater()
    other.optionxform = str.lower
    other.read_string("[section1]\nkEy = value")
    option = other["section1"]["key"].detach()

    with pytest.raises(ValueError):
        # otherkey exists in section1, but option is `key` instead of `otherkey`
        cfg["section1"]["otherkey"] = option
    with pytest.raises(ValueError):
        # anotherkey exists in section1 and option is `key` instead of `anotherkey`
        cfg["section1"]["anotherkey"] = option

    assert cfg["section1"]["key"].raw_key == "key"
    cfg["section1"]["key"] = option
    assert cfg["section1"]["key"].value == "value"
    assert cfg["section1"]["key"].key == "KEY"
    assert cfg["section1"]["key"].raw_key == "kEy"
def test_get_option():
    updater = ConfigUpdater()
    updater.read_string(test1_cfg_in)
    option = updater['default']['key']
    assert option.value == '1'
    with pytest.raises(KeyError):
        updater['default']['wrong_key']
def test_del_option():
    updater = ConfigUpdater()
    updater.read_string(test1_cfg_in)
    del updater['default']['key']
    assert str(updater) == "\n[default]\n"
    with pytest.raises(KeyError):
        del updater['default']['key']
Exemple #8
0
def add_pyscaffold(config: ConfigUpdater, opts: ScaffoldOpts) -> ConfigUpdater:
    """Add PyScaffold section to a ``setup.cfg``-like file + PyScaffold's version +
    extensions and their associated options.
    """
    if "pyscaffold" not in config:
        config.add_section("pyscaffold")

    pyscaffold = config["pyscaffold"]
    pyscaffold["version"] = pyscaffold_version

    # Add the new extensions alongside the existing ones
    extensions = {
        ext.name
        for ext in opts.get("extensions", []) if ext.persist
    }
    old = pyscaffold.pop("extensions", "")
    old = parse_extensions(getattr(old, "value",
                                   old))  # coerce configupdater return
    pyscaffold.set("extensions")
    pyscaffold["extensions"].set_values(sorted(old | extensions))

    # Add extension-related opts, i.e. opts which start with an extension name
    allowed = {
        k: v
        for k, v in opts.items() if any(map(k.startswith, extensions))
    }
    pyscaffold.update(allowed)

    return config
def test_add_before_then_add_after_option():
    updater = ConfigUpdater()
    updater.read_string(test17_cfg_in)
    updater['section']['key1'].add_before.option('key0', '0')
    updater['section']['key1'].add_after.option('key2', '2')
    updater['section']['key2'].add_after.option('key3', '3')
    assert str(updater) == test17_cfg_out
Exemple #10
0
def test_modify_multiline_value():
    ml_value = """\
    [metadata]
    classifiers =
        Development Status :: 3 - Alpha
        #Development Status :: 4 - Beta
        #Development Status :: 5 - Production/Stable
        Programming Language :: Python :: 3 :: Only
        Programming Language :: Python :: 3
        Programming Language :: Python :: Implementation :: CPython
        Programming Language :: Python :: Implementation :: PyPy
        License :: OSI Approved :: MIT License
    """
    ml_value = dedent(ml_value)
    updater = ConfigUpdater()
    updater.read_string(ml_value)

    with pytest.raises(AssignMultilineValueError):
        updater["metadata"][
            "classifiers"].value += "License :: OSI Approved :: BSD"

    new_classifiers = updater["metadata"]["classifiers"].value.strip().split(
        "\n")
    new_classifiers += ["Topic :: Utilities"]
    updater["metadata"]["classifiers"].set_values(new_classifiers)
    ml_value += "    Topic :: Utilities\n"
    assert str(updater) == ml_value

    updater["metadata"]["classifiers"].value = "new_value"
    updater["metadata"]["classifiers"].value += "_and_more"
    expected = """\
    [metadata]
    classifiers = new_value_and_more
    """
    assert str(updater) == dedent(expected)
Exemple #11
0
class SingleConfigFileRule(SinglePathRule):
    """
    Extend :class:`hammurabi.rules.base.Rule` to handle parsed content
    manipulations on a single file.
    """
    def __init__(
        self,
        name: str,
        path: Optional[Path] = None,
        section: Optional[str] = None,
        **kwargs,
    ) -> None:
        self.section = self.validate(section, required=True)
        self.updater = ConfigUpdater()

        super().__init__(name, path, **kwargs)

    def pre_task_hook(self) -> None:
        """
        Parse the configuration file for later use.
        """

        logging.debug('Parsing "%s" configuration file', self.param)
        self.updater.read(self.param)

    @abstractmethod
    def task(self) -> Any:
        """
def test_read_mixed_case_options():
    updater = ConfigUpdater()
    updater.read_string(test15_cfg_in)
    assert updater.has_option('section', 'OptionA')
    assert updater.has_option('section', 'optiona')
    assert updater['section']['OptionA'].value == '2'
    assert updater['section']['optiona'].value == '2'
Exemple #13
0
 def read(self):
     self.main_file.read()
     if not self.main_file.cleartext:
         self.main_file.cleartext = NEW_FILE_TEMPLATE
     self.config = ConfigUpdater()
     self.config.read_string(self.main_file.cleartext)
     self.set_members(self.get_members())
def test_updater_to_dict(setup_cfg_path):
    updater = ConfigUpdater()
    updater.read(setup_cfg_path)
    parser = ConfigParser()
    parser.read(setup_cfg_path)
    parser_dict = {sect: dict(parser[sect]) for sect in parser.sections()}
    assert updater.to_dict() == parser_dict
def test_add_before_then_add_after_option():
    updater = ConfigUpdater()
    updater.read_string(test17_cfg_in)
    updater["section"]["key1"].add_before.option("key0", "0")
    updater["section"]["key1"].add_after.option("key2", "2")
    updater["section"]["key2"].add_after.option("key3", "3")
    assert str(updater) == test17_cfg_out
def test_read_mixed_case_options():
    updater = ConfigUpdater()
    updater.read_string(test15_cfg_in)
    assert updater.has_option("section", "OptionA")
    assert updater.has_option("section", "optiona")
    assert updater["section"]["OptionA"].value == "2"
    assert updater["section"]["optiona"].value == "2"
def test_no_duplicate_blocks_with_blockbuilder():
    updater = ConfigUpdater()
    updater.read_string(test19_cfg_in)
    with pytest.raises(DuplicateOptionError):
        updater['section']['Key0'].add_after.option('key0', '1')
    with pytest.raises(DuplicateSectionError):
        updater['section'].add_after.section('section')
    assert str(updater) == test19_cfg_in
def test_section_to_dict(setup_cfg_path):
    updater = ConfigUpdater()
    updater.read(setup_cfg_path)
    parser = ConfigParser()
    parser.read(setup_cfg_path)
    updater_dict = updater['metadata'].to_dict()
    parser_dict = dict(parser['metadata'])
    assert updater_dict == parser_dict
def test_no_duplicate_blocks_with_blockbuilder():
    updater = ConfigUpdater()
    updater.read_string(test19_cfg_in)
    with pytest.raises(DuplicateOptionError):
        updater["section"]["Key0"].add_after.option("key0", "1")
    with pytest.raises(DuplicateSectionError):
        updater["section"].add_after.section("section")
    assert str(updater) == test19_cfg_in
def test_add_before_after_option():
    updater = ConfigUpdater()
    updater.read_string(test4_cfg_in)
    with pytest.raises(ValueError):
        updater["section"].add_before.option("key0", 0)
    updater["section"]["key1"].add_before.option("key0", 0)
    updater["section"]["key1"].add_after.option("key2")
    assert str(updater) == test4_cfg_out
Exemple #21
0
def test_iter_consistency_with_configparser():
    parser = ConfigParser()
    parser.read_string(test24_cfg_in)
    updater = ConfigUpdater()
    updater.read_string(test24_cfg_in)
    # [1:] to drop 'DEFAULT' section
    assert list(parser)[1:] == list(updater)
    assert list(parser["sec1"]) == list(updater["sec1"])
def test_add_before_after_option():
    updater = ConfigUpdater()
    updater.read_string(test4_cfg_in)
    with pytest.raises(ValueError):
        updater['section'].add_before.option('key0', 0)
    updater['section']['key1'].add_before.option('key0', 0)
    updater['section']['key1'].add_after.option('key2')
    assert str(updater) == test4_cfg_out
def test_sections(setup_cfg_path):
    updater = ConfigUpdater()
    updater.read(setup_cfg_path)
    exp_sections = [
        'metadata', 'options', 'options.packages.find',
        'options.extras_require', 'test', 'tool:pytest', 'aliases',
        'bdist_wheel', 'build_sphinx', 'devpi:upload', 'flake8', 'pyscaffold'
    ]
    assert updater.sections() == exp_sections
Exemple #24
0
def test_iter_option(setup_cfg_path):
    updater = ConfigUpdater()
    updater.read(setup_cfg_path)
    section = updater["metadata"]
    # iter_blocks will give us everything, iter_options just the option objects and
    # __iter__ should work as iter_blocks
    assert len([entry for entry in section.iter_blocks()]) == 12
    assert len([entry for entry in section.iter_options()]) == 9
    assert len([entry for entry in section]) == 9
def test_del_section():
    updater = ConfigUpdater()
    updater.read_string(test2_cfg_in)
    del updater['section2']
    assert str(updater) == test2_cfg_out
    with pytest.raises(KeyError):
        del updater['section2']
    with pytest.raises(ValueError):
        updater['section1']._get_option_idx('wrong key')
def test_iter_items_section(setup_cfg_path):
    updater = ConfigUpdater()
    updater.read(setup_cfg_path)

    result = list(k for k, v in updater['metadata'].items())
    assert result == [
        'name', 'description', 'author', 'author-email', 'license', 'url',
        'long-description', 'platforms', 'classifiers'
    ]
def test_add_section():
    updater = ConfigUpdater()
    updater.read_string(test7_cfg_in)
    with pytest.raises(DuplicateSectionError):
        updater.add_section('section1')
    updater.add_section('section2')
    updater['section2']['key1'] = 1
    assert str(updater) == test7_cfg_out
    with pytest.raises(ValueError):
        updater.add_section(updater['section2']['key1'])
Exemple #28
0
def update_setup_cfg(setupcfg: ConfigUpdater, opts: ScaffoldOpts):
    """Update `pyscaffold` in setupcfg and ensure some values are there as expected"""
    if "options" not in setupcfg:
        template = templates.setup_cfg(opts)
        new_section = ConfigUpdater().read_string(template)["options"]
        setupcfg["metadata"].add_after.section(new_section.detach())

    # Add "PyScaffold" section if missing and update saved extensions
    setupcfg = templates.add_pyscaffold(setupcfg, opts)
    return setupcfg, opts
def test_value_change():
    updater = ConfigUpdater()
    updater.read_string(test1_cfg_in)
    assert updater['default']['key'].value == '1'
    updater['default']['key'].value = '2'
    assert str(updater) == test1_cfg_out
    # try another way
    section = updater['default']
    section['key'] = '1'
    assert str(updater) == test1_cfg_in
Exemple #30
0
def write_config_updater(path: Path, config: ConfigUpdater) -> None:
    """Write the config file."""
    to_write_config = copy.deepcopy(config)
    # Do not save the pwd if that's not wanted!
    if (config.has_option("discovergy_account", "save_password")
            and not config.get("discovergy_account", "save_password").value):
        to_write_config.set("discovergy_account", "password", value="")
    with os.fdopen(os.open(path.as_posix(), os.O_WRONLY | os.O_CREAT, 0o600),
                   "w") as fh:
        to_write_config.write(fh)