예제 #1
0
def test_component_id_same_prefix():
    """Test ComponentId.same_prefix"""
    component_id_1 = ComponentId(ComponentType.PROTOCOL,
                                 PublicId("author", "name", "0.1.0"))
    component_id_2 = ComponentId(ComponentType.PROTOCOL,
                                 PublicId("author", "name", "0.2.0"))
    assert component_id_1.same_prefix(component_id_2)
예제 #2
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)
예제 #3
0
 def test_register_when_component_id_mismatch(self):
     """Test AgentComponentRegistry.register when the component ids mismatch."""
     component_id_1 = ComponentId(ComponentType.PROTOCOL,
                                  PublicId("author", "name", "0.1.0"))
     component_id_2 = ComponentId(ComponentType.PROTOCOL,
                                  PublicId("author", "name", "0.2.0"))
     component_mock = MagicMock(component_id=component_id_1)
     with pytest.raises(
             ValueError,
             match="Component id '.*' is different to the id '.*' specified."
     ):
         self.registry.register(component_id_2, component_mock)
     self.registry._registered_keys = set()
예제 #4
0
    def setup(self):
        """Set up the tests."""
        self.aea_config_path = Path(CUR_PATH, "data", "dummy_aea",
                                    DEFAULT_AEA_CONFIG_FILE)
        self.loader = ConfigLoaders.from_package_type(PackageType.AGENT)
        self.aea_config: AgentConfig = self.loader.load(
            self.aea_config_path.open())
        self.dummy_skill_component_id = ComponentId(ComponentType.SKILL,
                                                    DUMMY_SKILL_PUBLIC_ID)

        self.new_dummy_skill_config = {
            "behaviours": {
                "dummy": {
                    "args": dict(behaviour_arg_1=42)
                }
            },
            "handlers": {
                "dummy": {
                    "args": dict(handler_arg_1=42)
                }
            },
            "models": {
                "dummy": {
                    "args": dict(model_arg_1=42)
                }
            },
        }
예제 #5
0
 def test_fetch(self):
     """Test that the `fetch` method works as expected."""
     contract_id = PublicId.from_str("fetchai/erc1155:0.6.0")
     contract = self.registry.fetch(
         ComponentId(ComponentType.CONTRACT, contract_id))
     assert isinstance(contract, Contract)
     assert contract.id == contract_id
예제 #6
0
def test_override_ledger_configurations_positive():
    """Test override ledger configurations function util with fields to override."""
    new_chain_id = "some_chain"
    agent_config = MagicMock()
    agent_config.component_configurations = {
        ComponentId(ComponentType.CONNECTION, LEDGER_CONNECTION): {
            "config": {"ledger_apis": {DEFAULT_LEDGER: {"chain_id": new_chain_id}}}
        }
    }
    old_configurations = deepcopy(LedgerApis.ledger_api_configs)

    expected_configurations = deepcopy(old_configurations[DEFAULT_LEDGER])
    expected_configurations["chain_id"] = new_chain_id
    try:
        _override_ledger_configurations(agent_config)
        actual_configurations = LedgerApis.ledger_api_configs.get("fetchai")
        assert expected_configurations == actual_configurations
    finally:
        # this is important - _ovveride_ledger_configurations does
        # side-effect to LedgerApis.ledger_api_configs
        LedgerApis.ledger_api_configs = old_configurations
        assert (
            LedgerApis.ledger_api_configs[DEFAULT_LEDGER]["chain_id"]
            == DEFAULT_CHAIN_ID
        )
