Пример #1
0
def test_multiplexer_setup_replaces_connections():
    """Test proper connections reset on setup call."""
    m = AsyncMultiplexer([MagicMock(), MagicMock(), MagicMock()])
    assert len(m._id_to_connection) == 3
    assert len(m._connections) == 3

    m._setup([MagicMock()], MagicMock())
    assert len(m._id_to_connection) == 1
    assert len(m._connections) == 1
Пример #2
0
async def test_exit_on_none_envelope():
    """Test sending task exit on None envelope."""
    connection_1 = _make_dummy_connection()
    connections = [connection_1]
    multiplexer = AsyncMultiplexer(connections, loop=asyncio.get_event_loop())
    try:
        await multiplexer.connect()
        assert multiplexer.is_connected
        multiplexer.put(None)

        await asyncio.sleep(0.5)
        assert multiplexer._send_loop_task.done()
    finally:
        await multiplexer.disconnect()
Пример #3
0
    def setup(cls) -> None:
        """Set up the skill test case."""
        identity = Identity("test_agent_name", "test_agent_address")

        cls._multiplexer = AsyncMultiplexer()
        cls._multiplexer._out_queue = (  # pylint: disable=protected-access
            asyncio.Queue()
        )
        cls._outbox = OutBox(cast(Multiplexer, cls._multiplexer))

        agent_context = AgentContext(
            identity=identity,
            connection_status=cls._multiplexer.connection_status,
            outbox=cls._outbox,
            decision_maker_message_queue=Queue(),
            decision_maker_handler_context=SimpleNamespace(),
            task_manager=TaskManager(),
            default_ledger_id=identity.default_address_key,
            currency_denominations=DEFAULT_CURRENCY_DENOMINATIONS,
            default_connection=None,
            default_routing={},
            search_service_address="dummy_search_service_address",
            decision_maker_address="dummy_decision_maker_address",
        )

        cls._skill = Skill.from_dir(str(cls.path_to_skill), agent_context)
Пример #4
0
async def test_disconnect_when_not_connected():
    """Test disconnect when not connected."""
    connection_1 = _make_dummy_connection()
    connections = [connection_1]
    multiplexer = AsyncMultiplexer(connections)
    with patch.object(multiplexer, "_disconnect_all") as disconnect_all_mocked:
        await multiplexer.disconnect()

    disconnect_all_mocked.assert_not_called()
Пример #5
0
async def test_run_bad_conneect():
    """Test that connecting twice a single connection behaves correctly."""
    connection = _make_dummy_connection()
    multiplexer = AsyncMultiplexer([connection])
    f = asyncio.Future()
    f.set_result(None)
    with unittest.mock.patch.object(multiplexer, "connect", return_value=f):
        with pytest.raises(ValueError,
                           match="Multiplexer is not connected properly."):
            await multiplexer.run()
Пример #6
0
 def _get_multiplexer_instance(self) -> AsyncMultiplexer:
     """Create multiplexer instance."""
     exception_policy = getattr(
         self._agent, "_connection_exception_policy", ExceptionPolicyEnum.propagate
     )
     return AsyncMultiplexer(
         self._agent.connections,
         loop=self.loop,
         exception_policy=exception_policy,
         agent_name=self._agent.name,
     )
Пример #7
0
async def test_outbox_negative():
    """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"",
    )
    context = EnvelopeContext(connection_id=connection_1.connection_id)
    envelope = Envelope(
        to="to",
        sender="sender",
        protocol_specification_id=msg.protocol_specification_id,
        message=b"",
        context=context,
    )

    try:
        await multiplexer.connect()
        outbox = OutBox(multiplexer)

        assert outbox.empty()

        with pytest.raises(ValueError) as execinfo:
            outbox.put(envelope)
        assert (
            str(execinfo.value) ==
            "Only Message type allowed in envelope message field when putting into outbox."
        )

        assert outbox.empty()

        with pytest.raises(ValueError) as execinfo:
            outbox.put_message("")
        assert str(execinfo.value) == "Provided message not of type Message."

        assert outbox.empty()

        with pytest.raises(ValueError) as execinfo:
            outbox.put_message(msg)
        assert str(
            execinfo.value) == "Provided message has message.to not set."

        assert outbox.empty()
        msg.to = "to"

        with pytest.raises(ValueError) as execinfo:
            outbox.put_message(msg)
        assert str(
            execinfo.value) == "Provided message has message.sender not set."

    finally:
        await multiplexer.disconnect()
Пример #8
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
Пример #9
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()
Пример #10
0
    def setup(cls, **kwargs: Any) -> None:
        """Set up the skill test case."""
        identity = Identity("test_agent_name", "test_agent_address")

        cls._multiplexer = AsyncMultiplexer()
        cls._multiplexer._out_queue = (  # pylint: disable=protected-access
            asyncio.Queue()
        )
        cls._outbox = OutBox(cast(Multiplexer, cls._multiplexer))
        _shared_state = cast(Dict[str, Any], kwargs.pop("shared_state", dict()))
        _skill_config_overrides = cast(
            Dict[str, Any], kwargs.pop("config_overrides", dict())
        )
        agent_context = AgentContext(
            identity=identity,
            connection_status=cls._multiplexer.connection_status,
            outbox=cls._outbox,
            decision_maker_message_queue=Queue(),
            decision_maker_handler_context=SimpleNamespace(),
            task_manager=TaskManager(),
            default_ledger_id=identity.default_address_key,
            currency_denominations=DEFAULT_CURRENCY_DENOMINATIONS,
            default_connection=None,
            default_routing={},
            search_service_address="dummy_search_service_address",
            decision_maker_address="dummy_decision_maker_address",
            data_dir=os.getcwd(),
        )

        # This enables pre-populating the 'shared_state' prior to loading the skill
        if _shared_state != dict():
            for key, value in _shared_state.items():
                agent_context.shared_state[key] = value

        skill_configuration_file_path: Path = Path(cls.path_to_skill, "skill.yaml")
        loader = ConfigLoaders.from_package_type(PackageType.SKILL)

        with open_file(skill_configuration_file_path) as fp:
            skill_config: SkillConfig = loader.load(fp)

        # This enables overriding the skill's config prior to loading
        if _skill_config_overrides != {}:
            skill_config.update(_skill_config_overrides)

        skill_config.directory = cls.path_to_skill

        cls._skill = Skill.from_config(skill_config, agent_context)
Пример #11
0
 def _get_multiplexer_instance(self,
                               multiplexer_options: Dict,
                               threaded: bool = False) -> AsyncMultiplexer:
     """Create multiplexer instance."""
     loop: Optional[AbstractEventLoop] = None
     if not threaded:
         loop = self.loop
     return AsyncMultiplexer(
         loop=loop,
         threaded=threaded,
         agent_name=self._agent.name,
         connections=multiplexer_options["connections"],
         exception_policy=multiplexer_options.get(
             "connection_exception_policy", ExceptionPolicyEnum.propagate),
         default_routing=multiplexer_options.get("default_routing"),
         default_connection=multiplexer_options.get("default_connection"),
         protocols=multiplexer_options.get("protocols", []),
     )
Пример #12
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()
Пример #13
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()
Пример #14
0
 def _get_multiplexer_instance(self) -> AsyncMultiplexer:
     """Create multiplexer instance."""
     return AsyncMultiplexer(self._agent.connections, threaded=True)