예제 #1
0
def _crete_agent_config(ctx: Context, agent_name: str,
                        set_author: str) -> AgentConfig:
    """
    Create agent config.

    :param ctx: context object.
    :param agent_name: agent name.
    :param set_author: author name to set.

    :return: AgentConfig object.
    """
    agent_config = AgentConfig(
        agent_name=agent_name,
        aea_version=aea.__version__,
        author=set_author,
        version=DEFAULT_VERSION,
        license_=DEFAULT_LICENSE,
        registry_path=os.path.join("..", DEFAULT_REGISTRY_PATH),
        description="",
    )
    agent_config.default_connection = str(DEFAULT_CONNECTION)
    agent_config.default_ledger = DEFAULT_LEDGER

    with open(os.path.join(agent_name, DEFAULT_AEA_CONFIG_FILE),
              "w") as config_file:
        ctx.agent_loader.dump(agent_config, config_file)

    return agent_config
예제 #2
0
    def test_from_json_and_to_json(self, agent_path):
        """Test the 'from_json' method and 'to_json' work correctly."""
        f = open(agent_path)
        original_json = yaml.safe_load(f)

        expected_config = AgentConfig.from_json(original_json)
        assert isinstance(expected_config, AgentConfig)
        expected_json = expected_config.json
        actual_config = AgentConfig.from_json(expected_json)
        actual_json = actual_config.json
        assert expected_json == actual_json
예제 #3
0
    def test_from_json_and_to_json(self, agent_path):
        """Test the 'from_json' method and 'to_json' work correctly."""
        f = open(agent_path)
        original_jsons = list(yaml.safe_load_all(f))
        components = original_jsons[1:]
        original_json = original_jsons[0]
        original_json["component_configurations"] = components

        expected_config = AgentConfig.from_json(original_json)
        assert isinstance(expected_config, AgentConfig)
        expected_json = expected_config.json
        actual_config = AgentConfig.from_json(expected_json)
        actual_json = actual_config.json
        assert expected_json == actual_json
예제 #4
0
def _create_aea(click_context, agent_name: str, set_author: str,
                local: bool) -> None:
    ctx = cast(Context, click_context.obj)
    path = Path(agent_name)
    ctx.clean_paths.append(str(path))

    # we have already checked that the directory does not exist.
    path.mkdir(exist_ok=False)

    try:
        # set up packages directories.
        _setup_package_folder(Path(agent_name, "protocols"))
        _setup_package_folder(Path(agent_name, "contracts"))
        _setup_package_folder(Path(agent_name, "connections"))
        _setup_package_folder(Path(agent_name, "skills"))

        # set up a vendor directory
        Path(agent_name, "vendor").mkdir(exist_ok=False)
        Path(agent_name, "vendor", "__init__.py").touch(exist_ok=False)

        # create a config file inside it
        click.echo("Creating config file {}".format(DEFAULT_AEA_CONFIG_FILE))
        config_file = open(os.path.join(agent_name, DEFAULT_AEA_CONFIG_FILE),
                           "w")
        agent_config = AgentConfig(
            agent_name=agent_name,
            aea_version=aea.__version__,
            author=set_author,
            version=DEFAULT_VERSION,
            license=DEFAULT_LICENSE,
            registry_path=os.path.join("..", DEFAULT_REGISTRY_PATH),
            description="",
        )
        agent_config.default_connection = DEFAULT_CONNECTION  # type: ignore
        agent_config.default_ledger = DEFAULT_LEDGER
        ctx.agent_loader.dump(agent_config, config_file)

        # next commands must be done from the agent's directory -> overwrite ctx.cwd
        ctx.agent_config = agent_config
        ctx.cwd = agent_config.agent_name

        click.echo("Adding default packages ...")
        if local:
            ctx.set_config("is_local", True)
        _add_item(click_context, "connection", DEFAULT_CONNECTION)
        _add_item(click_context, "skill", DEFAULT_SKILL)

    except Exception as e:
        raise click.ClickException(str(e))