예제 #7
0
def is_item_present(
    path: str,
    agent_config: AgentConfig,
    item_type: str,
    item_public_id: PublicId,
    is_vendor: bool = True,
    with_version: bool = False,
) -> bool:
    """
    Check if item is already present in AEA.

    Optionally, consider the check also with the version.

    :param path: path to look for packages.
    :param agent_config: agent config
    :param item_type: type of an item.
    :param item_public_id: PublicId of an item.
    :param is_vendor: flag for vendorized path (True by default).
    :param with_version: if true, consider also the package version.

    :return: boolean is item present.
    """
    item_path = Path(
        get_package_path(path, item_type, item_public_id, is_vendor=is_vendor))
    registered_item_public_id = get_item_public_id_by_author_name(
        agent_config, item_type, item_public_id.author, item_public_id.name)
    is_item_registered_no_version = registered_item_public_id is not None
    does_path_exist = Path(item_path).exists()
    if item_public_id.package_version.is_latest or not with_version:
        return is_item_registered_no_version and does_path_exist

    # the following makes sense because public id is not latest
    component_id = ComponentId(ComponentType(item_type), item_public_id)
    component_is_registered = component_id in agent_config.package_dependencies
    return component_is_registered and does_path_exist
예제 #8
0
    def __init__(self, ctx: Context, item_type: str,
                 item_public_id: PublicId) -> None:
        """
        Init item upgrader.

        :param ctx: context
        :param item_type: str, type of the package
        :param item_public_id: item to upgrade.
        """
        self.ctx = ctx
        self.ctx.set_config("with_dependencies", True)
        self.item_type = item_type
        self.item_public_id = item_public_id
        self.component_id = ComponentId(self.item_type, self.item_public_id)
        self.current_item_public_id = self.get_current_item()
        (
            self.in_requirements,
            self.deps_can_be_removed,
            self.deps_can_not_be_removed,
        ) = self.get_dependencies()
        self.dependencies: Set[PackageId] = set()
        self.dependencies.update(self.deps_can_be_removed)
        self.dependencies.update(self.deps_can_not_be_removed)

        self._current_aea_version = aea.__version__
예제 #9
0
def test_find_import_order():
    """Test find import order works on cycle dependency."""
    builder = AEABuilder()
    builder.set_name("aea_1")
    builder.add_private_key("fetchai")

    _old_load = ComponentConfiguration.load

    def _new_load(*args, **kwargs):
        skill_config = _old_load(*args, **kwargs)
        skill_config.skills = [Mock()]
        return skill_config

    with patch.object(ComponentConfiguration, "load", _new_load):
        with pytest.raises(
                AEAException,
                match=r"Cannot load skills, there is a cyclic dependency."):
            builder._find_import_order(
                [
                    ComponentId(ComponentType.SKILL,
                                PublicId("dummy_author", "dummy", "0.1.0")),
                ],
                Path(os.path.join(CUR_PATH, "data", "dummy_aea")),
                True,
            )
예제 #10
0
 def test_fetch(self):
     """Test that the `fetch` method works as expected."""
     contract_id = ERC1155_PUBLIC_ID
     contract = self.registry.fetch(
         ComponentId(ComponentType.CONTRACT, contract_id))
     assert isinstance(contract, Contract)
     assert contract.id == contract_id
예제 #11
0
    def remove_skill(self, public_id: PublicId) -> "AEABuilder":
        """
        Remove protocol.

        :param public_id: the public id of the skill
        :return: the AEABuilder
        """
        self.remove_component(ComponentId(ComponentType.SKILL, public_id))
        return self
예제 #12
0
    def remove_connection(self, public_id: PublicId) -> "AEABuilder":
        """
        Remove a connection.

        :param public_id: the public id of the connection
        :return: the AEABuilder
        """
        self.remove_component(ComponentId(ComponentType.CONNECTION, public_id))
        return self
예제 #13
0
    def remove_connection(self, connection_id: ConnectionId) -> None:
        """
        Remove a connection from the set of resources.

        :param connection_id: the connection id for the connection to be removed.
        :return: None
        """
        self._component_registry.unregister(
            ComponentId(ComponentType.CONNECTION, connection_id))
