Beispiel #1
0
def test_run_agent():
    """Test that we can set up and then run the agent."""
    with LocalNode() as node:
        agent_name = "dummyagent"
        agent_address = "some_address"
        identity = Identity(agent_name, address=agent_address)
        oef_local_connection = _make_local_connection(agent_address, node)
        oef_local_connection._local_node = node
        agent = DummyAgent(identity, [oef_local_connection],)
        assert agent.name == identity.name
        assert agent.tick == 0
        assert (
            agent.agent_state == AgentState.INITIATED
        ), "Agent state must be 'initiated'"

        agent.multiplexer.connect()
        assert (
            agent.agent_state == AgentState.CONNECTED
        ), "Agent state must be 'connected'"

        assert isinstance(agent.inbox, InBox)
        assert isinstance(agent.outbox, OutBox)

        agent_thread = Thread(target=agent.start)
        agent_thread.start()
        time.sleep(1.0)

        try:
            assert (
                agent.agent_state == AgentState.RUNNING
            ), "Agent state must be 'running'"
        finally:
            agent.stop()
            agent.multiplexer.disconnect()
            agent_thread.join()
Beispiel #2
0
    def setup_class(cls):
        """Test the initialisation of the AEA."""
        cls.node = LocalNode()
        private_key_path = os.path.join(CUR_PATH, "data", "fet_private_key.txt")
        cls.wallet = Wallet({FETCHAI: private_key_path})
        cls.ledger_apis = LedgerApis({}, FETCHAI)
        cls.agent_name = "Agent0"

        cls.connection = _make_dummy_connection()
        cls.connections = [cls.connection]
        cls.identity = Identity(cls.agent_name, address=cls.wallet.addresses[FETCHAI])
        cls.address = cls.identity.address
        cls.my_aea = AEA(
            cls.identity,
            cls.connections,
            cls.wallet,
            cls.ledger_apis,
            timeout=2.0,
            resources=Resources(str(Path(CUR_PATH, "data/dummy_aea"))),
            is_programmatic=False,
        )
        cls.skill_context = SkillContext(cls.my_aea._context)
        logger_name = "aea.{}.skills.{}.{}".format(
            cls.my_aea._context.agent_name, "fetchai", "error"
        )
        cls.skill_context._logger = logging.getLogger(logger_name)
        cls.my_error_handler = ErrorHandler(
            name="error", skill_context=cls.skill_context
        )
        cls.t = Thread(target=cls.my_aea.start)
        cls.t.start()
        time.sleep(0.5)
Beispiel #3
0
    def setup_class(cls):
        """Set up the test."""
        cls.node = LocalNode()
        cls.node.start()

        cls.address_1 = "address"
        cls.multiplexer = Multiplexer(
            [_make_local_connection(cls.address_1, cls.node,)]
        )

        cls.multiplexer.connect()

        # register a service.
        request_id = 1
        cls.data_model = DataModel("foobar", attributes=[])
        service_description = Description(
            {"foo": 1, "bar": "baz"}, data_model=cls.data_model
        )
        register_service_request = OefSearchMessage(
            performative=OefSearchMessage.Performative.REGISTER_SERVICE,
            dialogue_reference=(str(request_id), ""),
            service_description=service_description,
        )
        msg_bytes = OefSearchSerializer().encode(register_service_request)
        envelope = Envelope(
            to=DEFAULT_OEF,
            sender=cls.address_1,
            protocol_id=OefSearchMessage.protocol_id,
            message=msg_bytes,
        )
        cls.multiplexer.put(envelope)
Beispiel #4
0
    def setup_class(cls):
        """Set the test up."""
        agent_name = "MyAgent"
        private_key_path = os.path.join(CUR_PATH, "data",
                                        "fet_private_key.txt")
        wallet = Wallet({FETCHAI: private_key_path})
        ledger_apis = LedgerApis({}, FETCHAI)
        resources = Resources()
        resources.add_component(
            Skill.from_dir(Path(CUR_PATH, "data", "dummy_skill")))
        identity = Identity(agent_name, address=wallet.addresses[FETCHAI])
        cls.input_file = tempfile.mkstemp()[1]
        cls.output_file = tempfile.mkstemp()[1]
        cls.agent = AEA(
            identity,
            [_make_local_connection(identity.address, LocalNode())],
            wallet,
            ledger_apis,
            resources,
        )
        for skill in resources.get_all_skills():
            skill.skill_context.set_agent_context(cls.agent.context)

        cls.t = Thread(target=cls.agent.start)
        cls.t.start()
        time.sleep(1.0)
