Exemplo n.º 1
0
def test_check_public_id_consistency_negative():
    """Test ComponentId.check_public_id_consistency raises error when directory does not exists."""
    random_dir_name = random_string()
    with pytest.raises(ValueError,
                       match=f"Directory {random_dir_name} is not valid."):
        component_configuration = ProtocolConfig("name", "author")
        component_configuration.check_public_id_consistency(
            Path(random_dir_name))
Exemplo n.º 2
0
    def test_from_json_and_to_json(self, protocol_path):
        """Test the 'from_json' method and 'to_json' work correctly."""
        f = open(protocol_path)
        original_json = yaml.safe_load(f)

        expected_config = ProtocolConfig.from_json(original_json)
        assert isinstance(expected_config, ProtocolConfig)
        expected_json = expected_config.json
        actual_config = ProtocolConfig.from_json(expected_json)
        actual_json = actual_config.json
        assert expected_json == actual_json
Exemplo n.º 3
0
def test_dependency_manager_highest_version():
    """Test dependency version priority."""
    dep_manager = _DependenciesManager()
    dep_manager.add_component(ProtocolConfig("a_protocol", "author", "0.1.0"))
    dep_manager.add_component(ProtocolConfig("a_protocol", "author", "0.2.0"))

    assert len(dep_manager.dependencies_highest_version) == 1
    assert list(dep_manager.dependencies_highest_version)[0].version == "0.2.0"

    assert len(dep_manager.protocols) == 2

    assert len(dep_manager.skills) == 0
    assert len(dep_manager.contracts) == 0
Exemplo n.º 4
0
def test_remove_component_not_exists():
    """Test component remove not exists."""
    dep_manager = _DependenciesManager()
    with pytest.raises(ValueError,
                       match=r"Component .* of type .* not present."):
        dep_manager.remove_component(
            ProtocolConfig("a_protocol", "author", "0.1.0").component_id)
Exemplo n.º 5
0
 def setup_class(self):
     """Setup test."""
     self.configuration = ProtocolConfig("name", "author", "0.1.0")
     self.configuration.build_directory = "test"
     self.component = Component(configuration=self.configuration)
     self.directory = Path()
     self.component._directory = self.directory
Exemplo n.º 6
0
def test_multiple_builds_with_component_instance():
    """Test multiple calls to the 'build()' method when adding component instances."""
    builder = AEABuilder()
    builder.set_name("aea_1")
    builder.add_private_key("fetchai")

    a_protocol = Protocol(
        ProtocolConfig("a_protocol", "author", "0.1.0"), DefaultMessage
    )
    builder.add_component_instance(a_protocol)

    # the first call works
    aea_1 = builder.build()
    assert isinstance(aea_1, AEA)

    # the second call fails
    with pytest.raises(ValueError, match="Cannot build.*"):
        builder.build()

    # after reset, it works
    builder.reset()
    builder.set_name("aea_1")
    builder.add_private_key("fetchai")
    builder.add_component_instance(a_protocol)
    aea_2 = builder.build()
    assert isinstance(aea_2, AEA)
Exemplo n.º 7
0
    def setup_class(cls):
        """Set the test up."""
        cls.node = LocalNode()
        cls.node.start()
        cls.agent_name = "MyAgent"
        cls.private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem")
        cls.wallet = Wallet({'default': cls.private_key_pem_path})
        cls.ledger_apis = LedgerApis({})
        cls.connection = OEFLocalConnection(cls.agent_name, cls.node)
        cls.connections = [cls.connection]

        cls.temp = tempfile.mkdtemp(prefix="test_aea_resources")
        cls.resources = Resources(cls.temp)
        cls.aea = AEA(cls.agent_name, cls.connections, cls.wallet, cls.ledger_apis, resources=cls.resources)

        cls.default_protocol_configuration = ProtocolConfig.from_json(
            yaml.safe_load(open(Path(AEA_DIR, "protocols", "default", "protocol.yaml"))))
        cls.default_protocol = Protocol("default",
                                        DefaultSerializer(),
                                        cls.default_protocol_configuration)
        cls.resources.protocol_registry.register(("default", None), cls.default_protocol)

        cls.error_skill = Skill.from_dir(Path(AEA_DIR, "skills", "error"), cls.aea.context)
        cls.dummy_skill = Skill.from_dir(Path(CUR_PATH, "data", "dummy_skill"), cls.aea.context)
        cls.resources.add_skill(cls.dummy_skill)
        cls.resources.add_skill(cls.error_skill)

        cls.expected_message = DefaultMessage(type=DefaultMessage.Type.BYTES, content=b"hello")

        cls.t = Thread(target=cls.aea.start)
        cls.t.start()
        time.sleep(0.5)

        cls.aea.outbox.put(Envelope(to=cls.agent_name, sender=cls.agent_name, protocol_id="default", message=DefaultSerializer().encode(cls.expected_message)))
