示例#1
0
def test_outbox_put():
    """Tests that an envelope is putted into the queue."""
    agent_address = "Agent0"
    receiver_address = "Agent1"
    msg = DefaultMessage(
        dialogue_reference=("", ""),
        message_id=1,
        target=0,
        performative=DefaultMessage.Performative.BYTES,
        content=b"hello",
    )
    msg.counterparty = receiver_address
    dummy_connection = _make_dummy_connection()
    multiplexer = Multiplexer([dummy_connection])
    outbox = OutBox(multiplexer, agent_address)
    inbox = InBox(multiplexer)
    multiplexer.connect()
    envelope = Envelope(
        to=receiver_address,
        sender=agent_address,
        protocol_id=DefaultMessage.protocol_id,
        message=msg,
    )
    outbox.put(envelope)
    time.sleep(0.5)
    assert not inbox.empty(), "Inbox must not be empty after putting an envelope"
    multiplexer.disconnect()
示例#2
0
def _process_envelopes(
    agent_name: str,
    identity_stub: Identity,
    inbox: InBox,
    outbox: OutBox,
    dialogues: DefaultDialogues,
) -> None:
    """
    Process envelopes.

    :param agent_name: name of an agent.
    :param identity_stub: stub identity.
    :param inbox: an inbox object.
    :param outbox: an outbox object.
    :param dialogues: the dialogues object.

    :return: None.
    """
    envelope = _try_construct_envelope(agent_name, identity_stub.name,
                                       dialogues)
    if envelope is None:
        if not inbox.empty():
            envelope = inbox.get_nowait()
            assert envelope is not None, "Could not recover envelope from inbox."
            click.echo(_construct_message("received", envelope))
        else:
            click.echo("Received no new envelope!")
    else:
        outbox.put(envelope)
        click.echo(_construct_message("sending", envelope))
示例#3
0
def test_outbox_put():
    """Tests that an envelope is putted into the queue."""
    agent_address = "Agent0"
    receiver_address = "Agent1"
    msg = DefaultMessage(
        dialogue_reference=("", ""),
        message_id=1,
        target=0,
        performative=DefaultMessage.Performative.BYTES,
        content=b"hello",
    )
    msg.to = receiver_address
    msg.sender = agent_address
    dummy_connection = _make_dummy_connection()
    multiplexer = Multiplexer([dummy_connection])
    outbox = OutBox(multiplexer)
    inbox = InBox(multiplexer)
    multiplexer.connect()
    envelope = Envelope(
        to=receiver_address,
        sender=agent_address,
        message=msg,
    )
    outbox.put(envelope)
    wait_for_condition(lambda: inbox.empty(), 15,
                       "Inbox must not be empty after putting an envelope")
    multiplexer.disconnect()
示例#4
0
def _check_for_incoming_envelope(inbox: InBox, message_class: Type[Message]):
    if not inbox.empty():
        envelope = inbox.get_nowait()
        if envelope is None:
            raise ValueError("Could not recover envelope from inbox.")
        click.echo(_construct_message("received", envelope, message_class))
    else:
        click.echo("Received no new envelope!")
示例#5
0
def test_inbox_get_raises_exception_when_empty():
    """Test that getting an envelope from an empty inbox raises an exception."""
    multiplexer = Multiplexer([_make_dummy_connection()])
    inbox = InBox(multiplexer)

    with pytest.raises(aea.mail.base.Empty):
        with unittest.mock.patch.object(multiplexer, "get", return_value=None):
            inbox.get()
示例#6
0
    def test_filtered_search_result(self):
        """Test that the search result contains only the entries matching the query."""
        request_id = 1
        query = Query(constraints=[], model=self.data_model_barfoo)

        # build and send the request
        search_services_request = OefSearchMessage(
            performative=OefSearchMessage.Performative.SEARCH_SERVICES,
            dialogue_reference=(str(request_id), ""),
            query=query,
        )
        envelope = Envelope(
            to=DEFAULT_OEF,
            sender=self.address_1,
            protocol_id=OefSearchMessage.protocol_id,
            message=search_services_request,
        )
        self.multiplexer1.put(envelope)

        # check the result
        response_envelope = InBox(self.multiplexer1).get(block=True,
                                                         timeout=5.0)
        assert response_envelope.protocol_id == OefSearchMessage.protocol_id
        assert response_envelope.to == self.address_1
        assert response_envelope.sender == DEFAULT_OEF
        search_result = response_envelope.message
        assert search_result.performative == OefSearchMessage.Performative.SEARCH_RESULT
        assert search_result.agents == (self.address_2, )
