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()
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()
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()
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()
async def test_connection_twice_return_none(): """Test that connecting twice works.""" with LocalNode() as node: address = "address" connection = OEFLocalConnection(address, node, connection_id=PublicId( "fetchai", "local", "0.1.0")) 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()
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()
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)
def test_connection(): """Test that two OEF local connection can connect to a local node.""" with LocalNode() as node: local_id_1 = PublicId("fetchai", "local1", "0.1.0") local_id_2 = PublicId("fetchai", "local2", "0.1.0") multiplexer1 = Multiplexer([ OEFLocalConnection("multiplexer1", node, connection_id=local_id_1) ]) multiplexer2 = Multiplexer([ OEFLocalConnection("multiplexer2", node, connection_id=local_id_2) ]) multiplexer1.connect() multiplexer2.connect() multiplexer1.disconnect() multiplexer2.disconnect()
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()
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()
def _make_local_connection( address: Address, node: LocalNode, restricted_to_protocols=None, excluded_protocols=None, ) -> Connection: oef_local_connection = OEFLocalConnection( node, address=address, connection_id=PublicId("fetchai", "local", "0.1.0"), restricted_to_protocols=restricted_to_protocols, excluded_protocols=excluded_protocols, ) return oef_local_connection
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)
def _make_local_connection( address: Address, node: LocalNode, restricted_to_protocols=None, excluded_protocols=None, ) -> Connection: configuration = ConnectionConfig( restricted_to_protocols=restricted_to_protocols, excluded_protocols=excluded_protocols, connection_id=OEFLocalConnection.connection_id, ) oef_local_connection = OEFLocalConnection( configuration=configuration, identity=Identity("name", address), local_node=node ) return oef_local_connection
def test_multiplexer(): """Tests if the multiplexer is connected.""" with LocalNode() as node: address_1 = "address_1" multiplexer = Multiplexer([ OEFLocalConnection(address_1, node, connection_id=PublicId("fetchai", "local", "0.1.0")) ]) multiplexer.connect() assert ( multiplexer.is_connected ), "Mailbox cannot connect to the specific Connection(OEFLocalConnection)" multiplexer.disconnect()
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 = OEFLocalConnection(address, node, connection_id=PublicId( "fetchai", "local", "0.1.0")) 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()
def setup_class(cls): """Set up the test.""" cls.node = LocalNode() cls.node.start() cls.address_1 = "address" cls.multiplexer = Multiplexer( [ OEFLocalConnection( cls.address_1, cls.node, connection_id=PublicId("fetchai", "local", "0.1.0"), ) ] ) cls.multiplexer.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( 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.address_1, protocol_id=OEFMessage.protocol_id, message=msg_bytes, ) cls.multiplexer.put(envelope)
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) agent = DummyAgent( identity, [ OEFLocalConnection("mypbk", node, connection_id=PublicId( "fetchai", "oef", "0.1.0")) ], ) 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()
def test_communication(): """Test that two multiplexer can communicate through the node.""" with LocalNode() as node: local_public_id = PublicId("fetchai", "local", "0.1.0") multiplexer1 = Multiplexer([ OEFLocalConnection("multiplexer1", node, connection_id=local_public_id) ]) multiplexer2 = Multiplexer([ OEFLocalConnection("multiplexer2", node, connection_id=local_public_id) ]) multiplexer1.connect() multiplexer2.connect() msg = DefaultMessage( dialogue_reference=("", ""), message_id=1, target=0, performative=DefaultMessage.Performative.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 == DefaultMessage.protocol_id assert msg.get("content") == b"hello" envelope = multiplexer2.get(block=True, timeout=1.0) msg = FIPASerializer().decode(envelope.message) assert envelope.protocol_id == FIPAMessage.protocol_id assert msg.get("performative") == FIPAMessage.Performative.CFP envelope = multiplexer2.get(block=True, timeout=1.0) msg = FIPASerializer().decode(envelope.message) assert envelope.protocol_id == FIPAMessage.protocol_id assert msg.get("performative") == FIPAMessage.Performative.PROPOSE envelope = multiplexer2.get(block=True, timeout=1.0) msg = FIPASerializer().decode(envelope.message) assert envelope.protocol_id == FIPAMessage.protocol_id assert msg.get("performative") == FIPAMessage.Performative.ACCEPT envelope = multiplexer2.get(block=True, timeout=1.0) msg = FIPASerializer().decode(envelope.message) assert envelope.protocol_id == FIPAMessage.protocol_id assert msg.get("performative") == FIPAMessage.Performative.DECLINE multiplexer1.disconnect() multiplexer2.disconnect()
def setup_class(cls): """Set up the test.""" cls.node = LocalNode() cls.node.start() cls.address_1 = "multiplexer1" cls.address_2 = "multiplexer2" cls.multiplexer1 = Multiplexer( [ OEFLocalConnection( cls.address_1, cls.node, connection_id=PublicId("fetchai", "local", "0.1.0"), ) ] ) cls.multiplexer2 = Multiplexer( [ OEFLocalConnection( cls.address_2, cls.node, connection_id=PublicId("fetchai", "local", "0.1.0"), ) ] ) 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( 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.address_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( 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.address_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( 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.address_1, protocol_id=OEFMessage.protocol_id, message=msg_bytes, ) cls.multiplexer1.put(envelope)
def test_from_config(self): """Test the configuration loading.""" con = OEFLocalConnection.from_config( address="pk", connection_configuration=ConnectionConfig(), ) assert not con.connection_status.is_connected, "We are connected..."
async def test_handle(): """Tests handle method of an agent.""" 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}) ledger_apis = LedgerApis({}, FETCHAI) identity = Identity(agent_name, address=wallet.addresses[FETCHAI]) connection = OEFLocalConnection(identity.address, node, connection_id=DUMMY_SKILL_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 = agent_name message_bytes = DefaultSerializer().encode(msg) envelope = Envelope( to=identity.address, sender=identity.address, protocol_id=UNKNOWN_PROTOCOL_PUBLIC_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(2.0) dummy_skill = agent.resources.get_skill(DUMMY_SKILL_PUBLIC_ID) dummy_handler = dummy_skill.handlers["dummy"] expected_envelope = envelope agent.outbox.put(expected_envelope) time.sleep(2.0) assert len(dummy_handler.handled_messages) == 1 # DECODING ERROR msg = "hello".encode("utf-8") envelope = Envelope( to=identity.address, sender=identity.address, protocol_id=DefaultMessage.protocol_id, message=msg, ) expected_envelope = envelope agent.outbox.put(expected_envelope) time.sleep(2.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=identity.address, sender=identity.address, protocol_id=FIPAMessage.protocol_id, message=msg, ) expected_envelope = envelope agent.outbox.put(expected_envelope) time.sleep(2.0) assert len(dummy_handler.handled_messages) == 3 finally: agent.stop() t.join()
def setup_class(cls): """Set the test up.""" cls.node = LocalNode() cls.node.start() cls.agent_name = "MyAgent" cls.private_key_path = os.path.join(CUR_PATH, "data", "fet_private_key.txt") cls.wallet = Wallet({FETCHAI: cls.private_key_path}) cls.ledger_apis = LedgerApis({}, FETCHAI) cls.identity = Identity(cls.agent_name, address=cls.wallet.addresses[FETCHAI]) cls.connection = OEFLocalConnection( cls.agent_name, cls.node, connection_id=LOCAL_CONNECTION_PUBLIC_ID) cls.connections = [cls.connection] cls.temp = tempfile.mkdtemp(prefix="test_aea_resources") cls.resources = Resources(cls.temp) cls.aea = AEA( cls.identity, cls.connections, cls.wallet, cls.ledger_apis, resources=cls.resources, ) default_protocol_id = DefaultMessage.protocol_id cls.default_protocol_configuration = ProtocolConfig.from_json( yaml.safe_load( open(Path(AEA_DIR, "protocols", "default", "protocol.yaml")))) cls.default_protocol = Protocol(default_protocol_id, DefaultSerializer(), cls.default_protocol_configuration) cls.resources.protocol_registry.register(default_protocol_id, cls.default_protocol) cls.error_skill = Skill.from_dir(Path(AEA_DIR, "skills", "error"), cls.aea.context) cls.dummy_skill = Skill.from_dir(Path(CUR_PATH, "data", "dummy_skill"), cls.aea.context) cls.resources.add_skill(cls.dummy_skill) cls.resources.add_skill(cls.error_skill) cls.expected_message = DefaultMessage( dialogue_reference=("", ""), message_id=1, target=0, performative=DefaultMessage.Performative.BYTES, content=b"hello", ) cls.expected_message.counterparty = cls.agent_name cls.t = Thread(target=cls.aea.start) cls.t.start() time.sleep(0.5) cls.aea.outbox.put( Envelope( to=cls.agent_name, sender=cls.agent_name, protocol_id=default_protocol_id, message=DefaultSerializer().encode(cls.expected_message), ))
def run( duration: int, runtime_mode: str, runner_mode: str, start_messages: int, num_of_agents: int, ) -> List[Tuple[str, Union[int, float]]]: """Test multiagent message exchange.""" # pylint: disable=import-outside-toplevel,unused-import # import manually due to some lazy imports in decision_maker import aea.decision_maker.default # noqa: F401 local_node = LocalNode() local_node.start() agents = [] skills = {} handler_name = "httpingpong" for i in range(num_of_agents): agent_name = f"agent{i}" agent = make_agent(agent_name=agent_name, runtime_mode=runtime_mode) connection = OEFLocalConnection( local_node, configuration=ConnectionConfig( connection_id=OEFLocalConnection.connection_id, ), identity=agent.identity, ) agent.resources.add_connection(connection) skill = make_skill(agent, handlers={handler_name: HttpPingPongHandler}) agent.resources.add_skill(skill) agents.append(agent) skills[agent_name] = skill runner = AEARunner(agents, runner_mode) runner.start(threaded=True) for agent in agents: wait_for_condition(lambda: agent.is_running, timeout=5) wait_for_condition(lambda: runner.is_running, timeout=5) time.sleep(1) for agent1, agent2 in itertools.permutations(agents, 2): for _ in range(int(start_messages)): cast( HttpPingPongHandler, skills[agent1.identity.address].handlers[handler_name], ).make_request(agent2.identity.address) time.sleep(duration) mem_usage = get_mem_usage_in_mb() local_node.stop() runner.stop() total_messages = sum([ cast(HttpPingPongHandler, skill.handlers[handler_name]).count for skill in skills.values() ]) rate = total_messages / duration rtt_total_time = sum([ cast(HttpPingPongHandler, skill.handlers[handler_name]).rtt_total_time for skill in skills.values() ]) rtt_count = sum([ cast(HttpPingPongHandler, skill.handlers[handler_name]).rtt_count for skill in skills.values() ]) if rtt_count == 0: rtt_count = -1 latency_total_time = sum([ cast(HttpPingPongHandler, skill.handlers[handler_name]).latency_total_time for skill in skills.values() ]) latency_count = sum([ cast(HttpPingPongHandler, skill.handlers[handler_name]).latency_count for skill in skills.values() ]) if latency_count == 0: latency_count = -1 return [ ("Total Messages handled", total_messages), ("Messages rate(envelopes/second)", rate), ("Mem usage(Mb)", mem_usage), ("RTT (ms)", rtt_total_time / rtt_count), ("Latency (ms)", latency_total_time / latency_count), ]
def run(duration, runtime_mode, runner_mode, start_messages, num_of_agents): """Test multiagent message exchange.""" # pylint: disable=import-outside-toplevel,unused-import # import manually due to some lazy imports in decision_maker import aea.decision_maker.default # noqa: F401 local_node = LocalNode() local_node.start() agents = [] skills = [] for i in range(num_of_agents): agent = make_agent(agent_name=f"agent{i}", runtime_mode=runtime_mode) connection = OEFLocalConnection( local_node, configuration=ConnectionConfig( connection_id=OEFLocalConnection.connection_id, ), identity=agent.identity, ) agent.resources.add_connection(connection) skill = make_skill(agent, handlers={"test": TestHandler}) agent.resources.add_skill(skill) agents.append(agent) skills.append(skill) runner = AEARunner(agents, runner_mode) runner.start(threaded=True) for agent in agents: wait_for_condition(lambda: agent.is_running, timeout=5) wait_for_condition(lambda: runner.is_running, timeout=5) time.sleep(1) for agent1, agent2 in itertools.permutations(agents, 2): env = make_envelope(agent1.identity.address, agent2.identity.address) for _ in range(int(start_messages)): agent1.outbox.put(env) time.sleep(duration) mem_usage = get_mem_usage_in_mb() local_node.stop() runner.stop() total_messages = sum([skill.handlers["test"].count for skill in skills]) rate = total_messages / duration rtt_total_time = sum( [skill.handlers["test"].rtt_total_time for skill in skills]) rtt_count = sum([skill.handlers["test"].rtt_count for skill in skills]) if rtt_count == 0: rtt_count = -1 latency_total_time = sum( [skill.handlers["test"].latency_total_time for skill in skills]) latency_count = sum( [skill.handlers["test"].latency_count for skill in skills]) if latency_count == 0: latency_count = -1 return [ ("Total Messages handled", total_messages), ("Messages rate(envelopes/second)", rate), ("Mem usage(Mb)", mem_usage), ("RTT (ms)", rtt_total_time / rtt_count), ("Latency (ms)", latency_total_time / latency_count), ]