Beispiel #5
0
    def setup_class(cls):
        """Set up the test."""
        cls.node = LocalNode()
        cls.node.start()

        cls.address_1 = "address_1"
        cls.multiplexer1 = Multiplexer(
            [
                OEFLocalConnection(
                    cls.address_1,
                    cls.node,
                    connection_id=PublicId("fetchai", "local", "0.1.0"),
                )
            ]
        )
        cls.address_2 = "address_2"
        cls.multiplexer2 = Multiplexer(
            [
                OEFLocalConnection(
                    cls.address_2,
                    cls.node,
                    connection_id=PublicId("fetchai", "local", "0.1.0"),
                )
            ]
        )
        cls.multiplexer1.connect()
        cls.multiplexer2.connect()
Beispiel #6
0
def test_initialise_aea():
    """Tests the initialisation of the AEA."""
    node = LocalNode()
    private_key_path = os.path.join(CUR_PATH, "data", "fet_private_key.txt")
    wallet = Wallet({FETCHAI: private_key_path})
    identity = Identity("my_name", address=wallet.addresses[FETCHAI])
    connections1 = [
        OEFLocalConnection(identity.address,
                           node,
                           connection_id=OEFLocalConnection.connection_id)
    ]
    ledger_apis = LedgerApis({}, FETCHAI)
    my_AEA = AEA(
        identity,
        connections1,
        wallet,
        ledger_apis,
        resources=Resources(str(Path(CUR_PATH, "aea"))),
    )
    assert my_AEA.context == my_AEA._context, "Cannot access the Agent's Context"
    assert (not my_AEA.context.connection_status.is_connected
            ), "AEA should not be connected."
    my_AEA.setup()
    assert my_AEA.resources is not None, "Resources must not be None after setup"
    my_AEA.resources = Resources(str(Path(CUR_PATH, "aea")))
    assert my_AEA.resources is not None, "Resources must not be None after set"
    assert (my_AEA.context.shared_state
            is not None), "Shared state must not be None after set"
    assert my_AEA.context.task_manager is not None
    assert my_AEA.context.identity is not None, "Identity must not be None after set."
    my_AEA.stop()
Beispiel #7
0
def test_act():
    """Tests the act function of the AEA."""
    with LocalNode() as node:
        agent_name = "MyAgent"
        private_key_path = os.path.join(CUR_PATH, "data",
                                        "fet_private_key.txt")
        wallet = Wallet({FETCHAI: private_key_path})
        identity = Identity(agent_name, address=wallet.addresses[FETCHAI])
        ledger_apis = LedgerApis({}, FETCHAI)
        connections = [
            OEFLocalConnection(identity.address,
                               node,
                               connection_id=LOCAL_CONNECTION_PUBLIC_ID)
        ]
        resources = Resources(str(Path(CUR_PATH, "data", "dummy_aea")))

        agent = AEA(identity,
                    connections,
                    wallet,
                    ledger_apis,
                    resources,
                    is_programmatic=False)
        t = Thread(target=agent.start)
        try:
            t.start()
            time.sleep(1.0)

            behaviour = agent.resources.behaviour_registry.fetch(
                (DUMMY_SKILL_PUBLIC_ID, "dummy"))
            assert behaviour.nb_act_called > 0, "Act() wasn't called"
        finally:
            agent.stop()
            t.join()
Beispiel #8
0
async def test_receiving_when_not_connected_raise_exception():
    """Test that when we try to receive an envelope from a not connected connection we raise exception."""
    with pytest.raises(AEAConnectionError, match="Connection not established yet."):
        with LocalNode() as node:
            address = "address"
            connection = _make_local_connection(address, node)
            await connection.receive()