示例#7
0
def _run_interaction_channel():
    # load agent configuration file
    loader = ConfigLoader.from_configuration_type(PackageType.AGENT)
    agent_configuration = loader.load(Path(DEFAULT_AEA_CONFIG_FILE).open())
    agent_name = agent_configuration.name
    # load stub connection
    configuration = ConnectionConfig(
        input_file=DEFAULT_OUTPUT_FILE_NAME,
        output_file=DEFAULT_INPUT_FILE_NAME,
        connection_id=StubConnection.connection_id,
    )
    identity_stub = Identity(agent_name + "_interact", "interact")
    stub_connection = StubConnection(configuration=configuration,
                                     identity=identity_stub)
    multiplexer = Multiplexer([stub_connection])
    inbox = InBox(multiplexer)
    outbox = OutBox(multiplexer, default_address=identity_stub.address)
    dialogues = DefaultDialogues(identity_stub.name)

    try:
        multiplexer.connect()
        while True:  # pragma: no cover
            _process_envelopes(agent_name, identity_stub, inbox, outbox,
                               dialogues)

    except KeyboardInterrupt:
        click.echo("Interaction interrupted!")
    except BaseException as e:  # pylint: disable=broad-except # pragma: no cover
        click.echo(e)
    finally:
        multiplexer.disconnect()
示例#8
0
    def test_filtered_search_result(self):
        """Test that the search result contains only the entries matching the query."""
        query = Query(constraints=[], model=self.data_model_barfoo)

        # build and send the request
        search_services_request = OefSearchMessage(
            performative=OefSearchMessage.Performative.SEARCH_SERVICES,
            dialogue_reference=self.dialogues1.new_self_initiated_dialogue_reference(),
            query=query,
        )
        search_services_request.counterparty = str(OEFLocalConnection.connection_id)
        sending_dialogue = cast(
            Optional[OefSearchDialogue], self.dialogues1.update(search_services_request)
        )
        assert sending_dialogue is not None
        envelope = Envelope(
            to=search_services_request.counterparty,
            sender=search_services_request.sender,
            protocol_id=search_services_request.protocol_id,
            message=search_services_request,
        )
        self.multiplexer1.put(envelope)

        # check the result
        response_envelope = InBox(self.multiplexer1).get(block=True, timeout=5.0)
        search_result_orig = cast(OefSearchMessage, response_envelope.message)
        search_result = copy.copy(search_result_orig)
        search_result.is_incoming = True
        search_result.counterparty = search_result_orig.sender
        response_dialogue = self.dialogues1.update(search_result)
        assert response_dialogue == sending_dialogue
        assert search_result.performative == OefSearchMessage.Performative.SEARCH_RESULT
        assert search_result.agents == (self.address_2,), self.node.services
示例#9
0
    def __init__(
        self,
        identity: Identity,
        connections: List[Connection],
        loop: Optional[AbstractEventLoop] = None,
        period: float = 1.0,
        loop_mode: Optional[str] = None,
        runtime_mode: Optional[str] = None,
        logger: Logger = _default_logger,
    ) -> None:
        """
        Instantiate the agent.

        :param identity: the identity of the agent.
        :param connections: the list of connections of the agent.
        :param loop: the event loop to run the connections.
        :param period: period to call agent's act
        :param loop_mode: loop_mode to choose agent run loop.
        :param runtime_mode: runtime mode to up agent.

        :return: None
        """
        WithLogger.__init__(self, logger=logger)
        self._connections = connections
        self._identity = identity
        self._period = period
        self._tick = 0
        self._runtime_mode = runtime_mode or self.DEFAULT_RUNTIME
        runtime_cls = self._get_runtime_class()
        self._runtime: BaseRuntime = runtime_cls(agent=self,
                                                 loop_mode=loop_mode,
                                                 loop=loop)

        self._inbox = InBox(self.runtime.multiplexer)
        self._outbox = OutBox(self.runtime.multiplexer)
