def test_merge_deep3(self): fact = ConfigFactory() fact.add_source(InMemorySource({"a": {"b": [1], "c": 3}})) fact.add_source(InMemorySource({"a": {"c": 2, "b": [2]}})) conf = fact.build() self.assertEqual(1, conf.get("a:b")[0]) self.assertEqual(2, conf.get("a:b")[1])
def test_single_key(self): ap = ArgumentParser() ap.add_argument('-f', '--foo') fact = ConfigFactory() fact.add_source(ArgumentSource(ap, ["--foo", "bar"])) conf = fact.build() self.assertEqual("bar", conf.get("foo"))
def test_merge_deep2(self): fact = ConfigFactory() fact.add_source(InMemorySource({"a": {"b": 1, "c": 3}})) fact.add_source(InMemorySource({"a": {"c": 2}})) conf = fact.build() self.assertEqual(1, conf.get("a:b")) self.assertEqual(2, conf.get("a:c"))
def test_merge(self): fact = ConfigFactory() fact.add_source(InMemorySource({"a": 1})) fact.add_source(InMemorySource({"b": 2})) conf = fact.build() self.assertEqual(1, conf.get("a")) self.assertEqual(2, conf.get("b"))
def main(): print("Reads values from an in-memory configuration\n") fact = ConfigFactory() fact.add_source(InMemorySource({"key": { "one": "value" }})) conf = fact.build() print("key is", conf.get("key:one"))
def main(): print("Execute as:\n $ python from_args.py --key value\n") ap = ArgumentParser(description="Sample from arguments") ap.add_argument("--key") fact = ConfigFactory() fact.add_source(ArgumentSource(ap)) conf = fact.build() print("key is", conf.get("key"))
def main(): print( "To test, execute as:\n$ SAMPLE_key=value python ./from_environment.py\n" ) factory = ConfigFactory() factory.add_source(EnvironmentSource("SAMPLE")) conf = factory.build() print("Key one is", conf.get("key"))
def main(): ap = ArgumentParser() ap.add_argument("--config") ap.add_argument("--name", default="world") fact = ConfigFactory() fact.add_source(ArgumentSource(ap)) fact.add_source(DelegateSource(add_sources)) conf = fact.build() print(f"{conf.get('greeting')}, {conf.get('name')}!")
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 test_many_nested_keys(self): ap = ArgumentParser() ap.add_argument('--foo:bar') ap.add_argument('--bar') ap.add_argument('--foo:baz') fact = ConfigFactory() fact.add_source( ArgumentSource(ap, ["--foo:bar", "a", "--bar", "b", "--foo:baz", "c"])) conf = fact.build() self.assertEqual("a", conf.get("foo:bar")) self.assertEqual("b", conf.get("bar")) self.assertEqual("c", conf.get("foo:baz"))
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')}!")
class SrvHostBuilder(ISrvHostBuilder): __settings: Dict[str, str] __configuration: IConfigSection __services: StaticContainerBuilder __hosting_environment: IHostingEnvironment __configuration_builder: IConfigFactory __ctx: ISrvHostContext __configDelegates: List[ConfigConfigurationDelegate] __serviceDelegates: List[ConfigServicesDelegate] def __init__(self, app_name: str, env_key: str = "SERVICE_ENV", **kwargs): if "configuration_builder" in kwargs: self.__configuration_builder = kwargs["configuration_builder"] else: self.__configuration_builder = ConfigFactory() if "hosting_environment" in kwargs: self.__hosting_environment = kwargs["hosting_environment"] else: self.__hosting_environment = HostingEnvironment( application_name=app_name, environment_name=os.environ.get(env_key, "Development")) self.__settings = dict() self.__configDelegates = list() self.__serviceDelegates = list() self.__configuration = self.__configuration_builder.build() self.__services = StaticContainerBuilder() self.__services.bind(annotation=ISrvHost, implementation=_NoopHost) def config_configuration( self, config: ConfigConfigurationDelegate) -> ISrvHostBuilder: self.__configDelegates.append(config) return self def config_services(self, config: ConfigServicesDelegate) -> ISrvHostBuilder: self.__serviceDelegates.append(config) return self def add_setting(self, key: str, value: str) -> ISrvHostBuilder: self.__settings[key] = value return self def get_setting(self, key: str): if key in self.__settings: return self.__settings[key] return self.__configuration.get(key) def build(self) -> ISrvHost: # If custom settings are set, rebuild configuration if len(self.__settings) > 0: self.__configuration_builder.add_source( InMemorySource(config_helpers.explode(self.__settings))) self.__configuration = self.__configuration_builder.build() # Create a context to start building self.__ctx = SrvHostContext(environment=self.__hosting_environment, configuration=self.__configuration) # Call the the configuration delegates for configDelegate in self.__configDelegates: configDelegate(self.__ctx, self.__configuration_builder) # Rebuild configuration after the config delegates have completed self.__configuration = self.__configuration_builder.build() self.__ctx.configuration = self.__configuration # Call the service container delegates for serviceDelegate in self.__serviceDelegates: serviceDelegate(self.__ctx, self.__services) # Add config into the container self.__services.bind_constant(annotation=IConfigSection, value=self.__ctx.configuration) # Add environment into the container self.__services.bind_constant(annotation=IHostingEnvironment, value=self.__ctx.environment) # Build the service provider service_provider = self.__services.build() # Get the service host out of the container host: ISrvHost = service_provider.get(ISrvHost) # Setup the service host host.service_provider = service_provider host.configuration = self.__ctx.configuration host.environment = self.__ctx.environment # All done return host
def test_single_key(self): fact = ConfigFactory() fact.add_source(InMemorySource({"a": 1})) conf = fact.build() val = conf.get("a") self.assertEqual(1, val)
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"))