コード例 #1
0
 def test_query_check(self):
     """Test that the query.check() method works."""
     attribute_foo = Attribute("foo", int, True, "a foo attribute.")
     attribute_bar = Attribute("bar", str, True, "a bar attribute.")
     data_model_foobar = DataModel(
         "foobar", [attribute_foo, attribute_bar], "A foobar data model."
     )
     description_foobar = Description(
         {"foo": 1, "bar": "baz"}, data_model=data_model_foobar
     )
     query = Query(
         [
             And(
                 [
                     Or(
                         [
                             Not(Constraint("foo", ConstraintType("==", 1))),
                             Not(Constraint("bar", ConstraintType("==", "baz"))),
                         ]
                     ),
                     Constraint("foo", ConstraintType("<", 2)),
                 ]
             )
         ],
         data_model_foobar,
     )
     assert not query.check(description=description_foobar)
コード例 #2
0
    def test_get_location_and_service_query(self):
        """Test the get_location_and_service_query method of the Strategy class."""
        query = self.strategy.get_location_and_service_query()

        assert type(query) == Query
        assert len(query.constraints) == 2
        assert query.model is None

        location_constraint = Constraint(
            "location",
            ConstraintType(
                "distance",
                (
                    Location(
                        latitude=self.location["latitude"],
                        longitude=self.location["longitude"],
                    ),
                    self.search_radius,
                ),
            ),
        )
        assert query.constraints[0] == location_constraint

        service_key_filter = Constraint(self.service_key,
                                        ConstraintType("==", self.search_for))
        assert query.constraints[1] == service_key_filter
コード例 #3
0
    def test_serialisation_fipa(self):
        """Tests a Value Error flag for wrong CFP query."""
        with pytest.raises(ValueError):
            msg = FipaMessage(
                performative=FipaMessage.Performative.CFP,
                message_id=1,
                dialogue_reference=(str(0), ""),
                target=0,
                query=Query([Constraint("something", ConstraintType(">", 1))]),
            )
            with mock.patch(
                "packages.fetchai.protocols.fipa.message.FipaMessage.Performative"
            ) as mock_performative_enum:
                mock_performative_enum.CFP.value = "unknown"
                FipaSerializer().encode(msg), "Raises Value Error"
        with pytest.raises(EOFError):
            cfp_msg = FipaMessage(
                message_id=1,
                dialogue_reference=(str(0), ""),
                target=0,
                performative=FipaMessage.Performative.CFP,
                query=Query([Constraint("something", ConstraintType(">", 1))]),
            )
            cfp_msg.set("query", "hello")
            fipa_msg = fipa_pb2.FipaMessage()
            fipa_msg.message_id = cfp_msg.message_id
            dialogue_reference = cast(Dict[str, str], cfp_msg.dialogue_reference)
            fipa_msg.dialogue_starter_reference = dialogue_reference[0]
            fipa_msg.dialogue_responder_reference = dialogue_reference[1]
            fipa_msg.target = cfp_msg.target
            performative = fipa_pb2.FipaMessage.Cfp_Performative()
            fipa_msg.cfp.CopyFrom(performative)
            fipa_bytes = fipa_msg.SerializeToString()

            # The encoded message is not a valid FIPA message.
            FipaSerializer().decode(fipa_bytes)
        with pytest.raises(ValueError):
            cfp_msg = FipaMessage(
                message_id=1,
                dialogue_reference=(str(0), ""),
                target=0,
                performative=FipaMessage.Performative.CFP,
                query=Query([Constraint("something", ConstraintType(">", 1))]),
            )
            with mock.patch(
                "packages.fetchai.protocols.fipa.message.FipaMessage.Performative"
            ) as mock_performative_enum:
                mock_performative_enum.CFP.value = "unknown"
                fipa_msg = fipa_pb2.FipaMessage()
                fipa_msg.message_id = cfp_msg.message_id
                dialogue_reference = cast(Dict[str, str], cfp_msg.dialogue_reference)
                fipa_msg.dialogue_starter_reference = dialogue_reference[0]
                fipa_msg.dialogue_responder_reference = dialogue_reference[1]
                fipa_msg.target = cfp_msg.target
                performative = fipa_pb2.FipaMessage.Cfp_Performative()
                fipa_msg.cfp.CopyFrom(performative)
                fipa_bytes = fipa_msg.SerializeToString()

                # The encoded message is not a FIPA message
                FipaSerializer().decode(fipa_bytes)
