예제 #1
0
def test_envelope_context_raises_with_public_id_specified_twice():
    """Test the EnvelopeContext constructor, negative"""
    with pytest.raises(
            ValueError,
            match="Cannot define connection_id explicitly and in URI."):
        EnvelopeContext(
            uri=URI("connection/author/connection_name/0.1.0"),
            connection_id=PublicId("author", "connection_name", "0.1.0"),
        )
    with pytest.raises(ValueError,
                       match="Cannot define skill_id explicitly and in URI."):
        EnvelopeContext(
            uri=URI("skill/author/skill_name/0.1.0"),
            skill_id=PublicId("author", "skill_name", "0.1.0"),
        )
예제 #2
0
    async def to_envelope(self, request: web.Request) -> Envelope:
        """
        Convert a webhook request object into an Envelope containing an HttpMessage `from the 'http' Protocol`.

        :param request: the webhook request
        :return: The envelop representing the webhook request
        """
        payload_bytes = await request.read()
        version = str(request.version[0]) + "." + str(request.version[1])

        context = EnvelopeContext(uri=URI("aea/mail/base.py"))
        http_message = HttpMessage(
            performative=HttpMessage.Performative.REQUEST,
            method=request.method,
            url=str(request.url),
            version=version,
            headers=json.dumps(dict(request.headers)),
            bodyy=payload_bytes if payload_bytes is not None else b"",
        )
        envelope = Envelope(
            to=self.agent_address,
            sender=request.remote,
            protocol_id=PublicId.from_str("fetchai/http:0.3.0"),
            context=context,
            message=http_message,
        )
        return envelope
예제 #3
0
    async def to_envelope(self, request: web.Request) -> Envelope:
        """
        Convert a webhook request object into an Envelope containing an HttpMessage `from the 'http' Protocol`.

        :param request: the webhook request
        :return: The envelop representing the webhook request
        """
        payload_bytes = await request.read()
        version = str(request.version[0]) + "." + str(request.version[1])

        context = EnvelopeContext(uri=URI("aea/mail/base.py"))
        http_message = HttpMessage(
            performative=HttpMessage.Performative.REQUEST,
            method=request.method,
            url=str(request.url),
            version=version,
            headers=json.dumps(dict(request.headers)),
            bodyy=payload_bytes if payload_bytes is not None else b"",
            dialogue_reference=self._dialogues.
            new_self_initiated_dialogue_reference(),
        )
        http_message.counterparty = self.agent_address
        http_dialogue = self._dialogues.update(http_message)
        assert http_dialogue is not None, "Could not create dialogue."
        envelope = Envelope(
            to=http_message.counterparty,
            sender=http_message.sender,
            protocol_id=http_message.protocol_id,
            context=context,
            message=http_message,
        )
        return envelope
예제 #4
0
    def to_envelope(self, connection_id: PublicId, agent_address: str) -> Envelope:
        """
        Process incoming API request by packaging into Envelope and sending it in-queue.

        The Envelope's message body contains the "performative", "path", "params", and "payload".

        :param http_method: the http method
        :param url: the url
        :param param: the parameter
        :param body: the body
        """
        uri = URI(self.full_url_pattern)
        context = EnvelopeContext(connection_id=connection_id, uri=uri)
        http_message = HttpMessage(
            dialogue_reference=("", ""),
            target=0,
            message_id=1,
            performative=HttpMessage.Performative.REQUEST,
            method=self.method,
            url=self.full_url_pattern,
            headers=self.parameters.header.as_string(),
            bodyy=self.body.encode() if self.body is not None else b"",
            version="",
        )
        envelope = Envelope(
            to=agent_address,
            sender=self.id,
            protocol_id=PublicId.from_str("fetchai/http:0.1.0"),
            context=context,
            message=HttpSerializer().encode(http_message),
        )
        return envelope
예제 #5
0
def test_envelope_skill_id():
    """Test the property Envelope.skill_id."""
    envelope_context = EnvelopeContext(uri=URI("author/skill_name/0.1.0"))
    envelope = Envelope(
        to="to",
        sender="sender",
        protocol_id=PublicId("author", "name", "0.1.0"),
        message=b"message",
        context=envelope_context,
    )

    assert envelope.skill_id == PublicId("author", "skill_name", "0.1.0")