Exemplo n.º 8
0
 def test_protocols_config(self):
     """Test the protocol config."""
     protocol = Protocol(
         protocol_id=PublicId.from_str("author/my_own_protocol:0.1.0"),
         serializer=cast(Serializer, ProtobufSerializer),
         config=ProtocolConfig(),
     )
     assert protocol.config is not None
Exemplo n.º 9
0
def test_can_remove_not_exists_component():
    """Test fail on remove component not registered."""
    builder = AEABuilder()
    builder.set_name("aea_1")
    builder.add_private_key("fetchai")
    protocol = ProtocolConfig("a_protocol", "author", "0.1.0")
    with pytest.raises(ValueError):
        builder._check_can_remove(protocol.component_id)
Exemplo n.º 10
0
def test_remove_component_success():
    """Test remove registered component."""
    dep_manager = _DependenciesManager()
    protocol = ProtocolConfig("a_protocol", "author", "0.1.0")
    skill = SkillConfig("skill", "author", "0.1.0", protocols=[protocol.public_id])
    dep_manager.add_component(protocol)
    dep_manager.add_component(skill)
    dep_manager.remove_component(skill.component_id)
Exemplo n.º 11
0
def test_check_aea_version_when_it_fails():
    """Test the check for the AEA version when it fails."""
    config = ProtocolConfig("name", "author", "0.1.0", aea_version=">0.1.0")
    with mock.patch.object(aea, "__version__", "0.1.0"):
        with pytest.raises(
            ValueError,
            match="The CLI version is 0.1.0, but package author/name:0.1.0 requires version >0.1.0",
        ):
            _check_aea_version(config)
Exemplo n.º 12
0
def test_find_component_failed():
    """Test fail on compomnent not found."""
    builder = AEABuilder()
    builder.set_name("aea_1")
    builder.add_private_key("fetchai")
    a_protocol = Protocol(ProtocolConfig("a_protocol", "author", "0.1.0"),
                          DefaultMessage)
    with pytest.raises(ValueError, match=r"Package .* not found"):
        builder._find_component_directory_from_component_id(
            Path("/some_dir"), a_protocol.component_id)
Exemplo n.º 13
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", "dummy_aea", "protocols", "default",
                         "protocol.yaml"))
        expected_json = yaml.safe_load(f)
        config = ProtocolConfig.from_json(expected_json)

        assert isinstance(config, ProtocolConfig)
        actual_json = config.json
        assert expected_json == actual_json
Exemplo n.º 14
0
def test_directory_setter():
    """Test directory."""
    configuration = ProtocolConfig("author", "name", "0.1.0")
    component = Component(configuration=configuration)

    with pytest.raises(ValueError):
        component.directory

    new_path = Path("new_path")
    component.directory = new_path
    assert component.directory == new_path
Exemplo n.º 15
0
def _bump_protocol_specification_id(package_path: Path,
                                    configuration: ProtocolConfig) -> None:
    """Bump spec id version."""
    spec_id: PublicId = configuration.protocol_specification_id  # type: ignore
    old_version = semver.VersionInfo.parse(spec_id.version)
    new_version = str(old_version.bump_minor())
    new_spec_id = PublicId(spec_id.author, spec_id.name, new_version)
    configuration.protocol_specification_id = new_spec_id
    with (package_path /
          DEFAULT_PROTOCOL_CONFIG_FILE).open("w") as file_output:
        ConfigLoaders.from_package_type(configuration.package_type).dump(
            configuration, file_output)