コード例 #4
0
    def test_query(self):
        """Test that the translation for the Query class works."""
        attribute_foo = Attribute("foo", int, True, "a foo attribute.")
        attribute_bar = Attribute("bar", str, True, "a bar attribute.")
        data_model_foobar = DataModel(
            "foobar", [attribute_foo, attribute_bar], "A foobar data model."
        )

        query = Query(
            [
                And(
                    [
                        Or(
                            [
                                Not(Constraint("foo", ConstraintType("==", 1))),
                                Not(Constraint("bar", ConstraintType("==", "baz"))),
                            ]
                        ),
                        Constraint("foo", ConstraintType("<", 2)),
                    ]
                )
            ],
            data_model_foobar,
        )

        oef_query = OEFObjectTranslator.to_oef_query(query)
        expected_query = OEFObjectTranslator.from_oef_query(oef_query)
        actual_query = query
        assert expected_query == actual_query
コード例 #5
0
    def test_pickable_query(self):
        """Test that an istance of the Query class is pickable."""
        attribute_foo = Attribute("foo", int, True, "a foo attribute.")
        attribute_bar = Attribute("bar", str, True, "a bar attribute.")
        data_model_foobar = DataModel(
            "foobar", [attribute_foo, attribute_bar], "A foobar data model."
        )

        query = Query(
            [
                And(
                    [
                        Or(
                            [
                                Not(Constraint("foo", ConstraintType("==", 1))),
                                Not(Constraint("bar", ConstraintType("==", "baz"))),
                            ]
                        ),
                        Constraint("foo", ConstraintType("<", 2)),
                    ]
                )
            ],
            data_model_foobar,
        )
        try:
            pickle.dumps(query)
        except Exception:
            pytest.fail("Error during pickling.")
コード例 #6
0
def test_constraints_and():
    """Test And."""
    and_expression = And([
        Constraint("number", ConstraintType(ConstraintTypes.LESS_THAN, 15)),
        Constraint("number", ConstraintType(ConstraintTypes.GREATER_THAN, 10)),
    ])
    and_expression.check_validity()
    assert and_expression.check(Description({"number": 12}))
    assert and_expression.is_valid(
        DataModel("some_name", [Attribute("number", int, True)]))
    and_expression_pb = and_expression.encode()
    actual_and_expression = And.decode(and_expression_pb)
    assert actual_and_expression == and_expression
コード例 #7
0
def test_constraints_or():
    """Test Or."""
    or_expression = Or([
        Constraint("number", ConstraintType(ConstraintTypes.EQUAL, 12)),
        Constraint("number", ConstraintType(ConstraintTypes.EQUAL, 13)),
    ])
    or_expression.check_validity()
    assert or_expression.check(Description({"number": 12}))
    assert or_expression.is_valid(
        DataModel("some_name", [Attribute("number", int, True)]))
    or_expression_pb = or_expression.encode()
    actual_or_expression = Or.decode(or_expression_pb)
    assert actual_or_expression == or_expression
コード例 #8
0
    def test_is_matching_supply(self):
        """Test the is_matching_supply method of the GenericStrategy class."""
        acceptable_constraint = Constraint(
            "seller_service", ConstraintType("==", "some_service"))
        matching_query = Query([acceptable_constraint])
        is_matching_supply = self.strategy.is_matching_supply(matching_query)
        assert is_matching_supply

        unacceptable_constraint = Constraint(
            "seller_service", ConstraintType("==", "some_other_service"))
        unmatching_query = Query([unacceptable_constraint])
        is_matching_supply = self.strategy.is_matching_supply(unmatching_query)
        assert not is_matching_supply
