示例#1
0
def test_constraint():
    """Test Constraint."""
    c1 = Constraint("author", ConstraintType("==", "Stephen King"))
    c2 = Constraint("author", ConstraintType("in", ["Stephen King"]))
    book_1 = Description({
        "author": "Stephen King",
        "year": 1991,
        "genre": "horror"
    })
    book_2 = Description({
        "author": "George Orwell",
        "year": 1948,
        "genre": "horror"
    })
    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
示例#2
0
    def test_is_acceptable_proposal(self):
        """Test the is_acceptable_proposal method of the GenericStrategy class."""
        acceptable_description = Description({
            "ledger_id": self.ledger_id,
            "price": 150,
            "currency_id": self.currency_id,
            "service_id": self.service_id,
            "quantity": 10,
            "tx_nonce": "some_tx_nonce",
        })
        is_acceptable = self.strategy.is_acceptable_proposal(
            acceptable_description)
        assert is_acceptable

        unacceptable_description = Description({
            "ledger_id": self.ledger_id,
            "price": 250,
            "currency_id": self.currency_id,
            "service_id": self.service_id,
            "quantity": 10,
            "tx_nonce": "some_tx_nonce",
        })
        is_acceptable = self.strategy.is_acceptable_proposal(
            unacceptable_description)
        assert not is_acceptable
示例#3
0
def test_fipa_propose_serialization():
    """Test that the serialization for the 'fipa' protocol works."""
    proposal = [
        Description({"foo1": 1, "bar1": 2}),
        Description({"foo2": 1, "bar2": 2}),
    ]
    msg = FIPAMessage(
        message_id=0,
        dialogue_reference=(str(0), ""),
        target=0,
        performative=FIPAMessage.Performative.PROPOSE,
        proposal=proposal,
    )
    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

    p1 = actual_msg.get("proposal")
    p2 = expected_msg.get("proposal")
    assert p1[0].values == p2[0].values
    assert p1[1].values == p2[1].values
示例#4
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)
示例#5
0
    def setup(cls):
        """Setup the test class."""
        super().setup()
        cls.service_behaviour = cast(
            ServiceRegistrationBehaviour, cls._skill.skill_context.behaviours.service
        )
        cls.strategy = cast(Strategy, cls._skill.skill_context.strategy)
        cls.logger = cls._skill.skill_context.logger

        cls.mocked_description_1 = Description({"foo1": 1, "bar1": 2})
        cls.mocked_description_2 = Description({"foo2": 1, "bar2": 2})
示例#6
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
示例#7
0
    def test_propose(self):
        """Test that a Propose can be sent correctly."""
        propose_empty = FipaMessage(
            message_id=1,
            dialogue_reference=(str(0), ""),
            target=0,
            performative=FipaMessage.Performative.PROPOSE,
            proposal=Description({"foo": "bar"}),
        )
        propose_empty.to = FETCHAI_ADDRESS_TWO
        propose_empty.sender = FETCHAI_ADDRESS_ONE
        self.multiplexer1.put(
            Envelope(
                to=propose_empty.to,
                sender=propose_empty.sender,
                protocol_id=propose_empty.protocol_id,
                message=propose_empty,
            ))
        envelope = self.multiplexer2.get(block=True, timeout=2.0)
        expected_propose_empty = FipaMessage.serializer.decode(
            envelope.message)
        expected_propose_empty.to = propose_empty.to
        expected_propose_empty.sender = propose_empty.sender
        assert expected_propose_empty == propose_empty

        propose_descriptions = FipaMessage(
            message_id=1,
            dialogue_reference=(str(0), ""),
            target=0,
            performative=FipaMessage.Performative.PROPOSE,
            proposal=Description({"foo": "bar"},
                                 DataModel("foobar",
                                           [Attribute("foo", str, True)])),
        )

        propose_descriptions.to = FETCHAI_ADDRESS_TWO
        propose_descriptions.sender = FETCHAI_ADDRESS_ONE
        self.multiplexer1.put(
            Envelope(
                to=propose_descriptions.to,
                sender=propose_descriptions.sender,
                protocol_id=propose_descriptions.protocol_id,
                message=propose_descriptions,
            ))
        envelope = self.multiplexer2.get(block=True, timeout=2.0)
        expected_propose_descriptions = FipaMessage.serializer.decode(
            envelope.message)
        expected_propose_descriptions.to = propose_descriptions.to
        expected_propose_descriptions.sender = propose_descriptions.sender
        assert expected_propose_descriptions == propose_descriptions
示例#8
0
def test_propose_serialization():
    """Test that the serialization for the 'fipa' protocol works."""
    msg = FipaMessage(
        message_id=1,
        dialogue_reference=(str(0), ""),
        target=0,
        performative=FipaMessage.Performative.PROPOSE,
        proposal=Description({
            "foo1": 1,
            "bar1": 2
        }),
    )
    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
