示例#1
0
def test_connection():
    """Test that two mailbox can connect to the node."""
    node = LocalNode()
    mailbox1 = MailBox(OEFLocalConnection("mailbox1", node))
    mailbox2 = MailBox(OEFLocalConnection("mailbox2", node))

    mailbox1.connect()
    mailbox2.connect()

    mailbox1.disconnect()
    mailbox2.disconnect()
    def setup_class(cls):
        """Set up the test."""
        cls.node = LocalNode()
        cls.node.start()

        cls.public_key_1 = "public_key_1"
        cls.multiplexer1 = Multiplexer([OEFLocalConnection(cls.public_key_1, cls.node)])
        cls.public_key_2 = "public_key_2"
        cls.multiplexer2 = Multiplexer([OEFLocalConnection(cls.public_key_2, cls.node)])
        cls.multiplexer1.connect()
        cls.multiplexer2.connect()
示例#3
0
def test_connection():
    """Test that two OEF local connection can connect to a local node."""
    with LocalNode() as node:

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

        multiplexer1.connect()
        multiplexer2.connect()

        multiplexer1.disconnect()
        multiplexer2.disconnect()
示例#4
0
def test_run_agent():
    """Test that we can set up and then run the agent."""
    agent_name = "dummyagent"
    agent = DummyAgent(agent_name)
    mailbox = MailBox(OEFLocalConnection("mypbk", LocalNode()))
    agent.mailbox = mailbox
    assert agent.name == agent_name
    assert isinstance(agent.crypto, Crypto)
    assert agent.agent_state == AgentState.INITIATED,\
        "Agent state must be 'initiated'"

    agent.mailbox.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)

    try:
        assert agent.agent_state == AgentState.RUNNING,\
            "Agent state must be 'running'"
    finally:
        agent.stop()
        agent.mailbox.disconnect()
        agent_thread.join()
示例#5
0
    def setup_class(cls):
        """Set up the test."""
        cls.node = LocalNode()

        cls.public_key_1 = "mailbox1"
        cls.mailbox1 = MailBox(OEFLocalConnection(cls.public_key_1, cls.node))

        cls.mailbox1.connect()

        # register a service.
        request_id = 1
        service_id = ''
        cls.data_model = DataModel("foobar", attributes=[])
        service_description = Description({
            "foo": 1,
            "bar": "baz"
        },
                                          data_model=cls.data_model)
        register_service_request = OEFMessage(
            oef_type=OEFMessage.Type.REGISTER_SERVICE,
            id=request_id,
            service_description=service_description,
            service_id=service_id)
        msg_bytes = OEFSerializer().encode(register_service_request)
        envelope = Envelope(to=DEFAULT_OEF,
                            sender=cls.public_key_1,
                            protocol_id=OEFMessage.protocol_id,
                            message=msg_bytes)
        cls.mailbox1.send(envelope)
示例#6
0
def test_act():
    """Tests the act function of the AEA."""
    with LocalNode() as node:
        agent_name = "MyAgent"
        private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem")
        wallet = Wallet({'default': private_key_pem_path})
        ledger_apis = LedgerApis({})
        public_key = wallet.public_keys['default']
        connections = [OEFLocalConnection(public_key, node)]

        agent = AEA(
            agent_name,
            connections,
            wallet,
            ledger_apis,
            resources=Resources(str(Path(CUR_PATH, "data", "dummy_aea"))))
        t = Thread(target=agent.start)
        try:
            t.start()
            time.sleep(1.0)

            behaviour = agent.resources.behaviour_registry.fetch("dummy")
            assert behaviour[0].nb_act_called > 0, "Act() wasn't called"
        finally:
            agent.stop()
            t.join()
示例#7
0
def test_multiplexer_disconnect_one_raises_error_many_connections():
    """Test the case when the multiplexer raises an exception while attempting the disconnection of one connection."""
    with LocalNode() as node:
        tmpdir = Path(tempfile.mktemp())
        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_pbk", node)
        connection_2 = StubConnection(input_file_path, output_file_path)
        connection_3 = DummyConnection()
        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

        multiplexer.connect()

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

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

        # TODO is this what we want?
        assert not connection_1.connection_status.is_connected
        assert not connection_2.connection_status.is_connected
        assert connection_3.connection_status.is_connected

        shutil.rmtree(tmpdir)