예제 #6
0
def test_envelope_connection_id():
    """Test the property Envelope.connection_id."""
    envelope_context = EnvelopeContext(
        uri=URI("connection/author/connection_name/0.1.0"))
    envelope = Envelope(
        to="to",
        sender="sender",
        protocol_specification_id=PublicId("author", "name", "0.1.0"),
        message=b"message",
        context=envelope_context,
    )

    assert envelope.connection_id == PublicId("author", "connection_name",
                                              "0.1.0")
예제 #7
0
def test_uri():
    """Testing the uri initialisation."""
    uri_raw = "http://*****:*****@NetLoc:80/path;param?query=arg#frag"
    uri = URI(uri_raw=uri_raw)
    assert uri_raw == str(uri)
    assert uri.scheme == "http"
    assert uri.netloc == "user:pwd@NetLoc:80"
    assert uri.path == "/path"
    assert uri.params == "param"
    assert uri.query == "query=arg"
    assert uri.fragment == "frag"
    assert uri.host == "netloc"
    assert uri.port == 80
    assert uri.username == "user"
    assert uri.password == "pwd"
예제 #8
0
def test_protobuf_envelope_serializer():
    """Test Protobuf envelope serializer."""
    serializer = ProtobufEnvelopeSerializer()
    # connection id is None because it is not included in the encoded envelope
    envelope_context = EnvelopeContext(connection_id=None, uri=URI("/uri"))
    expected_envelope = Envelope(
        to="to",
        sender="sender",
        protocol_id=PublicId("author", "name", "0.1.0"),
        message=b"message",
        context=envelope_context,
    )
    encoded_envelope = serializer.encode(expected_envelope)
    actual_envelope = serializer.decode(encoded_envelope)

    assert actual_envelope == expected_envelope
예제 #9
0
def test_envelope_skill_id_raises_value_error(caplog):
    """Test the property Envelope.skill_id raises ValueError if the URI is not a public id.."""
    with caplog.at_level(logging.DEBUG, logger="aea.mail.base"):
        bad_uri = "author/skill_name/bad_version"
        envelope_context = EnvelopeContext(uri=URI(bad_uri))
        envelope = Envelope(
            to="to",
            sender="sender",
            protocol_id=PublicId("author", "name", "0.1.0"),
            message=b"message",
            context=envelope_context,
        )

        assert envelope.skill_id is None
        assert (
            f"URI - {bad_uri} - not a valid skill id." in caplog.text
        ), f"Cannot find message in output: {caplog.text}"
예제 #10
0
def test_envelope_skill_id_raises_value_error_wrong_package_type():
    """Test the property Envelope.skill_id raises ValueError if the URI is not a valid package type."""
    with unittest.mock.patch.object(aea.mail.base._default_logger,
                                    "debug") as mock_logger_method:
        invalid_uri = "protocol/author/skill_name/0.1.0"
        envelope_context = EnvelopeContext(uri=URI(invalid_uri))
        envelope = Envelope(
            to="to",
            sender="sender",
            protocol_specification_id=PublicId("author", "name", "0.1.0"),
            message=b"message",
            context=envelope_context,
        )

        assert envelope.skill_id is None
        mock_logger_method.assert_called_with(
            f"URI - {invalid_uri} - not a valid package_id id. Error: Invalid package type protocol in uri for envelope context."
        )
예제 #11
0
def test_envelope_skill_id_raises_value_error():
    """Test the property Envelope.skill_id raises ValueError if the URI is not a package id.."""
    with unittest.mock.patch.object(aea.mail.base._default_logger,
                                    "debug") as mock_logger_method:
        bad_uri = "skill/author/skill_name/bad_version"
        envelope_context = EnvelopeContext(uri=URI(bad_uri))
        envelope = Envelope(
            to="to",
            sender="sender",
            protocol_specification_id=PublicId("author", "name", "0.1.0"),
            message=b"message",
            context=envelope_context,
        )

        assert envelope.skill_id is None
        mock_logger_method.assert_called_with(
            f"URI - {bad_uri} - not a valid package_id id. Error: Input '{bad_uri}' is not well formatted."
        )