예제 #14
0
    def remove_contract(self, contract_id: ContractId) -> None:
        """
        Remove a contract from the set of resources.

        :param contract_id: the contract id for the contract to be removed.
        :return: None
        """
        self._component_registry.unregister(
            ComponentId(ComponentType.CONTRACT, contract_id))
예제 #15
0
def test_component_id_from_json():
    """Test ComponentId.from_json."""
    json_data = {
        "type": "connection",
        "author": "author",
        "name": "name",
        "version": "1.0.0",
    }
    assert ComponentId.from_json(json_data).json == json_data
예제 #16
0
def _override_ledger_configurations(agent_config: AgentConfig) -> None:
    """Override LedgerApis configurations with agent override configurations."""
    ledger_component_id = ComponentId(ComponentType.CONNECTION,
                                      LEDGER_CONNECTION)
    if ledger_component_id not in agent_config.component_configurations:
        return
    ledger_apis_config = agent_config.component_configurations[
        ledger_component_id]["config"].get("ledger_apis", {})
    recursive_update(LedgerApis.ledger_api_configs, ledger_apis_config)
예제 #17
0
    def remove_protocol(self, protocol_id: ProtocolId) -> None:
        """
        Remove a protocol from the set of resources.

        :param protocol_id: the protocol id for the protocol to be removed.
        :return: None
        """
        self._component_registry.unregister(
            ComponentId(ComponentType.PROTOCOL, protocol_id))
예제 #18
0
    def remove_contract(self, public_id: PublicId) -> "AEABuilder":
        """
        Remove protocol.

        :param public_id: the public id of the contract
        :return: the AEABuilder
        """
        self.remove_component(ComponentId(ComponentType.CONTRACT, public_id))
        return self
예제 #19
0
 def _remove_from_config(self) -> None:
     """Remove item from agent config."""
     current_item = self.get_current_item()
     logger.debug("Removing the {} from {}".format(self.item_type,
                                                   DEFAULT_AEA_CONFIG_FILE))
     self.agent_items.remove(current_item)
     self.agent_config.component_configurations.pop(
         ComponentId(self.item_type, current_item), None)
     self.ctx.dump_agent_config()
예제 #20
0
    def get_connection(self, connection_id: PublicId) -> Optional[Connection]:
        """
        Get connection for given connection id.

        :param connection_id: the connection id
        :return: a matching connection, if present, else None
        """
        connection = self._component_registry.fetch(
            ComponentId(ComponentType.CONNECTION, connection_id))
        return cast(Connection, connection)
예제 #21
0
    def get_protocol(self, protocol_id: ProtocolId) -> Optional[Protocol]:
        """
        Get protocol for given protocol id.

        :param protocol_id: the protocol id
        :return: a matching protocol, if present, else None
        """
        protocol = self._component_registry.fetch(
            ComponentId(ComponentType.PROTOCOL, protocol_id))
        return cast(Protocol, protocol)
예제 #22
0
    def get_contract(self, contract_id: ContractId) -> Optional[Contract]:
        """
        Get contract for given contract id.

        :param contract_id: the contract id
        :return: a matching contract, if present, else None
        """
        contract = self._component_registry.fetch(
            ComponentId(ComponentType.CONTRACT, contract_id))
        return cast(Contract, contract)
예제 #23
0
    def get_skill(self, skill_id: SkillId) -> Optional[Skill]:
        """
        Get the skill for a given skill id.

        :param skill_id: the skill id
        :return: a matching skill, if present, else None
        """
        skill = self._component_registry.fetch(
            ComponentId(ComponentType.SKILL, skill_id))
        return cast(Skill, skill)
예제 #24
0
def test_get_latest_component_id_from_prefix():
    """Test the utility to get the latest concrete version id."""
    agent_config = MagicMock()
    expected_component_id = ComponentId(ComponentType.PROTOCOL,
                                        PublicId("author", "name", "0.1.0"))
    agent_config.package_dependencies = {expected_component_id}

    result = get_latest_component_id_from_prefix(
        agent_config, expected_component_id.component_prefix)
    assert result == expected_component_id