Exemplo n.º 16
0
def test_remove_protocol():
    """Test add/remove protocol."""
    builder = AEABuilder()
    builder.set_name("aea_1")
    builder.add_private_key("fetchai")
    a_protocol = Protocol(
        ProtocolConfig("a_protocol", "author", "0.1.0"), DefaultMessage
    )
    num_deps = len(builder._package_dependency_manager.all_dependencies)
    builder.add_component_instance(a_protocol)
    assert len(builder._package_dependency_manager.all_dependencies) == num_deps + 1
    builder.remove_protocol(a_protocol.public_id)
    assert len(builder._package_dependency_manager.all_dependencies) == num_deps
Exemplo n.º 17
0
def test_component_configuration_check_fingerprint_different_fingerprints_no_vendor():
    """Test ComponentConfiguration.check_fingerprint when the fingerprints differ for a non-vendor package."""
    config = ProtocolConfig("name", "author", "0.1.0")
    package_dir = Path("path", "to", "dir")
    error_regex = (
        f"Fingerprints for package {package_dir} do not match:\nExpected: {dict()}\nActual: {dict(foo='bar')}\n"
        + "Please fingerprint the package before continuing: 'aea fingerprint protocol author/name:0.1.0"
    )

    with pytest.raises(ValueError, match=error_regex):
        with mock.patch(
            "aea.configurations.base._compute_fingerprint", return_value={"foo": "bar"}
        ):
            _compare_fingerprints(config, package_dir, False, PackageType.PROTOCOL)
Exemplo n.º 18
0
def test_component_configuration_check_fingerprint_different_fingerprints_vendor():
    """Test ComponentConfiguration.check_fingerprint when the fingerprints differ for a vendor package."""
    config = ProtocolConfig("name", "author", "0.1.0")
    package_dir = Path("path", "to", "dir")
    error_regex = (
        f"Fingerprints for package {package_dir} do not match:\nExpected: {dict()}\nActual: {dict(foo='bar')}\n"
        + "Vendorized projects should not be tampered with, please revert any changes to protocol author/name:0.1.0"
    )

    with pytest.raises(ValueError, match=error_regex):
        with mock.patch(
            "aea.configurations.base._compute_fingerprint", return_value={"foo": "bar"}
        ):
            _compare_fingerprints(config, package_dir, True, PackageType.PROTOCOL)
Exemplo n.º 19
0
def test_remove_component_depends_on_fail():
    """Test component remove fails cause dependency."""
    dep_manager = _DependenciesManager()
    protocol = ProtocolConfig("a_protocol", "author", "0.1.0")
    dep_manager.add_component(protocol)
    dep_manager.add_component(
        SkillConfig("skill", "author", "0.1.0", protocols=[protocol.public_id])
    )

    with pytest.raises(
        ValueError,
        match=r"Cannot remove component .* of type .*. Other components depends on it: .*",
    ):
        dep_manager.remove_component(protocol.component_id)
Exemplo n.º 20
0
def test_component_add_bad_dep():
    """Test component load failed cause dependency."""
    builder = AEABuilder()
    builder.set_name("aea_1")
    builder.add_private_key("fetchai")
    connection = _make_dummy_connection()
    connection.configuration.pypi_dependencies = {
        "something": Dependency("something", "==0.1.0")
    }
    builder.add_component_instance(connection)

    a_protocol = Protocol(
        ProtocolConfig("a_protocol", "author", "0.1.0"), DefaultMessage
    )
    a_protocol.configuration.pypi_dependencies = {
        "something": Dependency("something", "==0.2.0")
    }
    with pytest.raises(
        AEAException, match=r"Conflict on package something: specifier set .*"
    ):
        builder.add_component_instance(a_protocol)
Exemplo n.º 21
0
 def setup_class(self):
     self.configuration = ProtocolConfig("name", "author", "0.1.0")
     self.component = Component(configuration=self.configuration)
     self.directory = Path()
     self.component._directory = self.directory