Beispiel #9
0
async def test_connection_twice_return_none():
    """Test that connecting twice works."""
    with LocalNode() as node:
        address = "address"
        connection = _make_local_connection(address, node)
        await connection.connect()
        await node.connect(address, connection._reader)
        message = DefaultMessage(
            dialogue_reference=("", ""),
            message_id=1,
            target=0,
            performative=DefaultMessage.Performative.BYTES,
            content=b"hello",
        )
        message_bytes = DefaultSerializer().encode(message)
        expected_envelope = Envelope(
            to=address,
            sender=address,
            protocol_id=DefaultMessage.protocol_id,
            message=message_bytes,
        )
        await connection.send(expected_envelope)
        actual_envelope = await connection.receive()

        assert expected_envelope == actual_envelope

        await connection.disconnect()
Beispiel #10
0
def test_multiplexer_connect_one_raises_error_many_connections():
    """Test the case when the multiplexer raises an exception while attempting the connection of one connection."""
    node = LocalNode()
    tmpdir = Path(tempfile.mkdtemp())
    d = tmpdir / "test_stub"
    d.mkdir(parents=True)
    input_file_path = d / "input_file.csv"
    output_file_path = d / "input_file.csv"

    connection_1 = _make_local_connection("my_addr", node)
    connection_2 = _make_stub_connection(input_file_path, output_file_path)
    connection_3 = _make_dummy_connection()
    multiplexer = Multiplexer([connection_1, connection_2, connection_3])

    assert not connection_1.connection_status.is_connected
    assert not connection_2.connection_status.is_connected
    assert not connection_3.connection_status.is_connected

    with unittest.mock.patch.object(connection_3, "connect", side_effect=Exception):
        with pytest.raises(
            AEAConnectionError, match="Failed to connect the multiplexer."
        ):
            multiplexer.connect()

    assert not connection_1.connection_status.is_connected
    assert not connection_2.connection_status.is_connected
    assert not connection_3.connection_status.is_connected

    multiplexer.disconnect()
    try:
        shutil.rmtree(tmpdir)
    except OSError as e:
        logger.warning("Couldn't delete {}".format(tmpdir))
        logger.exception(e)
Beispiel #11
0
def test_send_message_no_supported_protocol():
    """Test the case when we send an envelope with a specific connection that does not support the protocol."""
    with LocalNode() as node:
        identity_1 = Identity("", address="address_1")
        public_id = PublicId.from_str("fetchai/my_private_protocol:0.1.0")
        connection_1 = _make_local_connection(
            identity_1.address,
            node,
            restricted_to_protocols={public_id},
            excluded_protocols={public_id},
        )
        multiplexer = Multiplexer([connection_1])

        multiplexer.connect()

        with mock.patch.object(aea.mail.base.logger, "warning") as mock_logger_warning:
            protocol_id = UNKNOWN_PROTOCOL_PUBLIC_ID
            envelope = Envelope(
                to=identity_1.address,
                sender=identity_1.address,
                protocol_id=protocol_id,
                message=b"some bytes",
            )
            multiplexer.put(envelope)
            time.sleep(0.5)
            mock_logger_warning.assert_called_with(
                "Connection {} cannot handle protocol {}. Cannot send the envelope.".format(
                    connection_1.connection_id, protocol_id
                )
            )

        multiplexer.disconnect()
Beispiel #12
0
def test_run_agent():
    """Test that we can set up and then run the agent."""
    with LocalNode() as node:
        agent_name = "dummyagent"
        agent_address = "some_address"
        identity = Identity(agent_name, address=agent_address)
        oef_local_connection = _make_local_connection(agent_address, node)
        oef_local_connection._local_node = node

        agent = DummyAgent(identity, [oef_local_connection],
                           loop=asyncio.new_event_loop())
        agent_thread = Thread(target=agent.start)
        assert agent.state == RuntimeStates.stopped
        agent_thread.start()
        try:
            wait_for_condition(
                lambda: agent.state == RuntimeStates.starting,
                timeout=10,
                error_msg="Agent state must be 'starting'",
            )
            wait_for_condition(
                lambda: agent.state == RuntimeStates.running,
                timeout=10,
                error_msg="Agent state must be 'running'",
            )
        finally:
            agent.stop()
            assert agent.state == RuntimeStates.stopped
            agent_thread.join()