예제 #5
0
def _create_agent_config(ctx: Context, agent_name: str,
                         set_author: str) -> AgentConfig:
    """
    Create agent config.

    :param ctx: context object.
    :param agent_name: agent name.
    :param set_author: author name to set.

    :return: AgentConfig object.
    """
    agent_config = AgentConfig(
        agent_name=agent_name,
        aea_version=compute_specifier_from_version(get_current_aea_version()),
        author=set_author,
        version=DEFAULT_VERSION,
        license_=DEFAULT_LICENSE,
        registry_path=os.path.join("..", DEFAULT_REGISTRY_PATH),
        description="",
        default_ledger=DEFAULT_LEDGER,
        default_connection=None,
    )

    with open_file(os.path.join(agent_name, DEFAULT_AEA_CONFIG_FILE),
                   "w") as config_file:
        ctx.agent_loader.dump(agent_config, config_file)

    return agent_config
예제 #6
0
    def setup_class(cls):
        """Set the test up."""
        cls.runner = CliRunner()
        cls.agent_name = "myagent"
        cls.cwd = os.getcwd()
        cls.t = tempfile.mkdtemp()
        cls.skill_name = "gym"
        cls.patch = unittest.mock.patch.object(aea.cli.common.logger, 'error')
        cls.mocked_logger_error = cls.patch.__enter__()

        os.chdir(cls.t)
        result = cls.runner.invoke(cli, ["create", cls.agent_name])
        assert result.exit_code == 0
        os.chdir(cls.agent_name)

        # change default registry path
        config = AgentConfig.from_json(
            yaml.safe_load(open(DEFAULT_AEA_CONFIG_FILE)))
        config.registry_path = os.path.join(ROOT_DIR, "packages")
        yaml.safe_dump(config.json, open(DEFAULT_AEA_CONFIG_FILE, "w"))

        result = cls.runner.invoke(cli, ["add", "skill", cls.skill_name])
        assert result.exit_code == 0
        cls.result = cls.runner.invoke(cli,
                                       ["remove", "skill", cls.skill_name])
예제 #7
0
    def test_add_many_keys(self, pytestconfig):
        """Test that the keys are added correctly."""

        result = self.runner.invoke(
            cli,
            [
                *CLI_LOG_OPTION,
                "add-key",
                FetchAICrypto.identifier,
                FETCHAI_PRIVATE_KEY_FILE,
            ],
        )
        assert result.exit_code == 0
        result = self.runner.invoke(
            cli,
            [
                *CLI_LOG_OPTION,
                "add-key",
                EthereumCrypto.identifier,
                ETHEREUM_PRIVATE_KEY_FILE,
            ],
        )
        assert result.exit_code == 0

        f = open(Path(self.agent_folder, DEFAULT_AEA_CONFIG_FILE))
        expected_json = yaml.safe_load(f)
        config = AgentConfig.from_json(expected_json)
        private_key_path_ethereum = config.private_key_paths.read(
            FetchAICrypto.identifier)
        assert private_key_path_ethereum == FETCHAI_PRIVATE_KEY_FILE
        private_key_path_ethereum = config.private_key_paths.read(
            EthereumCrypto.identifier)
        assert private_key_path_ethereum == ETHEREUM_PRIVATE_KEY_FILE
        assert len(config.private_key_paths.read_all()) == 2
예제 #8
0
def test_add_key_fails_bad_key():
    """Test that 'aea add-key' fails because the key is not valid."""
    oldcwd = os.getcwd()
    runner = CliRunner()
    agent_name = "myagent"
    with tempfile.TemporaryDirectory() as tmpdir:
        with mock.patch.object(aea.crypto.helpers.logger, "error") as mock_logger_error:
            os.chdir(tmpdir)
            result = runner.invoke(cli, [*CLI_LOG_OPTION, "create", agent_name])
            assert result.exit_code == 0
            os.chdir(Path(tmpdir, agent_name))

            # create an empty file - surely not a private key
            pvk_file = "this_is_not_a_key.pem"
            Path(pvk_file).touch()

            result = runner.invoke(cli, [*CLI_LOG_OPTION, "add-key", DEFAULT, pvk_file])
            assert result.exit_code == 1
            mock_logger_error.assert_called_with("This is not a valid private key file: '{}'".format(pvk_file))

            # check that no key has been added.
            f = open(Path(DEFAULT_AEA_CONFIG_FILE))
            expected_json = yaml.safe_load(f)
            config = AgentConfig.from_json(expected_json)
            assert len(config.private_key_paths.read_all()) == 0

    os.chdir(oldcwd)