示例#8
0
def test_react():
    """Tests income messages."""
    node = LocalNode()
    agent_name = "MyAgent"
    private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem")
    crypto = Crypto(private_key_pem_path=private_key_pem_path)
    public_key = crypto.public_key
    mailbox = MailBox(OEFLocalConnection(public_key, node))

    msg = DefaultMessage(type=DefaultMessage.Type.BYTES, content=b"hello")
    message_bytes = DefaultSerializer().encode(msg)

    envelope = Envelope(to="Agent1",
                        sender=public_key,
                        protocol_id="default",
                        message=message_bytes)

    agent = AEA(agent_name,
                mailbox,
                private_key_pem_path=private_key_pem_path,
                directory=str(Path(CUR_PATH, "data", "dummy_aea")))
    t = Thread(target=agent.start)
    try:
        t.start()
        agent.mailbox.inbox._queue.put(envelope)
        time.sleep(1)
        handler = agent.resources \
            .handler_registry.fetch_by_skill('default', "dummy")
        assert envelope in handler.handled_envelopes, \
            "The envelope is not inside the handled_envelopes."
    finally:
        agent.stop()
        t.join()
示例#9
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)))
示例#10
0
def test_run_agent():
    """Test that we can set up and then run the agent."""
    with LocalNode() as node:
        agent_name = "dummyagent"
        private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem")
        wallet = Wallet({'default': private_key_pem_path})
        agent = DummyAgent(agent_name, [OEFLocalConnection("mypbk", node)], wallet)
        assert agent.name == agent_name
        assert isinstance(agent.wallet, Wallet)
        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()
示例#11
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:
            public_key = "public_key"
            connection = OEFLocalConnection(public_key, node)
            await connection.receive()
示例#12
0
def test_multiplexer():
    """Tests if the multiplexer is connected."""
    with LocalNode() as node:
        public_key_1 = "public_key_1"
        multiplexer = Multiplexer([OEFLocalConnection(public_key_1, node)])
        multiplexer.connect()
        assert multiplexer.is_connected, "Mailbox cannot connect to the specific Connection(OEFLocalConnection)"
        multiplexer.disconnect()
示例#13
0
    def setup_class(cls):
        """Set up the test."""
        cls.node = LocalNode()

        cls.public_key_1 = "mailbox1"
        cls.mailbox1 = MailBox(OEFLocalConnection(cls.public_key_1, cls.node))

        cls.mailbox1.connect()
示例#14
0
def test_mailBox():
    """Tests if the mailbox is connected."""
    node = LocalNode()
    public_key_1 = "mailbox1"
    mailbox1 = MailBox(OEFLocalConnection(public_key_1, node))
    mailbox1.connect()
    assert mailbox1.is_connected,\
        "Mailbox cannot connect to the specific Connection(OEFLocalConnection)"
    mailbox1.disconnect()
示例#15
0
    def setup_class(cls):
        """Set up the test."""
        cls.node = LocalNode()
        cls.node.start()

        cls.public_key_1 = "multiplexer1"
        cls.public_key_2 = "multiplexer2"
        cls.multiplexer1 = Multiplexer([OEFLocalConnection(cls.public_key_1, cls.node)])
        cls.multiplexer2 = Multiplexer([OEFLocalConnection(cls.public_key_2, cls.node)])
        cls.multiplexer1.connect()
        cls.multiplexer2.connect()

        # register 'multiplexer1' as a service 'foobar'.
        request_id = 1
        service_id = ''
        cls.data_model_foobar = DataModel("foobar", attributes=[])
        service_description = Description({"foo": 1, "bar": "baz"}, data_model=cls.data_model_foobar)
        register_service_request = OEFMessage(oef_type=OEFMessage.Type.REGISTER_SERVICE, id=request_id,
                                              service_description=service_description, service_id=service_id)
        msg_bytes = OEFSerializer().encode(register_service_request)
        envelope = Envelope(to=DEFAULT_OEF, sender=cls.public_key_1, protocol_id=OEFMessage.protocol_id,
                            message=msg_bytes)
        cls.multiplexer1.put(envelope)

        time.sleep(1.0)

        # register 'multiplexer2' as a service 'barfoo'.
        cls.data_model_barfoo = DataModel("barfoo", attributes=[])
        service_description = Description({"foo": 1, "bar": "baz"}, data_model=cls.data_model_barfoo)
        register_service_request = OEFMessage(oef_type=OEFMessage.Type.REGISTER_SERVICE, id=request_id,
                                              service_description=service_description, service_id=service_id)
        msg_bytes = OEFSerializer().encode(register_service_request)
        envelope = Envelope(to=DEFAULT_OEF, sender=cls.public_key_2, protocol_id=OEFMessage.protocol_id,
                            message=msg_bytes)
        cls.multiplexer2.put(envelope)

        # unregister multiplexer1
        data_model = DataModel("foobar", attributes=[])
        service_description = Description({"foo": 1, "bar": "baz"}, data_model=data_model)
        msg = OEFMessage(oef_type=OEFMessage.Type.UNREGISTER_SERVICE, id=0, service_description=service_description,
                         service_id="Test_service")
        msg_bytes = OEFSerializer().encode(msg)
        envelope = Envelope(to=DEFAULT_OEF, sender=cls.public_key_1, protocol_id=OEFMessage.protocol_id, message=msg_bytes)
        cls.multiplexer1.put(envelope)