Beispiel #13
0
def test_send_message_no_supported_protocol():
    """Test the case when we send an envelope with a specific connection that does not support the protocol."""
    with LocalNode() as node:
        address_1 = "address_1"
        connection_1_id = PublicId.from_str("author/local_1:0.1.0")
        connection_1 = OEFLocalConnection(
            address_1,
            node,
            connection_id=connection_1_id,
            restricted_to_protocols={"my_private_protocol"},
            excluded_protocols={"my_other_protocol"},
        )
        multiplexer = Multiplexer([connection_1])

        multiplexer.connect()

        with mock.patch.object(aea.mail.base.logger, "warning") as mock_logger_warning:
            protocol_id = UNKNOWN_PROTOCOL_PUBLIC_ID
            envelope = Envelope(
                to=address_1,
                sender=address_1,
                protocol_id=protocol_id,
                message=b"some bytes",
            )
            multiplexer.put(envelope)
            time.sleep(0.5)
            mock_logger_warning.assert_called_with(
                "Connection {} cannot handle protocol {}. Cannot send the message.".format(
                    connection_1_id, protocol_id
                )
            )

        multiplexer.disconnect()
Beispiel #14
0
def test_multiplexer_connect_one_raises_error_many_connections():
    """Test the case when the multiplexer raises an exception while attempting the connection of one connection."""
    node = LocalNode()
    tmpdir = Path(tempfile.mkdtemp())
    d = tmpdir / "test_stub"
    d.mkdir(parents=True)
    input_file_path = d / "input_file.csv"
    output_file_path = d / "input_file.csv"

    connection_1 = OEFLocalConnection(
        "my_addr", node, connection_id=PublicId("fetchai", "local", "0.1.0")
    )
    connection_2 = StubConnection(
        input_file_path,
        output_file_path,
        connection_id=PublicId("fetchai", "stub", "0.1.0"),
    )
    connection_3 = DummyConnection(connection_id=DUMMY_CONNECTION_PUBLIC_ID)
    multiplexer = Multiplexer([connection_1, connection_2, connection_3])

    assert not connection_1.connection_status.is_connected
    assert not connection_2.connection_status.is_connected
    assert not connection_3.connection_status.is_connected

    with unittest.mock.patch.object(connection_3, "connect", side_effect=Exception):
        with pytest.raises(
            AEAConnectionError, match="Failed to connect the multiplexer."
        ):
            multiplexer.connect()

    assert not connection_1.connection_status.is_connected
    assert not connection_2.connection_status.is_connected
    assert not connection_3.connection_status.is_connected

    shutil.rmtree(tmpdir)
Beispiel #15
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 = _make_local_connection(cls.agent_name, cls.node)
        cls.connections = [cls.connection]
        cls.temp = tempfile.mkdtemp(prefix="test_aea_resources")
        cls.resources = Resources(cls.temp)

        cls.default_protocol = Protocol.from_dir(
            str(Path(AEA_DIR, "protocols", "default")))
        cls.resources.add_protocol(cls.default_protocol)

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

        cls.aea = AEA(
            cls.identity,
            cls.connections,
            cls.wallet,
            cls.ledger_apis,
            resources=cls.resources,
        )

        cls.error_skill.skill_context.set_agent_context(cls.aea.context)
        cls.dummy_skill.skill_context.set_agent_context(cls.aea.context)

        default_protocol_id = DefaultMessage.protocol_id

        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),
            ))
