def test_simple_properties(self): """Test the properties of Parameters class.""" # phase assert self.parameters.ledger_id == "some_ledger_id" self.parameters._contract_address = None with pytest.raises(AEAEnforceError, match="No contract address provided."): assert self.parameters.contract_address self.parameters.contract_address = "some_contract_address" assert self.parameters.contract_address == "some_contract_address" with pytest.raises(AEAEnforceError, match="Contract address already provided."): self.parameters.contract_address = "some_contract_address" assert self.parameters.contract_id == self.parameters._contract_id assert self.parameters.is_contract_deployed is True self.parameters._contract_address = None assert self.parameters.is_contract_deployed is False assert self.parameters.registration_end_time == datetime.datetime.strptime( "01 01 2020 00:02", "%d %m %Y %H:%M") assert self.parameters.inactivity_timeout == 30 assert self.parameters.agent_location == { "location": Location(latitude=51.5194, longitude=0.1270) } assert self.parameters.set_service_data == { "key": "tac", "value": "v1" } assert self.parameters.remove_service_data == {"key": "tac"} assert self.parameters.simple_service_data == {"tac": "v1"}
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", dialogue_reference=self.oef_search_dialogues. new_self_initiated_dialogue_reference(), service_description=service_description, ) message.counterparty = SOEFConnection.connection_id.latest sending_dialogue = self.oef_search_dialogues.update(message) assert sending_dialogue is None message.sender = self.crypto.address envelope = Envelope( to=message.counterparty, sender=message.sender, protocol_id=message.protocol_id, message=message, ) with pytest.raises(ValueError): await self.connection.send(envelope)
def test_generic_command(self): """Test generic command.""" agent_location = Location(*self.LOCATION) agent = Instance(agent_location) agent.start() try: agent.generic_command("set_service_key", { "key": "test", "value": "test" }) envelope = agent.get() assert (envelope.message.performative == OefSearchMessage.Performative.SUCCESS) ET.fromstring( envelope.message.agents_info.body["response"]["content"]) agent.generic_command("bad_command") envelope = agent.get() assert (envelope.message.performative == OefSearchMessage.Performative.OEF_ERROR) finally: agent.stop()
async def test_unregister_service(self): """Test unregister service.""" agent_location = Location(52.2057092, 2.1183431) service_instance = {"location": agent_location} service_description = Description( service_instance, data_model=models.AGENT_LOCATION_MODEL) message, _ = self.oef_search_dialogues.create( counterparty=str(SOEFConnection.connection_id.to_any()), performative=OefSearchMessage.Performative.UNREGISTER_SERVICE, service_description=service_description, ) envelope = Envelope( to=message.to, sender=message.sender, message=message, ) with patch.object( self.connection.channel, "_request_text", make_async("<response><message>Goodbye!</message></response>"), ): await self.connection.send(envelope) assert self.connection.channel.unique_page_address is None
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, sending_dialogue = self.oef_search_dialogues.create( counterparty=str(self.connection.connection_id), performative=OefSearchMessage.Performative.SEARCH_SERVICES, query=search_query, ) self.multiplexer.put( Envelope( to=oef_search_request.to, sender=oef_search_request.sender, protocol_id=oef_search_request.protocol_id, message=oef_search_request, )) envelope = self.multiplexer.get(block=True, timeout=5.0) oef_search_response = envelope.message 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 == ()
def test_ping(self): """Test ping command.""" agent_location = Location(*self.LOCATION) agent = Instance(agent_location) agent.start() try: service_description = Description({}, data_model=models.PING_MODEL) message, _ = agent.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=agent.crypto.address, message=message, ) logger.info("Pinging") agent.multiplexer.put(envelope) time.sleep(3) assert agent.multiplexer.in_queue.empty() finally: agent.stop()
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) request_id = 1 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, ) search_request = OefSearchMessage( performative=OefSearchMessage.Performative.SEARCH_SERVICES, dialogue_reference=(str(request_id), ""), query=search_query, ) self.multiplexer.put( Envelope( to=DEFAULT_OEF, sender=FETCHAI_ADDRESS_ONE, protocol_id=OefSearchMessage.protocol_id, message=OefSearchSerializer().encode(search_request), )) envelope = self.multiplexer.get(block=True, timeout=5.0) search_result = OefSearchSerializer().decode(envelope.message) print("HERE:" + str(search_result)) assert (search_result.performative == OefSearchMessage.Performative.SEARCH_RESULT) assert search_result.dialogue_reference[0] == str(request_id) assert search_result.agents == ()
def __init__(self, **kwargs): """Instantiate the game class.""" self._expected_version_id = kwargs.pop("expected_version_id", "") # type: str self._expected_controller_addr = kwargs.pop( "expected_controller_addr", None) # type: Optional[str] self._search_query = kwargs.pop("search_query", DEFAULT_SEARCH_QUERY) location = kwargs.pop("location", DEFAULT_LOCATION) self._agent_location = Location(latitude=location["latitude"], longitude=location["longitude"]) self._radius = kwargs.pop("search_radius", DEFAULT_SEARCH_RADIUS) ledger_id = kwargs.pop("ledger_id", None) self._is_using_contract = kwargs.pop("is_using_contract", False) # type: bool super().__init__(**kwargs) self._phase = Phase.PRE_GAME self._conf = None # type: Optional[Configuration] self._contract_address = None # type: Optional[str] self._tac_dialogue = None # type: Optional[TacDialogue] self._state_update_dialogue = None # type: Optional[StateUpdateDialogue] self._ledger_id = (ledger_id if ledger_id is not None else self.context.default_ledger_id)
def test_constraint(): """Test Constraint.""" c1 = Constraint("author", ConstraintType("==", "Stephen King")) c2 = Constraint("year", ConstraintType("within", (2000, 2010))) c3 = Constraint("author", ConstraintType("in", ("Stephen King", "J. K. Rowling"))) c4 = Constraint( "author", ConstraintType("not_in", ("Stephen King", "J. K. Rowling"))) c5 = Constraint("address", ConstraintType("distance", (Location(1.1, 2.2), 2.2))) book_1 = Description({ "author": "Stephen King", "year": 2005, "address": Location(1.1, 2.2) }) book_2 = Description({ "author": "George Orwell", "year": 1948, "address": Location(1.1, 2.2) }) assert c1.check(book_1) assert not c1.check(book_2) # empty description assert not c1.check(Description({})) # bad type assert not c1.check(Description({"author": 12})) # bad type assert not c2.check(Description({"author": 12})) assert c1.is_valid(generate_data_model("test", {"author": "some author"})) assert not c1.is_valid( generate_data_model("test", {"not_author": "some author"})) assert c1 == c1 assert c1 != c2 assert ( str(c1) == f"Constraint(attribute_name=author,constraint_type={c1.constraint_type})" ) assert ( str(c2) == f"Constraint(attribute_name=year,constraint_type={c2.constraint_type})" ) c1_pb = c1.encode() actual_c1 = Constraint.decode(c1_pb) assert actual_c1 == c1 c2_pb = c2.encode() actual_c2 = Constraint.decode(c2_pb) assert actual_c2 == c2 c3_pb = c3.encode() actual_c3 = Constraint.decode(c3_pb) assert actual_c3 == c3 c4_pb = c4.encode() actual_c4 = Constraint.decode(c4_pb) assert actual_c4 == c4 c5_pb = c5.encode() actual_c5 = Constraint.decode(c5_pb) assert actual_c5 == c5
def test_search_filters(self): """Test find agents near me with filter.""" agent_location = Location(*self.LOCATION) agent = Instance(agent_location) agent2 = Instance(agent_location) agent3 = Instance(agent_location) agent.start() agent2.start() agent3.start() try: agent2.register_personality_pieces(piece="genus", value="service") agent2.register_service_key(key="test", value="test") agent2.register_location(disclosure_accuracy="medium") agent3.register_personality_pieces(piece="genus", value="service") agent3.register_service_key(key="test", value="test") time.sleep(3) radius = 0.1 close_to_my_service = Constraint( "location", ConstraintType("distance", (agent_location, radius))) personality_filters = [ Constraint("genus", ConstraintType("==", "service")), ] service_key_filters = [ Constraint("test", ConstraintType("==", "test")), ] constraints = ([close_to_my_service] + personality_filters + service_key_filters) closeness_query = Query(constraints) logger.info( "Searching for agents in radius={} of myself at location=({},{}) with personality filters" .format( radius, agent_location.latitude, agent_location.longitude, )) message = agent.search(closeness_query) assert message.performative == OefSearchMessage.Performative.SEARCH_RESULT assert len(message.agents) >= 1 assert agent2.address in message.agents assert agent3.address in message.agents agent2_info = message.agents_info.get_info_for_agent( agent2.address) assert agent2_info assert "name" in agent2_info assert "location" in agent2_info assert agent2_info["genus"] == "service" agent3_info = message.agents_info.get_info_for_agent( agent3.address) assert agent3_info assert "name" in agent3_info assert "location" not in agent3_info assert agent3_info["genus"] == "service" finally: agent.stop() agent2.stop() agent3.stop()
def test_oef_constraint_types(self): """Test the constraint types of the OEF.""" with pytest.raises(ValueError): m_constraint = self.obj_transaltor.from_oef_constraint_type( ConstraintType(ConstraintTypes.EQUAL, "==")) eq = self.obj_transaltor.to_oef_constraint_type(m_constraint) assert eq.value == "==" m_constraint = ConstraintType(ConstraintTypes.NOT_EQUAL, "!=") neq = self.obj_transaltor.to_oef_constraint_type(m_constraint) m_constr = self.obj_transaltor.from_oef_constraint_type(neq) assert m_constraint == m_constr assert neq.value == "!=" m_constraint = ConstraintType(ConstraintTypes.LESS_THAN, "<") lt = self.obj_transaltor.to_oef_constraint_type(m_constraint) m_constr = self.obj_transaltor.from_oef_constraint_type(lt) assert m_constraint == m_constr assert lt.value == "<" m_constraint = ConstraintType(ConstraintTypes.LESS_THAN_EQ, "<=") lt_eq = self.obj_transaltor.to_oef_constraint_type(m_constraint) m_constr = self.obj_transaltor.from_oef_constraint_type(lt_eq) assert m_constraint == m_constr assert lt_eq.value == "<=" m_constraint = ConstraintType(ConstraintTypes.GREATER_THAN, ">") gt = self.obj_transaltor.to_oef_constraint_type(m_constraint) m_constr = self.obj_transaltor.from_oef_constraint_type(gt) assert m_constraint == m_constr assert gt.value == ">" m_constraint = ConstraintType(ConstraintTypes.GREATER_THAN_EQ, ">=") gt_eq = self.obj_transaltor.to_oef_constraint_type(m_constraint) m_constr = self.obj_transaltor.from_oef_constraint_type(gt_eq) assert m_constraint == m_constr assert gt_eq.value == ">=" m_constraint = ConstraintType("within", (-10.0, 10.0)) with_in = self.obj_transaltor.to_oef_constraint_type(m_constraint) m_constr = self.obj_transaltor.from_oef_constraint_type(with_in) assert m_constraint == m_constr assert with_in._value[0] <= 10 <= with_in._value[1] m_constraint = ConstraintType("in", [1, 2, 3]) in_set = self.obj_transaltor.to_oef_constraint_type(m_constraint) m_constr = self.obj_transaltor.from_oef_constraint_type(in_set) assert m_constraint == m_constr assert 2 in in_set._value m_constraint = ConstraintType("not_in", {"C", "Java", "Python"}) not_in = self.obj_transaltor.to_oef_constraint_type(m_constraint) m_constr = self.obj_transaltor.from_oef_constraint_type(not_in) assert m_constraint == m_constr assert "C++" not in not_in._value location = Location(47.692180, 10.039470) distance_float = 0.2 m_constraint = ConstraintType("distance", (location, distance_float)) distance = self.obj_transaltor.to_oef_constraint_type(m_constraint) m_constr = self.obj_transaltor.from_oef_constraint_type(distance) assert m_constraint == m_constr assert (distance.center == self.obj_transaltor.to_oef_location(location) and distance.distance == distance_float) with pytest.raises(ValueError): m_constraint = ConstraintType(ConstraintTypes.EQUAL, "foo") with mock.patch.object(m_constraint, "type", return_value="unknown_constraint_type"): eq = self.obj_transaltor.to_oef_constraint_type(m_constraint) with pytest.raises(ValueError): self.obj_transaltor.from_oef_constraint_expr( oef_constraint_expr=cast(ConstraintExpr, DummyConstrainExpr()))
def test_soef(): """Perform tests over real network.""" # First run OEF in a separate terminal: python scripts/oef/launch.py -c ./scripts/oef/launch_config.json crypto = FetchAICrypto() identity = Identity("", address=crypto.address) # create the connection and multiplexer objects configuration = ConnectionConfig( api_key="TwiCIriSl0mLahw17pyqoA", soef_addr="soef.fetch.ai", soef_port=9002, restricted_to_protocols={ PublicId.from_str("fetchai/oef_search:0.3.0") }, connection_id=SOEFConnection.connection_id, ) soef_connection = SOEFConnection( configuration=configuration, identity=identity, ) multiplexer = Multiplexer([soef_connection]) try: # Set the multiplexer running in a different thread t = Thread(target=multiplexer.connect) t.start() wait_for_condition(lambda: multiplexer.is_connected, timeout=5) # register an agent with location 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=OefSearchMessage.Performative.REGISTER_SERVICE, service_description=service_description, ) envelope = Envelope( to="soef", sender=crypto.address, protocol_id=message.protocol_id, message=message, ) logger.info("Registering agent at location=({},{}) by agent={}".format( agent_location.latitude, agent_location.longitude, crypto.address, )) multiplexer.put(envelope) # register personality pieces service_instance = {"piece": "genus", "value": "service"} service_description = Description( service_instance, data_model=models.AGENT_PERSONALITY_MODEL) message = OefSearchMessage( performative=OefSearchMessage.Performative.REGISTER_SERVICE, service_description=service_description, ) envelope = Envelope( to="soef", sender=crypto.address, protocol_id=message.protocol_id, message=message, ) logger.info("Registering agent personality") multiplexer.put(envelope) # register service key service_instance = {"key": "test", "value": "test"} service_description = Description( service_instance, data_model=models.SET_SERVICE_KEY_MODEL) message = OefSearchMessage( performative=OefSearchMessage.Performative.REGISTER_SERVICE, service_description=service_description, ) envelope = Envelope( to="soef", sender=crypto.address, protocol_id=message.protocol_id, message=message, ) logger.info("Registering agent service key") multiplexer.put(envelope) # find agents near me radius = 0.1 close_to_my_service = Constraint( "location", ConstraintType("distance", (agent_location, radius))) closeness_query = Query([close_to_my_service], model=models.AGENT_LOCATION_MODEL) message = OefSearchMessage( performative=OefSearchMessage.Performative.SEARCH_SERVICES, query=closeness_query, ) envelope = Envelope( to="soef", sender=crypto.address, protocol_id=message.protocol_id, message=message, ) logger.info( "Searching for agents in radius={} of myself at location=({},{})". format( radius, agent_location.latitude, agent_location.longitude, )) multiplexer.put(envelope) wait_for_condition(lambda: not multiplexer.in_queue.empty(), timeout=20) # check for search results envelope = multiplexer.get() message = envelope.message assert len(message.agents) >= 0 # find agents near me with filter radius = 0.1 close_to_my_service = Constraint( "location", ConstraintType("distance", (agent_location, radius))) personality_filters = [ Constraint("genus", ConstraintType("==", "vehicle")), Constraint("classification", ConstraintType("==", "mobility.railway.train")), ] service_key_filters = [ Constraint("test", ConstraintType("==", "test")), ] closeness_query = Query([close_to_my_service] + personality_filters + service_key_filters) message = OefSearchMessage( performative=OefSearchMessage.Performative.SEARCH_SERVICES, query=closeness_query, ) envelope = Envelope( to="soef", sender=crypto.address, protocol_id=message.protocol_id, message=message, ) logger.info( "Searching for agents in radius={} of myself at location=({},{}) with personality filters" .format( radius, agent_location.latitude, agent_location.longitude, )) time.sleep(3) # cause requests rate limit on server :( multiplexer.put(envelope) wait_for_condition(lambda: not multiplexer.in_queue.empty(), timeout=20) envelope = multiplexer.get() message = envelope.message assert len(message.agents) >= 0 # test ping command service_description = Description({}, data_model=models.PING_MODEL) message = OefSearchMessage( performative=OefSearchMessage.Performative.REGISTER_SERVICE, service_description=service_description, ) envelope = Envelope( to="soef", sender=crypto.address, protocol_id=message.protocol_id, message=message, ) logger.info("Registering agent service key") multiplexer.put(envelope) time.sleep(3) assert multiplexer.in_queue.empty() finally: # Shut down the multiplexer multiplexer.disconnect() t.join()
def __init__(self, **kwargs: Any) -> None: """Initialize the strategy of the agent.""" ledger_id = kwargs.pop("ledger_id", None) self._token_type = kwargs.pop("token_type", DEFAULT_TOKEN_TYPE) enforce(self._token_type in [1, 2], "Token type must be 1 (NFT) or 2 (FT)") self._nb_tokens = kwargs.pop("nb_tokens", DEFAULT_NB_TOKENS) self._token_ids = kwargs.pop("token_ids", None) self._mint_quantities = kwargs.pop("mint_quantities", DEFAULT_MINT_QUANTITIES) enforce( len(self._mint_quantities) == self._nb_tokens, "Number of tokens must match mint quantities array size.", ) if self._token_type == 1: enforce( all(quantity == 1 for quantity in self._mint_quantities), "NFTs must have a quantity of 1", ) self._contract_address = kwargs.pop("contract_address", None) enforce( (self._token_ids is None and self._contract_address is None) or (self._token_ids is not None and self._contract_address is not None), "Either provide contract address and token ids or provide neither.", ) self.from_supply = kwargs.pop("from_supply", DEFAULT_FROM_SUPPLY) self.to_supply = kwargs.pop("to_supply", DEFAULT_TO_SUPPLY) self.value = kwargs.pop("value", DEFAULT_VALUE) location = kwargs.pop("location", DEFAULT_LOCATION) self._agent_location = { "location": Location(latitude=location["latitude"], longitude=location["longitude"]) } self._set_service_data = kwargs.pop("service_data", DEFAULT_SERVICE_DATA) enforce( len(self._set_service_data) == 2 and "key" in self._set_service_data and "value" in self._set_service_data, "service_data must contain keys `key` and `value`", ) self._remove_service_data = {"key": self._set_service_data["key"]} self._simple_service_data = { self._set_service_data["key"]: self._set_service_data["value"] } self._gas = kwargs.pop("gas", DEFAULT_GAS) super().__init__(**kwargs) self._ledger_id = (ledger_id if ledger_id is not None else self.context.default_ledger_id) self._contract_id = str(ERC1155Contract.contract_id) self.is_behaviour_active = True self._is_contract_deployed = self._contract_address is not None self._is_tokens_created = self._token_ids is not None self._is_tokens_minted = self._token_ids is not None if self._token_ids is None: self._token_ids = ERC1155Contract.generate_token_ids( token_type=self._token_type, nb_tokens=self._nb_tokens)
def test_soef(): # First run OEF in a separate terminal: python scripts/oef/launch.py -c ./scripts/oef/launch_config.json crypto = FetchAICrypto() # create the connection and multiplexer objects soef_connection = SOEFConnection( api_key="TwiCIriSl0mLahw17pyqoA", soef_addr="soef.fetch.ai", soef_port=9002, address=crypto.address, ) multiplexer = Multiplexer([soef_connection]) try: # Set the multiplexer running in a different thread t = Thread(target=multiplexer.connect) t.start() time.sleep(3.0) # register a service with location attr_service_name = Attribute("service_name", str, True, "The name of the service.") attr_location = Attribute( "location", Location, True, "The location where the service is provided.") service_location_model = DataModel( "location_service", [attr_service_name, attr_location], "A data model to describe location of a service.", ) service_name = "train" service_location = Location(52.2057092, 2.1183431) service_instance = { "service_name": service_name, "location": service_location } service_description = Description(service_instance, data_model=service_location_model) message = OefSearchMessage( performative=OefSearchMessage.Performative.REGISTER_SERVICE, service_description=service_description, ) message_b = OefSearchSerializer().encode(message) envelope = Envelope( to="soef", sender=crypto.address, protocol_id=ProtocolId.from_str("fetchai/oef_search:0.1.0"), message=message_b, ) logger.info( "Registering service={} at location=({},{}) by agent={}".format( service_name, service_location.latitude, service_location.longitude, crypto.address, )) multiplexer.put(envelope) # find agents near the previously registered service radius = 0.1 matches_my_service_name = Constraint( "service_name", ConstraintType("==", service_name)) close_to_my_service = Constraint( "location", ConstraintType("distance", (service_location, radius))) closeness_query = Query([matches_my_service_name, close_to_my_service], model=service_location_model) message = OefSearchMessage( performative=OefSearchMessage.Performative.SEARCH_SERVICES, query=closeness_query, ) message_b = OefSearchSerializer().encode(message) envelope = Envelope( to="soef", sender=crypto.address, protocol_id=ProtocolId.from_str("fetchai/oef_search:0.1.0"), message=message_b, ) logger.info( "Searching for agents in radius={} of service={} at location=({},{})" .format( radius, service_name, service_location.latitude, service_location.longitude, )) multiplexer.put(envelope) time.sleep(4.0) # check for search results envelope = multiplexer.get() message = OefSearchSerializer().decode(envelope.message) assert len(message.agents) >= 0 finally: # Shut down the multiplexer multiplexer.disconnect() t.join()
async def test_find_around_me(self): """Test internal method find around me.""" agent_location = Location(52.2057092, 2.1183431) radius = 0.1 close_to_my_service = Constraint( "location", ConstraintType("distance", (agent_location, radius))) personality_filters = [ Constraint("genus", ConstraintType("==", "vehicle")), Constraint("classification", ConstraintType("==", "mobility.railway.train")), ] service_key_filters = [ Constraint("custom_key", ConstraintType("==", "custom_value")), ] closeness_query = Query([close_to_my_service] + personality_filters + service_key_filters) message_1, sending_dialogue = self.oef_search_dialogues.create( counterparty=str(SOEFConnection.connection_id.to_any()), performative=OefSearchMessage.Performative.SEARCH_SERVICES, query=closeness_query, ) internal_dialogue_1 = self.connection.channel.oef_search_dialogues.update( message_1) assert internal_dialogue_1 is not None message_2, sending_dialogue = self.oef_search_dialogues.create( counterparty=str(SOEFConnection.connection_id.to_any()), performative=OefSearchMessage.Performative.SEARCH_SERVICES, query=closeness_query, ) internal_dialogue_2 = self.connection.channel.oef_search_dialogues.update( message_2) assert internal_dialogue_2 is not None message_3, sending_dialogue = self.oef_search_dialogues.create( counterparty=str(SOEFConnection.connection_id.to_any()), performative=OefSearchMessage.Performative.SEARCH_SERVICES, query=closeness_query, ) internal_dialogue_3 = self.connection.channel.oef_search_dialogues.update( message_3) assert internal_dialogue_3 is not None with patch.object( self.connection.channel, "_request_text", new_callable=MagicMock, side_effect=[ wrap_future(self.search_empty_response), wrap_future(self.search_success_response), wrap_future(self.search_fail_response), ], ): await self.connection.channel._find_around_me_handle_requet( message_1, internal_dialogue_1, 1, {}) await self.connection.channel._find_around_me_handle_requet( message_2, internal_dialogue_2, 1, {}) with pytest.raises(SOEFException, match=r"`find_around_me` error: .*"): await self.connection.channel._find_around_me_handle_requet( message_3, internal_dialogue_3, 1, {})
def test_constraint_type(): """Test ConstraintType.""" constraint_type_values = { "int": 12, "bool": True, "float": 10.4, "str": "some_string", "location": Location(1.1, 2.2), } constraint_type_types = { "int": int, "bool": bool, "float": float, "str": str, "location": Location, } to_check = { "int": 13, "bool": False, "float": 9.3, "str": "some_other_string", "location": Location(1.2, 2.3), } # = and != for constraint_types_type in [ ConstraintTypes.EQUAL, ConstraintTypes.NOT_EQUAL ]: for allowed_type in ["int", "bool", "float", "str"]: constraint_type = ConstraintType( constraint_types_type, constraint_type_values[allowed_type]) constraint_type.is_valid( Attribute("test", constraint_type_types[allowed_type], True)) constraint_type.check(to_check[allowed_type]) assert constraint_type == ConstraintType( constraint_types_type, constraint_type_values[allowed_type]) assert ( str(constraint_type) == f"ConstraintType(value={constraint_type_values[allowed_type]},type={constraint_types_type})" ) constraint_type_pb = constraint_type.encode() actual_constraint_type = ConstraintType.decode( constraint_type_pb, "relation") assert actual_constraint_type == constraint_type # < and <= and > and >= for constraint_types_type in [ ConstraintTypes.LESS_THAN, ConstraintTypes.LESS_THAN_EQ, ConstraintTypes.GREATER_THAN, ConstraintTypes.GREATER_THAN_EQ, ]: for allowed_type in ["int", "float", "str"]: constraint_type = ConstraintType( constraint_types_type, constraint_type_values[allowed_type]) constraint_type.is_valid( Attribute("test", constraint_type_types[allowed_type], True)) constraint_type.check(to_check[allowed_type]) assert constraint_type == ConstraintType( constraint_types_type, constraint_type_values[allowed_type]) assert ( str(constraint_type) == f"ConstraintType(value={constraint_type_values[allowed_type]},type={constraint_types_type})" ) constraint_type_pb = constraint_type.encode() actual_constraint_type = ConstraintType.decode( constraint_type_pb, "relation") assert actual_constraint_type == constraint_type # within constraint_type_values = { "int": (1, 2), "float": (2.4, 5.4), "str": ("str_1", "str_2"), "location": (Location(1.1, 2.2), Location(1.2, 5.2)), } constraint_type_types = { "int": int, "float": float, "str": str, "location": Location, } to_check = { "int": 13, "float": 9.3, "str": "some_other_string", "location": Location(1.2, 2.3), } for range_constraint_type in ["int", "float", "str"]: # location is not working constraint_type = ConstraintType( ConstraintTypes.WITHIN, constraint_type_values[range_constraint_type]) constraint_type.is_valid( Attribute("test", constraint_type_types[range_constraint_type], True)) constraint_type.check(to_check[range_constraint_type]) assert constraint_type == ConstraintType( ConstraintTypes.WITHIN, constraint_type_values[range_constraint_type]) assert ( str(constraint_type) == f"ConstraintType(value={constraint_type_values[range_constraint_type]},type=within)" ) constraint_type_pb = constraint_type.encode() actual_constraint_type = ConstraintType.decode(constraint_type_pb, "range") assert actual_constraint_type == constraint_type # in and not_in constraint_type_values = { "int": (1, 2), "bool": (True, False), "float": (2.4, 5.4), "str": ("str_1", "str_2"), "location": (Location(1.1, 2.2), Location(1.2, 5.2)), } constraint_type_types = { "int": int, "bool": bool, "float": float, "str": str, "location": Location, } to_check = { "int": 13, "bool": False, "float": 9.3, "str": "some_other_string", "location": Location(1.2, 2.3), } for constraint_types_type in [ConstraintTypes.IN, ConstraintTypes.NOT_IN]: for constraint_set in ["int", "bool", "float", "str", "location"]: constraint_type = ConstraintType( constraint_types_type, constraint_type_values[constraint_set]) constraint_type.is_valid( Attribute("test", constraint_type_types[constraint_set], True)) constraint_type.check(to_check[constraint_set]) assert constraint_type == ConstraintType( constraint_types_type, constraint_type_values[constraint_set]) assert ( str(constraint_type) == f"ConstraintType(value={constraint_type_values[constraint_set]},type={constraint_types_type})" ) constraint_type_pb = constraint_type.encode() actual_constraint_type = ConstraintType.decode( constraint_type_pb, "set") assert actual_constraint_type == constraint_type # distance constraint_location = (Location(1.1, 2.2), 2.2) constraint_type_distance = ConstraintType(ConstraintTypes.DISTANCE, constraint_location) constraint_type_distance.is_valid(Attribute("test", int, True)) constraint_type_distance.check(Location(1.1, 2.2)) assert constraint_type_distance == ConstraintType(ConstraintTypes.DISTANCE, constraint_location) constraint_type_distance_pb = constraint_type_distance.encode() actual_constraint_type_distance = ConstraintType.decode( constraint_type_distance_pb, "distance") assert actual_constraint_type_distance == constraint_type_distance # failures with pytest.raises(ValueError): ConstraintType("something", [Location(1.1, 2.2), 2.2]).is_valid( Attribute("test", int, True)) with pytest.raises(AEAEnforceError, match=""): ConstraintType(ConstraintTypes.GREATER_THAN, str) list_value = [1, 2] set_value = {1, 2} list_location = [Location(1.1, 2.2), 2.2] with pytest.raises(AEAEnforceError, match=f"Expected tuple, got {type(list_value)}"): ConstraintType(ConstraintTypes.WITHIN, list_value) with pytest.raises(AEAEnforceError, match=f"Expected tuple, got {type(list_value)}"): ConstraintType(ConstraintTypes.IN, list_value) with pytest.raises(AEAEnforceError, match=f"Expected tuple, got {type(set_value)}"): ConstraintType(ConstraintTypes.IN, set_value) with pytest.raises(AEAEnforceError, match=f"Expected tuple, got {type(list_value)}"): ConstraintType(ConstraintTypes.NOT_IN, list_value) with pytest.raises(AEAEnforceError, match=f"Expected tuple, got {type(set_value)}"): ConstraintType(ConstraintTypes.NOT_IN, set_value) with pytest.raises(AEAEnforceError, match=f"Expected tuple, got {type(list_location)}"): ConstraintType(ConstraintTypes.DISTANCE, list_location) incorrect_category = "some_incorrect_category" with pytest.raises( ValueError, match= r"Incorrect category. Expected either of .* Found some_incorrect_category.", ): constraint_type_distance_pb = constraint_type_distance.encode() ConstraintType.decode(constraint_type_distance_pb, incorrect_category)
def __init__(self, **kwargs): """Instantiate the parameter class.""" ledger_id = kwargs.pop("ledger_id", None) self._contract_address = kwargs.pop( "contract_address", None ) # type: Optional[str] self._good_ids = kwargs.pop("good_ids", []) # type: List[int] self._currency_ids = kwargs.pop("currency_ids", []) # type: List[int] self._min_nb_agents = kwargs.pop( "min_nb_agents", DEFAULT_MIN_NB_AGENTS ) # type: int self._money_endowment = kwargs.pop( "money_endowment", DEFAULT_MONEY_ENDOWMENT ) # type: int self._nb_goods = kwargs.pop("nb_goods", DEFAULT_NB_GOODS) # type: int self._nb_currencies = kwargs.pop( "nb_currencies", DEFAULT_NB_CURRENCIES ) # type: int self._tx_fee = kwargs.pop("tx_fee", DEFAULT_TX_FEE) # type: int self._base_good_endowment = kwargs.pop( "base_good_endowment", DEFAULT_BASE_GOOD_ENDOWMENT ) # type: int self._lower_bound_factor = kwargs.pop( "lower_bound_factor", DEFAULT_LOWER_BOUND_FACTOR ) # type: int self._upper_bound_factor = kwargs.pop( "upper_bound_factor", DEFAULT_UPPER_BOUND_FACTOR ) # type: int registration_start_time = kwargs.pop( "registration_start_time", DEFAULT_REGISTRATION_START_TIME ) # type: str self._registration_start_time = datetime.datetime.strptime( registration_start_time, "%d %m %Y %H:%M" ) # type: datetime.datetime self._registration_timeout = kwargs.pop( "registration_timeout", DEFAULT_REGISTRATION_TIMEOUT ) # type: int self._item_setup_timeout = kwargs.pop( "item_setup_timeout", DEFAULT_ITEM_SETUP_TIMEOUT ) # type: int self._competition_timeout = kwargs.pop( "competition_timeout", DEFAULT_COMPETITION_TIMEOUT ) # type: int self._inactivity_timeout = kwargs.pop( "inactivity_timeout", DEFAULT_INACTIVITY_TIMEOUT ) # type: int self._whitelist = set(kwargs.pop("whitelist", [])) # type: Set[str] self._location = kwargs.pop("location", DEFAULT_LOCATION) self._service_data = kwargs.pop("service_data", DEFAULT_SERVICE_DATA) enforce( len(self._service_data) == 2 and "key" in self._service_data and "value" in self._service_data, "service_data must contain keys `key` and `value`", ) self._version_id = self._service_data["value"] # type: str self._agent_location = { "location": Location( latitude=self._location["latitude"], longitude=self._location["longitude"], ) } self._set_service_data = self._service_data self._remove_service_data = {"key": self._service_data["key"]} self._simple_service_data = { self._service_data["key"]: self._service_data["value"] } super().__init__(**kwargs) self._ledger_id = ( ledger_id if ledger_id is not None else self.context.default_ledger_id ) self._contract_id = str(CONTRACT_ID) self._currency_id_to_name = generate_currency_id_to_name( self.nb_currencies, self.currency_ids ) self._good_id_to_name = generate_good_id_to_name( self.nb_goods, self.good_ids, starting_index=1 ) self._registration_end_time = ( self._registration_start_time + datetime.timedelta(seconds=self._registration_timeout) ) self._start_time = self._registration_end_time + datetime.timedelta( seconds=self._item_setup_timeout ) self._end_time = self._start_time + datetime.timedelta( seconds=self._competition_timeout ) now = datetime.datetime.now() if now > self.registration_start_time: self.context.logger.warning( "TAC registration start time {} is in the past! Deregistering skill.".format( self.registration_start_time ) ) self.context.is_active = False else: self.context.logger.info( "TAC registation start time: {}, and registration end time: {}, and start time: {}, and end time: {}".format( self.registration_start_time, self.registration_end_time, self.start_time, self.end_time, ) ) self._check_consistency()
def from_oef_location(cls, oef_location: OEFLocation) -> Location: """From oef location to our location.""" return Location(latitude=oef_location.latitude, longitude=oef_location.longitude)
def __init__(self, **kwargs) -> None: """ Initialize the strategy of the agent. :param register_as: determines whether the agent registers as seller, buyer or both :param search_for: determines whether the agent searches for sellers, buyers or both :return: None """ ledger_id = kwargs.pop("ledger_id", None) currency_id = kwargs.pop("currency_id", None) self._is_ledger_tx = kwargs.pop("is_ledger_tx", DEFAULT_IS_LEDGER_TX) self._unit_price = kwargs.pop("unit_price", DEFAULT_UNIT_PRICE) self._service_id = kwargs.pop("service_id", DEFAULT_SERVICE_ID) location = kwargs.pop("location", DEFAULT_LOCATION) self._agent_location = { "location": Location(latitude=location["latitude"], longitude=location["longitude"]) } self._set_service_data = kwargs.pop("service_data", DEFAULT_SERVICE_DATA) enforce( len(self._set_service_data) == 2 and "key" in self._set_service_data and "value" in self._set_service_data, "service_data must contain keys `key` and `value`", ) self._remove_service_data = {"key": self._set_service_data["key"]} self._simple_service_data = { self._set_service_data["key"]: self._set_service_data["value"] } self._has_data_source = kwargs.pop("has_data_source", DEFAULT_HAS_DATA_SOURCE) data_for_sale_ordered = kwargs.pop("data_for_sale", DEFAULT_DATA_FOR_SALE) data_for_sale = { str(key): str(value) for key, value in data_for_sale_ordered.items() } super().__init__(**kwargs) self._ledger_id = (ledger_id if ledger_id is not None else self.context.default_ledger_id) if currency_id is None: currency_id = self.context.currency_denominations.get( self._ledger_id, None) enforce( currency_id is not None, f"Currency denomination for ledger_id={self._ledger_id} not specified.", ) self._currency_id = currency_id enforce( self.context.agent_addresses.get(self._ledger_id, None) is not None, "Wallet does not contain cryptos for provided ledger id.", ) self._data_for_sale = data_for_sale
def __init__(self, **kwargs: Any) -> None: """Initialize the strategy of the agent.""" self.price_per_data_batch = kwargs.pop("price_per_data_batch", DEFAULT_PRICE_PER_DATA_BATCH) self.batch_size = kwargs.pop("batch_size", DEFAULT_BATCH_SIZE) self.seller_tx_fee = kwargs.pop("seller_tx_fee", DEFAULT_SELLER_TX_FEE) self.buyer_tx_fee = kwargs.pop("buyer_tx_fee", DEFAULT_BUYER_TX_FEE) currency_id = kwargs.pop("currency_id", None) ledger_id = kwargs.pop("ledger_id", None) self._is_ledger_tx = kwargs.pop("is_ledger_tx", False) self._service_id = kwargs.pop("service_id", DEFAULT_SERVICE_ID) location = kwargs.pop("location", DEFAULT_LOCATION) self._agent_location = { "location": Location(latitude=location["latitude"], longitude=location["longitude"]) } self._set_personality_data = kwargs.pop("personality_data", DEFAULT_PERSONALITY_DATA) enforce( len(self._set_personality_data) == 2 and "piece" in self._set_personality_data and "value" in self._set_personality_data, "personality_data must contain keys `key` and `value`", ) self._set_classification = kwargs.pop("classification", DEFAULT_CLASSIFICATION) enforce( len(self._set_classification) == 2 and "piece" in self._set_classification and "value" in self._set_classification, "classification must contain keys `key` and `value`", ) self._set_service_data = kwargs.pop("service_data", DEFAULT_SERVICE_DATA) enforce( len(self._set_service_data) == 2 and "key" in self._set_service_data and "value" in self._set_service_data, "service_data must contain keys `key` and `value`", ) self._remove_service_data = {"key": self._set_service_data["key"]} self._simple_service_data = { self._set_service_data["key"]: self._set_service_data["value"] } super().__init__(**kwargs) self._ledger_id = (ledger_id if ledger_id is not None else self.context.default_ledger_id) if currency_id is None: currency_id = self.context.currency_denominations.get( self._ledger_id, None) enforce( currency_id is not None, f"Currency denomination for ledger_id={self._ledger_id} not specified.", ) self._currency_id = currency_id # loading ML dataset # (this could be parametrized) ( (self.train_x, self.train_y), (self.test_x, self.test_y), ) = keras.datasets.fashion_mnist.load_data()