예제 #12
0
 def test_error_unsupported_skill_when_skill_id_is_none(self):
     """Test the 'send_unsupported_skill' when the skill id in the envelope is None."""
     skill_id = PublicId.from_str("author/skill:0.1.0")
     protocol_id = PublicId.from_str("author/name:0.1.0")
     envelope = Envelope(
         to="",
         sender="",
         protocol_id=protocol_id,
         message=b"",
         context=EnvelopeContext(uri=URI(skill_id.to_uri_path)),
     )
     with unittest.mock.patch.object(self.skill_context.outbox,
                                     "put_message"):
         with unittest.mock.patch.object(self.skill_context._logger,
                                         "warning") as mock_logger_warning:
             self.my_error_handler.send_unsupported_skill(envelope)
             mock_logger_warning.assert_called_with(
                 f"Cannot handle envelope: no active handler registered for the protocol_id='{protocol_id}' and skill_id='{skill_id}'."
             )
예제 #13
0
    def to_envelope_and_set_id(
        self,
        connection_id: PublicId,
        agent_address: str,
        dialogues: HttpDialogues,
    ) -> Envelope:
        """
        Process incoming API request by packaging into Envelope and sending it in-queue.

        :param connection_id: id of the connection
        :param agent_address: agent's address
        :param dialogue_reference: new dialog refernece for envelope

        :return: envelope
        """
        url = (self.full_url_pattern if self.parameters.query == {} else
               self.full_url_pattern + "?" + urlencode(self.parameters.query))
        uri = URI(self.full_url_pattern)
        context = EnvelopeContext(connection_id=connection_id, uri=uri)
        http_message = HttpMessage(
            dialogue_reference=dialogues.new_self_initiated_dialogue_reference(
            ),
            performative=HttpMessage.Performative.REQUEST,
            method=self.method,
            url=url,
            headers=self.parameters.header,
            bodyy=self.body if self.body is not None else b"",
            version="",
        )
        http_message.counterparty = agent_address
        dialogue = cast(Optional[HttpDialogue], dialogues.update(http_message))
        assert dialogue is not None, "Could not create dialogue for message={}".format(
            http_message)
        self.id = dialogue.incomplete_dialogue_label
        envelope = Envelope(
            to=agent_address,
            sender=str(connection_id),
            protocol_id=http_message.protocol_id,
            context=context,
            message=http_message,
        )
        return envelope
예제 #14
0
def test_envelope_skill_id_raises_value_error():
    """Test the property Envelope.skill_id raises ValueError if the URI is not a public id.."""
    with unittest.mock.patch.object(aea.mail.base.logger,
                                    "debug") as mock_logger_method:
        # with caplog.at_level(logging.DEBUG, logger="aea.mail.base"):
        bad_uri = "author/skill_name/bad_version"
        envelope_context = EnvelopeContext(uri=URI(bad_uri))
        envelope = Envelope(
            to="to",
            sender="sender",
            protocol_id=PublicId("author", "name", "0.1.0"),
            message=b"message",
            context=envelope_context,
        )

        assert envelope.skill_id is None
        # assert (
        #     f"URI - {bad_uri} - not a valid skill id." in caplog.text
        # ), f"Cannot find message in output: {caplog.text}"
        mock_logger_method.assert_called_with(
            f"URI - {bad_uri} - not a valid skill id.")
예제 #15
0
    def to_envelope_and_set_id(
        self,
        connection_id: PublicId,
        agent_address: str,
        dialogues: HttpDialogues,
    ) -> Envelope:
        """
        Process incoming API request by packaging into Envelope and sending it in-queue.

        :param connection_id: id of the connection
        :param agent_address: agent's address
        :param dialogue_reference: new dialog refernece for envelope

        :return: envelope
        """
        url = self.full_url_pattern
        uri = URI(self.full_url_pattern)
        context = EnvelopeContext(connection_id=connection_id, uri=uri)
        http_message, http_dialogue = dialogues.create(
            counterparty=agent_address,
            performative=HttpMessage.Performative.REQUEST,
            method=self.method,
            url=url,
            headers=self.parameters.header,
            body=self.body if self.body is not None else b"",
            version="",
        )
        dialogue = cast(HttpDialogue, http_dialogue)
        self.id = dialogue.incomplete_dialogue_label
        envelope = Envelope(
            to=http_message.to,
            sender=http_message.sender,
            context=context,
            message=http_message,
        )
        return envelope
예제 #16
0
def test_uri_eq():
    """Testing the uri __eq__ function."""
    uri_raw = "http://*****:*****@NetLoc:80/path;param?query=arg#frag"
    uri = URI(uri_raw=uri_raw)
    assert uri == uri