Beispiel #16
0
def test_multiple_connection():
    """Test that we can send a message with two different connections."""
    with LocalNode() as node:
        address_1 = "address_1"
        address_2 = "address_2"
        connection_1_id = PublicId.from_str("author/local_1:0.1.0")
        connection_2_id = PublicId.from_str("author/local_2:0.1.0")

        connection_1 = OEFLocalConnection(node,
                                          address=address_1,
                                          connection_id=connection_1_id)

        connection_2 = OEFLocalConnection(node,
                                          address=address_2,
                                          connection_id=connection_2_id)

        multiplexer = Multiplexer([connection_1, connection_2])

        assert not connection_1.connection_status.is_connected
        assert not connection_2.connection_status.is_connected

        multiplexer.connect()

        assert connection_1.connection_status.is_connected
        assert connection_2.connection_status.is_connected

        message = DefaultMessage(
            dialogue_reference=("", ""),
            message_id=1,
            target=0,
            performative=DefaultMessage.Performative.BYTES,
            content=b"hello",
        )
        envelope_from_1_to_2 = Envelope(
            to=address_2,
            sender=address_1,
            protocol_id=DefaultMessage.protocol_id,
            message=DefaultSerializer().encode(message),
            context=EnvelopeContext(connection_id=connection_1_id),
        )
        multiplexer.put(envelope_from_1_to_2)

        actual_envelope = multiplexer.get(block=True, timeout=2.0)
        assert envelope_from_1_to_2 == actual_envelope

        envelope_from_2_to_1 = Envelope(
            to=address_1,
            sender=address_2,
            protocol_id=DefaultMessage.protocol_id,
            message=DefaultSerializer().encode(message),
            context=EnvelopeContext(connection_id=connection_2_id),
        )
        multiplexer.put(envelope_from_2_to_1)

        actual_envelope = multiplexer.get(block=True, timeout=2.0)
        assert envelope_from_2_to_1 == actual_envelope

        multiplexer.disconnect()
Beispiel #17
0
    def setup_class(cls):
        """Set up the test."""
        cls.node = LocalNode()
        cls.node.start()

        cls.address_1 = "address_1"
        cls.multiplexer1 = Multiplexer(
            [_make_local_connection(cls.address_1, cls.node,)]
        )
Beispiel #18
0
async def test_connecting_to_node_with_same_key():
    """Test that connecting twice with the same key works correctly."""
    with LocalNode() as node:
        address = "my_address"
        my_queue = asyncio.Queue()

        ret = await node.connect(address, my_queue)
        assert ret is not None and isinstance(ret, asyncio.Queue)
        ret = await node.connect(address, my_queue)
        assert ret is None
Beispiel #19
0
def test_react():
    """Tests income messages."""
    with LocalNode() as node:
        agent_name = "MyAgent"
        private_key_path = os.path.join(CUR_PATH, "data",
                                        "fet_private_key.txt")
        builder = AEABuilder()
        builder.set_name(agent_name)
        builder.add_private_key(FETCHAI, private_key_path)
        builder.add_protocol(
            Path(ROOT_DIR, "packages", "fetchai", "protocols", "oef_search"))
        builder.add_connection(
            Path(ROOT_DIR, "packages", "fetchai", "connections", "local"))
        builder.set_default_connection(
            PublicId.from_str("fetchai/local:0.1.0"))
        builder.add_skill(Path(CUR_PATH, "data", "dummy_skill"))
        agent = builder.build(
            connection_ids=[PublicId.from_str("fetchai/local:0.1.0")])
        # This is a temporary workaround to feed the local node to the OEF Local connection
        # TODO remove it.
        list(agent._connections)[0]._local_node = node

        msg = DefaultMessage(
            dialogue_reference=("", ""),
            message_id=1,
            target=0,
            performative=DefaultMessage.Performative.BYTES,
            content=b"hello",
        )
        msg.counterparty = agent.identity.address
        message_bytes = DefaultSerializer().encode(msg)

        envelope = Envelope(
            to=agent.identity.address,
            sender=agent.identity.address,
            protocol_id=DefaultMessage.protocol_id,
            message=message_bytes,
        )

        with run_in_thread(agent.start, timeout=20, on_exit=agent.stop):
            wait_for_condition(
                lambda: agent._main_loop and agent._main_loop.is_running,
                timeout=10)
            agent.outbox.put(envelope)
            default_protocol_public_id = DefaultMessage.protocol_id
            dummy_skill_public_id = DUMMY_SKILL_PUBLIC_ID
            handler = agent.resources.get_handler(default_protocol_public_id,
                                                  dummy_skill_public_id)
            assert handler is not None, "Handler is not set."
            wait_for_condition(
                lambda: msg in handler.handled_messages,
                timeout=10,
                error_msg="The message is not inside the handled_messages.",
            )
            agent.stop()
