Ejemplo n.º 1
0
def test_constraints_expression():
    """Test constraint expressions: And, Or, Not, Constraint."""
    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 = ConstraintExpr._encode(and_expression)
    actual_and_expression = ConstraintExpr._decode(and_expression_pb)
    assert actual_and_expression == and_expression

    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 = ConstraintExpr._encode(or_expression)
    actual_or_expression = ConstraintExpr._decode(or_expression_pb)
    assert actual_or_expression == or_expression

    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 = ConstraintExpr._encode(not_expression)
    actual_not_expression = ConstraintExpr._decode(not_expression_pb)
    assert actual_not_expression == not_expression

    # constraint
    constraint_expression = Constraint("author",
                                       ConstraintType("==", "Stephen King"))
    constraint_expression.check_validity()
    assert constraint_expression.check(Description({"author": "Stephen King"}))
    assert constraint_expression.is_valid(
        DataModel("some_name", [Attribute("author", str, True)]))
    constraint_expression_pb = ConstraintExpr._encode(constraint_expression)
    actual_constraint_expression = ConstraintExpr._decode(
        constraint_expression_pb)
    assert actual_constraint_expression == constraint_expression

    incorrect_expression = Location(1.1, 2.2)
    with pytest.raises(
            ValueError,
            match=
            f"Invalid expression type. Expected either of 'And', 'Or', 'Not', 'Constraint'. Found {type(incorrect_expression)}.",
    ):
        ConstraintExpr._encode(incorrect_expression)
Ejemplo n.º 2
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)
        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") == []
Ejemplo n.º 4
0
def test_generate_data_model():
    """Test model generated from description."""
    params = dict(name="test", type_=str, is_required=True)

    data_model = DataModel("test", [Attribute(**params)])

    assert generate_data_model("test", {"test": "str"}) == data_model
Ejemplo n.º 5
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
Ejemplo n.º 6
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.")
Ejemplo n.º 7
0
    def setup_class(cls):
        """Set up the test."""
        cls.node = LocalNode()
        cls.node.start()

        cls.address_1 = "address"
        cls.multiplexer = Multiplexer(
            [_make_local_connection(cls.address_1, cls.node,)]
        )

        cls.multiplexer.connect()

        # register a service.
        request_id = 1
        cls.data_model = DataModel("foobar", attributes=[])
        service_description = Description(
            {"foo": 1, "bar": "baz"}, data_model=cls.data_model
        )
        register_service_request = OefSearchMessage(
            performative=OefSearchMessage.Performative.REGISTER_SERVICE,
            dialogue_reference=(str(request_id), ""),
            service_description=service_description,
        )
        msg_bytes = OefSearchSerializer().encode(register_service_request)
        envelope = Envelope(
            to=DEFAULT_OEF,
            sender=cls.address_1,
            protocol_id=OefSearchMessage.protocol_id,
            message=msg_bytes,
        )
        cls.multiplexer.put(envelope)
Ejemplo n.º 8
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 == ()
Ejemplo n.º 9
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 == ()
Ejemplo n.º 10
0
 def from_oef_data_model(cls, oef_data_model: OEFDataModel) -> DataModel:
     """From an OEF data model to our data model."""
     attributes = [
         cls.from_oef_attribute(oef_attribute)
         for oef_attribute in oef_data_model.attribute_schemas
     ]
     return DataModel(oef_data_model.name, attributes, oef_data_model.description)
