Esempio n. 1
0
def test_is_env_variable():
    """Test is_env_variable."""
    assert is_env_variable("${test}")
    assert is_env_variable("${test:int}")
    assert is_env_variable("${test:int:12}")

    assert not is_env_variable("sdfsdf")
Esempio n. 2
0
def private_key_verify_or_create(
    aea_conf: AgentConfig, aea_project_path: Path, create_keys: bool = True
) -> None:
    """
    Check key or create if none present.

    :param aea_conf: AgentConfig
    :param aea_project_path: Path, where project placed.

    :return: None
    """
    for identifier, _ in aea_conf.private_key_paths.read_all():
        if identifier not in crypto_registry.supported_ids:  # pragma: nocover
            raise ValueError(
                "Unsupported identifier `{}` in private key paths. Supported identifiers: {}.".format(
                    identifier, sorted(crypto_registry.supported_ids)
                )
            )

    for identifier in crypto_registry.supported_ids:
        config_private_key_path = aea_conf.private_key_paths.read(identifier)

        if is_env_variable(config_private_key_path):
            # config_private_key_path is env vaariable to be used, skip it. check will be performed after substitution
            continue

        if config_private_key_path is None:
            private_key_path = PRIVATE_KEY_PATH_SCHEMA.format(identifier)
            if identifier == aea_conf.default_ledger:  # pragma: nocover
                if os.path.exists(private_key_path):
                    raise ValueError(
                        "File {} for private key {} already exists. Add to aea-config.yaml.".format(
                            repr(config_private_key_path), identifier
                        )
                    )
                if create_keys:
                    create_private_key(
                        identifier,
                        private_key_file=str(aea_project_path / private_key_path),
                    )
                    aea_conf.private_key_paths.update(identifier, private_key_path)
        else:
            try:
                try_validate_private_key_path(
                    identifier,
                    str(aea_project_path / config_private_key_path),
                    exit_on_error=False,  # do not exit process
                )
            except FileNotFoundError:  # pragma: no cover
                raise ValueError(
                    "File {} for private key {} not found.".format(
                        repr(config_private_key_path), identifier,
                    )
                )
Esempio n. 3
0
 def is_type(self, instance, type) -> bool:  # type: ignore # pylint: disable=redefined-builtin
     """Check is instance of type."""
     if is_env_variable(instance):
         return True
     return super().is_type(instance, type)
Esempio n. 4
0
def validate_data_with_pattern(
    data: dict,
    pattern: dict,
    excludes: Optional[List[Tuple[str]]] = None,
    skip_env_vars: bool = False,
) -> List[str]:
    """
    Validate data dict with pattern dict for attributes present and type match.

    :param pattern: dict with pattern to check over
    :param excludes: list of tuples of str of paths to be skipped during the check
    :param skip_env_vars: is set True will not check data type over env variables.

    :return: list of str with error descriptions
    """
    if excludes is None:
        excludes_: List[Tuple[str]] = []
    else:
        excludes_ = excludes
    pattern_path_value = {
        tuple(path): value
        for path, value in dict_to_path_value(pattern)
    }
    data_path_value = {
        tuple(path): value
        for path, value in dict_to_path_value(data)
    }
    errors = []

    def check_excludes(path: Tuple[str, ...]) -> bool:
        for exclude in excludes_:
            if len(exclude) > len(path):  # pragma: nocover
                continue

            if path[:len(exclude)] == exclude:
                return True
        return False

    for path, new_value in data_path_value.items():
        if check_excludes(path):
            continue

        if path not in pattern_path_value:
            errors.append(
                f"Attribute `{'.'.join(path)}` is not allowed to be updated!")
            continue

        pattern_value = pattern_path_value[path]

        if pattern_value is None:
            # not possible to determine data type for optional value not set
            # it will be checked with jsonschema later
            continue  # pragma: nocover

        if skip_env_vars and (is_env_variable(pattern_value)
                              or is_env_variable(new_value)):
            # one of the values is env variable: skip data type check
            continue

        if (not issubclass(type(new_value), type(pattern_value))
                and new_value is not None):
            errors.append(
                f"For attribute `{'.'.join(path)}` `{type(pattern_value).__name__}` data type is expected, but `{type(new_value).__name__}` was provided!"
            )

    return errors