Exemplo n.º 22
0
def ipfs_hashing(
    package_hashes: Dict[str, str],
    target_dir: str,
    package_type: str,
    package_name: str,
    ipfs_hash_only: IPFSHashOnly,
):
    """Hashes a package and its components."""
    print("Processing package {} of type {}".format(package_name,
                                                    package_type))

    # load config file to get ignore patterns, dump again immediately to impose ordering
    if package_type == "agents":
        config = AgentConfig.from_json(
            yaml.safe_load(open(Path(target_dir, DEFAULT_AEA_CONFIG_FILE))))
        yaml_dump(config.json,
                  open(Path(target_dir, DEFAULT_AEA_CONFIG_FILE), "w"))
    elif package_type == "connections":
        config = ConnectionConfig.from_json(
            yaml.safe_load(
                open(Path(target_dir, DEFAULT_CONNECTION_CONFIG_FILE))))
        yaml_dump(config.json,
                  open(Path(target_dir, DEFAULT_CONNECTION_CONFIG_FILE), "w"))
    elif package_type == "contracts":
        config = ContractConfig.from_json(
            yaml.safe_load(open(Path(target_dir,
                                     DEFAULT_CONTRACT_CONFIG_FILE))))
        yaml_dump(config.json,
                  open(Path(target_dir, DEFAULT_CONTRACT_CONFIG_FILE), "w"))
    elif package_type == "protocols":
        config = ProtocolConfig.from_json(
            yaml.safe_load(open(Path(target_dir,
                                     DEFAULT_PROTOCOL_CONFIG_FILE))))
        yaml_dump(config.json,
                  open(Path(target_dir, DEFAULT_PROTOCOL_CONFIG_FILE), "w"))
    elif package_type == "skills":
        config = SkillConfig.from_json(
            yaml.safe_load(open(Path(target_dir, DEFAULT_SKILL_CONFIG_FILE))))
        yaml_dump(config.json,
                  open(Path(target_dir, DEFAULT_SKILL_CONFIG_FILE), "w"))
    config = yaml.safe_load(next(Path(target_dir).glob("*.yaml")).open())
    ignore_patterns = config.get("fingerprint_ignore_patterns", [])
    if package_type != "agents":
        # hash inner components
        fingerprints_dict = _compute_fingerprint(Path(target_dir),
                                                 ignore_patterns)
        # confirm ipfs only generates same hash:
        for file_name, ipfs_hash in fingerprints_dict.items():
            path = os.path.join(target_dir, file_name)
            ipfsho_hash = ipfs_hash_only.get(path)
            if ipfsho_hash != ipfs_hash:
                print("WARNING, hashes don't match for: {}".format(path))

        # update fingerprints
        file_name = package_type[:-1] + ".yaml"
        yaml_path = os.path.join(target_dir, file_name)
        file = open(yaml_path, mode="r")

        # read all lines at once
        whole_file = file.read()

        # close the file
        file.close()

        file = open(yaml_path, mode="r")

        # find and replace
        # TODO this can be simplified after https://github.com/fetchai/agents-aea/issues/932
        existing = ""
        fingerprint_block = False
        for line in file:
            if line.find("fingerprint:") == 0:
                existing += line
                fingerprint_block = True
            elif fingerprint_block:
                if line.find("  ") == 0:
                    # still inside fingerprint block
                    existing += line
                else:
                    # fingerprint block has ended
                    break

        if len(fingerprints_dict) > 0:
            replacement = "fingerprint:\n"
            ordered_fingerprints_dict = collections.OrderedDict(
                sorted(fingerprints_dict.items()))
            for file_name, ipfs_hash in ordered_fingerprints_dict.items():
                replacement += "  " + file_name + ": " + ipfs_hash + "\n"
        else:
            replacement = "fingerprint: {}\n"
        whole_file = whole_file.replace(existing, replacement)

        # close the file
        file.close()

        # update fingerprints
        with open(yaml_path, "w") as f:
            f.write(whole_file)

    # hash again to get outer hash (this time all files):
    # TODO we still need to ignore some files
    result_list = client.add(target_dir)
    for result_dict in result_list:
        if package_name == result_dict["Name"]:
            key = os.path.join(AUTHOR, package_type, package_name)
            package_hashes[key] = result_dict["Hash"]
