def test_add_detached_section_option_objects(): updater = ConfigUpdater() updater.read_string(test24_cfg_in) sec1 = updater["sec1"] sec2 = updater["sec2"] assert sec2.container is updater sec2.detach() assert not updater.has_section("sec2") assert not sec2.has_container() with pytest.raises(NotAttachedError): sec2.container new_sec2 = Section("new-sec2") new_opt = Option(key="new-key", value="new-value") new_sec2.add_option(new_opt) with pytest.raises(AlreadyAttachedError): sec1.add_option(new_opt) updater.add_section(new_sec2) assert updater.has_section("new-sec2") assert updater["new-sec2"]["new-key"].value == "new-value" new_sec3 = Section("new-sec3") new_opt2 = Option(key="new-key", value="new-value") updater["new-sec3"] = new_sec3 new_sec3["new-key"] = new_opt2
def config_updater_factory(config: Box) -> Tuple[Path, ConfigUpdater]: """Return a ConfigUpdater object and the path obj to the config file. Note, the config file must exist. There isn't too much error checking in this function. E. g. that will not work with an empty config file. """ config_updater_data = copy.deepcopy(config) if "config_file_path" in config_updater_data: path = Path(config_updater_data.pop("config_file_path")) else: raise AttributeError( "The config is missing the config_file_path. This should not happen." ) config_updater = ConfigUpdater() to_add = [] with open(path.as_posix()) as fh: config_updater.read_file(fh) for section in config_updater_data: if config_updater.has_section(section): config_updater_section = config_updater[section] last_option = config_updater_section.options()[-1] for option, value in config[section].items(): if option in config_updater_section: config_updater_section[option].value = value else: config_updater_section[last_option].add_after.option( option, value) last_option = option config_updater[section] = config_updater_section else: tmp_updater = ConfigUpdater() section_txt = f"[{section}]\n" + "\n".join( (f"{option}: {value}" for option, value in config_updater_data[section].items())) tmp_updater.read_string(section_txt) to_add.append(tmp_updater[section]) if to_add: last_section = config_updater[config_updater.sections()[-1]] for section in to_add: # Add a new line for readability config_updater[last_section.name].add_after.space().section( section) last_section = section return path, config_updater
def test_inline_comments(): updater = ConfigUpdater(inline_comment_prefixes='#') updater.read_string(test8_inline_prefixes) assert updater.has_section('section') assert updater['section']['key'].value == 'value'
def test_has_section(setup_cfg_path): updater = ConfigUpdater() updater.read(setup_cfg_path) assert updater.has_section('metadata') assert not updater.has_section('nonexistent_section')
def test_inline_comments(): updater = ConfigUpdater(inline_comment_prefixes="#") updater.read_string(test8_inline_prefixes) assert updater.has_section("section") assert updater["section"]["key"].value == "value"