Beispiel #20
0
def test_react():
    """Tests income messages."""
    with LocalNode() as node:
        agent_name = "MyAgent"
        private_key_path = os.path.join(CUR_PATH, "data",
                                        "fet_private_key.txt")
        wallet = Wallet({FETCHAI: private_key_path})
        identity = Identity(agent_name, address=wallet.addresses[FETCHAI])
        ledger_apis = LedgerApis({}, FETCHAI)
        connection = OEFLocalConnection(
            identity.address, node, connection_id=LOCAL_CONNECTION_PUBLIC_ID)
        connections = [connection]
        resources = Resources(str(Path(CUR_PATH, "data", "dummy_aea")))

        msg = DefaultMessage(
            dialogue_reference=("", ""),
            message_id=1,
            target=0,
            performative=DefaultMessage.Performative.BYTES,
            content=b"hello",
        )
        msg.counterparty = identity.address
        message_bytes = DefaultSerializer().encode(msg)

        envelope = Envelope(
            to=identity.address,
            sender=identity.address,
            protocol_id=DefaultMessage.protocol_id,
            message=message_bytes,
        )

        agent = AEA(identity,
                    connections,
                    wallet,
                    ledger_apis,
                    resources,
                    is_programmatic=False)
        t = Thread(target=agent.start)
        try:
            t.start()
            time.sleep(1.0)
            agent.outbox.put(envelope)
            time.sleep(2.0)
            default_protocol_public_id = DefaultMessage.protocol_id
            dummy_skill_public_id = DUMMY_SKILL_PUBLIC_ID
            handler = agent.resources.handler_registry.fetch_by_protocol_and_skill(
                default_protocol_public_id, dummy_skill_public_id)
            assert handler is not None, "Handler is not set."
            assert (msg in handler.handled_messages
                    ), "The message is not inside the handled_messages."
        except Exception:
            raise
        finally:
            agent.stop()
            t.join()
Beispiel #21
0
    def setup_class(cls):
        """Set up the test."""
        cls.node = LocalNode()
        cls.node.start()

        cls.address_1 = "address_1"
        cls.connection = _make_local_connection(cls.address_1, cls.node,)
        cls.multiplexer = Multiplexer([cls.connection])

        cls.multiplexer.connect()
        cls.dialogues = OefSearchDialogues(cls.address_1)
Beispiel #22
0
def test_multiplexer():
    """Tests if the multiplexer is connected."""
    with LocalNode() as node:
        address_1 = "address_1"
        oef_local_connection = _make_local_connection(address_1, node)
        multiplexer = Multiplexer([oef_local_connection])
        multiplexer.connect()
        assert (
            multiplexer.is_connected
        ), "Mailbox cannot connect to the specific Connection(OEFLocalConnection)"
        multiplexer.disconnect()
Beispiel #23
0
async def test_receiving_when_not_connected_raise_exception():
    """Test that when we try to receive an envelope from a not connected connection we raise exception."""
    with pytest.raises(AEAConnectionError,
                       match="Connection not established yet."):
        with LocalNode() as node:
            address = "address"
            connection = OEFLocalConnection(address,
                                            node,
                                            connection_id=PublicId(
                                                "fetchai", "local", "0.1.0"))
            await connection.receive()
Beispiel #24
0
def test_connection():
    """Test that two OEF local connection can connect to a local node."""
    with LocalNode() as node:

        multiplexer1 = Multiplexer([_make_local_connection("multiplexer1", node)])
        multiplexer2 = Multiplexer([_make_local_connection("multiplexer2", node)])

        multiplexer1.connect()
        multiplexer2.connect()

        multiplexer1.disconnect()
        multiplexer2.disconnect()