Exemplo n.º 23
0
def test_component_configuration_check_fingerprint_bad_directory():
    """Test ComponentConfiguration.check_fingerprint when a bad directory is provided."""
    config = ProtocolConfig("name", "author", "0.1.0")
    with pytest.raises(ValueError, match="Directory .* is not valid."):
        config.check_fingerprint(Path("non_existing_directory"))
Exemplo n.º 24
0
def test_configuration_ordered_json():
    """Test configuration ordered json."""
    configuration = ProtocolConfig("name", "author", "0.1.0")
    configuration._key_order = ["aea_version"]
    configuration.ordered_json
    async def test_end_to_end_aea_aca(self):
        # AEA components
        ledger_apis = LedgerApis({}, FetchAICrypto.identifier)
        wallet = Wallet({FetchAICrypto.identifier: FETCHAI_PRIVATE_KEY_FILE})
        identity = Identity(
            name="my_aea_1",
            address=wallet.addresses.get(FetchAICrypto.identifier),
            default_address_key=FetchAICrypto.identifier,
        )
        http_client_connection = HTTPClientConnection(
            address=self.aea_address,
            provider_address=self.aca_admin_address,
            provider_port=self.aca_admin_port,
        )
        resources = Resources()

        # create AEA
        aea = AEA(identity, [http_client_connection], wallet, ledger_apis,
                  resources)

        # Add http protocol to AEA resources
        http_protocol_configuration = ProtocolConfig.from_json(
            yaml.safe_load(
                open(
                    os.path.join(
                        self.cwd,
                        "packages",
                        "fetchai",
                        "protocols",
                        "http",
                        "protocol.yaml",
                    ))))
        http_protocol = Protocol(http_protocol_configuration, HttpSerializer())
        resources.add_protocol(http_protocol)

        # Request message & envelope
        request_http_message = HttpMessage(
            dialogue_reference=("", ""),
            target=0,
            message_id=1,
            performative=HttpMessage.Performative.REQUEST,
            method="GET",
            url="http://{}:{}/status".format(self.aca_admin_address,
                                             self.aca_admin_port),
            headers="",
            version="",
            bodyy=b"",
        )
        request_envelope = Envelope(
            to="ACA",
            sender="AEA",
            protocol_id=HTTP_PROTOCOL_PUBLIC_ID,
            message=HttpSerializer().encode(request_http_message),
        )

        # add a simple skill with handler
        skill_context = SkillContext(aea.context)
        skill_config = SkillConfig(name="simple_skill",
                                   author="fetchai",
                                   version="0.1.0")
        aea_handler = AEAHandler(skill_context=skill_context,
                                 name="aea_handler")
        simple_skill = Skill(skill_config,
                             skill_context,
                             handlers={aea_handler.name: aea_handler})
        resources.add_skill(simple_skill)

        # add error skill to AEA
        error_skill = Skill.from_dir(os.path.join(AEA_DIR, "skills", "error"))
        resources.add_skill(error_skill)

        # start AEA thread
        t_aea = Thread(target=aea.start)
        try:
            t_aea.start()
            time.sleep(1.0)
            aea.outbox.put(request_envelope)
            time.sleep(5.0)
            assert (aea_handler.handled_message.performative ==
                    HttpMessage.Performative.RESPONSE)
            assert aea_handler.handled_message.version == ""
            assert aea_handler.handled_message.status_code == 200
            assert aea_handler.handled_message.status_text == "OK"
            assert aea_handler.handled_message.headers is not None
            assert aea_handler.handled_message.version is not None
        finally:
            aea.stop()
            t_aea.join()