예제 #9
0
    def setup_class(cls):
        """Set the test up."""
        cls.runner = CliRunner()
        cls.agent_name = "myagent"
        cls.cwd = os.getcwd()
        cls.t = tempfile.mkdtemp()
        cls.skill_name = "error"
        cls.patch = unittest.mock.patch.object(aea.cli.common.logger, 'error')
        cls.mocked_logger_error = cls.patch.__enter__()

        os.chdir(cls.t)
        result = cls.runner.invoke(cli,
                                   [*CLI_LOG_OPTION, "create", cls.agent_name],
                                   standalone_mode=False)
        # this also by default adds the oef connection and error skill
        assert result.exit_code == 0
        os.chdir(cls.agent_name)

        # change default registry path
        config = AgentConfig.from_json(
            yaml.safe_load(open(DEFAULT_AEA_CONFIG_FILE)))
        config.registry_path = os.path.join(ROOT_DIR, "packages")
        yaml.safe_dump(config.json, open(DEFAULT_AEA_CONFIG_FILE, "w"))

        # add the error skill again
        cls.result = cls.runner.invoke(
            cli, [*CLI_LOG_OPTION, "add", "skill", cls.skill_name],
            standalone_mode=False)
예제 #10
0
    def setup_class(cls):
        """Set the test up."""
        cls.runner = CliRunner()
        cls.agent_name = "myagent"
        cls.cwd = os.getcwd()
        cls.t = tempfile.mkdtemp()
        cls.skill_name = "echo"
        cls.patch = unittest.mock.patch.object(aea.cli.common.logger, 'error')
        cls.mocked_logger_error = cls.patch.__enter__()

        os.chdir(cls.t)
        result = cls.runner.invoke(cli, ["create", cls.agent_name])
        assert result.exit_code == 0
        os.chdir(cls.agent_name)

        # change default registry path
        config = AgentConfig.from_json(
            yaml.safe_load(open(DEFAULT_AEA_CONFIG_FILE)))
        config.registry_path = os.path.join(ROOT_DIR, "packages")
        yaml.safe_dump(config.json, open(DEFAULT_AEA_CONFIG_FILE, "w"))

        # change the serialization of the AgentConfig class so to make the parsing to fail.
        cls.patch = unittest.mock.patch.object(
            aea.configurations.base.SkillConfig,
            "from_json",
            side_effect=ValidationError("test error message"))
        cls.patch.__enter__()

        cls.result = cls.runner.invoke(cli, ["add", "skill", cls.skill_name])
예제 #11
0
def test_add_key_fails_bad_ledger_id():
    """Test that 'aea add-key' fails because the ledger id is not valid."""
    oldcwd = os.getcwd()
    runner = CliRunner()
    agent_name = "myagent"
    tmpdir = tempfile.mkdtemp()
    os.chdir(tmpdir)
    try:
        result = runner.invoke(
            cli, [*CLI_LOG_OPTION, "init", "--local", "--author", AUTHOR]
        )

        result = runner.invoke(cli, [*CLI_LOG_OPTION, "create", "--local", agent_name])
        assert result.exit_code == 0
        os.chdir(Path(tmpdir, agent_name))

        # generate a private key file
        result = runner.invoke(cli, [*CLI_LOG_OPTION, "generate-key", FETCHAI])
        assert result.exit_code == 0
        assert Path(FETCHAI_PRIVATE_KEY_FILE).exists()
        bad_ledger_id = "this_is_a_bad_ledger_id"

        result = runner.invoke(
            cli, [*CLI_LOG_OPTION, "add-key", bad_ledger_id, FETCHAI_PRIVATE_KEY_FILE]
        )
        assert result.exit_code == 2

        # check that no key has been added.
        f = open(Path(DEFAULT_AEA_CONFIG_FILE))
        expected_json = yaml.safe_load(f)
        config = AgentConfig.from_json(expected_json)
        assert len(config.private_key_paths.read_all()) == 0
    finally:
        os.chdir(oldcwd)