Beispiel #25
0
def test_react():
    """Tests income messages."""
    with LocalNode() as node:
        agent_name = "MyAgent"
        private_key_path = os.path.join(CUR_PATH, "data",
                                        "fet_private_key.txt")
        builder = AEABuilder()
        builder.set_name(agent_name)
        builder.add_private_key(FETCHAI, private_key_path)
        builder.add_connection(
            Path(ROOT_DIR, "packages", "fetchai", "connections", "local"))
        builder.add_skill(Path(CUR_PATH, "data", "dummy_skill"))
        agent = builder.build(
            connection_ids=[PublicId.from_str("fetchai/local:0.1.0")])
        # This is a temporary workaround to feed the local node to the OEF Local connection
        # TODO remove it.
        list(agent._connections)[0]._local_node = node

        msg = DefaultMessage(
            dialogue_reference=("", ""),
            message_id=1,
            target=0,
            performative=DefaultMessage.Performative.BYTES,
            content=b"hello",
        )
        msg.counterparty = agent.identity.address
        message_bytes = DefaultSerializer().encode(msg)

        envelope = Envelope(
            to=agent.identity.address,
            sender=agent.identity.address,
            protocol_id=DefaultMessage.protocol_id,
            message=message_bytes,
        )

        t = Thread(target=agent.start)
        try:
            t.start()
            time.sleep(1.0)
            agent.outbox.put(envelope)
            time.sleep(2.0)
            default_protocol_public_id = DefaultMessage.protocol_id
            dummy_skill_public_id = DUMMY_SKILL_PUBLIC_ID
            handler = agent.resources.get_handler(default_protocol_public_id,
                                                  dummy_skill_public_id)
            assert handler is not None, "Handler is not set."
            assert (msg in handler.handled_messages
                    ), "The message is not inside the handled_messages."
        except Exception:
            raise
        finally:
            agent.stop()
            t.join()
Beispiel #26
0
def test_react():
    """Tests income messages."""
    with LocalNode() as node:
        agent_name = "MyAgent"
        private_key_path = os.path.join(CUR_PATH, "data",
                                        DEFAULT_PRIVATE_KEY_FILE)
        builder = AEABuilder()
        builder.set_name(agent_name)
        builder.add_private_key(DEFAULT_LEDGER, private_key_path)
        builder.add_protocol(
            Path(ROOT_DIR, "packages", "fetchai", "protocols", "oef_search"))
        builder.add_connection(
            Path(ROOT_DIR, "packages", "fetchai", "connections", "local"))
        local_connection_id = OEFLocalConnection.connection_id
        builder.set_default_connection(local_connection_id)
        builder.add_skill(Path(CUR_PATH, "data", "dummy_skill"))
        agent = builder.build(connection_ids=[local_connection_id])
        # This is a temporary workaround to feed the local node to the OEF Local connection
        # TODO remove it.
        local_connection = agent.resources.get_connection(local_connection_id)
        local_connection._local_node = node

        msg = DefaultMessage(
            dialogue_reference=("", ""),
            message_id=1,
            target=0,
            performative=DefaultMessage.Performative.BYTES,
            content=b"hello",
        )
        msg.to = agent.identity.address
        msg.sender = agent.identity.address
        envelope = Envelope(
            to=msg.to,
            sender=msg.sender,
            protocol_id=msg.protocol_id,
            message=msg,
        )

        with run_in_thread(agent.start, timeout=20, on_exit=agent.stop):
            wait_for_condition(lambda: agent.is_running, timeout=20)
            agent.outbox.put(envelope)
            default_protocol_public_id = DefaultMessage.protocol_id
            dummy_skill_public_id = DUMMY_SKILL_PUBLIC_ID
            handler = agent.resources.get_handler(default_protocol_public_id,
                                                  dummy_skill_public_id)

            assert handler is not None, "Handler is not set."

            wait_for_condition(
                lambda: len(handler.handled_messages) > 0,
                timeout=20,
                error_msg="The message is not inside the handled_messages.",
            )