예제 #25
0
 def test_register_when_component_is_already_registered(self):
     """Test AgentComponentRegistry.register when the component is already registered."""
     component_id = ComponentId(ComponentType.PROTOCOL,
                                PublicId("author", "name", "0.1.0"))
     component_mock = MagicMock(component_id=component_id)
     self.registry._registered_keys.add(component_id)
     with pytest.raises(ValueError,
                        match=r"Component already registered with item id"):
         self.registry.register(component_id, component_mock)
     self.registry._registered_keys = set()
예제 #26
0
def test_from_dir():
    """Test Connection.from_dir"""
    dummy_connection_dir = os.path.join(CUR_PATH, "data", "dummy_connection")
    identity = MagicMock()
    identity.name = "agent_name"
    crypto_store = MagicMock()
    connection = Connection.from_dir(dummy_connection_dir, identity, crypto_store)
    assert isinstance(connection, Connection)
    assert connection.component_id == ComponentId(
        ComponentType.CONNECTION, PublicId("fetchai", "dummy", "0.1.0")
    )
예제 #27
0
 def test_unregister_when_no_item_registered(self):
     """Test AgentComponentRegistry.register when the item was not registered."""
     component_id = ComponentId(
         ComponentType.PROTOCOL, PublicId("author", "name", "0.1.0")
     )
     component_mock = MagicMock(component_id=component_id)
     self.registry.register(component_id, component_mock)
     self.registry._registered_keys.remove(component_id)
     with pytest.raises(ValueError, match="No item registered with item id '.*'"):
         self.registry.unregister(component_id)
     self.registry._registered_keys.add(component_id)
     self.registry.unregister(component_id)
예제 #28
0
    def get_component_directory(package_id: PackageId) -> Path:
        """Return path for package."""
        try:
            return AEABuilder.find_component_directory_from_component_id(
                Path("."),
                ComponentId(str(package_id.package_type), package_id.public_id),
            )

        except ValueError:
            raise click.ClickException(
                f"Can not find folder for the package: {package_id.package_type} {package_id.public_id}"
            )
예제 #29
0
def _override_ledger_configurations(agent_config: AgentConfig) -> None:
    """Override LedgerApis configurations with agent override configurations."""
    ledger_component_id = ComponentId(ComponentType.CONNECTION,
                                      PublicId.from_str(LEDGER_CONNECTION))
    prefix_to_component_configuration = {
        key.component_prefix: value
        for key, value in agent_config.component_configurations.items()
    }
    if ledger_component_id.component_prefix not in prefix_to_component_configuration:
        return
    ledger_apis_config = prefix_to_component_configuration[
        ledger_component_id.component_prefix]["config"].get("ledger_apis", {})
    recursive_update(LedgerApis.ledger_api_configs, ledger_apis_config)
예제 #30
0
    def test_custom_configuration_updated(self):
        """Test default routing updated."""
        component_protocol_id = ComponentId(ComponentType.PROTOCOL,
                                            self.new_protocol_id)
        component_contract_id = ComponentId(ComponentType.CONTRACT,
                                            self.new_contract_id)
        component_connection_id = ComponentId(ComponentType.CONNECTION,
                                              self.new_connection_id)
        component_skill_id = ComponentId(ComponentType.SKILL,
                                         self.new_skill_id)

        assert (
            self.agent_config.component_configurations[component_protocol_id]
            == self.expected_custom_component_configuration)
        assert (
            self.agent_config.component_configurations[component_contract_id]
            == self.expected_custom_component_configuration)
        assert (
            self.agent_config.component_configurations[component_connection_id]
            == self.expected_custom_component_configuration)
        assert (self.agent_config.component_configurations[component_skill_id]
                == self.expected_custom_component_configuration)