示例#10
0
def _run_interaction_channel():
    loader = ConfigLoader.from_configuration_type(PackageType.AGENT)
    agent_configuration = loader.load(Path(DEFAULT_AEA_CONFIG_FILE).open())
    agent_name = agent_configuration.name

    identity_stub = Identity(agent_name + "_interact", "interact")
    _load_packages(identity_stub)

    # load agent configuration file
    from packages.fetchai.connections.stub.connection import (  # noqa: F811 # pylint: disable=import-outside-toplevel
        DEFAULT_INPUT_FILE_NAME,
        DEFAULT_OUTPUT_FILE_NAME,
        StubConnection,
    )
    from packages.fetchai.protocols.default.dialogues import (  # noqa: F811 # pylint: disable=import-outside-toplevel
        DefaultDialogue,
        DefaultDialogues,
    )
    from packages.fetchai.protocols.default.message import (  # noqa: F811 # pylint: disable=import-outside-toplevel
        DefaultMessage,
    )

    # load stub connection
    configuration = ConnectionConfig(
        input_file=DEFAULT_OUTPUT_FILE_NAME,
        output_file=DEFAULT_INPUT_FILE_NAME,
        connection_id=StubConnection.connection_id,
    )

    stub_connection = StubConnection(
        configuration=configuration, identity=identity_stub
    )
    multiplexer = Multiplexer([stub_connection])
    inbox = InBox(multiplexer)
    outbox = OutBox(multiplexer)

    def role_from_first_message(  # pylint: disable=unused-argument
        message: Message, receiver_address: Address
    ) -> BaseDialogue.Role:
        """Infer the role of the agent from an incoming/outgoing first message

        :param message: an incoming/outgoing first message
        :param receiver_address: the address of the receiving agent
        :return: The role of the agent
        """
        return DefaultDialogue.Role.AGENT

    dialogues = DefaultDialogues(identity_stub.name, role_from_first_message)

    try:
        multiplexer.connect()
        while True:  # pragma: no cover
            _process_envelopes(agent_name, inbox, outbox, dialogues, DefaultMessage)

    except KeyboardInterrupt:
        click.echo("Interaction interrupted!")
    except BaseException as e:  # pylint: disable=broad-except # pragma: no cover
        click.echo(e)
    finally:
        multiplexer.disconnect()
示例#11
0
def test_inbox_nowait():
    """Tests the inbox without waiting."""
    agent_address = "Agent0"
    receiver_address = "Agent1"
    msg = Message(content="hello")
    msg.counterparty = receiver_address
    multiplexer = Multiplexer([_make_dummy_connection()])
    envelope = Envelope(
        to=receiver_address,
        sender=agent_address,
        protocol_id=UNKNOWN_PROTOCOL_PUBLIC_ID,
        message=msg,
    )
    multiplexer.in_queue.put(envelope)
    inbox = InBox(multiplexer)
    assert (inbox.get_nowait() == envelope
            ), "Check for a message on the in queue and wait for no time."
示例#12
0
def test_inbox_nowait():
    """Tests the inbox without waiting."""
    agent_address = "Agent0"
    receiver_address = "Agent1"
    msg = DefaultMessage(performative=DefaultMessage.Performative.BYTES,
                         content="hello")
    msg.to = receiver_address
    multiplexer = Multiplexer([_make_dummy_connection()])
    envelope = Envelope(
        to=receiver_address,
        sender=agent_address,
        message=msg,
    )
    multiplexer.in_queue.put(envelope)
    inbox = InBox(multiplexer)
    assert (inbox.get_nowait() == envelope
            ), "Check for a message on the in queue and wait for no time."
示例#13
0
def test_inbox_get():
    """Tests for a envelope on the in queue."""
    agent_address = "Agent0"
    receiver_address = "Agent1"
    msg = DefaultMessage(performative=DefaultMessage.Performative.BYTES,
                         content="hello")
    msg.to = receiver_address
    multiplexer = Multiplexer([_make_dummy_connection()])
    envelope = Envelope(
        to=receiver_address,
        sender=agent_address,
        message=msg,
    )
    multiplexer.in_queue.put(envelope)
    inbox = InBox(multiplexer)

    assert (
        inbox.get() == envelope
    ), "Checks if the returned envelope is the same with the queued envelope."
示例#14
0
def test_inbox_get():
    """Tests for a envelope on the in queue."""
    agent_address = "Agent0"
    receiver_address = "Agent1"
    msg = Message(content="hello")
    msg.counterparty = receiver_address
    multiplexer = Multiplexer([_make_dummy_connection()])
    envelope = Envelope(
        to=receiver_address,
        sender=agent_address,
        protocol_id=UNKNOWN_PROTOCOL_PUBLIC_ID,
        message=msg,
    )
    multiplexer.in_queue.put(envelope)
    inbox = InBox(multiplexer)

    assert (
        inbox.get() == envelope
    ), "Checks if the returned envelope is the same with the queued envelope."