Ejemplo n.º 11
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 = OefSearchMessage(
                performative=OefSearchMessage.Performative.SEARCH_SERVICES,
                dialogue_reference=self.oef_search_dialogues.new_self_initiated_dialogue_reference(),
                query=search_query,
            )
            oef_search_request.counterparty = DEFAULT_OEF
            sending_dialogue = self.oef_search_dialogues.update(oef_search_request)
            self.multiplexer.put(
                Envelope(
                    to=DEFAULT_OEF,
                    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 = 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 == ()
Ejemplo n.º 12
0
def test_ml_messge_consistency():
    """Test the consistency of the message."""
    dm = DataModel("ml_datamodel", [Attribute("dataset_id", str, True)])
    query = Query([Constraint("dataset_id", ConstraintType("==", "fmnist"))], model=dm)
    msg = MlTradeMessage(performative=MlTradeMessage.Performative.CFP, query=query)
    with mock.patch.object(MlTradeMessage.Performative, "__eq__", return_value=False):
        assert not msg._is_consistent()
Ejemplo n.º 13
0
    async def test_bad_register_service(self):
        """Test register service fails on bad values provided."""
        bad_location_model = DataModel(
            "not_location_agent",
            [
                Attribute("non_location", Location, True,
                          "The location where the agent is.")
            ],
            "A data model to describe location of an agent.",
        )
        agent_location = Location(52.2057092, 2.1183431)
        service_instance = {"non_location": agent_location}
        service_description = Description(service_instance,
                                          data_model=bad_location_model)
        message = OefSearchMessage(
            performative=OefSearchMessage.Performative.REGISTER_SERVICE,
            service_description=service_description,
        )
        envelope = Envelope(
            to="soef",
            sender=self.crypto.address,
            protocol_id=message.protocol_id,
            message=message,
        )
        await self.connection.send(envelope)

        expected_envelope = await asyncio.wait_for(self.connection.receive(),
                                                   timeout=1)
        assert expected_envelope
        assert (expected_envelope.message.performative ==
                OefSearchMessage.Performative.OEF_ERROR)
Ejemplo n.º 14
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 == ()
Ejemplo n.º 15
0
 def test_build_goods_datamodel_demand(self):
     """Test the _build_goods_datamodel of Helpers module for a demand."""
     good_ids = ["1", "2"]
     is_supply = False
     attributes = [
         Attribute("1", int, True, "A good on offer."),
         Attribute("2", 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(DEMAND_DATAMODEL_NAME, attributes)
     actual_data_model = _build_goods_datamodel(good_ids, is_supply)
     assert actual_data_model == expected_data_model
Ejemplo n.º 16
0
    async def test_bad_register_service(self):
        """Test register service fails on bad values provided."""
        bad_location_model = DataModel(
            "not_location_agent",
            [
                Attribute("non_location", Location, True,
                          "The location where the agent is.")
            ],
            "A data model to describe location of an agent.",
        )
        agent_location = Location(52.2057092, 2.1183431)
        service_instance = {"non_location": agent_location}
        service_description = Description(service_instance,
                                          data_model=bad_location_model)
        message, sending_dialogue = 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,
            protocol_id=message.protocol_id,
            message=message,
        )
        await self.connection.send(envelope)

        expected_envelope = await asyncio.wait_for(self.connection.receive(),
                                                   timeout=1)
        assert expected_envelope
        assert (expected_envelope.message.performative ==
                OefSearchMessage.Performative.OEF_ERROR)
        message = expected_envelope.message
        receiving_dialogue = self.oef_search_dialogues.update(message)
        assert sending_dialogue == receiving_dialogue
Ejemplo n.º 17
0
    def setup(cls):
        """Setup the test class."""
        super().setup()
        cls.oef_search_handler = cast(
            OefSearchHandler, cls._skill.skill_context.handlers.oef_search)
        cls.strategy = cast(Strategy, cls._skill.skill_context.strategy)
        cls.logger = cls._skill.skill_context.logger

        cls.oef_search_dialogues = cast(
            OefSearchDialogues, cls._skill.skill_context.oef_search_dialogues)

        cls.data = b"some_body"
        cls.query = Query(
            [
                Constraint("some_attribute",
                           ConstraintType("==", "some_service"))
            ],
            DataModel(
                "some_name",
                [
                    Attribute("some_attribute", str, False,
                              "Some attribute descriptions.")
                ],
            ),
        )
        cls.mocked_description = Description({"foo1": 1, "bar1": 2})

        cls.list_of_messages = (DialogueMessage(
            OefSearchMessage.Performative.SEARCH_SERVICES,
            {"query": cls.query}), )
Ejemplo n.º 18
0
        def test_register_service(self):
            """Test that a register service request works correctly."""
            foo_datamodel = DataModel(
                "foo", [Attribute("bar", int, True, "A bar attribute.")])
            desc = Description({"bar": 1}, data_model=foo_datamodel)
            oef_search_registration = OefSearchMessage(
                performative=OefSearchMessage.Performative.REGISTER_SERVICE,
                dialogue_reference=self.oef_search_dialogues.
                new_self_initiated_dialogue_reference(),
                service_description=desc,
            )
            oef_search_registration.counterparty = str(
                self.connection.connection_id)
            sending_dialogue_1 = self.oef_search_dialogues.update(
                oef_search_registration)
            assert sending_dialogue_1 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_registration,
                ))
            time.sleep(0.5)

            oef_search_request = OefSearchMessage(
                performative=OefSearchMessage.Performative.SEARCH_SERVICES,
                dialogue_reference=self.oef_search_dialogues.
                new_self_initiated_dialogue_reference(),
                query=Query([Constraint("bar", ConstraintType("==", 1))],
                            model=foo_datamodel),
            )
            oef_search_request.counterparty = str(
                self.connection.connection_id)
            sending_dialogue_2 = self.oef_search_dialogues.update(
                oef_search_request)
            assert sending_dialogue_2 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 == sending_dialogue_2
            assert oef_search_response.agents == (
                FETCHAI_ADDRESS_ONE,
            ), "search_result.agents != [FETCHAI_ADDRESS_ONE] FAILED in test_oef/test_communication.py"
Ejemplo n.º 19
0
    def get_service_description(self) -> Description:
        """
        Get the service description.

        :return: a description of the offered services
        """
        dm = DataModel("ml_datamodel", [Attribute("dataset_id", str, True)])
        desc = Description({"dataset_id": self.dataset_id}, data_model=dm)
        return desc
Ejemplo n.º 20
0
    async def test_send_oef_message(self, pytestconfig, caplog):
        """Test the send oef message."""
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            oef_connection = _make_oef_connection(
                address=FETCHAI_ADDRESS_ONE,
                oef_addr="127.0.0.1",
                oef_port=10000,
            )
            await oef_connection.connect()
            oef_search_dialogues = OefSearchDialogues(FETCHAI_ADDRESS_ONE)
            msg = OefSearchMessage(
                performative=OefSearchMessage.Performative.OEF_ERROR,
                dialogue_reference=oef_search_dialogues.
                new_self_initiated_dialogue_reference(),
                oef_error_operation=OefSearchMessage.OefErrorOperation.
                SEARCH_SERVICES,
            )
            msg.to = str(oef_connection.connection_id)
            msg.sender = FETCHAI_ADDRESS_ONE
            envelope = Envelope(
                to=msg.to,
                sender=msg.sender,
                message=msg,
            )
            with caplog.at_level(logging.DEBUG,
                                 "aea.packages.fetchai.connections.oef"):
                await oef_connection.send(envelope)
                assert "Could not create dialogue for message=" in caplog.text

            data_model = DataModel("foobar",
                                   attributes=[Attribute("foo", str, True)])
            query = Query(
                constraints=[Constraint("foo", ConstraintType("==", "bar"))],
                model=data_model,
            )

            msg, sending_dialogue = oef_search_dialogues.create(
                counterparty=str(oef_connection.connection_id),
                performative=OefSearchMessage.Performative.SEARCH_SERVICES,
                query=query,
            )
            envelope = Envelope(
                to=msg.to,
                sender=msg.sender,
                message=msg,
            )
            await oef_connection.send(envelope)
            envelope = await oef_connection.receive()
            search_result = envelope.message
            response_dialogue = oef_search_dialogues.update(search_result)
            assert (search_result.performative ==
                    OefSearchMessage.Performative.SEARCH_RESULT)
            assert sending_dialogue == response_dialogue
            await asyncio.sleep(2.0)
            await oef_connection.disconnect()
Ejemplo n.º 21
0
 def test_pickable_data_model(self):
     """Test that an istance of the DataModel 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.")
     try:
         pickle.dumps(data_model_foobar)
     except Exception:
         pytest.fail("Error during pickling.")
Ejemplo n.º 22
0
 def test_data_model(self):
     """Test that the translation for the DataModel 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."
     )
     oef_data_model = OEFObjectTranslator.to_oef_data_model(data_model_foobar)
     expected_data_model = OEFObjectTranslator.from_oef_data_model(oef_data_model)
     actual_data_model = data_model_foobar
     assert expected_data_model == actual_data_model
