def make_config_with_temp(data: dict): _, file = tempfile.mkstemp() try: with open(file, 'w') as fd: yaml.dump(data, stream=fd, Dumper=yaml.SafeDumper) factory = ConfigFactory() factory.add_source(YamlSource(file)) return factory.build() finally: os.unlink(file)
def add_sources(fact: IConfigFactory, conf: IConfigSection): # Add defaults fact.add_source(InMemorySource({"greeting": "Hello"})) # If the user specified a configuration file, load it. if conf.has("config"): fact.add_source(YamlSource(conf.get("config"))) # The parsed command line is passed in in conf. Adding this to the factory # will allow CLI inputs to override keys from previous sources if they # are specified fact.add_configuration(conf)
def test_empty_yaml_file(self): temp_file = f"./{uuid4()}.yaml" with open(temp_file, 'w') as fd: fd.write('\n') try: fact = ConfigFactory() fact.add_source(YamlSource(temp_file)) conf = fact.build() none_val = conf.get("no:key") self.assertIsNone(none_val) finally: os.remove(temp_file)
def test_bad_yaml(self): _, file = tempfile.mkstemp() throw_error = False try: with open(file, 'w') as fd: fd.write(':') factory = ConfigFactory() factory.add_source(YamlSource(file)) conf = factory.build() except ParserError: throw_error = True finally: os.unlink(file) self.assertTrue(throw_error)
def main(): print("Try running a few different ways.") print(" 1. Run without arguments") print(" 2. Add key1 under app in ./config1.yaml") print(" 2. Run with environment SAMPLE_app_key2 set with a value.") print(" 3. Run with commandline: --app:key2 'humans'") defaults = {"app": {"key1": "Hello", "key2": "World"}} ap = ArgumentParser(description="Full Example") ap.add_argument("--app:key1") ap.add_argument("--app:key2") fact = ConfigFactory() fact.add_source(InMemorySource(defaults)) fact.add_source(EnvironmentSource("SAMPLE")) fact.add_source(YamlSource("./config1.yaml", False)) fact.add_source(ArgumentSource(ap)) conf = fact.build() print(f"{conf.get('app:key1')}, {conf.get('app:key2')}!")
def test_optional_flag(self): fact = ConfigFactory() fact.add_source(YamlSource(f"./{uuid4()}", required=False)) conf = fact.build() none_val = conf.get("no:key") self.assertIsNone(none_val)
def main(): print("Edit the ./config1.yaml to change values.\n") factory = ConfigFactory() factory.add_source(YamlSource("./config1.yaml")) conf = factory.build() print("Key one is", conf.get("key:one"))