Exemplo n.º 26
0
def component_configuration():
    """Return a component configuration."""
    return ProtocolConfig("a_protocol", "an_author", "0.1.0")
    async def test_end_to_end_aea_aca(self):
        """Test the end to end aea aca interaction."""
        # AEA components
        wallet = Wallet({DEFAULT_LEDGER: DEFAULT_PRIVATE_KEY_FILE})
        identity = Identity(
            name="my_aea_1",
            address=wallet.addresses.get(DEFAULT_LEDGER),
            default_address_key=DEFAULT_LEDGER,
        )
        configuration = ConnectionConfig(
            host=self.aca_admin_address,
            port=self.aca_admin_port,
            connection_id=HTTPClientConnection.connection_id,
        )
        http_client_connection = HTTPClientConnection(
            configuration=configuration,
            identity=identity,
        )
        resources = Resources()
        resources.add_connection(http_client_connection)

        # create AEA
        aea = AEA(identity, wallet, resources)

        # Add http protocol to AEA resources
        http_protocol_configuration = ProtocolConfig.from_json(
            yaml.safe_load(
                open(
                    os.path.join(
                        self.cwd,
                        "packages",
                        "fetchai",
                        "protocols",
                        "http",
                        "protocol.yaml",
                    ))))
        http_protocol = Protocol(http_protocol_configuration,
                                 HttpMessage.serializer())
        resources.add_protocol(http_protocol)

        # Request message & envelope
        request_http_message = HttpMessage(
            dialogue_reference=("", ""),
            target=0,
            message_id=1,
            performative=HttpMessage.Performative.REQUEST,
            method="GET",
            url="http://{}:{}/status".format(self.aca_admin_address,
                                             self.aca_admin_port),
            headers="",
            version="",
            body=b"",
        )
        request_http_message.to = "ACA"
        request_envelope = Envelope(
            to="ACA",
            sender="AEA",
            protocol_id=HttpMessage.protocol_id,
            message=request_http_message,
        )

        # add a simple skill with handler
        skill_context = SkillContext(aea.context)
        skill_config = SkillConfig(name="simple_skill",
                                   author="fetchai",
                                   version="0.1.0")
        aea_handler = AEAHandler(skill_context=skill_context,
                                 name="aea_handler")
        simple_skill = Skill(skill_config,
                             skill_context,
                             handlers={aea_handler.name: aea_handler})
        resources.add_skill(simple_skill)

        # add error skill to AEA
        error_skill = Skill.from_dir(os.path.join(AEA_DIR, "skills", "error"),
                                     agent_context=aea.context)
        resources.add_skill(error_skill)

        # start AEA thread
        t_aea = Thread(target=aea.start)
        try:
            t_aea.start()
            time.sleep(1.0)
            aea.outbox.put(request_envelope)
            time.sleep(5.0)
            assert (aea_handler.handled_message.performative ==
                    HttpMessage.Performative.RESPONSE)
            assert aea_handler.handled_message.version == ""
            assert aea_handler.handled_message.status_code == 200
            assert aea_handler.handled_message.status_text == "OK"
            assert aea_handler.handled_message.headers is not None
            assert aea_handler.handled_message.version is not None
        finally:
            aea.stop()
            t_aea.join()
Exemplo n.º 28
0
    def setup_class(cls):
        """Set the test up."""
        cls.node = LocalNode()
        cls.node.start()
        cls.agent_name = "MyAgent"
        cls.private_key_path = os.path.join(CUR_PATH, "data",
                                            "fet_private_key.txt")
        cls.wallet = Wallet({FETCHAI: cls.private_key_path})
        cls.ledger_apis = LedgerApis({}, FETCHAI)
        cls.identity = Identity(cls.agent_name,
                                address=cls.wallet.addresses[FETCHAI])
        cls.connection = OEFLocalConnection(
            cls.agent_name, cls.node, connection_id=LOCAL_CONNECTION_PUBLIC_ID)
        cls.connections = [cls.connection]

        cls.temp = tempfile.mkdtemp(prefix="test_aea_resources")
        cls.resources = Resources(cls.temp)
        cls.aea = AEA(
            cls.identity,
            cls.connections,
            cls.wallet,
            cls.ledger_apis,
            resources=cls.resources,
        )

        default_protocol_id = DefaultMessage.protocol_id

        cls.default_protocol_configuration = ProtocolConfig.from_json(
            yaml.safe_load(
                open(Path(AEA_DIR, "protocols", "default", "protocol.yaml"))))
        cls.default_protocol = Protocol(default_protocol_id,
                                        DefaultSerializer(),
                                        cls.default_protocol_configuration)
        cls.resources.protocol_registry.register(default_protocol_id,
                                                 cls.default_protocol)

        cls.error_skill = Skill.from_dir(Path(AEA_DIR, "skills", "error"),
                                         cls.aea.context)
        cls.dummy_skill = Skill.from_dir(Path(CUR_PATH, "data", "dummy_skill"),
                                         cls.aea.context)
        cls.resources.add_skill(cls.dummy_skill)
        cls.resources.add_skill(cls.error_skill)

        cls.expected_message = DefaultMessage(
            dialogue_reference=("", ""),
            message_id=1,
            target=0,
            performative=DefaultMessage.Performative.BYTES,
            content=b"hello",
        )
        cls.expected_message.counterparty = cls.agent_name

        cls.t = Thread(target=cls.aea.start)
        cls.t.start()
        time.sleep(0.5)

        cls.aea.outbox.put(
            Envelope(
                to=cls.agent_name,
                sender=cls.agent_name,
                protocol_id=default_protocol_id,
                message=DefaultSerializer().encode(cls.expected_message),
            ))