示例#15
0
async def test_threaded_mode():
    """Test InBox OutBox objects in threaded mode."""
    connection_1 = _make_dummy_connection()
    connections = [connection_1]
    multiplexer = AsyncMultiplexer(connections, threaded=True)
    msg = DefaultMessage(
        performative=DefaultMessage.Performative.BYTES,
        content=b"",
    )
    msg.to = "to"
    msg.sender = "sender"
    context = EnvelopeContext(connection_id=connection_1.connection_id)
    envelope = Envelope(
        to="to",
        sender="sender",
        message=msg,
        context=context,
    )
    try:
        await multiplexer.connect()
        await asyncio.sleep(0.5)
        inbox = InBox(multiplexer)
        outbox = OutBox(multiplexer)

        assert inbox.empty()
        assert outbox.empty()

        outbox.put(envelope)
        received = await inbox.async_get()
        assert received == envelope

        assert inbox.empty()
        assert outbox.empty()

        outbox.put_message(msg, context=context)
        await inbox.async_wait()
        received = inbox.get_nowait()
        assert received == envelope

    finally:
        await multiplexer.disconnect()
示例#16
0
def test_outbox_put_message():
    """Tests that an envelope is created from the message is in the queue."""
    agent_address = "Agent0"
    receiver_address = "Agent1"
    msg = DefaultMessage(
        dialogue_reference=("", ""),
        message_id=1,
        target=0,
        performative=DefaultMessage.Performative.BYTES,
        content=b"hello",
    )
    msg.counterparty = receiver_address
    dummy_connection = _make_dummy_connection()
    multiplexer = Multiplexer([dummy_connection])
    outbox = OutBox(multiplexer, agent_address)
    inbox = InBox(multiplexer)
    multiplexer.connect()
    outbox.put_message(msg)
    time.sleep(0.5)
    assert not inbox.empty(), "Inbox will not be empty after putting a message."
    multiplexer.disconnect()
示例#17
0
async def test_default_route_applied(caplog):
    """Test default route is selected automatically."""
    logger = logging.getLogger("aea.multiplexer")
    with caplog.at_level(logging.DEBUG, logger="aea.multiplexer"):
        connection_1 = _make_dummy_connection()
        connections = [connection_1]
        multiplexer = AsyncMultiplexer(connections, loop=asyncio.get_event_loop())
        multiplexer.logger = logger
        envelope = Envelope(
            to="",
            sender="",
            protocol_id=DefaultMessage.protocol_id,
            message=b"",
            context=EnvelopeContext(),
        )
        multiplexer.default_routing = {
            DefaultMessage.protocol_id: connection_1.connection_id
        }
        try:
            await multiplexer.connect()
            inbox = InBox(multiplexer)
            outbox = InBox(multiplexer)

            assert inbox.empty()
            assert outbox.empty()

            multiplexer.put(envelope)
            await outbox.async_get()
        finally:
            await multiplexer.disconnect()

            assert "Using default routing:" in caplog.text
示例#18
0
async def test_inbox_outbox():
    """Test InBox OutBox objects."""
    connection_1 = _make_dummy_connection()
    connections = [connection_1]
    multiplexer = AsyncMultiplexer(connections, loop=asyncio.get_event_loop())
    msg = DefaultMessage(performative=DefaultMessage.Performative.BYTES, content=b"",)
    msg.counterparty = "to"
    msg.sender = "sender"
    context = EnvelopeContext(connection_id=connection_1.connection_id)
    envelope = Envelope(
        to="to",
        sender="sender",
        protocol_id=msg.protocol_id,
        message=msg,
        context=context,
    )
    try:
        await multiplexer.connect()
        inbox = InBox(multiplexer)
        outbox = OutBox(multiplexer, "default_address")

        assert inbox.empty()
        assert outbox.empty()

        outbox.put(envelope)
        received = await inbox.async_get()
        assert received == envelope

        assert inbox.empty()
        assert outbox.empty()

        outbox.put_message(msg, context=context)
        await inbox.async_wait()
        received = inbox.get_nowait()
        assert received == envelope

    finally:
        await multiplexer.disconnect()