예제 #12
0
    def setup_class(cls):
        """Set up the test."""
        cls.expected_custom_component_configuration = dict(foo="bar")

        cls.agent_config = AgentConfig(
            agent_name="agent_name",
            author="author",
            version="0.1.0",
            default_routing={
                str(cls.old_protocol_id): str(cls.old_connection_id)
            },
            default_connection=str(cls.old_connection_id),
        )

        cls.agent_config.protocols = {cls.old_protocol_id}
        cls.agent_config.contracts = {cls.old_contract_id}
        cls.agent_config.connections = {cls.old_connection_id}
        cls.agent_config.skills = {cls.old_skill_id}
        cls.agent_config.component_configurations[ComponentId(
            ComponentType.PROTOCOL,
            cls.old_protocol_id)] = cls.expected_custom_component_configuration
        cls.agent_config.component_configurations[ComponentId(
            ComponentType.CONTRACT,
            cls.old_contract_id)] = cls.expected_custom_component_configuration
        cls.agent_config.component_configurations[ComponentId(
            ComponentType.CONNECTION, cls.old_connection_id
        )] = cls.expected_custom_component_configuration
        cls.agent_config.component_configurations[ComponentId(
            ComponentType.SKILL,
            cls.old_skill_id)] = cls.expected_custom_component_configuration

        replace_component_ids(cls.agent_config, cls.replacements)
예제 #13
0
파일: core.py 프로젝트: 8ball030/agents-aea
def create(click_context, agent_name):
    """Create an agent."""
    ctx = cast(Context, click_context.obj)
    path = Path(agent_name)
    logger.info("Initializing AEA project '{}'".format(agent_name))
    logger.info("Creating project directory '/{}'".format(agent_name))

    # create the agent's directory
    try:
        path.mkdir(exist_ok=False)

        # create a config file inside it
        logger.info("Creating config file {}".format(DEFAULT_AEA_CONFIG_FILE))
        config_file = open(os.path.join(agent_name, DEFAULT_AEA_CONFIG_FILE),
                           "w")
        agent_config = AgentConfig(agent_name=agent_name,
                                   aea_version=aea.__version__,
                                   authors="",
                                   version="v1",
                                   license="",
                                   url="",
                                   registry_path=DEFAULT_REGISTRY_PATH,
                                   description="")
        agent_config.default_connection = DEFAULT_CONNECTION
        ctx.agent_loader.dump(agent_config, config_file)

        # next commands must be done from the agent's directory -> overwrite ctx.cwd
        ctx.agent_config = agent_config
        ctx.cwd = agent_config.agent_name

        logger.info("Default connections:")
        click_context.invoke(connection, connection_name=DEFAULT_CONNECTION)

        logger.info("Default skills:")
        click_context.invoke(skill, skill_name=DEFAULT_SKILL)

    except OSError:
        logger.error("Directory already exist. Aborting...")
        sys.exit(1)
    except ValidationError as e:
        logger.error(str(e))
        shutil.rmtree(agent_name, ignore_errors=True)
        sys.exit(1)
    except Exception as e:
        logger.exception(e)
        shutil.rmtree(agent_name, ignore_errors=True)
        sys.exit(1)
예제 #14
0
 def test_key_added(self):
     """Test that the fetch private key has been added correctly."""
     f = open(Path(self.agent_folder, DEFAULT_AEA_CONFIG_FILE))
     expected_json = yaml.safe_load(f)
     config = AgentConfig.from_json(expected_json)
     private_key_path = config.private_key_paths.read(FetchAICrypto.identifier)
     assert private_key_path == FETCHAI_PRIVATE_KEY_FILE
     assert len(config.private_key_paths.read_all()) == 1