コード例 #9
0
def test_constraints_not():
    """Test Not."""
    not_expression = Not(
        And([
            Constraint("number", ConstraintType(ConstraintTypes.EQUAL, 12)),
            Constraint("number", ConstraintType(ConstraintTypes.EQUAL, 12)),
        ]))
    not_expression.check_validity()
    assert not_expression.check(Description({"number": 13}))
    assert not_expression.is_valid(
        DataModel("some_name", [Attribute("number", int, True)]))
    not_expression_pb = not_expression.encode()
    actual_not_expression = Not.decode(not_expression_pb)
    assert actual_not_expression == not_expression
コード例 #10
0
    async def test_search(self):
        """Test search."""
        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 = OefSearchMessage(
            performative=OefSearchMessage.Performative.SEARCH_SERVICES,
            dialogue_reference=self.oef_search_dialogues.new_self_initiated_dialogue_reference(),
            query=closeness_query,
        )
        message.counterparty = SOEFConnection.connection_id.latest
        sending_dialogue = self.oef_search_dialogues.update(message)
        assert sending_dialogue is not None
        envelope = Envelope(
            to=message.counterparty,
            sender=self.crypto.address,
            protocol_id=message.protocol_id,
            message=message,
        )

        with patch.object(
            self.connection.channel,
            "_request_text",
            make_async(self.search_success_response),
        ):
            await self.connection.send(envelope)

        expected_envelope = await asyncio.wait_for(self.connection.receive(), timeout=1)
        assert expected_envelope
        message = expected_envelope.message
        assert len(message.agents) >= 1
        message = copy.deepcopy(expected_envelope.message)
        message.is_incoming = True  # TODO: fix
        message.counterparty = SOEFConnection.connection_id.latest  # TODO; fix
        receiving_dialogue = self.oef_search_dialogues.update(message)
        assert sending_dialogue == receiving_dialogue
コード例 #11
0
    def test_build_goods_query(self):
        """Test the build_goods_query of Helpers module."""
        good_ids = ["2", "3"]
        currency_id = "1"
        ledger_id = "some_ledger_id"
        is_searching_for_sellers = True

        attributes = [
            Attribute("2", int, True, "A good on offer."),
            Attribute("3", int, True, "A good on offer."),
            Attribute("ledger_id", str, True, "The ledger for transacting."),
            Attribute(
                "currency_id",
                str,
                True,
                "The currency for pricing and transacting the goods.",
            ),
            Attribute("price", int, False,
                      "The price of the goods in the currency."),
            Attribute(
                "fee",
                int,
                False,
                "The transaction fee payable by the buyer in the currency.",
            ),
            Attribute("nonce", str, False,
                      "The nonce to distinguish identical descriptions."),
        ]
        expected_data_model = DataModel(SUPPLY_DATAMODEL_NAME, attributes)

        expected_constraints = [
            Constraint("2", ConstraintType(">=", 1)),
            Constraint("3", ConstraintType(">=", 1)),
            Constraint("ledger_id", ConstraintType("==", ledger_id)),
            Constraint("currency_id", ConstraintType("==", currency_id)),
        ]

        actual_query = build_goods_query(good_ids, currency_id, ledger_id,
                                         is_searching_for_sellers)

        constraints = [(c.constraint_type.type, c.constraint_type.value)
                       for c in actual_query.constraints[0].constraints]
        for constraint in expected_constraints:
            assert (
                constraint.constraint_type.type,
                constraint.constraint_type.value,
            ) in constraints
        assert actual_query.model == expected_data_model