示例#16
0
def test_initialiseAeA():
    """Tests the initialisation of the AeA."""
    node = LocalNode()
    public_key_1 = "mailbox1"
    mailbox1 = MailBox(OEFLocalConnection(public_key_1, node))
    myAea = AEA("Agent0", mailbox1, directory=str(Path(CUR_PATH, "aea")))
    assert AEA("Agent0", mailbox1), "Agent is not inisialised"
    print(myAea.context)
    assert myAea.context == myAea._context, "Cannot access the Agent's Context"
    myAea.setup()
    assert myAea.resources is not None,\
        "Resources must not be None after setup"
示例#17
0
def test_handle():
    """Tests handle method of an agent."""
    node = LocalNode()
    agent_name = "MyAgent"
    private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem")
    crypto = Crypto(private_key_pem_path=private_key_pem_path)
    public_key = crypto.public_key
    mailbox = MailBox(OEFLocalConnection(public_key, node))

    msg = DefaultMessage(type=DefaultMessage.Type.BYTES, content=b"hello")
    message_bytes = DefaultSerializer().encode(msg)

    envelope = Envelope(to="Agent1",
                        sender=public_key,
                        protocol_id="unknown_protocol",
                        message=message_bytes)

    agent = AEA(agent_name,
                mailbox,
                private_key_pem_path=private_key_pem_path,
                directory=str(Path(CUR_PATH, "data", "dummy_aea")))
    t = Thread(target=agent.start)
    try:
        t.start()
        agent.mailbox.inbox._queue.put(envelope)
        env = agent.mailbox.outbox._queue.get(block=True, timeout=5.0)
        assert env.protocol_id == "default", \
            "The envelope is not the expected protocol (Unsupported protocol)"

        #   DECODING ERROR
        msg = "hello".encode("utf-8")
        envelope = Envelope(to=public_key,
                            sender=public_key,
                            protocol_id='default',
                            message=msg)
        agent.mailbox.inbox._queue.put(envelope)
        #   UNSUPPORTED SKILL
        msg = FIPASerializer().encode(
            FIPAMessage(performative=FIPAMessage.Performative.ACCEPT,
                        message_id=0,
                        dialogue_id=0,
                        destination=public_key,
                        target=1))
        envelope = Envelope(to=public_key,
                            sender=public_key,
                            protocol_id="fipa",
                            message=msg)
        agent.mailbox.inbox._queue.put(envelope)
    finally:
        agent.stop()
        t.join()