예제 #15
0
def test_agent_config_to_json_with_optional_configurations():
    """Test agent config to json with optional configurations."""
    agent_config = AgentConfig(
        "name",
        "author",
        timeout=0.1,
        execution_timeout=1.0,
        max_reactions=100,
        decision_maker_handler=dict(dotted_path="", file_path=""),
        skill_exception_policy="propagate",
        default_routing={"author/name:0.1.0": "author/name:0.1.0"},
        loop_mode="sync",
        runtime_mode="async",
    )
    agent_config.default_connection = "author/name:0.1.0"
    agent_config.default_ledger = DEFAULT_LEDGER
    agent_config.json
예제 #16
0
 def _dump_agent_config(self, configuration: AgentConfig,
                        file_pointer: TextIO) -> None:
     """Dump agent configuration."""
     agent_config_part = configuration.ordered_json
     self.validate(agent_config_part)
     agent_config_part.pop("component_configurations")
     result = [agent_config_part
               ] + configuration.component_configurations_json()
     yaml_dump_all(result, file_pointer)
예제 #17
0
    def test_from_json_and_to_json(self):
        """Test the 'from_json' method and 'to_json' work correctly."""
        f = open(os.path.join(CUR_PATH, "data", "aea-config.example.yaml"))
        expected_json = yaml.safe_load(f)
        config = AgentConfig.from_json(expected_json)

        assert isinstance(config, AgentConfig)
        actual_json = config.json

        expected_protocols = expected_json.pop("protocols")
        actual_protocols = actual_json.pop("protocols")
        assert set(expected_protocols) == set(actual_protocols)
        assert actual_json == expected_json
예제 #18
0
def create(click_context, agent_name):
    """Create an agent."""
    ctx = cast(Context, click_context.obj)
    path = Path(agent_name)
    logger.info("Creating agent's directory in '{}'".format(path))

    # create the agent's directory
    try:
        path.mkdir(exist_ok=False)

        # create a config file inside it
        config_file = open(os.path.join(agent_name, DEFAULT_AEA_CONFIG_FILE), "w")
        agent_config = AgentConfig(agent_name=agent_name, aea_version=aea.__version__, authors="", version="v1", license="", url="", registry_path="../packages", private_key_pem_path="")
        agent_config.default_connection = DEFAULT_CONNECTION
        ctx.agent_loader.dump(agent_config, config_file)
        logger.info("Created config file {}".format(DEFAULT_AEA_CONFIG_FILE))

        # next commands must be done from the agent's directory -> overwrite ctx.cwd
        ctx.agent_config = agent_config
        ctx.cwd = agent_config.agent_name

        logger.info("Adding default connection '{}' to the agent...".format(DEFAULT_CONNECTION))
        click_context.invoke(connection, connection_name=DEFAULT_CONNECTION)

        logger.info("Adding default skill '{}' to the agent...".format(DEFAULT_SKILL))
        click_context.invoke(skill, skill_name=DEFAULT_SKILL)

    except OSError:
        logger.error("Directory already exist. Aborting...")
        exit(-1)
    except ValidationError as e:
        logger.error(str(e))
        shutil.rmtree(agent_name, ignore_errors=True)
        exit(-1)
    except Exception as e:
        logger.exception(e)
        shutil.rmtree(agent_name, ignore_errors=True)
        exit(-1)
예제 #19
0
    def with_config_update(self):
        """Context manager to update item version to 0.0.1."""
        original_config = self.load_config()

        config_data = original_config.json
        if str(self.ITEM_PUBLIC_ID) in config_data[f"{self.ITEM_TYPE}s"]:
            config_data[f"{self.ITEM_TYPE}s"].remove(str(self.ITEM_PUBLIC_ID))
        config_data[f"{self.ITEM_TYPE}s"].append(
            f"{self.ITEM_PUBLIC_ID.author}/{self.ITEM_PUBLIC_ID.name}:0.0.1")
        self.dump_config(AgentConfig.from_json(config_data))
        try:
            yield
        finally:
            self.dump_config(original_config)