コード例 #12
0
        def test_search_count_increases(self):
            """Test that the search count increases."""
            request_id = 1
            search_query_empty_model = Query(
                [Constraint("foo", ConstraintType("==", "bar"))], model=None
            )
            search_request = OefSearchMessage(
                performative=OefSearchMessage.Performative.SEARCH_SERVICES,
                dialogue_reference=(str(request_id), ""),
                query=search_query_empty_model,
            )
            self.multiplexer.put(
                Envelope(
                    to=DEFAULT_OEF,
                    sender=self.crypto1.address,
                    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)
            assert (
                search_result.performative
                == OefSearchMessage.Performative.SEARCH_RESULT
            )
            assert search_result.dialogue_reference[0] == str(request_id)
            assert request_id and search_result.agents == ()
コード例 #13
0
        def test_search_services_with_query_with_model(self):
            """Test that a search services request can be sent correctly.

            In this test, the query has a simple data model.
            """
            request_id = 1
            data_model = DataModel("foobar", [Attribute("foo", str, True)])
            search_query = Query(
                [Constraint("foo", ConstraintType("==", "bar"))], 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=self.crypto1.address,
                    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)
            assert (
                search_result.performative
                == OefSearchMessage.Performative.SEARCH_RESULT
            )
            assert search_result.dialogue_reference[0] == str(request_id)
            assert search_result.agents == ()
コード例 #14
0
    def test_on_oef_error(self):
        """Test the oef error."""
        oef_connection = self.multiplexer1.connections[0]
        oef_channel = oef_connection.channel

        oef_channel.oef_msg_id += 1
        dialogue_reference = ("1", "2")
        query = Query(
            constraints=[Constraint("foo", ConstraintType("==", "bar"))], model=None,
        )
        dialogue = OefSearchDialogue(
            BaseDialogueLabel(dialogue_reference, "agent", "agent"),
            "agent",
            OefSearchDialogue.Role.OEF_NODE,
        )
        oef_search_msg = OefSearchMessage(
            performative=OefSearchMessage.Performative.SEARCH_SERVICES,
            dialogue_reference=dialogue_reference,
            query=query,
        )
        oef_search_msg.is_incoming = True
        oef_search_msg.counterparty = "agent"
        dialogue._incoming_messages = [oef_search_msg]
        oef_channel.oef_msg_id_to_dialogue[oef_channel.oef_msg_id] = dialogue
        oef_channel.on_oef_error(
            answer_id=oef_channel.oef_msg_id,
            operation=OEFErrorOperation.SEARCH_SERVICES,
        )
        envelope = self.multiplexer1.get(block=True, timeout=5.0)
        dec_msg = envelope.message
        assert dec_msg.dialogue_reference == dialogue_reference
        assert (
            dec_msg.performative is OefSearchMessage.Performative.OEF_ERROR
        ), "It should be an error message"
コード例 #15
0
ファイル: test_fipa.py プロジェクト: pbukva/agents-aea
def test_fipa_cfp_serialization_bytes():
    """Test that the serialization - deserialization for the 'fipa' protocol works."""
    query = Query([Constraint("something", ConstraintType(">", 1))])
    msg = FipaMessage(
        message_id=1,
        dialogue_reference=(str(0), ""),
        target=0,
        performative=FipaMessage.Performative.CFP,
        query=query,
    )
    msg.counterparty = "sender"
    msg_bytes = FipaSerializer().encode(msg)
    envelope = Envelope(
        to="receiver",
        sender="sender",
        protocol_id=FipaMessage.protocol_id,
        message=msg_bytes,
    )
    envelope_bytes = envelope.encode()

    actual_envelope = Envelope.decode(envelope_bytes)
    expected_envelope = envelope
    assert expected_envelope == actual_envelope

    actual_msg = FipaSerializer().decode(actual_envelope.message)
    actual_msg.counterparty = "sender"
    expected_msg = msg
    assert expected_msg == actual_msg

    deserialised_msg = FipaSerializer().decode(envelope.message)
    deserialised_msg.counterparty = "sender"
    assert msg.get("performative") == deserialised_msg.get("performative")
コード例 #16
0
    def test_search_no_filters(self):
        """Perform tests over real networ with no filters."""
        agent_location = Location(*self.LOCATION)
        agent = Instance(agent_location)
        agent2 = Instance(agent_location)

        try:
            agent.start()
            agent2.start()
            agent.wait_registered()
            agent2.wait_registered()
            time.sleep(2)
            # 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)

            # search for agents close to me
            message = agent.search(closeness_query)
            assert message.performative == OefSearchMessage.Performative.SEARCH_RESULT
            assert len(message.agents) >= 1

            # second message in a raw to check we dont hit limit
            message = agent.search(closeness_query)
            assert message.performative == OefSearchMessage.Performative.SEARCH_RESULT
            assert len(message.agents) >= 1

            assert agent2.address in message.agents
        finally:
            agent.stop()
            agent2.stop()
コード例 #17
0
        def test_search_services_with_query_with_model(self):
            """Test that a search services request can be sent correctly.

            In this test, the query has a simple data model.
            """
            data_model = DataModel("foobar", [Attribute("foo", str, True)])
            search_query = Query(
                [Constraint("foo", ConstraintType("==", "bar"))],
                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 == ()
コード例 #18
0
        def test_search_services_with_query_with_model(self):
            """Test that a search services request can be sent correctly.

            In this test, the query has a simple data model.
            """
            request_id = 2
            data_model = DataModel("foobar", [Attribute("foo", str, True)])
            search_query = Query(
                [Constraint("foo", ConstraintType("==", "bar"))], model=data_model
            )
            search_request = OEFMessage(
                type=OEFMessage.Type.SEARCH_SERVICES, id=request_id, query=search_query
            )
            self.multiplexer.put(
                Envelope(
                    to=DEFAULT_OEF,
                    sender=self.crypto1.address,
                    protocol_id=OEFMessage.protocol_id,
                    message=OEFSerializer().encode(search_request),
                )
            )

            envelope = self.multiplexer.get(block=True, timeout=5.0)
            search_result = OEFSerializer().decode(envelope.message)
            assert search_result.get("type") == OEFMessage.Type.SEARCH_RESULT
            assert search_result.get("id") == request_id
            assert search_result.get("agents") == []
コード例 #19
0
 def test_and_check(self):
     """Test the and().check function."""
     attribute_foo = Attribute("foo", int, True, "a foo attribute.")
     attribute_bar = Attribute("bar", str, True, "a bar attribute.")
     data_model_foobar = DataModel("foobar", [attribute_foo, attribute_bar],
                                   "A foobar data model.")
     description_foobar = Description({
         "foo": 1,
         "bar": "baz"
     },
                                      data_model=data_model_foobar)
     constraint = And([
         (Constraint("foo", ConstraintType("==", 1))),
         (Constraint("bar", ConstraintType("==", "baz"))),
     ])
     assert constraint.check(description_foobar)
コード例 #20
0
        def test_search_count_increases(self):
            """Test that the search count increases."""
            request_id = 1
            search_query_empty_model = Query(
                [Constraint("foo", ConstraintType("==", "bar"))], model=None
            )
            search_request = OEFMessage(
                type=OEFMessage.Type.SEARCH_SERVICES,
                id=request_id,
                query=search_query_empty_model,
            )
            self.multiplexer.put(
                Envelope(
                    to=DEFAULT_OEF,
                    sender=self.crypto1.address,
                    protocol_id=OEFMessage.protocol_id,
                    message=OEFSerializer().encode(search_request),
                )
            )

            envelope = self.multiplexer.get(block=True, timeout=5.0)
            search_result = OEFSerializer().decode(envelope.message)
            assert search_result.get("type") == OEFMessage.Type.SEARCH_RESULT
            assert search_result.get("id")
            assert request_id and search_result.get("agents") == []
コード例 #21
0
def test_cfp_serialization():
    """Test the serialization for 'cfp' speech-act works."""
    msg = MlTradeMessage(
        performative=MlTradeMessage.Performative.CFP,
        query=Query([Constraint("something", ConstraintType(">", 1))]),
    )
    msg.to = "receiver"
    envelope = Envelope(
        to=msg.to,
        sender="sender",
        message=msg,
    )
    envelope_bytes = envelope.encode()

    actual_envelope = Envelope.decode(envelope_bytes)
    expected_envelope = envelope
    assert expected_envelope.to == actual_envelope.to
    assert expected_envelope.sender == actual_envelope.sender
    assert (expected_envelope.protocol_specification_id ==
            actual_envelope.protocol_specification_id)
    assert expected_envelope.message != actual_envelope.message

    actual_msg = MlTradeMessage.serializer.decode(actual_envelope.message)
    actual_msg.to = actual_envelope.to
    actual_msg.sender = actual_envelope.sender
    expected_msg = msg
    assert expected_msg == actual_msg
コード例 #22
0
def test_search_services_serialization():
    """Test the serialization for 'search_services' speech-act works."""
    msg = OefSearchMessage(
        performative=OefSearchMessage.Performative.SEARCH_SERVICES,
        query=Query([Constraint("something", ConstraintType(">", 1))]),
    )
    msg.to = "receiver"
    envelope = Envelope(
        to=msg.to,
        sender="sender",
        protocol_id=OefSearchMessage.protocol_id,
        message=msg,
    )
    envelope_bytes = envelope.encode()

    actual_envelope = Envelope.decode(envelope_bytes)
    expected_envelope = envelope
    assert expected_envelope.to == actual_envelope.to
    assert expected_envelope.sender == actual_envelope.sender
    assert expected_envelope.protocol_id == actual_envelope.protocol_id
    assert expected_envelope.message != actual_envelope.message

    actual_msg = OefSearchMessage.serializer.decode(actual_envelope.message)
    actual_msg.to = actual_envelope.to
    actual_msg.sender = actual_envelope.sender
    expected_msg = msg
    assert expected_msg == actual_msg
コード例 #23
0
        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,
                    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 == ()
コード例 #24
0
def test_cfp_serialization():
    """Test that the serialization for the 'fipa' protocol works."""
    msg = FipaMessage(
        message_id=1,
        dialogue_reference=(str(0), ""),
        target=0,
        performative=FipaMessage.Performative.CFP,
        query=Query([Constraint("something", ConstraintType(">", 1))]),
    )
    msg.to = "receiver"
    envelope = Envelope(
        to=msg.to,
        sender="sender",
        protocol_id=FipaMessage.protocol_id,
        message=msg,
    )
    envelope_bytes = envelope.encode()

    actual_envelope = Envelope.decode(envelope_bytes)
    expected_envelope = envelope
    assert expected_envelope.to == actual_envelope.to
    assert expected_envelope.sender == actual_envelope.sender
    assert expected_envelope.protocol_id == actual_envelope.protocol_id
    assert expected_envelope.message != actual_envelope.message

    actual_msg = FipaMessage.serializer.decode(actual_envelope.message)
    actual_msg.to = actual_envelope.to
    actual_msg.sender = actual_envelope.sender
    expected_msg = msg
    assert expected_msg == actual_msg
コード例 #25
0
 def from_oef_constraint_expr(
     cls, oef_constraint_expr: OEFConstraintExpr
 ) -> ConstraintExpr:
     """From our query to OEF query."""
     if isinstance(oef_constraint_expr, OEFAnd):
         return And(
             [
                 cls.from_oef_constraint_expr(c)
                 for c in oef_constraint_expr.constraints
             ]
         )
     elif isinstance(oef_constraint_expr, OEFOr):
         return Or(
             [
                 cls.from_oef_constraint_expr(c)
                 for c in oef_constraint_expr.constraints
             ]
         )
     elif isinstance(oef_constraint_expr, OEFNot):
         return Not(cls.from_oef_constraint_expr(oef_constraint_expr.constraint))
     elif isinstance(oef_constraint_expr, OEFConstraint):
         constraint_type = cls.from_oef_constraint_type(
             oef_constraint_expr.constraint
         )
         return Constraint(oef_constraint_expr.attribute_name, constraint_type)
     else:
         raise ValueError("OEF Constraint not supported.")
コード例 #26
0
def test_query():
    """Test Query."""
    c1 = Constraint("author", ConstraintType("==", "Stephen King"))
    query = Query([c1])
    query.check_validity()
    assert query.check(
        Description({"author": "Stephen King", "year": 1991, "genre": "horror"})
    )
    assert query.is_valid(generate_data_model("test", {"author": "some author"}))

    with pytest.raises(ValueError, match=r"Constraints must be a list .*"):
        query = Query(c1)

    Query([]).check_validity()

    with pytest.raises(
        ValueError,
        match=r"Invalid input value for type 'Query': the query is not valid for the given data model.",
    ):
        Query(
            [c1], generate_data_model("test", {"notauthor": "not some author"})
        ).check_validity()

    assert Query([]) == Query([])

    mock = Mock()
    Query.encode(mock, Query([]))
    assert Query.decode(mock) == Query([])
コード例 #27
0
    def test_on_oef_error(self):
        """Test the oef error."""
        oef_connection = self.multiplexer1.connections[0]
        oef_channel = oef_connection.channel

        oef_channel.oef_msg_id += 1
        dialogue_reference = ("1", "")
        query = Query(
            constraints=[Constraint("foo", ConstraintType("==", "bar"))],
            model=None,
        )
        dialogues = oef_channel.oef_search_dialogues
        oef_search_msg = OefSearchMessage(
            performative=OefSearchMessage.Performative.SEARCH_SERVICES,
            dialogue_reference=dialogue_reference,
            query=query,
        )
        oef_search_msg.to = str(oef_connection.connection_id)
        oef_search_msg.sender = "agent"
        dialogue = dialogues.update(oef_search_msg)
        assert dialogue is not None
        oef_channel.oef_msg_id_to_dialogue[oef_channel.oef_msg_id] = dialogue
        oef_channel.on_oef_error(
            answer_id=oef_channel.oef_msg_id,
            operation=OEFErrorOperation.SEARCH_SERVICES,
        )
        envelope = self.multiplexer1.get(block=True, timeout=5.0)
        dec_msg = envelope.message
        assert dec_msg.dialogue_reference[0] == dialogue_reference[0]
        assert (dec_msg.performative is OefSearchMessage.Performative.OEF_ERROR
                ), "It should be an error message"
コード例 #28
0
def test_fipa_cfp_serialization():
    """Test that the serialization for the 'fipa' protocol works."""
    query = Query([Constraint("something", ConstraintType(">", 1))])

    msg = FIPAMessage(
        message_id=0,
        dialogue_reference=(str(0), ""),
        target=0,
        performative=FIPAMessage.Performative.CFP,
        query=query,
    )
    msg_bytes = FIPASerializer().encode(msg)
    envelope = Envelope(
        to="receiver",
        sender="sender",
        protocol_id=FIPAMessage.protocol_id,
        message=msg_bytes,
    )
    envelope_bytes = envelope.encode()

    actual_envelope = Envelope.decode(envelope_bytes)
    expected_envelope = envelope
    assert expected_envelope == actual_envelope

    actual_msg = FIPASerializer().decode(actual_envelope.message)
    expected_msg = msg
    assert expected_msg == actual_msg

    msg.set("query", "not_supported_query")
    with pytest.raises(ValueError, match="Query type not supported:"):
        FIPASerializer().encode(msg)
コード例 #29
0
    async def test_wrong_dialogue(self):
        """Test that at the beginning, the search request returns an empty search result."""
        query = Query(constraints=[Constraint("foo", ConstraintType("==", 1))],
                      model=None)

        # build and send the request
        search_services_request = OefSearchMessage(
            performative=OefSearchMessage.Performative.SEARCH_SERVICES,
            message_id=2,
            target=1,
            dialogue_reference=self.dialogues.
            new_self_initiated_dialogue_reference(),
            query=query,
        )
        search_services_request.to = str(OEFLocalConnection.connection_id)

        # the incorrect message cannot be sent into a dialogue, so this is omitted.

        search_services_request.sender = self.address_1
        envelope = Envelope(
            to=search_services_request.to,
            sender=search_services_request.sender,
            message=search_services_request,
        )
        with unittest.mock.patch.object(
                self.node,
                "_handle_oef_message",
                side_effect=self.node._handle_oef_message) as mock_handle:
            with unittest.mock.patch.object(self.node.logger,
                                            "warning") as mock_logger:
                self.multiplexer.put(envelope)
                wait_for_condition(lambda: mock_handle.called, timeout=1.0)
                mock_logger.assert_any_call(
                    AnyStringWith("Could not create dialogue for message="))
コード例 #30
0
        def test_search_services_with_query_without_model(self):
            """Test that a search services request can be sent correctly.

            In this test, the query has no data model.
            """
            request_id = 1
            search_query_empty_model = Query(
                [Constraint("foo", ConstraintType("==", "bar"))], model=None)
            search_request = OefSearchMessage(
                performative=OefSearchMessage.Performative.SEARCH_SERVICES,
                dialogue_reference=(str(request_id), ""),
                query=search_query_empty_model,
            )
            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)
            assert (search_result.performative ==
                    OefSearchMessage.Performative.SEARCH_RESULT)
            assert search_result.dialogue_reference[0] == str(request_id)
            assert request_id and search_result.agents == ()