示例#9
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([])
示例#10
0
    def _register_tac(self) -> None:
        """
        Register on the OEF as a TAC controller agent.

        :return: None.
        """
        self._oef_msg_id += 1
        desc = Description(
            {"version": self.context.parameters.version_id},
            data_model=CONTROLLER_DATAMODEL,
        )
        self.context.logger.info("[{}]: Registering TAC data model".format(
            self.context.agent_name))
        oef_msg = OEFMessage(
            type=OEFMessage.Type.REGISTER_SERVICE,
            id=self._oef_msg_id,
            service_description=desc,
            service_id="",
        )
        self.context.outbox.put_message(
            to=DEFAULT_OEF,
            sender=self.context.agent_address,
            protocol_id=OEFMessage.protocol_id,
            message=OEFSerializer().encode(oef_msg),
        )
        self._registered_desc = desc
示例#11
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)
    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,
                protocol_id=message.protocol_id,
                message=message,
            )
            logger.info("Pinging")
            agent.multiplexer.put(envelope)
            time.sleep(3)
            assert agent.multiplexer.in_queue.empty()

        finally:
            agent.stop()
示例#13
0
    def generate_proposal_and_data(
            self, query: Query,
            counterparty: Address) -> Tuple[Description, Dict[str, str]]:
        """
        Generate a proposal matching the query.

        :param counterparty: the counterparty of the proposal.
        :param query: the query
        :return: a tuple of proposal and the weather data
        """
        if self.is_ledger_tx:
            tx_nonce = self.context.ledger_apis.generate_tx_nonce(
                identifier=self._ledger_id,
                seller=self.context.agent_addresses[self._ledger_id],
                client=counterparty,
            )
        else:
            tx_nonce = uuid.uuid4().hex
        assert (self._total_price - self._seller_tx_fee >
                0), "This sale would generate a loss, change the configs!"
        proposal = Description({
            "price": self._total_price,
            "seller_tx_fee": self._seller_tx_fee,
            "currency_id": self._currency_id,
            "ledger_id": self._ledger_id,
            "tx_nonce": tx_nonce,
        })
        return proposal, self._data_for_sale
示例#14
0
    def _register_tac(self, parameters) -> None:
        """
        Register on the OEF as a TAC controller agent.

        :return: None.
        """
        self._oef_msg_id += 1
        desc = Description(
            {"version": parameters.version_id}, data_model=CONTROLLER_DATAMODEL,
        )
        self.context.logger.info(
            "[{}]: Registering TAC data model".format(self.context.agent_name)
        )
        oef_msg = OefSearchMessage(
            performative=OefSearchMessage.Performative.REGISTER_SERVICE,
            dialogue_reference=(str(self._oef_msg_id), ""),
            service_description=desc,
        )
        self.context.outbox.put_message(
            to=self.context.search_service_address,
            sender=self.context.agent_address,
            protocol_id=OefSearchMessage.protocol_id,
            message=OefSearchSerializer().encode(oef_msg),
        )
        self._registered_desc = desc
        self.context.logger.info(
            "[{}]: TAC open for registration until: {}".format(
                self.context.agent_name, parameters.registration_end_time
            )
        )
示例#15
0
    def test_terms_from_proposal_buyer(self):
        """Test the terms_from_proposal method of the Strategy class where is_seller is False."""
        proposal = Description({
            "2": 5,
            "ledger_id": self.ledger_id,
            "price": 100,
            "currency_id": "FET",
            "fee": 1,
            "nonce": self.nonce,
        })
        role = FipaDialogue.Role.BUYER
        is_seller = False

        expected_terms = Terms(
            ledger_id=self.ledger_id,
            sender_address=self.sender,
            counterparty_address=self.counterparty,
            amount_by_currency_id={
                proposal.values["currency_id"]: -proposal.values["price"]
            },
            quantities_by_good_id={"2": 5},
            is_sender_payable_tx_fee=not is_seller,
            nonce=self.nonce,
            fee_by_currency_id={
                proposal.values["currency_id"]: proposal.values["fee"]
            },
        )

        actual_terms = self.strategy.terms_from_proposal(
            proposal, self.sender, self.counterparty, role)

        assert actual_terms == expected_terms
示例#16
0
    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,
            protocol_id=message.protocol_id,
            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
示例#17
0
    async def test_register_personailty_pieces(self):
        """Test register service with personality pieces."""
        service_instance = {"piece": "genus", "value": "service"}
        service_description = Description(
            service_instance, data_model=models.AGENT_PERSONALITY_MODEL)
        message, _ = self.oef_search_dialogues.create(
            counterparty=str(SOEFConnection.connection_id.to_any()),
            performative=OefSearchMessage.Performative.REGISTER_SERVICE,
            service_description=service_description,
        )
        envelope = Envelope(
            to=message.to,
            sender=message.sender,
            protocol_id=message.protocol_id,
            message=message,
        )
        with patch.object(
                self.connection.channel,
                "_request_text",
                make_async(self.generic_success_response),
        ):
            await self.connection.send(envelope)

        with pytest.raises(asyncio.TimeoutError):  # got no message back
            await asyncio.wait_for(self.connection.receive(), timeout=1)