예제 #20
0
def test_agent_config_to_json_with_optional_configurations():
    """Test agent config to json with optional configurations."""
    agent_config = AgentConfig(
        "name",
        "author",
        period=0.1,
        execution_timeout=1.0,
        max_reactions=100,
        decision_maker_handler=dict(dotted_path="", file_path=""),
        error_handler=dict(dotted_path="", file_path=""),
        skill_exception_policy="propagate",
        connection_exception_policy="propagate",
        default_routing={"author/name:0.1.0": "author/name:0.1.0"},
        currency_denominations={"fetchai": "fet"},
        loop_mode="sync",
        runtime_mode="async",
        storage_uri="some_uri_to_storage",
    )
    agent_config.default_connection = "author/name:0.1.0"
    agent_config.default_ledger = DEFAULT_LEDGER
    agent_config.json
    assert agent_config.package_id == PackageId.from_uri_path(
        "agent/author/name/0.1.0")
예제 #21
0
    def setup_class(cls):
        """Set the test up."""
        cls.runner = CliRunner()
        cls.agent_name = "myagent"
        cls.cwd = os.getcwd()
        cls.t = tempfile.mkdtemp()
        dir_path = Path("packages")
        tmp_dir = cls.t / dir_path
        src_dir = cls.cwd / Path(ROOT_DIR, dir_path)
        shutil.copytree(str(src_dir), str(tmp_dir))
        cls.skill_id = str(GYM_SKILL_PUBLIC_ID)
        cls.skill_name = "gym"

        os.chdir(cls.t)
        result = cls.runner.invoke(
            cli, [*CLI_LOG_OPTION, "init", "--local", "--author", AUTHOR]
        )
        assert result.exit_code == 0

        result = cls.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "create", "--local", cls.agent_name],
            standalone_mode=False,
        )
        assert result.exit_code == 0
        os.chdir(cls.agent_name)

        # change default registry path
        config = AgentConfig.from_json(yaml.safe_load(open(DEFAULT_AEA_CONFIG_FILE)))
        config.registry_path = os.path.join(ROOT_DIR, "packages")
        yaml.safe_dump(dict(config.json), open(DEFAULT_AEA_CONFIG_FILE, "w"))

        result = cls.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "add", "--local", "skill", cls.skill_id],
            standalone_mode=False,
        )
        assert result.exit_code == 0

        cls.patch = unittest.mock.patch(
            "shutil.rmtree", side_effect=BaseException("an exception")
        )
        cls.patch.start()

        cls.result = cls.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "remove", "skill", cls.skill_name],
            standalone_mode=False,
        )
예제 #22
0
def test_add_key_fails_bad_key():
    """Test that 'aea add-key' fails because the key is not valid."""
    oldcwd = os.getcwd()
    runner = CliRunner()
    agent_name = "myagent"
    tmpdir = tempfile.mkdtemp()
    dir_path = Path("packages")
    tmp_dir = tmpdir / dir_path
    src_dir = oldcwd / Path(ROOT_DIR, dir_path)
    shutil.copytree(str(src_dir), str(tmp_dir))
    os.chdir(tmpdir)
    try:
        with mock.patch.object(
            aea.crypto.helpers._default_logger, "error"
        ) as mock_logger_error:

            result = runner.invoke(
                cli, [*CLI_LOG_OPTION, "init", "--local", "--author", AUTHOR]
            )

            result = runner.invoke(
                cli, [*CLI_LOG_OPTION, "create", "--local", agent_name]
            )
            assert result.exit_code == 0
            os.chdir(Path(tmpdir, agent_name))

            # create an empty file - surely not a private key
            pvk_file = "this_is_not_a_key.txt"
            Path(pvk_file).touch()

            result = runner.invoke(cli, [*CLI_LOG_OPTION, "add-key", FETCHAI, pvk_file])
            assert result.exit_code == 1
            error_message = "Invalid length of private key, received 0, expected 32"
            mock_logger_error.assert_called_with(
                "This is not a valid private key file: '{}'\n Exception: '{}'".format(
                    pvk_file, error_message
                ),
                exc_info=True,
            )

            # check that no key has been added.
            f = open(Path(DEFAULT_AEA_CONFIG_FILE))
            expected_json = yaml.safe_load(f)
            config = AgentConfig.from_json(expected_json)
            assert len(config.private_key_paths.read_all()) == 0
    finally:
        os.chdir(oldcwd)