示例#18
0
def test_multiple_connection():
    """Test that we can send a message with two different connections."""
    with LocalNode() as node:
        public_key_1 = "public_key_1"
        public_key_2 = "public_key_2"
        connection_1_id = "local_1"
        connection_2_id = "local_2"

        connection_1 = OEFLocalConnection(public_key_1, node, connection_id=connection_1_id)
        connection_2 = OEFLocalConnection(public_key_2, node, 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(type=DefaultMessage.Type.BYTES, content=b"hello")
        envelope_from_1_to_2 = Envelope(to=public_key_2, sender=public_key_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=public_key_1, sender=public_key_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()
示例#19
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:
        public_key = "public_key"
        connection = OEFLocalConnection(public_key, 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()
示例#20
0
def test_initialise_AEA():
    """Tests the initialisation of the AEA."""
    node = LocalNode()
    public_key_1 = "public_key"
    connections1 = [OEFLocalConnection(public_key_1, node)]
    private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem")
    wallet = Wallet({'default': private_key_pem_path})
    ledger_apis = LedgerApis({})
    my_AEA = AEA("Agent0", 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"
示例#21
0
async def test_connection_twice_return_none():
    """Test that connecting twice works."""
    with LocalNode() as node:
        public_key = "public_key"
        connection = OEFLocalConnection(public_key, node)
        await connection.connect()
        await node.connect(public_key, connection._reader)
        message = DefaultMessage(type=DefaultMessage.Type.BYTES,
                                 content=b"hello")
        message_bytes = DefaultSerializer().encode(message)
        expected_envelope = Envelope(to=public_key,
                                     sender=public_key,
                                     protocol_id="default",
                                     message=message_bytes)
        await connection.send(expected_envelope)
        actual_envelope = await connection.receive()

        assert expected_envelope == actual_envelope

        await connection.disconnect()
示例#22
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:
        public_key_1 = "public_key_1"
        connection_1_id = "local_1"
        connection_1 = OEFLocalConnection(public_key_1, node, connection_id=connection_1_id,
                                          restricted_to_protocols={"my_private_protocol"})
        multiplexer = Multiplexer([connection_1])

        multiplexer.connect()

        with mock.patch.object(aea.mail.base.logger, "warning") as mock_logger_warning:
            protocol_id = "this_is_a_non_existing_protocol_id"
            envelope = Envelope(to=public_key_1, sender=public_key_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()
示例#23
0
def test_react():
    """Tests income messages."""
    with LocalNode() as node:
        agent_name = "MyAgent"
        private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem")
        wallet = Wallet({'default': private_key_pem_path})
        ledger_apis = LedgerApis({})
        public_key = wallet.public_keys['default']
        connection = OEFLocalConnection(public_key, node)
        connections = [connection]

        msg = DefaultMessage(type=DefaultMessage.Type.BYTES, content=b"hello")
        message_bytes = DefaultSerializer().encode(msg)

        envelope = Envelope(
            to=public_key,
            sender=public_key,
            protocol_id="default",
            message=message_bytes)

        agent = AEA(
            agent_name,
            connections,
            wallet,
            ledger_apis,
            resources=Resources(str(Path(CUR_PATH, "data", "dummy_aea"))))
        t = Thread(target=agent.start)
        try:
            t.start()
            time.sleep(0.1)
            agent.outbox.put(envelope)
            time.sleep(0.5)
            handler = agent.resources.handler_registry.fetch_by_skill('default', "dummy")
            assert msg in handler.handled_messages, "The message is not inside the handled_messages."
        except Exception:
            raise
        finally:
            agent.stop()
            t.join()
示例#24
0
def test_act():
    """Tests the act function of the AeA."""
    node = LocalNode()
    agent_name = "MyAgent"
    private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem")
    crypto = Crypto(private_key_pem_path=private_key_pem_path)
    public_key = crypto.public_key
    mailbox = MailBox(OEFLocalConnection(public_key, node))

    agent = AEA(agent_name,
                mailbox,
                private_key_pem_path=private_key_pem_path,
                directory=str(Path(CUR_PATH, "data", "dummy_aea")))
    t = Thread(target=agent.start)
    try:
        t.start()
        time.sleep(1)

        behaviour = agent.resources.behaviour_registry.fetch("dummy")
        assert behaviour[0].nb_act_called > 0, "Act() wasn't called"
    finally:
        agent.stop()
        t.join()
示例#25
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.resources = Resources(os.path.join(CUR_PATH, "data", "dummy_aea"))
        cls.aea = AEA(cls.agent_name, cls.connections, cls.wallet, cls.ledger_apis, cls.resources)

        cls.expected_message = DefaultMessage(type=DefaultMessage.Type.BYTES, content=b"hello")
        envelope = Envelope(to=cls.agent_name, sender=cls.agent_name, protocol_id="default", 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)
示例#26
0
def test_communication():
    """Test that two multiplexer can communicate through the node."""
    with LocalNode() as node:

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

        multiplexer1.connect()
        multiplexer2.connect()

        msg = DefaultMessage(type=DefaultMessage.Type.BYTES, content=b"hello")
        msg_bytes = DefaultSerializer().encode(msg)
        envelope = Envelope(to="multiplexer2",
                            sender="multiplexer1",
                            protocol_id=DefaultMessage.protocol_id,
                            message=msg_bytes)
        multiplexer1.put(envelope)

        msg = FIPAMessage((str(0), ''),
                          0,
                          0,
                          FIPAMessage.Performative.CFP,
                          query=None)
        msg_bytes = FIPASerializer().encode(msg)
        envelope = Envelope(to="multiplexer2",
                            sender="multiplexer1",
                            protocol_id=FIPAMessage.protocol_id,
                            message=msg_bytes)
        multiplexer1.put(envelope)

        msg = FIPAMessage((str(0), str(1)),
                          0,
                          0,
                          FIPAMessage.Performative.PROPOSE,
                          proposal=[])
        msg_bytes = FIPASerializer().encode(msg)
        envelope = Envelope(to="multiplexer2",
                            sender="multiplexer1",
                            protocol_id=FIPAMessage.protocol_id,
                            message=msg_bytes)
        multiplexer1.put(envelope)

        msg = FIPAMessage((str(0), str(1)), 0, 0,
                          FIPAMessage.Performative.ACCEPT)
        msg_bytes = FIPASerializer().encode(msg)
        envelope = Envelope(to="multiplexer2",
                            sender="multiplexer1",
                            protocol_id=FIPAMessage.protocol_id,
                            message=msg_bytes)
        multiplexer1.put(envelope)

        msg = FIPAMessage((str(0), str(1)), 0, 0,
                          FIPAMessage.Performative.DECLINE)
        msg_bytes = FIPASerializer().encode(msg)
        envelope = Envelope(to="multiplexer2",
                            sender="multiplexer1",
                            protocol_id=FIPAMessage.protocol_id,
                            message=msg_bytes)
        multiplexer1.put(envelope)

        envelope = multiplexer2.get(block=True, timeout=1.0)
        msg = DefaultSerializer().decode(envelope.message)
        assert envelope.protocol_id == "default"
        assert msg.get("content") == b"hello"
        envelope = multiplexer2.get(block=True, timeout=1.0)
        msg = FIPASerializer().decode(envelope.message)
        assert envelope.protocol_id == "fipa"
        assert msg.get("performative") == FIPAMessage.Performative.CFP
        envelope = multiplexer2.get(block=True, timeout=1.0)
        msg = FIPASerializer().decode(envelope.message)
        assert envelope.protocol_id == "fipa"
        assert msg.get("performative") == FIPAMessage.Performative.PROPOSE
        envelope = multiplexer2.get(block=True, timeout=1.0)
        msg = FIPASerializer().decode(envelope.message)
        assert envelope.protocol_id == "fipa"
        assert msg.get("performative") == FIPAMessage.Performative.ACCEPT
        envelope = multiplexer2.get(block=True, timeout=1.0)
        msg = FIPASerializer().decode(envelope.message)
        assert envelope.protocol_id == "fipa"
        assert msg.get("performative") == FIPAMessage.Performative.DECLINE
        multiplexer1.disconnect()
        multiplexer2.disconnect()
示例#27
0
def test_communication():
    """Test that two mailbox can communicate through the node."""
    node = LocalNode()
    mailbox1 = MailBox(OEFLocalConnection("mailbox1", node))
    mailbox2 = MailBox(OEFLocalConnection("mailbox2", node))

    mailbox1.connect()
    mailbox2.connect()

    msg = DefaultMessage(type=DefaultMessage.Type.BYTES, content=b"hello")
    msg_bytes = DefaultSerializer().encode(msg)
    envelope = Envelope(to="mailbox2",
                        sender="mailbox1",
                        protocol_id=DefaultMessage.protocol_id,
                        message=msg_bytes)
    mailbox1.send(envelope)

    msg = FIPAMessage(0, 0, 0, FIPAMessage.Performative.CFP, query=None)
    msg_bytes = FIPASerializer().encode(msg)
    envelope = Envelope(to="mailbox2",
                        sender="mailbox1",
                        protocol_id=FIPAMessage.protocol_id,
                        message=msg_bytes)
    mailbox1.send(envelope)

    msg = FIPAMessage(0, 0, 0, FIPAMessage.Performative.PROPOSE, proposal=[])
    msg_bytes = FIPASerializer().encode(msg)
    envelope = Envelope(to="mailbox2",
                        sender="mailbox1",
                        protocol_id=FIPAMessage.protocol_id,
                        message=msg_bytes)
    mailbox1.send(envelope)

    msg = FIPAMessage(0, 0, 0, FIPAMessage.Performative.ACCEPT)
    msg_bytes = FIPASerializer().encode(msg)
    envelope = Envelope(to="mailbox2",
                        sender="mailbox1",
                        protocol_id=FIPAMessage.protocol_id,
                        message=msg_bytes)
    mailbox1.send(envelope)

    msg = FIPAMessage(0, 0, 0, FIPAMessage.Performative.DECLINE)
    msg_bytes = FIPASerializer().encode(msg)
    envelope = Envelope(to="mailbox2",
                        sender="mailbox1",
                        protocol_id=FIPAMessage.protocol_id,
                        message=msg_bytes)
    mailbox1.send(envelope)

    time.sleep(5.0)

    envelope = mailbox2.inbox.get(block=True, timeout=1.0)
    msg = DefaultSerializer().decode(envelope.message)
    assert envelope.protocol_id == "default"
    assert msg.get("content") == b"hello"
    envelope = mailbox2.inbox.get(block=True, timeout=1.0)
    msg = FIPASerializer().decode(envelope.message)
    assert envelope.protocol_id == "fipa"
    assert msg.get("performative") == FIPAMessage.Performative.CFP
    envelope = mailbox2.inbox.get(block=True, timeout=1.0)
    msg = FIPASerializer().decode(envelope.message)
    assert envelope.protocol_id == "fipa"
    assert msg.get("performative") == FIPAMessage.Performative.PROPOSE
    envelope = mailbox2.inbox.get(block=True, timeout=1.0)
    msg = FIPASerializer().decode(envelope.message)
    assert envelope.protocol_id == "fipa"
    assert msg.get("performative") == FIPAMessage.Performative.ACCEPT
    envelope = mailbox2.inbox.get(block=True, timeout=1.0)
    msg = FIPASerializer().decode(envelope.message)
    assert envelope.protocol_id == "fipa"
    assert msg.get("performative") == FIPAMessage.Performative.DECLINE

    mailbox1.disconnect()
    mailbox2.disconnect()
示例#28
0
 def test_from_config(self):
     """Test the configuration loading."""
     con = OEFLocalConnection.from_config(public_key="pk", connection_configuration=ConnectionConfig())
     assert not con.connection_status.is_connected, "We are connected..."
示例#29
0
async def test_handle():
    """Tests handle method of an agent."""
    with LocalNode() as node:
        agent_name = "MyAgent"
        private_key_pem_path = os.path.join(CUR_PATH, "data", "priv.pem")
        wallet = Wallet({'default': private_key_pem_path})
        ledger_apis = LedgerApis({})
        public_key = wallet.public_keys['default']
        connection = OEFLocalConnection(public_key, node)
        connections = [connection]

        msg = DefaultMessage(type=DefaultMessage.Type.BYTES, content=b"hello")
        message_bytes = DefaultSerializer().encode(msg)

        envelope = Envelope(
            to=public_key,
            sender=public_key,
            protocol_id="unknown_protocol",
            message=message_bytes)

        agent = AEA(
            agent_name,
            connections,
            wallet,
            ledger_apis,
            resources=Resources(str(Path(CUR_PATH, "data", "dummy_aea"))))
        t = Thread(target=agent.start)
        try:
            t.start()
            time.sleep(1.0)
            dummy_skill = agent.resources.get_skill("dummy")
            dummy_handler = dummy_skill.handlers[0]

            expected_envelope = envelope
            agent.outbox.put(expected_envelope)
            time.sleep(1.0)
            assert len(dummy_handler.handled_messages) == 1

            #   DECODING ERROR
            msg = "hello".encode("utf-8")
            envelope = Envelope(
                to=public_key,
                sender=public_key,
                protocol_id='default',
                message=msg)
            expected_envelope = envelope
            agent.outbox.put(expected_envelope)
            time.sleep(1.0)
            assert len(dummy_handler.handled_messages) == 2

            #   UNSUPPORTED SKILL
            msg = FIPASerializer().encode(
                FIPAMessage(performative=FIPAMessage.Performative.ACCEPT,
                            message_id=0,
                            dialogue_reference=(str(0), ''),
                            target=1))
            envelope = Envelope(
                to=public_key,
                sender=public_key,
                protocol_id="fipa",
                message=msg)
            expected_envelope = envelope
            agent.outbox.put(expected_envelope)
            time.sleep(1.0)
            assert len(dummy_handler.handled_messages) == 3

        finally:
            agent.stop()
            t.join()