示例#18
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
示例#19
0
    async def test_remove_service_key(self):
        """Test remove service key."""
        await self.test_set_service_key()
        service_instance = {"key": "test"}
        service_description = Description(
            service_instance, data_model=models.REMOVE_SERVICE_KEY_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,
            protocol_id=message.protocol_id,
            message=message,
        )

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

        with pytest.raises(asyncio.TimeoutError):  # got no message back
            await asyncio.wait_for(self.connection.receive(), timeout=1)
示例#20
0
def test_accept_serialization():
    """Test the serialization for 'accept' speech-act works."""
    msg = MlTradeMessage(
        performative=MlTradeMessage.Performative.ACCEPT,
        terms=Description({
            "foo1": 1,
            "bar1": 2
        }),
        tx_digest="some_tx_digest",
    )
    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
示例#21
0
def test_unregister_service_serialization():
    """Test the serialization for 'unregister_service' speech-act works."""
    msg = OefSearchMessage(
        message_id=2,
        target=1,
        performative=OefSearchMessage.Performative.UNREGISTER_SERVICE,
        service_description=Description({
            "foo1": 1,
            "bar1": 2
        }),
    )
    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
示例#22
0
    def register_location(self,
                          disclosure_accuracy: Optional[str] = None) -> None:
        """Register location."""
        service_instance: Dict[str, Any] = {"location": self.location}

        if disclosure_accuracy:
            service_instance["disclosure_accuracy"] = disclosure_accuracy

        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.REGISTER_SERVICE,
            service_description=service_description,
        )
        envelope = Envelope(
            to=message.to,
            sender=message.sender,
            message=message,
        )
        logger.info("Registering agent at location=({},{}) by agent={}".format(
            self.location.latitude,
            self.location.longitude,
            self.crypto.address,
        ))
        self.multiplexer.put(envelope)
示例#23
0
 def get_unregister_tac_description(self) -> Description:
     """Get the tac description for unregistering."""
     description = Description(
         self.context.parameters.remove_service_data,
         data_model=AGENT_REMOVE_SERVICE_MODEL,
     )
     return description
示例#24
0
def test_data_serialization():
    """Test the serialization for 'data' speech-act works."""
    msg = MlTradeMessage(
        performative=MlTradeMessage.Performative.DATA,
        terms=Description({
            "foo1": 1,
            "bar1": 2
        }),
        payload=b"some_payload",
    )
    msg.to = "receiver"
    envelope = Envelope(
        to=msg.to,
        sender="sender",
        protocol_id=MlTradeMessage.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 = 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
示例#25
0
    async def test_register_service(self):
        """Test register 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 = OefSearchMessage(
            performative=OefSearchMessage.Performative.REGISTER_SERVICE,
            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 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.generic_success_response),
        ):
            await self.connection.send(envelope)

        with pytest.raises(asyncio.TimeoutError):  # got no message back
            await asyncio.wait_for(self.connection.receive(), timeout=1)

        assert self.connection.channel.agent_location == agent_location
示例#26
0
def test_terms_serialization():
    """Test the serialization for 'terms' speech-act works."""
    msg = MlTradeMessage(
        message_id=2,
        target=1,
        performative=MlTradeMessage.Performative.TERMS,
        terms=Description({
            "foo1": 1,
            "bar1": 2
        }),
    )
    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
示例#27
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)
示例#28
0
    async def test_ping_command(self):
        """Test set service key."""
        service_description = Description({}, data_model=models.PING_MODEL)
        message = OefSearchMessage(
            performative=OefSearchMessage.Performative.REGISTER_SERVICE,
            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 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.generic_success_response),
        ):
            await self.connection.send(envelope)

        with pytest.raises(asyncio.TimeoutError):  # got no message back
            await asyncio.wait_for(self.connection.receive(), timeout=1)
示例#29
0
    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 = OefSearchMessage(
            performative=OefSearchMessage.Performative.UNREGISTER_SERVICE,
            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 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("<response><message>Goodbye!</message></response>"),
        ):
            await self.connection.send(envelope)

        assert self.connection.channel.unique_page_address is None
示例#30
0
def build_goods_description(
    good_id_to_quantities: Dict[str, int],
    currency_id: str,
    is_supply: bool,
    is_search_description: bool,
) -> Description:
    """
    Get the service description (good quantities supplied or demanded and their price).

    :param good_id_to_quantities: a dictionary mapping the ids of the goods to the quantities.
    :param currency_id: the currency used for pricing and transacting.
    :param is_supply: True if the description is indicating supply, False if it's indicating demand.
    :param is_search_description: Whether or not the description is used for search

    :return: the description to advertise on the Service Directory.
    """
    _good_id_to_quantities = copy.copy(good_id_to_quantities)
    if is_search_description:
        # the OEF does not accept attribute names consisting of integers only
        _good_id_to_quantities = {
            PREFIX + good_id: quantity
            for good_id, quantity in _good_id_to_quantities.items()
        }
    data_model = _build_goods_datamodel(good_ids=list(
        _good_id_to_quantities.keys()),
                                        is_supply=is_supply)
    values = cast(Dict[str, Union[int, str]], _good_id_to_quantities)
    values.update({"currency_id": currency_id})
    desc = Description(values, data_model=data_model)
    return desc