예제 #23
0
    def setup_class(cls):
        """Set the test up."""
        cls.runner = CliRunner()
        cls.agent_name = "myagent"
        cls.cwd = os.getcwd()
        cls.t = tempfile.mkdtemp()
        cls.skill_id = "fetchai/echo:0.1.0"
        cls.skill_name = "echo"
        cls.patch = unittest.mock.patch.object(aea.cli.common.logger, "error")
        cls.mocked_logger_error = cls.patch.__enter__()

        # copy the 'packages' directory in the parent of the agent folder.
        shutil.copytree(Path(CUR_PATH, "..", "packages"),
                        Path(cls.t, "packages"))

        os.chdir(cls.t)
        result = cls.runner.invoke(
            cli, [*CLI_LOG_OPTION, "init", "--local", "--author", AUTHOR])
        assert result.exit_code == 0

        result = cls.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "create", "--local", cls.agent_name],
            standalone_mode=False,
        )
        assert result.exit_code == 0
        os.chdir(cls.agent_name)

        # change default registry path
        config = AgentConfig.from_json(
            yaml.safe_load(open(DEFAULT_AEA_CONFIG_FILE)))
        config.registry_path = os.path.join(ROOT_DIR, "packages")
        yaml.safe_dump(dict(config.json), open(DEFAULT_AEA_CONFIG_FILE, "w"))

        # change the serialization of the AgentConfig class so to make the parsing to fail.
        cls.patch = unittest.mock.patch.object(
            aea.configurations.base.SkillConfig,
            "from_json",
            side_effect=ValidationError("test error message"),
        )
        cls.patch.__enter__()

        cls.result = cls.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "add", "--local", "skill", cls.skill_id],
            standalone_mode=False,
        )
예제 #24
0
    def setup_class(cls):
        """Set the test up."""
        cls.runner = CliRunner()
        cls.agent_name = "myagent"
        cls.cwd = os.getcwd()
        cls.t = tempfile.mkdtemp()
        cls.skill_id = "fetchai/gym:0.1.0"
        cls.skill_name = "gym"
        cls.patch = unittest.mock.patch.object(aea.cli.common.logger, "error")
        cls.mocked_logger_error = cls.patch.__enter__()

        os.chdir(cls.t)
        result = cls.runner.invoke(
            cli, [*CLI_LOG_OPTION, "init", "--local", "--author", AUTHOR])
        assert result.exit_code == 0

        result = cls.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "create", "--local", cls.agent_name],
            standalone_mode=False,
        )
        assert result.exit_code == 0
        os.chdir(cls.agent_name)

        # change default registry path
        config = AgentConfig.from_json(
            yaml.safe_load(open(DEFAULT_AEA_CONFIG_FILE)))
        config.registry_path = os.path.join(ROOT_DIR, "packages")
        yaml.safe_dump(dict(config.json), open(DEFAULT_AEA_CONFIG_FILE, "w"))

        result = cls.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "add", "--local", "skill", cls.skill_id],
            standalone_mode=False,
        )
        assert result.exit_code == 0

        cls.patch = unittest.mock.patch(
            "shutil.rmtree", side_effect=BaseException("an exception"))
        cls.patch.__enter__()

        cls.result = cls.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "remove", "skill", cls.skill_name],
            standalone_mode=False,
        )
예제 #25
0
def test_agent_config_package_dependencies():
    """Test agent config package dependencies."""
    agent_config = AgentConfig("name", "author")
    assert agent_config.package_dependencies == set()

    pid = PublicId("author", "name", "0.1.0")
    agent_config.protocols.add(pid)
    agent_config.connections.add(pid)
    agent_config.contracts.add(pid)
    agent_config.skills.add(pid)

    assert agent_config.package_dependencies == {
        PackageId(PackageType.PROTOCOL, pid),
        PackageId(PackageType.CONNECTION, pid),
        PackageId(PackageType.CONTRACT, pid),
        PackageId(PackageType.SKILL, pid),
    }