示例#19
0
 def _set_runtime_and_mail_boxes(
     self,
     runtime_class: Type[BaseRuntime],
     multiplexer_options: Dict,
     loop_mode: Optional[str] = None,
     loop: Optional[AbstractEventLoop] = None,
 ) -> None:
     """Set the runtime and inbox and outbox."""
     self._runtime = runtime_class(
         agent=self,
         loop_mode=loop_mode,
         loop=loop,
         multiplexer_options=multiplexer_options,
     )
     self._inbox = InBox(self.runtime.multiplexer)
     self._outbox = OutBox(self.runtime.multiplexer)
示例#20
0
    def __init__(
        self,
        identity: Identity,
        connections: List[Connection],
        loop: Optional[AbstractEventLoop] = None,
        timeout: float = 1.0,
        loop_mode: Optional[str] = None,
        runtime_mode: Optional[str] = None,
    ) -> None:
        """
        Instantiate the agent.

        :param identity: the identity of the agent.
        :param connections: the list of connections of the agent.
        :param loop: the event loop to run the connections.
        :param timeout: the time in (fractions of) seconds to time out an agent between act and react
        :param loop_mode: loop_mode to choose agent run loop.
        :param runtime_mode: runtime mode to up agent.

        :return: None
        """
        self._identity = identity
        self._connections = connections

        self._multiplexer = Multiplexer(self._connections, loop=loop)
        self._inbox = InBox(self._multiplexer)
        self._outbox = OutBox(self._multiplexer, identity.address)
        self._liveness = Liveness()
        self._timeout = timeout

        self._tick = 0

        self._loop_mode = loop_mode or self.DEFAULT_RUN_LOOP
        loop_cls = self._get_main_loop_class()
        self._main_loop: BaseAgentLoop = loop_cls(self)

        self._runtime_mode = runtime_mode or self.DEFAULT_RUNTIME
        runtime_cls = self._get_runtime_class()
        self._runtime: BaseRuntime = runtime_cls(agent=self, loop=loop)
示例#21
0
    def test_filtered_search_result(self):
        """Test that the search result contains only the entries matching the query."""
        # build and send the request
        search_services_request, sending_dialogue = self.dialogues1.create(
            counterparty=str(OEFLocalConnection.connection_id),
            performative=OefSearchMessage.Performative.SEARCH_SERVICES,
            query=Query(constraints=[], model=self.data_model_barfoo),
        )
        envelope = Envelope(
            to=search_services_request.to,
            sender=search_services_request.sender,
            message=search_services_request,
        )
        self.multiplexer1.put(envelope)

        # check the result
        response_envelope = InBox(self.multiplexer1).get(block=True,
                                                         timeout=5.0)
        search_result = cast(OefSearchMessage, response_envelope.message)
        response_dialogue = self.dialogues1.update(search_result)
        assert response_dialogue == sending_dialogue
        assert search_result.performative == OefSearchMessage.Performative.SEARCH_RESULT
        assert search_result.agents == (self.address_2, ), self.node.services
示例#22
0
async def test_inbox_outbox():
    """Test InBox OutBox objects."""
    connection_1 = _make_dummy_connection()
    connections = [connection_1]
    multiplexer = AsyncMultiplexer(connections, loop=asyncio.get_event_loop())
    envelope = Envelope(
        to="",
        sender="",
        protocol_id=DefaultMessage.protocol_id,
        message=b"",
        context=EnvelopeContext(connection_id=connection_1.connection_id),
    )
    try:
        await multiplexer.connect()
        inbox = InBox(multiplexer)
        outbox = InBox(multiplexer)

        assert inbox.empty()
        assert outbox.empty()

        multiplexer.put(envelope)
        await outbox.async_get()
    finally:
        await multiplexer.disconnect()
示例#23
0
def test_inbox_empty():
    """Tests if the inbox is empty."""
    multiplexer = Multiplexer([_make_dummy_connection()])
    _inbox = InBox(multiplexer)
    assert _inbox.empty(), "Inbox is not empty"
示例#24
0
def test_inbox_get_nowait_returns_none():
    """Test that getting an envelope from an empty inbox returns None."""
    # TODO get_nowait in this case should raise an exception, like it's done in queue.Queue
    multiplexer = Multiplexer([_make_dummy_connection()])
    inbox = InBox(multiplexer)
    assert inbox.get_nowait() is None