def on_message(self, msg_id: int, dialogue_id: int, origin: Address, content: bytes) -> None: """ On message event handler. :param msg_id: the message id. :param dialogue_id: the dialogue id. :param origin: the address of the sender. :param content: the bytes content. :return: None """ # We are not using the 'msg_id', 'dialogue_id' and 'origin' parameters because 'content' contains a # serialized instance of 'Envelope', hence it already contains this information. self._check_loop_and_queue() envelope = Envelope.decode(content) asyncio.run_coroutine_threadsafe(self.in_queue.put(envelope), self.loop)
def test_reception_c(self): """Test that the connection receives what has been enqueued in the input file.""" encoded_envelope = b"0x5E22777dD831A459535AA4306AceC9cb22eC4cB5,default_oef,fetchai/oef_search:0.3.0,\x08\x02\x12\x011\x1a\x011 \x01:,\n*0x32468dB8Ab79549B49C88DC991990E7910891dbd," expected_envelope = Envelope( to="0x5E22777dD831A459535AA4306AceC9cb22eC4cB5", sender="default_oef", protocol_id=PublicId.from_str("fetchai/oef_search:0.3.0"), message= b"\x08\x02\x12\x011\x1a\x011 \x01:,\n*0x32468dB8Ab79549B49C88DC991990E7910891dbd", ) with open(self.input_file_path, "ab+") as f: with lock_file(f): f.write(encoded_envelope) f.flush() actual_envelope = self.multiplexer.get(block=True, timeout=3.0) assert expected_envelope == actual_envelope
def test_inbox_get(): """Tests for a envelope on the in queue.""" msg = Message(content="hello") message_bytes = ProtobufSerializer().encode(msg) multiplexer = Multiplexer([_make_dummy_connection()]) envelope = Envelope( to="Agent1", sender="Agent0", protocol_id=UNKNOWN_PROTOCOL_PUBLIC_ID, message=message_bytes, ) multiplexer.in_queue.put(envelope) inbox = InBox(multiplexer) assert ( inbox.get() == envelope ), "Checks if the returned envelope is the same with the queued envelope."
def send_unsupported_skill(self, envelope: Envelope, protocol: Protocol) -> None: """ Handle the received envelope in case the skill is not supported. :param envelope: the envelope :param protocol: the protocol :return: None """ logger.warning("Cannot handle envelope: no handler registered for the protocol '{}'.".format(protocol.id)) encoded_envelope = base64.b85encode(envelope.encode()).decode("utf-8") reply = DefaultMessage(type=DefaultMessage.Type.ERROR, error_code=DefaultMessage.ErrorCode.UNSUPPORTED_SKILL.value, error_msg="Unsupported skill.", error_data={"envelope": encoded_envelope}) self.context.outbox.put_message(to=envelope.sender, sender=self.context.agent_public_key, protocol_id=DefaultMessage.protocol_id, message=DefaultSerializer().encode(reply))
def reset(self) -> None: """ Reset the environment. :return: None """ if not self._agent.multiplexer.is_connected: self._connect() gym_msg = GymMessage(performative=GymMessage.Performative.RESET) gym_bytes = GymSerializer().encode(gym_msg) envelope = Envelope( to=DEFAULT_GYM, sender=self._agent_address, protocol_id=GymMessage.protocol_id, message=gym_bytes, ) self._agent.outbox.put(envelope)
async def test_erc1155_get_state(erc1155_contract, ledger_apis_connection): """Test get state with contract erc1155.""" address = ETHEREUM_ADDRESS_ONE contract_address = "0x250A2aeb3eB84782e83365b4c42dbE3CDA9920e4" contract_api_dialogues = ContractApiDialogues() token_id = 1 request = ContractApiMessage( performative=ContractApiMessage.Performative.GET_STATE, dialogue_reference=contract_api_dialogues. new_self_initiated_dialogue_reference(), ledger_id=ETHEREUM, contract_id="fetchai/erc1155:0.6.0", contract_address=contract_address, callable="get_balance", kwargs=ContractApiMessage.Kwargs({ "agent_address": address, "token_id": token_id }), ) request.counterparty = str(ledger_apis_connection.connection_id) contract_api_dialogue = contract_api_dialogues.update(request) assert contract_api_dialogue is not None envelope = Envelope( to=str(ledger_apis_connection.connection_id), sender=address, protocol_id=request.protocol_id, message=request, ) await ledger_apis_connection.send(envelope) await asyncio.sleep(0.01) response = await ledger_apis_connection.receive() assert response is not None assert type(response.message) == ContractApiMessage response_message = cast(ContractApiMessage, response.message) assert (response_message.performative == ContractApiMessage.Performative.STATE), "Error: {}".format( response_message.message) response_dialogue = contract_api_dialogues.update(response_message) assert response_dialogue == contract_api_dialogue assert type(response_message.state) == State assert response_message.state.ledger_id == ETHEREUM result = response_message.state.body.get("balance", None) expected_result = {token_id: 0} assert result is not None and result == expected_result
def make_test_envelope() -> Envelope: """Create a test envelope.""" msg = DefaultMessage( dialogue_reference=("", ""), message_id=1, target=0, performative=DefaultMessage.Performative.BYTES, content=b"hello", ) msg.counterparty = "any" envelope = Envelope( to="any", sender="any", protocol_id=DefaultMessage.protocol_id, message=msg, ) return envelope
async def test_erc1155_get_raw_message(erc1155_contract, ledger_apis_connection): """Test get state with contract erc1155.""" address = ETHEREUM_ADDRESS_ONE contract_address = "0x250A2aeb3eB84782e83365b4c42dbE3CDA9920e4" contract_api_dialogues = ContractApiDialogues(address) request, contract_api_dialogue = contract_api_dialogues.create( counterparty=str(ledger_apis_connection.connection_id), performative=ContractApiMessage.Performative.GET_RAW_MESSAGE, ledger_id=ETHEREUM, contract_id=str(ERC1155_PUBLIC_ID), contract_address=contract_address, callable="get_hash_single", kwargs=ContractApiMessage.Kwargs({ "from_address": address, "to_address": address, "token_id": 1, "from_supply": 10, "to_supply": 0, "value": 0, "trade_nonce": 1, }), ) envelope = Envelope( to=request.to, sender=request.sender, protocol_id=request.protocol_id, message=request, ) await ledger_apis_connection.send(envelope) await asyncio.sleep(0.01) response = await ledger_apis_connection.receive() assert response is not None assert type(response.message) == ContractApiMessage response_message = cast(ContractApiMessage, response.message) assert (response_message.performative == ContractApiMessage.Performative.RAW_MESSAGE), "Error: {}".format( response_message.message) response_dialogue = contract_api_dialogues.update(response_message) assert response_dialogue == contract_api_dialogue assert type(response_message.raw_message) == RawMessage assert response_message.raw_message.ledger_id == ETHEREUM assert type(response.message.raw_message.body) == bytes
def test_storage_access_from_handler(): """Test storage access from handler component.""" builder = AEABuilder() builder.set_name("aea_1") builder.add_private_key(DEFAULT_LEDGER) skill_context = SkillContext() handler = THandler(name="behaviour", skill_context=skill_context) test_skill = Skill( SkillConfig(name="test_skill", author="fetchai"), skill_context=skill_context, handlers={"handler": handler}, behaviours={}, ) builder.add_component_instance(test_skill) builder.set_storage_uri("sqlite://:memory:") aea = builder.build() skill_context.set_agent_context(aea.context) aea.runtime._threaded = True aea.runtime.start() msg = DefaultMessage( dialogue_reference=("", ""), message_id=1, target=0, performative=DefaultMessage.Performative.BYTES, content=b"hello", ) msg.to = aea.identity.address msg.sender = aea.identity.address envelope = Envelope(to=msg.to, sender=msg.sender, message=msg,) try: wait_for_condition(lambda: aea.is_running, timeout=10) aea.runtime.multiplexer.in_queue.put(envelope) wait_for_condition(lambda: handler.counter > 0, timeout=10) col = skill_context.storage.get_sync_collection(handler.COL_NAME) assert col.get(handler.OBJ_ID) == handler.OBJ_BODY finally: aea.runtime.stop() aea.runtime.wait_completed(sync=True, timeout=10)
def test_search_services_with_distance_query(self): """Test that a search services request can be sent correctly. In this test, the query has a simple data model. """ tour_eiffel = Location(48.8581064, 2.29447) attribute = Attribute("latlon", Location, True) data_model = DataModel("geolocation", [attribute]) search_query = Query( [ Constraint(attribute.name, ConstraintType("distance", (tour_eiffel, 1.0))) ], model=data_model, ) oef_search_request = OefSearchMessage( performative=OefSearchMessage.Performative.SEARCH_SERVICES, dialogue_reference=self.oef_search_dialogues. new_self_initiated_dialogue_reference(), query=search_query, ) oef_search_request.counterparty = str( self.connection.connection_id) sending_dialogue = self.oef_search_dialogues.update( oef_search_request) assert sending_dialogue is not None self.multiplexer.put( Envelope( to=str(self.connection.connection_id), sender=FETCHAI_ADDRESS_ONE, protocol_id=OefSearchMessage.protocol_id, message=oef_search_request, )) envelope = self.multiplexer.get(block=True, timeout=5.0) oef_search_response_original = envelope.message oef_search_response = copy.copy(oef_search_response_original) oef_search_response.is_incoming = True oef_search_response.counterparty = oef_search_response_original.sender oef_search_dialogue = self.oef_search_dialogues.update( oef_search_response) assert (oef_search_response.performative == OefSearchMessage.Performative.SEARCH_RESULT) assert oef_search_dialogue is not None assert oef_search_dialogue == sending_dialogue assert oef_search_response.agents == ()
async def test_erc1155_get_raw_transaction(erc1155_contract, ledger_apis_connection): """Test get state with contract erc1155.""" address = ETHEREUM_ADDRESS_ONE contract_address = "0x250A2aeb3eB84782e83365b4c42dbE3CDA9920e4" contract_api_dialogues = ContractApiDialogues() request = ContractApiMessage( performative=ContractApiMessage.Performative.GET_RAW_TRANSACTION, dialogue_reference=contract_api_dialogues. new_self_initiated_dialogue_reference(), ledger_id=ETHEREUM, contract_id="fetchai/erc1155:0.6.0", contract_address=contract_address, callable="get_create_batch_transaction", kwargs=ContractApiMessage.Kwargs({ "deployer_address": address, "token_ids": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] }), ) request.counterparty = str(ledger_apis_connection.connection_id) contract_api_dialogue = contract_api_dialogues.update(request) assert contract_api_dialogue is not None envelope = Envelope( to=str(ledger_apis_connection.connection_id), sender=address, protocol_id=request.protocol_id, message=request, ) await ledger_apis_connection.send(envelope) await asyncio.sleep(0.01) response = await ledger_apis_connection.receive() assert response is not None assert type(response.message) == ContractApiMessage response_message = cast(ContractApiMessage, response.message) assert (response_message.performative == ContractApiMessage.Performative. RAW_TRANSACTION), "Error: {}".format(response_message.message) response_dialogue = contract_api_dialogues.update(response_message) assert response_dialogue == contract_api_dialogue assert type(response_message.raw_transaction) == RawTransaction assert response_message.raw_transaction.ledger_id == ETHEREUM assert len(response.message.raw_transaction.body) == 7 assert len(response.message.raw_transaction.body["data"]) > 0
async def test_channel_cancel_tasks_on_disconnect(self): """Test requests tasks cancelled on disconnect.""" await self.http_client_connection.connect() request_http_message, _ = self.http_dialogs.create( counterparty=self.connection_address, performative=HttpMessage.Performative.REQUEST, method="get", url="https://not-a-google.com", headers="", version="", body=b"", ) request_envelope = Envelope( to=self.connection_address, sender=self.agent_address, protocol_specification_id=UNKNOWN_PROTOCOL_PUBLIC_ID, message=request_http_message, ) connection_response_mock = Mock() connection_response_mock.status_code = 200 response_mock = Mock() response_mock.status = 200 response_mock.headers = {"headers": "some header"} response_mock.reason = "OK" response_mock._body = b"Some content" response_mock.read.return_value = asyncio.Future() with patch.object( aiohttp.ClientSession, "request", return_value=_MockRequest(response_mock), ): await self.http_client_connection.send(envelope=request_envelope) assert self.http_client_connection.channel._tasks task = list(self.http_client_connection.channel._tasks)[0] assert not task.done() await self.http_client_connection.disconnect() assert not self.http_client_connection.channel._tasks assert task.done() with pytest.raises(CancelledError): await task
async def _generic_command_handler( self, service_description: Description, oef_message: OefSearchMessage, oef_search_dialogue: OefSearchDialogue, ) -> None: """ Perform ping command. :param service_description: Service description :return None """ if not self.in_queue: # pragma: no cover """not connected.""" return self._check_data_model(service_description, ModelNames.GENERIC_COMMAND.value) command = service_description.values.get("command", None) params = service_description.values.get("parameters", {}) if params: params = urllib.parse.parse_qs(params) content = await self._generic_oef_command(command, params) message = oef_search_dialogue.reply( performative=OefSearchMessage.Performative.SUCCESS, target_message=oef_message, agents_info=AgentsInfo({ "response": { "content": content }, "command": service_description.values, }), ) envelope = Envelope( to=message.to, sender=message.sender, protocol_id=message.protocol_id, message=message, context=oef_search_dialogue.envelope_context, ) await self.in_queue.put(envelope)
async def test_p2p_send(): """Test the send functionality of the p2p connection.""" address = "127.0.0.1" port = 8000 m_fet_key = "6d56fd47e98465824aa85dfe620ad3dbf092b772abc6c6a182e458b5c56ad13b" ent = entity.Entity.from_hex(m_fet_key) p2p_client_connection = _make_p2p_client_connection( address=ent.public_key_hex, provider_addr=address, provider_port=port, ) p2p_client_connection.loop = asyncio.get_event_loop() envelope = Envelope( to="receiver", sender="sender", protocol_id=UNKNOWN_PROTOCOL_PUBLIC_ID, message=b"Hello", ) with mock.patch.object( fetch.p2p.api.http_calls.HTTPCalls, "get_messages", return_value=[] ): with mock.patch.object( fetch.p2p.api.http_calls.HTTPCalls, "register", return_value={"status": "OK"}, ): await p2p_client_connection.connect() assert p2p_client_connection.connection_status.is_connected is True with mock.patch.object( fetch.p2p.api.http_calls.HTTPCalls, "get_messages", return_value=[] ): with mock.patch.object( fetch.p2p.api.http_calls.HTTPCalls, "send_message", return_value={"status": "OK"}, ): await p2p_client_connection.send(envelope=envelope) # TODO: Consider returning the response from the server in order to be able to assert that the message send! assert True with mock.patch.object( fetch.p2p.api.http_calls.HTTPCalls, "unregister", return_value={"status": "OK"}, ): await p2p_client_connection.disconnect() assert p2p_client_connection.connection_status.is_connected is False
def test_echo(self): """Run the echo skill sequence.""" self.add_item("skill", "fetchai/echo:0.3.0") process = self.run_agent() is_running = self.is_running(process) assert is_running, "AEA not running within timeout!" # add sending and receiving envelope from input/output files message_content = b"hello" message = DefaultMessage( performative=DefaultMessage.Performative.BYTES, content=message_content, ) sent_envelope = Envelope( to=self.agent_name, sender="sender", protocol_id=message.protocol_id, message=message, ) self.send_envelope_to_agent(sent_envelope, self.agent_name) time.sleep(2.0) received_envelope = self.read_envelope_from_agent(self.agent_name) # assert sent_envelope.to == received_envelope.sender assert sent_envelope.sender == received_envelope.to assert sent_envelope.protocol_id == received_envelope.protocol_id msg = DefaultMessage.serializer.decode(received_envelope.message) assert sent_envelope.message == msg check_strings = ( "Echo Handler: setup method called.", "Echo Behaviour: setup method called.", "Echo Behaviour: act method called.", "content={}".format(message_content), ) missing_strings = self.missing_from_output(process, check_strings) assert ( missing_strings == [] ), "Strings {} didn't appear in agent output.".format(missing_strings) assert (self.is_successfully_terminated() ), "Echo agent wasn't successfully terminated."
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."
def test_envelope_skill_id_raises_value_error_wrong_package_type(): """Test the property Envelope.skill_id raises ValueError if the URI is not a valid package type.""" with unittest.mock.patch.object(aea.mail.base._default_logger, "debug") as mock_logger_method: invalid_uri = "protocol/author/skill_name/0.1.0" envelope_context = EnvelopeContext(uri=URI(invalid_uri)) envelope = Envelope( to="to", sender="sender", protocol_specification_id=PublicId("author", "name", "0.1.0"), message=b"message", context=envelope_context, ) assert envelope.skill_id is None mock_logger_method.assert_called_with( f"URI - {invalid_uri} - not a valid package_id id. Error: Invalid package type protocol in uri for envelope context." )
async def send_add_metric(self, title: str, metric_type: str) -> None: """Send an add_metric message.""" msg, sending_dialogue = self.dialogues.create( counterparty=self.prometheus_address, performative=PrometheusMessage.Performative.ADD_METRIC, title=title, type=metric_type, description="a gauge", labels={}, ) assert sending_dialogue is not None envelope = Envelope( to=msg.to, sender=msg.sender, message=msg, ) await self.prometheus_con.send(envelope)
async def test_send_connection_error(self): """Test send connection error.""" msg = GymMessage( performative=GymMessage.Performative.ACT, action=GymMessage.AnyObject("any_action"), step_id=1, ) msg_bytes = GymSerializer().encode(msg) envelope = Envelope( to="_to_key", sender="_from_key", protocol_id=GymMessage.protocol_id, message=msg_bytes, ) self.gym_con.connection_status.is_connected = False with pytest.raises(ConnectionError): await self.gym_con.send(envelope)
def on_search_result(self, search_id: int, agents: List[str]) -> None: """ On accept event handler. :param search_id: the search id. :param agents: the list of agents. :return: None """ self.mail_stats.search_end(search_id, len(agents)) msg = OEFMessage(oef_type=OEFMessage.Type.SEARCH_RESULT, id=search_id, agents=agents) msg_bytes = OEFSerializer().encode(msg) envelope = Envelope(to=self.public_key, sender=DEFAULT_OEF, protocol_id=OEFMessage.protocol_id, message=msg_bytes) self.in_queue.put(envelope)
async def test_send_envelope_with_non_registered_connection(): """Test that sending an envelope with an unregistered connection raises an exception.""" connection = _make_dummy_connection() multiplexer = Multiplexer([connection]) multiplexer.connect() envelope = Envelope( to="", sender="", protocol_id=DefaultMessage.protocol_id, message=b"", context=EnvelopeContext(connection_id=UNKNOWN_CONNECTION_PUBLIC_ID), ) with pytest.raises(AEAConnectionError, match="No connection registered with id:.*"): await multiplexer._send(envelope) multiplexer.disconnect()
def _decode(e: bytes, separator: bytes = SEPARATOR): split = e.split(separator) if len(split) < 5 or split[-1] not in [b"", b"\n"]: raise ValueError( "Expected at least 5 values separated by commas and last value being empty or new line, got {}".format( len(split) ) ) to = split[0].decode("utf-8").strip() sender = split[1].decode("utf-8").strip() protocol_id = PublicId.from_str(split[2].decode("utf-8").strip()) # protobuf messages cannot be delimited as they can contain an arbitrary byte sequence; however # we know everything remaining constitutes the protobuf message. message = SEPARATOR.join(split[3:-1]) return Envelope(to=to, sender=sender, protocol_id=protocol_id, message=message)
def test_envelope_skill_id_raises_value_error(): """Test the property Envelope.skill_id raises ValueError if the URI is not a package id..""" with unittest.mock.patch.object(aea.mail.base._default_logger, "debug") as mock_logger_method: bad_uri = "skill/author/skill_name/bad_version" envelope_context = EnvelopeContext(uri=URI(bad_uri)) envelope = Envelope( to="to", sender="sender", protocol_specification_id=PublicId("author", "name", "0.1.0"), message=b"message", context=envelope_context, ) assert envelope.skill_id is None mock_logger_method.assert_called_with( f"URI - {bad_uri} - not a valid package_id id. Error: Input '{bad_uri}' is not well formatted." )
def test_send_message(self): """Test that a default byte message can be sent correctly.""" msg = DefaultMessage( dialogue_reference=("", ""), message_id=1, target=0, performative=DefaultMessage.Performative.BYTES, content=b"hello", ) self.multiplexer.put( Envelope( to=FETCHAI_ADDRESS_ONE, sender=FETCHAI_ADDRESS_ONE, protocol_id=DefaultMessage.protocol_id, message=msg, )) recv_msg = self.multiplexer.get(block=True, timeout=3.0) assert recv_msg is not None
async def test_bad_performative(self, caplog): """Test fail on bad perfromative.""" agent_location = Location(52.2057092, 2.1183431) service_instance = {"location": agent_location} service_description = Description( service_instance, data_model=models.AGENT_LOCATION_MODEL ) message = OefSearchMessage( performative="oef_error", service_description=service_description, ) envelope = Envelope( to="soef", sender=self.crypto.address, protocol_id=message.protocol_id, message=message, ) with pytest.raises(ValueError): await self.connection.send(envelope)
async def test_callable_wrong_number_of_arguments_apis( erc1155_contract, ledger_apis_connection ): """ Test a contract callable with wrong number of arguments. Test the case of either GET_DEPLOY_TRANSACTION. """ contract, contract_address = erc1155_contract address = ETHEREUM_ADDRESS_ONE contract_api_dialogues = ContractApiDialogues(address) request, _ = contract_api_dialogues.create( counterparty=str(ledger_apis_connection.connection_id), performative=ContractApiMessage.Performative.GET_DEPLOY_TRANSACTION, ledger_id=ETHEREUM, contract_id=str(ERC1155_PUBLIC_ID), callable="get_deploy_transaction", kwargs=ContractApiMessage.Kwargs({}), ) envelope = Envelope(to=request.to, sender=request.sender, message=request,) with unittest.mock.patch( "inspect.getfullargspec", return_value=unittest.mock.MagicMock(args=[]) ): with unittest.mock.patch.object( ledger_apis_connection._contract_dispatcher, "_call_stub", return_value=None ): with unittest.mock.patch.object( ledger_apis_connection._contract_dispatcher.logger, "error" ) as mock_logger: await ledger_apis_connection.send(envelope) await asyncio.sleep(0.01) response = await ledger_apis_connection.receive() mock_logger.assert_any_call( "Exception during contract request: Expected one or more positional arguments, got 0" ) assert ( response.message.performative == ContractApiMessage.Performative.ERROR ) assert ( response.message.message == "Expected one or more positional arguments, got 0" )
def test_communication_direct(self): for uri in PUBLIC_DHT_DELEGATE_URIS: connection1 = _make_libp2p_client_connection(uri=uri) multiplexer1 = Multiplexer([connection1]) multiplexer1.connect() connection2 = _make_libp2p_client_connection(uri=uri) multiplexer2 = Multiplexer([connection2]) multiplexer2.connect() addr_1 = connection1.address addr_2 = connection2.address msg = DefaultMessage( dialogue_reference=("", ""), message_id=1, target=0, performative=DefaultMessage.Performative.BYTES, content=b"hello", ) envelope = Envelope( to=addr_2, sender=addr_1, protocol_id=DefaultMessage.protocol_id, message=msg, ) multiplexer1.put(envelope) delivered_envelope = multiplexer2.get(block=True, timeout=20) try: assert delivered_envelope is not None assert delivered_envelope.to == envelope.to assert delivered_envelope.sender == envelope.sender assert delivered_envelope.protocol_id == envelope.protocol_id assert delivered_envelope.message != envelope.message msg = DefaultMessage.serializer.decode( delivered_envelope.message) assert envelope.message == msg except Exception: raise finally: multiplexer1.disconnect() multiplexer2.disconnect()
def to_envelope( self, connection_id: PublicId, http_request_message: HttpMessage, status_code: int, headers: dict, status_text: Optional[Any], bodyy: bytes, dialogue: HttpDialogue, ) -> Envelope: """ Convert an HTTP response object (from the 'requests' library) into an Envelope containing an HttpMessage (from the 'http' Protocol). :param connection_id: the connection id :param http_request_message: the message of the http request envelop :param status_code: the http status code, int :param headers: dict of http response headers :param status_text: the http status_text, str :param bodyy: bytes of http response content :return: Envelope with http response data. """ context = EnvelopeContext(connection_id=connection_id) http_message = HttpMessage( performative=HttpMessage.Performative.RESPONSE, status_code=status_code, headers=json.dumps(dict(headers.items())), status_text=status_text, bodyy=bodyy, version="", dialogue_reference=dialogue.dialogue_label.dialogue_reference, target=http_request_message.message_id, message_id=http_request_message.message_id + 1, ) http_message.counterparty = http_request_message.counterparty assert dialogue.update(http_message) envelope = Envelope( to=self.agent_address, sender="HTTP Server", protocol_id=PublicId.from_str("fetchai/http:0.4.0"), context=context, message=http_message, ) return envelope
async def test_callable_wrong_number_of_arguments_api_and_contract_address( erc1155_contract, ledger_apis_connection): """ Test a contract callable with wrong number of arguments. Test the case of either GET_STATE, GET_RAW_MESSAGE or GET_RAW_TRANSACTION. """ address = ETHEREUM_ADDRESS_ONE contract_api_dialogues = ContractApiDialogues(address) token_id = 1 contract_address = "0x250A2aeb3eB84782e83365b4c42dbE3CDA9920e4" request, _ = contract_api_dialogues.create( counterparty=str(ledger_apis_connection.connection_id), performative=ContractApiMessage.Performative.GET_STATE, ledger_id=ETHEREUM, contract_id=str(ERC1155_PUBLIC_ID), contract_address=contract_address, callable="get_balance", kwargs=ContractApiMessage.Kwargs({ "agent_address": address, "token_id": token_id }), ) envelope = Envelope( to=request.to, sender=request.sender, protocol_id=request.protocol_id, message=request, ) with unittest.mock.patch( "inspect.getfullargspec", return_value=unittest.mock.MagicMock(args=[None])): with unittest.mock.patch.object(ledger_apis_connection._logger, "error") as mock_logger: await ledger_apis_connection.send(envelope) await asyncio.sleep(0.01) response = await ledger_apis_connection.receive() mock_logger.assert_any_call( "Expected two or more positional arguments, got 1") assert (response.message.performative == ContractApiMessage.Performative.ERROR) assert (response.message.message == "Expected two or more positional arguments, got 1")
def register_personality_pieces(self, piece: str = "genus", value: str = "service") -> None: """Register personality pieces.""" service_instance = {"piece": piece, "value": value} service_description = Description( service_instance, data_model=models.AGENT_PERSONALITY_MODEL) message, _ = self.oef_search_dialogues.create( counterparty=str(SOEFConnection.connection_id.to_any()), performative=OefSearchMessage.Performative.REGISTER_SERVICE, service_description=service_description, ) envelope = Envelope( to=message.to, sender=message.sender, message=message, ) logger.info("Registering agent personality") self.multiplexer.put(envelope)