Exemplo n.º 29
0
    def test_generated_protocol_end_to_end(self):
        """Test that a generated protocol could be used in exchanging messages between two agents."""
        # AEA components
        ledger_apis = LedgerApis({}, FETCHAI)

        wallet_1 = Wallet({FETCHAI: FETCHAI_PRIVATE_KEY_FILE})
        wallet_2 = Wallet({FETCHAI: FETCHAI_PRIVATE_KEY_FILE})

        identity_1 = Identity(
            name="my_aea_1",
            address=wallet_1.addresses.get(FETCHAI),
            default_address_key=FETCHAI,
        )
        identity_2 = Identity(
            name="my_aea_2",
            address=wallet_2.addresses.get(FETCHAI),
            default_address_key=FETCHAI,
        )

        oef_connection_1 = OEFConnection(
            address=identity_1.address, oef_addr=HOST, oef_port=PORT
        )
        oef_connection_2 = OEFConnection(
            address=identity_2.address, oef_addr=HOST, oef_port=PORT
        )

        resources_1 = Resources()
        resources_2 = Resources()

        # add generated protocols to resources
        generated_protocol_configuration = ProtocolConfig.from_json(
            yaml.safe_load(
                open(
                    os.path.join(
                        self.cwd,
                        "tests",
                        "data",
                        "generator",
                        "two_party_negotiation",
                        "protocol.yaml",
                    )
                )
            )
        )
        generated_protocol = Protocol(
            TwoPartyNegotiationMessage.protocol_id,
            TwoPartyNegotiationSerializer(),
            generated_protocol_configuration,
        )
        resources_1.protocol_registry.register(
            TwoPartyNegotiationMessage.protocol_id, generated_protocol
        )
        resources_2.protocol_registry.register(
            TwoPartyNegotiationMessage.protocol_id, generated_protocol
        )

        # create AEAs
        aea_1 = AEA(identity_1, [oef_connection_1], wallet_1, ledger_apis, resources_1)
        aea_2 = AEA(identity_2, [oef_connection_2], wallet_2, ledger_apis, resources_2)

        inform_number = tuple((1370, 1991, 1, 4, 17, 6))
        # message 1
        message = TwoPartyNegotiationMessage(
            message_id=1,
            dialogue_reference=(str(0), ""),
            target=0,
            performative=TwoPartyNegotiationMessage.Performative.INFORM,
            inform_number=inform_number,
        )
        encoded_message_in_bytes = TwoPartyNegotiationSerializer().encode(message)
        envelope = Envelope(
            to=identity_2.address,
            sender=identity_1.address,
            protocol_id=TwoPartyNegotiationMessage.protocol_id,
            message=encoded_message_in_bytes,
        )
        # message 2
        reply_message = {1: "number one", 2: "number two", 7: "number seven"}
        message_2 = TwoPartyNegotiationMessage(
            message_id=2,
            dialogue_reference=(str(0), ""),
            target=1,
            performative=TwoPartyNegotiationMessage.Performative.INFORM_REPLY,
            reply_message=reply_message,
        )
        encoded_message_2_in_bytes = TwoPartyNegotiationSerializer().encode(message_2)

        # add handlers to AEA resources
        agent_1_handler = Agent1Handler(
            skill_context=SkillContext(aea_1.context), name="fake_skill"
        )
        resources_1.handler_registry.register(
            (
                PublicId.from_str("fetchai/fake_skill:0.1.0"),
                TwoPartyNegotiationMessage.protocol_id,
            ),
            agent_1_handler,
        )
        agent_2_handler = Agent2Handler(
            encoded_messsage=encoded_message_2_in_bytes,
            skill_context=SkillContext(aea_2.context),
            name="fake_skill",
        )
        resources_2.handler_registry.register(
            (
                PublicId.from_str("fetchai/fake_skill:0.1.0"),
                TwoPartyNegotiationMessage.protocol_id,
            ),
            agent_2_handler,
        )

        # add error skill to AEAs
        error_skill_1 = Skill.from_dir(
            os.path.join(AEA_DIR, "skills", "error"), aea_1.context
        )
        resources_1.add_skill(error_skill_1)

        error_skill_2 = Skill.from_dir(
            os.path.join(AEA_DIR, "skills", "error"), aea_2.context
        )
        resources_2.add_skill(error_skill_2)

        # Start threads
        t_1 = Thread(target=aea_1.start)
        t_2 = Thread(target=aea_2.start)
        try:
            t_1.start()
            t_2.start()
            time.sleep(1.0)
            aea_1.outbox.put(envelope)
            time.sleep(5.0)
            assert (
                agent_2_handler.handled_message.message_id == message.message_id
            ), "Message from Agent 1 to 2: message ids do not match"
            assert (
                agent_2_handler.handled_message.dialogue_reference
                == message.dialogue_reference
            ), "Message from Agent 1 to 2: dialogue references do not match"
            assert (
                agent_2_handler.handled_message.dialogue_reference[0]
                == message.dialogue_reference[0]
            ), "Message from Agent 1 to 2: dialogue reference[0]s do not match"
            assert (
                agent_2_handler.handled_message.dialogue_reference[1]
                == message.dialogue_reference[1]
            ), "Message from Agent 1 to 2: dialogue reference[1]s do not match"
            assert (
                agent_2_handler.handled_message.target == message.target
            ), "Message from Agent 1 to 2: targets do not match"
            assert (
                agent_2_handler.handled_message.performative == message.performative
            ), "Message from Agent 1 to 2: performatives do not match"
            assert (
                agent_2_handler.handled_message.inform_number == message.inform_number
            ), "Message from Agent 1 to 2: inform_numbers do not match"

            assert (
                agent_1_handler.handled_message.message_id == message_2.message_id
            ), "Message from Agent 1 to 2: dialogue references do not match"
            assert (
                agent_1_handler.handled_message.dialogue_reference
                == message_2.dialogue_reference
            ), "Message from Agent 2 to 1: dialogue references do not match"
            assert (
                agent_1_handler.handled_message.dialogue_reference[0]
                == message_2.dialogue_reference[0]
            ), "Message from Agent 2 to 1: dialogue reference[0]s do not match"
            assert (
                agent_1_handler.handled_message.dialogue_reference[1]
                == message_2.dialogue_reference[1]
            ), "Message from Agent 2 to 1: dialogue reference[1]s do not match"
            assert (
                agent_1_handler.handled_message.target == message_2.target
            ), "Message from Agent 2 to 1: targets do not match"
            assert (
                agent_1_handler.handled_message.performative == message_2.performative
            ), "Message from Agent 2 to 1: performatives do not match"
            assert (
                agent_1_handler.handled_message.reply_message == message_2.reply_message
            ), "Message from Agent 1 to 2: reply_messages do not match"
            time.sleep(2.0)
        finally:
            aea_1.stop()
            aea_2.stop()
            t_1.join()
            t_2.join()
Exemplo n.º 30
0
 def test_protocols_config(self):
     """Test the protocol config."""
     protocol = Protocol(id="test",
                         serializer=cast(Serializer, ProtobufSerializer),
                         config=ProtocolConfig())
     assert protocol.config is not None