Ejemplo n.º 23
0
    def get_service_query(self) -> Query:
        """
        Get the service query of the agent.

        :return: the query
        """
        dm = DataModel("ml_datamodel", [Attribute("dataset_id", str, True)])
        query = Query(
            [Constraint("dataset_id", ConstraintType("==", self._dataset_id))], model=dm
        )
        return query
Ejemplo n.º 24
0
 def test_not_check(self):
     """Test the not().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
     )
     no_constraint = Not(Constraint("foo", ConstraintType("==", 5)))
     assert no_constraint.check(description_foobar)
Ejemplo n.º 25
0
    def test__get_proposal_for_query(self):
        """Test the _get_proposal_for_query method of the Strategy class."""
        # setup
        is_seller = True
        mocked_query = Query(
            [
                Constraint("some_attribute_name",
                           ConstraintType("==", "some_value"))
            ],
            DataModel(
                "some_data_model_name",
                [
                    Attribute(
                        "some_attribute_name",
                        str,
                        False,
                        "Some attribute descriptions.",
                    )
                ],
            ),
        )

        proposal_1 = Description({
            "some_attribute_name": "some_value",
            "ledger_id": self.ledger_id,
            "price": 100,
            "currency_id": "1",
            "fee": 1,
            "nonce": self.nonce,
        })
        proposal_2 = Description({
            "some_attribute_name": "some_value",
            "ledger_id": self.ledger_id,
            "price": -100,
            "currency_id": "1",
            "fee": 2,
            "nonce": self.nonce,
        })
        mocked_candidate_proposals = [proposal_1, proposal_2]

        # operation
        with patch.object(
                self.strategy,
                "_generate_candidate_proposals",
                return_value=mocked_candidate_proposals,
        ) as mock_candid:
            actual_query = self.strategy._get_proposal_for_query(
                mocked_query, is_seller)

        # after
        mock_candid.assert_any_call(is_seller)
        assert actual_query in mocked_candidate_proposals
def test_oef_serialization():
    """Testing the serialization of the OEF."""
    foo_datamodel = DataModel(
        "foo", [Attribute("bar", int, True, "A bar attribute.")])
    desc = Description({"bar": 1}, data_model=foo_datamodel)
    msg = OEFMessage(
        type=OEFMessage.Type.REGISTER_SERVICE,
        id=1,
        service_description=desc,
        service_id="",
    )
    msg_bytes = OEFSerializer().encode(msg)
    assert len(msg_bytes) > 0
Ejemplo n.º 27
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
Ejemplo n.º 28
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
Ejemplo n.º 29
0
    async def test_send_oef_message(self, pytestconfig):
        """Test the send oef message."""
        oef_connection = _make_oef_connection(
            address=FETCHAI_ADDRESS_ONE, oef_addr="127.0.0.1", oef_port=10000,
        )
        oef_connection.loop = asyncio.get_event_loop()
        await oef_connection.connect()
        oef_search_dialogues = OefSearchDialogues("agent_address")
        msg = OefSearchMessage(
            performative=OefSearchMessage.Performative.OEF_ERROR,
            dialogue_reference=oef_search_dialogues.new_self_initiated_dialogue_reference(),
            oef_error_operation=OefSearchMessage.OefErrorOperation.SEARCH_SERVICES,
        )
        msg.counterparty = DEFAULT_OEF
        sending_dialogue = oef_search_dialogues.update(msg)
        envelope = Envelope(
            to=DEFAULT_OEF,
            sender=FETCHAI_ADDRESS_ONE,
            protocol_id=OefSearchMessage.protocol_id,
            message=msg,
        )
        with pytest.raises(ValueError):
            await oef_connection.send(envelope)

        data_model = DataModel("foobar", attributes=[Attribute("foo", str, True)])
        query = Query(
            constraints=[Constraint("foo", ConstraintType("==", "bar"))],
            model=data_model,
        )

        msg = OefSearchMessage(
            performative=OefSearchMessage.Performative.SEARCH_SERVICES,
            dialogue_reference=oef_search_dialogues.new_self_initiated_dialogue_reference(),
            query=query,
        )
        msg.counterparty = DEFAULT_OEF
        sending_dialogue = oef_search_dialogues.update(msg)
        envelope = Envelope(
            to=DEFAULT_OEF,
            sender=FETCHAI_ADDRESS_ONE,
            protocol_id=OefSearchMessage.protocol_id,
            message=msg,
        )
        await oef_connection.send(envelope)
        envelope = await oef_connection.receive()
        search_result = envelope.message
        response_dialogue = oef_search_dialogues.update(search_result)
        assert search_result.performative == OefSearchMessage.Performative.SEARCH_RESULT
        assert sending_dialogue == response_dialogue
        await asyncio.sleep(2.0)
        await oef_connection.disconnect()
Ejemplo n.º 30
0
    async def test_send_oef_message(self, pytestconfig):
        """Test the send oef message."""
        oef_connection = _make_oef_connection(
            address=FETCHAI_ADDRESS_ONE,
            oef_addr="127.0.0.1",
            oef_port=10000,
        )
        request_id = 1
        oef_connection.loop = asyncio.get_event_loop()
        await oef_connection.connect()
        msg = OefSearchMessage(
            performative=OefSearchMessage.Performative.OEF_ERROR,
            dialogue_reference=(str(request_id), ""),
            oef_error_operation=OefSearchMessage.OefErrorOperation.
            SEARCH_SERVICES,
        )
        msg_bytes = OefSearchSerializer().encode(msg)
        envelope = Envelope(
            to=DEFAULT_OEF,
            sender=FETCHAI_ADDRESS_ONE,
            protocol_id=OefSearchMessage.protocol_id,
            message=msg_bytes,
        )
        with pytest.raises(ValueError):
            await oef_connection.send(envelope)

        data_model = DataModel("foobar",
                               attributes=[Attribute("foo", str, True)])
        query = Query(
            constraints=[Constraint("foo", ConstraintType("==", "bar"))],
            model=data_model,
        )

        request_id += 1
        msg = OefSearchMessage(
            performative=OefSearchMessage.Performative.SEARCH_SERVICES,
            dialogue_reference=(str(request_id), ""),
            query=query,
        )
        msg_bytes = OefSearchSerializer().encode(msg)
        envelope = Envelope(
            to=DEFAULT_OEF,
            sender=FETCHAI_ADDRESS_ONE,
            protocol_id=OefSearchMessage.protocol_id,
            message=msg_bytes,
        )
        await oef_connection.send(envelope)
        search_result = await oef_connection.receive()
        assert isinstance(search_result, Envelope)
        await asyncio.sleep(2.0)
        await oef_connection.disconnect()