예제 #26
0
    def test_fetch(self):
        """Test that the fetch private key is created correctly."""
        result = self.runner.invoke(cli, [*CLI_LOG_OPTION, "generate-key", FETCHAI])
        assert result.exit_code == 0
        assert Path(FETCHAI_PRIVATE_KEY_FILE).exists()

        # this line tests that the content of the file is correct.
        FetchAICrypto(FETCHAI_PRIVATE_KEY_FILE)

        result = self.runner.invoke(cli, [*CLI_LOG_OPTION, "add-key", FETCHAI, FETCHAI_PRIVATE_KEY_FILE])
        assert result.exit_code == 0

        f = open(Path(self.agent_folder, DEFAULT_AEA_CONFIG_FILE))
        expected_json = yaml.safe_load(f)
        config = AgentConfig.from_json(expected_json)
        private_key_configuration = config.private_key_paths.read(FETCHAI)
        assert private_key_configuration is not None
        assert private_key_configuration.ledger == FETCHAI
        assert private_key_configuration.path == FETCHAI_PRIVATE_KEY_FILE

        assert len(config.private_key_paths.read_all()) == 2
예제 #27
0
    def setup_class(cls):
        """Set the test up."""
        cls.runner = CliRunner()
        cls.agent_name = "myagent"
        cls.cwd = os.getcwd()
        cls.t = tempfile.mkdtemp()
        cls.skill_id = str(ECHO_PUBLIC_ID)
        cls.skill_name = "echo"

        # copy the 'packages' directory in the parent of the agent folder.
        shutil.copytree(Path(CUR_PATH, "..", "packages"), Path(cls.t, "packages"))

        os.chdir(cls.t)
        result = cls.runner.invoke(
            cli, [*CLI_LOG_OPTION, "init", "--local", "--author", AUTHOR]
        )
        assert result.exit_code == 0

        result = cls.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "create", "--local", cls.agent_name],
            standalone_mode=False,
        )
        assert result.exit_code == 0
        os.chdir(cls.agent_name)

        # change default registry path
        config = AgentConfig.from_json(yaml.safe_load(open(DEFAULT_AEA_CONFIG_FILE)))
        config.registry_path = os.path.join(ROOT_DIR, "packages")
        yaml.safe_dump(dict(config.json), open(DEFAULT_AEA_CONFIG_FILE, "w"))

        Path(
            cls.t, cls.agent_name, "vendor", "fetchai", "skills", cls.skill_name
        ).mkdir(parents=True, exist_ok=True)
        cls.result = cls.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "add", "--local", "skill", cls.skill_id],
            standalone_mode=False,
        )
예제 #28
0
    def setup_class(cls):
        """Set the test up."""
        cls.runner = CliRunner()
        cls.agent_name = "myagent"
        cls.cwd = os.getcwd()
        cls.t = tempfile.mkdtemp()
        cls.skill_id = "fetchai/gym:0.4.0"
        cls.skill_name = "gym"

        os.chdir(cls.t)
        result = cls.runner.invoke(
            cli, [*CLI_LOG_OPTION, "init", "--local", "--author", AUTHOR]
        )
        assert result.exit_code == 0

        result = cls.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "create", "--local", cls.agent_name],
            standalone_mode=False,
        )
        assert result.exit_code == 0
        os.chdir(cls.agent_name)

        # change default registry path
        config = AgentConfig.from_json(yaml.safe_load(open(DEFAULT_AEA_CONFIG_FILE)))
        config.registry_path = os.path.join(ROOT_DIR, "packages")
        yaml.safe_dump(dict(config.json), open(DEFAULT_AEA_CONFIG_FILE, "w"))

        result = cls.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "add", "--local", "skill", cls.skill_id],
            standalone_mode=False,
        )
        assert result.exit_code == 0
        cls.result = cls.runner.invoke(
            cli,
            [*CLI_LOG_OPTION, "remove", "skill", cls.skill_id],
            standalone_mode=False,
        )
예제 #29
0
 def test_default_connection(self):
     """Test case for default_connection setter positive result."""
     agent_config = AgentConfig(agent_name="my_agent", author="fetchai")
     agent_config.default_connection = None
     agent_config.default_connection = 1
     agent_config.public_id
예제 #30
0
 def test_init_logging_config_positive(self):
     """Test case for from_json method positive result."""
     AgentConfig(agent_name="my_agent", author="fetchai", logging_config={})