def get_config_ctx(template_file): ctx = click.get_current_context() samconfig_dir = getattr(ctx, "samconfig_dir", None) samconfig = SamConfig( config_dir=samconfig_dir if samconfig_dir else SamConfig.config_dir(template_file_path=template_file) ) return ctx, samconfig
def get_config_ctx(self, config_file=None): ctx = click.get_current_context() samconfig_dir = getattr(ctx, "samconfig_dir", None) samconfig = SamConfig( config_dir=samconfig_dir if samconfig_dir else SamConfig.config_dir(template_file_path=self.template_file), filename=config_file or DEFAULT_CONFIG_FILE_NAME, ) return ctx, samconfig
def __call__(self, config_dir, config_env, cmd_names): """ Get resolved config based on the `file_path` for the configuration file, `config_env` targeted inside the config file and corresponding `cmd_name` as denoted by `click`. :param config_env: The name of the sectional config_env within configuration file. :param cmd_names list(str): sam command name as defined by click :returns dictionary containing the configuration parameters under specified config_env """ resolved_config = {} samconfig = SamConfig(config_dir) LOG.debug("Config file location: %s", samconfig.path()) if not samconfig.exists(): LOG.debug("Config file does not exist") return resolved_config try: LOG.debug("Getting configuration value for %s %s %s", cmd_names, self.section, config_env) # NOTE(TheSriram): change from tomlkit table type to normal dictionary, # so that click defaults work out of the box. samconfig.sanity_check() resolved_config = { k: v for k, v in samconfig.get_all( cmd_names, self.section, env=config_env).items() } LOG.debug("Configuration values read from the file: %s", resolved_config) except KeyError as ex: LOG.debug( "Error reading configuration file at %s with config_env=%s, command=%s, section=%s %s", samconfig.path(), config_env, cmd_names, self.section, str(ex), ) except SamConfigVersionException as ex: LOG.debug("%s %s", samconfig.path(), str(ex)) raise ConfigException( f"Syntax invalid in samconfig.toml: {str(ex)}") except Exception as ex: LOG.debug("Error reading configuration file: %s %s", samconfig.path(), str(ex)) return resolved_config
def samconfig_parameters(cmd_names, config_dir=None, env=None, **kwargs): """ ContextManager to write a new SAM Config and remove the file after the contextmanager exists Parameters ---------- cmd_names : list(str) Name of the full commnad split as a list: ["generate-event", "s3", "put"] config_dir : str Path where the SAM config file should be written to. Defaults to os.getcwd() env : str Optional name of the config environment. This is currently unused kwargs : dict Parameter names and values to be written to the file. Returns ------- Path to the config file """ env = env or DEFAULT_ENV section = "parameters" samconfig = SamConfig(config_dir=config_dir) try: for k, v in kwargs.items(): samconfig.put(cmd_names, section, k, v, env=env) samconfig.flush() yield samconfig.path() finally: Path(samconfig.path()).unlink()
def test_get_ctx_defaults_non_nested(self): provider = MagicMock() mock_context1 = MockContext(info_name="sam", parent=None) mock_context2 = MockContext(info_name="local", parent=mock_context1) mock_context3 = MockContext(info_name="start-api", parent=mock_context2) get_ctx_defaults("start-api", provider, mock_context3, "default") provider.assert_called_with(SamConfig.config_dir(), "default", ["local", "start-api"])
def test_get_ctx_defaults_nested(self): provider = MagicMock() mock_context1 = MockContext(info_name="sam", parent=None) mock_context2 = MockContext(info_name="local", parent=mock_context1) mock_context3 = MockContext(info_name="generate-event", parent=mock_context2) mock_context4 = MockContext(info_name="alexa-skills-kit", parent=mock_context3) get_ctx_defaults("intent-answer", provider, mock_context4, "default") provider.assert_called_with( SamConfig.config_dir(), "default", ["local", "generate-event", "alexa-skills-kit", "intent-answer"] )
def setUp(self): self.config_dir = os.getcwd() self.samconfig = SamConfig(self.config_dir)
class TestSamConfig(TestCase): def setUp(self): self.config_dir = os.getcwd() self.samconfig = SamConfig(self.config_dir) def tearDown(self): if self.samconfig.exists(): os.remove(self.samconfig.path()) def _setup_config(self): self.samconfig.put(cmd_names=["local", "start", "api"], section="parameters", key="port", value=5401) self.samconfig.flush() self._check_config_file() def _check_config_file(self): self.assertTrue(self.samconfig.exists()) self.assertTrue(self.samconfig.sanity_check()) self.assertEqual(SAM_CONFIG_VERSION, self.samconfig.document.get(VERSION_KEY)) def test_init(self): self.assertEqual(self.samconfig.filepath, Path(self.config_dir, DEFAULT_CONFIG_FILE_NAME)) def test_param_overwrite(self): self.samconfig.put(cmd_names=["myCommand"], section="mySection", key="port", value=5401, env="myEnv") self.samconfig.flush() self._check_config_file() self.assertEqual({"port": 5401}, self.samconfig.get_all(cmd_names=["myCommand"], section="mySection", env="myEnv")) self.samconfig.document = {} self.samconfig.put(cmd_names=["myCommand"], section="mySection", key="port", value=5402, env="myEnv") self.samconfig.flush() self._check_config_file() self.assertEqual({"port": 5402}, self.samconfig.get_all(cmd_names=["myCommand"], section="mySection", env="myEnv")) self.samconfig.document = {} self.assertEqual({"port": 5402}, self.samconfig.get_all(cmd_names=["myCommand"], section="mySection", env="myEnv")) def test_add_params_from_different_env(self): self.samconfig.put(cmd_names=["myCommand"], section="mySection", key="port", value=5401, env="myEnvA") self.samconfig.flush() self._check_config_file() self.assertEqual({"port": 5401}, self.samconfig.get_all(cmd_names=["myCommand"], section="mySection", env="myEnvA")) self.samconfig.document = {} self.samconfig.put(cmd_names=["myCommand"], section="mySection", key="port", value=5402, env="myEnvB") self.samconfig.flush() self._check_config_file() self.assertEqual({"port": 5401}, self.samconfig.get_all(cmd_names=["myCommand"], section="mySection", env="myEnvA")) self.assertEqual({"port": 5402}, self.samconfig.get_all(cmd_names=["myCommand"], section="mySection", env="myEnvB")) def test_add_params_from_different_cmd_names(self): self.samconfig.put(cmd_names=["myCommand1"], section="mySection", key="port", value="ABC", env="myEnv") self.samconfig.flush() self._check_config_file() self.assertEqual({"port": "ABC"}, self.samconfig.get_all(cmd_names=["myCommand1"], section="mySection", env="myEnv")) self.samconfig.document = {} self.samconfig.put(cmd_names=["myCommand2", "mySubCommand"], section="mySection", key="port", value="DEF", env="myEnv") self.samconfig.flush() self._check_config_file() self.assertEqual({"port": "ABC"}, self.samconfig.get_all(cmd_names=["myCommand1"], section="mySection", env="myEnv")) self.assertEqual( {"port": "DEF"}, self.samconfig.get_all(cmd_names=["myCommand2", "mySubCommand"], section="mySection", env="myEnv"), ) def test_add_params_from_different_sections(self): self.samconfig.put(cmd_names=["myCommand"], section="mySection1", key="testKey1", value=True, env="myEnv") self.samconfig.flush() self._check_config_file() self.assertEqual({"testKey1": True}, self.samconfig.get_all(cmd_names=["myCommand"], section="mySection1", env="myEnv")) self.samconfig.document = {} self.samconfig.put(cmd_names=["myCommand"], section="mySection2", key="testKey2", value=False, env="myEnv") self.samconfig.flush() self._check_config_file() self.assertEqual( {"testKey1": True}, self.samconfig.get_all(cmd_names=["myCommand"], section="mySection1", env="myEnv"), ) self.assertEqual( {"testKey2": False}, self.samconfig.get_all(cmd_names=["myCommand"], section="mySection2", env="myEnv"), ) def test_add_params_from_different_keys(self): self.samconfig.put(cmd_names=["myCommand"], section="mySection", key="testKey1", value=True, env="myEnv") self.samconfig.flush() self._check_config_file() self.assertEqual({"testKey1": True}, self.samconfig.get_all(cmd_names=["myCommand"], section="mySection", env="myEnv")) self.samconfig.document = {} self.samconfig.put(cmd_names=["myCommand"], section="mySection", key="testKey2", value=321, env="myEnv") self.samconfig.flush() self._check_config_file() self.assertEqual( { "testKey1": True, "testKey2": 321 }, self.samconfig.get_all(cmd_names=["myCommand"], section="mySection", env="myEnv"), ) def test_check_config_get(self): self._setup_config() self.assertEqual({"port": 5401}, self.samconfig.get_all( cmd_names=["local", "start", "api"], section="parameters")) def test_check_config_exists(self): self._setup_config() self.assertTrue(self.samconfig.exists()) def test_check_sanity(self): self.assertTrue(self.samconfig.sanity_check()) def test_check_version_non_supported_type(self): self._setup_config() self.samconfig.document.remove(VERSION_KEY) self.samconfig.document.add(VERSION_KEY, "aadeff") with self.assertRaises(SamConfigVersionException): self.samconfig.sanity_check() def test_check_version_no_version_exists(self): self._setup_config() self.samconfig.document.remove(VERSION_KEY) with self.assertRaises(SamConfigVersionException): self.samconfig.sanity_check() def test_check_version_float(self): self._setup_config() self.samconfig.document.remove(VERSION_KEY) self.samconfig.document.add(VERSION_KEY, 0.2) self.samconfig.sanity_check() def test_write_config_file_non_standard_version(self): self._setup_config() self.samconfig.document.remove(VERSION_KEY) self.samconfig.document.add(VERSION_KEY, 0.2) self.samconfig.put(cmd_names=["local", "start", "api"], section="parameters", key="skip_pull_image", value=True) self.samconfig.sanity_check() self.assertEqual(self.samconfig.document.get(VERSION_KEY), 0.2)
def __call__(self, config_path, config_env, cmd_names): """ Get resolved config based on the `file_path` for the configuration file, `config_env` targeted inside the config file and corresponding `cmd_name` as denoted by `click`. :param config_path: The path of configuration file. :param config_env: The name of the sectional config_env within configuration file. :param cmd_names list(str): sam command name as defined by click :returns dictionary containing the configuration parameters under specified config_env """ resolved_config = {} # Use default sam config file name if config_path only contain the directory config_file_path = (Path(os.path.abspath(config_path)) if config_path else Path(os.getcwd(), DEFAULT_CONFIG_FILE_NAME)) config_file_name = config_file_path.name config_file_dir = config_file_path.parents[0] samconfig = SamConfig(config_file_dir, config_file_name) # Enable debug level logging by environment variable "SAM_DEBUG" if os.environ.get("SAM_DEBUG", "").lower() == "true": LOG.setLevel(logging.DEBUG) LOG.debug("Config file location: %s", samconfig.path()) if not samconfig.exists(): LOG.debug("Config file '%s' does not exist", samconfig.path()) return resolved_config try: LOG.debug( "Loading configuration values from [%s.%s.%s] (env.command_name.section) in config file at '%s'...", config_env, cmd_names, self.section, samconfig.path(), ) # NOTE(TheSriram): change from tomlkit table type to normal dictionary, # so that click defaults work out of the box. resolved_config = dict( samconfig.get_all(cmd_names, self.section, env=config_env).items()) LOG.debug("Configuration values successfully loaded.") LOG.debug("Configuration values are: %s", resolved_config) except KeyError as ex: LOG.debug( "Error reading configuration from [%s.%s.%s] (env.command_name.section) " "in configuration file at '%s' with : %s", config_env, cmd_names, self.section, samconfig.path(), str(ex), ) except Exception as ex: LOG.debug("Error reading configuration file: %s %s", samconfig.path(), str(ex)) raise ConfigException(f"Error reading configuration: {ex}") from ex return resolved_config
class TestSamConfig(TestCase): def setUp(self): self.config_dir = os.getcwd() self.samconfig = SamConfig(self.config_dir) def tearDown(self): if self.samconfig.exists(): os.remove(self.samconfig.path()) def _setup_config(self): self.samconfig.put(cmd_names=["local", "start", "api"], section="parameters", key="port", value=5401) self.samconfig.flush() self.assertTrue(self.samconfig.exists()) self.assertTrue(self.samconfig.sanity_check()) self.assertEqual(SAM_CONFIG_VERSION, self.samconfig.document.get(VERSION_KEY)) def test_init(self): self.assertEqual(self.samconfig.filepath, Path(self.config_dir, DEFAULT_CONFIG_FILE_NAME)) def test_check_config_get(self): self._setup_config() self.assertEqual({"port": 5401}, self.samconfig.get_all( cmd_names=["local", "start", "api"], section="parameters")) def test_check_config_exists(self): self._setup_config() self.assertTrue(self.samconfig.exists()) def test_check_sanity(self): self.assertTrue(self.samconfig.sanity_check()) def test_check_version_non_supported_type(self): self._setup_config() self.samconfig.document.remove(VERSION_KEY) self.samconfig.document.add(VERSION_KEY, "aadeff") with self.assertRaises(SamConfigVersionException): self.samconfig.sanity_check() def test_check_version_no_version_exists(self): self._setup_config() self.samconfig.document.remove(VERSION_KEY) with self.assertRaises(SamConfigVersionException): self.samconfig.sanity_check() def test_check_version_float(self): self._setup_config() self.samconfig.document.remove(VERSION_KEY) self.samconfig.document.add(VERSION_KEY, 0.2) self.samconfig.sanity_check() def test_write_config_file_non_standard_version(self): self._setup_config() self.samconfig.document.remove(VERSION_KEY) self.samconfig.document.add(VERSION_KEY, 0.2) self.samconfig.put(cmd_names=["local", "start", "api"], section="parameters", key="skip_pull_image", value=True) self.samconfig.sanity_check() self.assertEqual(self.samconfig.document.get(VERSION_KEY), 0.2)