Exemple #1
0
    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
Exemple #2
0
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.
            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 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 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
Exemple #4
0
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)