Beispiel #27
0
    def setup(self):
        """Set up the test."""
        self.node = LocalNode()
        self.node.start()

        self.address_1 = "address"
        self.multiplexer = Multiplexer(
            [_make_local_connection(
                self.address_1,
                self.node,
            )])

        self.multiplexer.connect()

        # register a service.
        self.dialogues = OefSearchDialogues(self.address_1)
        self.data_model = DataModel(
            "foobar",
            attributes=[
                Attribute("foo", int, True),
                Attribute("bar", str, True)
            ],
        )
        service_description = Description({
            "foo": 1,
            "bar": "baz"
        },
                                          data_model=self.data_model)
        register_service_request, self.sending_dialogue = self.dialogues.create(
            counterparty=str(OEFLocalConnection.connection_id),
            performative=OefSearchMessage.Performative.REGISTER_SERVICE,
            service_description=service_description,
        )
        envelope = Envelope(
            to=register_service_request.to,
            sender=register_service_request.sender,
            message=register_service_request,
        )
        self.multiplexer.put(envelope)
Beispiel #28
0
def test_send_message_no_supported_protocol():
    """Test the case when we send an envelope with a specific connection that does not support the protocol."""
    with LocalNode() as node:
        identity_1 = Identity("", address="address_1")
        connection_1 = _make_local_connection(
            identity_1.address,
            node,
            restricted_to_protocols={DefaultMessage.protocol_id},
            excluded_protocols={FipaMessage.protocol_id},
        )
        multiplexer = Multiplexer(
            [connection_1],
            protocols=[DefaultMessage, FipaMessage, UnknownProtocolMock])

        multiplexer.connect()

        with mock.patch.object(multiplexer.logger,
                               "warning") as mock_logger_warning:
            envelope = Envelope(
                to=identity_1.address,
                sender=identity_1.address,
                protocol_specification_id=FipaMessage.
                protocol_specification_id,
                message=b"some bytes",
            )
            multiplexer.put(envelope)
            time.sleep(0.5)
            mock_logger_warning.assert_called_with(
                "Connection {} does not support protocol {}. It is explicitly excluded."
                .format(connection_1.connection_id, FipaMessage.protocol_id))

        with mock.patch.object(multiplexer.logger,
                               "warning") as mock_logger_warning:
            envelope = Envelope(
                to=identity_1.address,
                sender=identity_1.address,
                protocol_specification_id=UnknownProtocolMock.
                protocol_specification_id,
                message=b"some bytes",
            )
            multiplexer.put(envelope)
            time.sleep(0.5)
            mock_logger_warning.assert_called_with(
                "Connection {} does not support protocol {}. The connection is restricted to protocols in {}."
                .format(
                    connection_1.connection_id,
                    UnknownProtocolMock.protocol_id,
                    connection_1.restricted_to_protocols,
                ))

        multiplexer.disconnect()
Beispiel #29
0
async def test_receiving_returns_none_when_error_occurs():
    """Test that when we try to receive an envelope and an error occurs we return None."""
    with LocalNode() as node:
        address = "address"
        connection = _make_local_connection(address, node)
        await connection.connect()

        with unittest.mock.patch.object(
            connection._reader, "get", side_effect=Exception
        ):
            result = await connection.receive()
            assert result is None

        await connection.disconnect()
Beispiel #30
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.resources = Resources(os.path.join(CUR_PATH, "data", "dummy_aea"))
        cls.aea = AEA(
            cls.identity,
            cls.connections,
            cls.wallet,
            cls.ledger_apis,
            cls.resources,
            is_programmatic=False,
        )

        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
        envelope = Envelope(
            to=cls.agent_name,
            sender=cls.agent_name,
            protocol_id=DefaultMessage.protocol_id,
            message=DefaultSerializer().encode(cls.expected_message),
        )

        cls.t = Thread(target=cls.aea.start)
        cls.t.start()

        time.sleep(0.5)
        cls.aea.outbox.put(envelope)
        time.sleep(0.5)