Exemple #1
0
def test_update_metric_serialization():
    """Test the serialization for 'update_metric' speech-act works."""
    msg = PrometheusMessage(
        message_id=2,
        dialogue_reference=(str(0), ""),
        target=1,
        performative=PrometheusMessage.Performative.UPDATE_METRIC,
        title="some_title",
        callable="some_update_function",
        value=1.0,
        labels={"label_key": "label_value"},
    )
    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 = PrometheusMessage.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
Exemple #2
0
def test_response_serialization():
    """Test the serialization for 'response' speech-act works."""
    msg = PrometheusMessage(
        message_id=1,
        dialogue_reference=(str(0), ""),
        target=0,
        performative=PrometheusMessage.Performative.RESPONSE,
        code=0,
        message="some_message",
    )
    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 = PrometheusMessage.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
    def decode(obj: bytes) -> Message:
        """
        Decode bytes into a 'Prometheus' message.

        :param obj: the bytes object.
        :return: the 'Prometheus' message.
        """
        message_pb = ProtobufMessage()
        prometheus_pb = prometheus_pb2.PrometheusMessage()
        message_pb.ParseFromString(obj)
        message_id = message_pb.dialogue_message.message_id
        dialogue_reference = (
            message_pb.dialogue_message.dialogue_starter_reference,
            message_pb.dialogue_message.dialogue_responder_reference,
        )
        target = message_pb.dialogue_message.target

        prometheus_pb.ParseFromString(message_pb.dialogue_message.content)
        performative = prometheus_pb.WhichOneof("performative")
        performative_id = PrometheusMessage.Performative(str(performative))
        performative_content = dict()  # type: Dict[str, Any]
        if performative_id == PrometheusMessage.Performative.ADD_METRIC:
            type = prometheus_pb.add_metric.type
            performative_content["type"] = type
            title = prometheus_pb.add_metric.title
            performative_content["title"] = title
            description = prometheus_pb.add_metric.description
            performative_content["description"] = description
            labels = prometheus_pb.add_metric.labels
            labels_dict = dict(labels)
            performative_content["labels"] = labels_dict
        elif performative_id == PrometheusMessage.Performative.UPDATE_METRIC:
            title = prometheus_pb.update_metric.title
            performative_content["title"] = title
            callable = prometheus_pb.update_metric.callable
            performative_content["callable"] = callable
            value = prometheus_pb.update_metric.value
            performative_content["value"] = value
            labels = prometheus_pb.update_metric.labels
            labels_dict = dict(labels)
            performative_content["labels"] = labels_dict
        elif performative_id == PrometheusMessage.Performative.RESPONSE:
            code = prometheus_pb.response.code
            performative_content["code"] = code
            if prometheus_pb.response.message_is_set:
                message = prometheus_pb.response.message
                performative_content["message"] = message
        else:
            raise ValueError(
                "Performative not valid: {}.".format(performative_id))

        return PrometheusMessage(message_id=message_id,
                                 dialogue_reference=dialogue_reference,
                                 target=target,
                                 performative=performative,
                                 **performative_content)
Exemple #4
0
def test_incorrect_message(mocked_enforce):
    """Test that we raise an exception when the message is incorrect."""
    with mock.patch.object(prometheus_message_logger, "error") as mock_logger:
        PrometheusMessage(
            message_id=1,
            dialogue_reference=(str(0), ""),
            target=0,
            performative=PrometheusMessage.Performative.RESPONSE,
            code=0,
            message="some_message",
        )

        mock_logger.assert_any_call("some error")
Exemple #5
0
def test_encoding_unknown_performative():
    """Test that we raise an exception when the performative is unknown during encoding."""
    msg = PrometheusMessage(
        message_id=1,
        dialogue_reference=(str(0), ""),
        target=0,
        performative=PrometheusMessage.Performative.RESPONSE,
        code=0,
        message="some_message",
    )

    with pytest.raises(ValueError, match="Performative not valid:"):
        with mock.patch.object(
            PrometheusMessage.Performative, "__eq__", return_value=False
        ):
            PrometheusMessage.serializer.encode(msg)
Exemple #6
0
    async def test_connection(self):
        """Test connect."""
        assert (self.prometheus_con.state == ConnectionStates.disconnected
                ), "should not be connected yet"
        await self.prometheus_con.connect()
        assert (self.prometheus_con.state == ConnectionStates.connected
                ), "should be connected"

        # test add metric (correct)
        await self.send_add_metric("some_metric", "Gauge")
        envelope = await self.prometheus_con.receive()
        msg = cast(PrometheusMessage, envelope.message)
        assert msg.performative == PrometheusMessage.Performative.RESPONSE
        assert msg.code == 200
        assert msg.message == "New Gauge successfully added: some_metric."

        # test add metric (already exists)
        await self.send_add_metric("some_metric", "Gauge")
        envelope = await self.prometheus_con.receive()
        msg = cast(PrometheusMessage, envelope.message)
        assert msg.performative == PrometheusMessage.Performative.RESPONSE
        assert msg.code == 409
        assert msg.message == "Metric already exists."

        # test add metric (wrong type)
        await self.send_add_metric("cool_metric", "CoolBar")
        envelope = await self.prometheus_con.receive()
        msg = cast(PrometheusMessage, envelope.message)
        assert msg.performative == PrometheusMessage.Performative.RESPONSE
        assert msg.code == 404
        assert msg.message == "CoolBar is not a recognized prometheus metric."

        # test update metric (inc: correct)
        await self.send_update_metric("some_metric", "inc")
        envelope = await self.prometheus_con.receive()
        msg = cast(PrometheusMessage, envelope.message)
        assert msg.performative == PrometheusMessage.Performative.RESPONSE
        assert msg.code == 200
        assert msg.message == "Metric some_metric successfully updated."

        # test update metric (set: correct)
        await self.send_update_metric("some_metric", "set")
        envelope = await self.prometheus_con.receive()
        msg = cast(PrometheusMessage, envelope.message)
        assert msg.performative == PrometheusMessage.Performative.RESPONSE
        assert msg.code == 200
        assert msg.message == "Metric some_metric successfully updated."

        # test update metric (doesn't exist)
        await self.send_update_metric("cool_metric", "inc")
        envelope = await self.prometheus_con.receive()
        msg = cast(PrometheusMessage, envelope.message)
        assert msg.performative == PrometheusMessage.Performative.RESPONSE
        assert msg.code == 404
        assert msg.message == "Metric cool_metric not found."

        # test update metric (bad update function: not found in attr)
        await self.send_update_metric("some_metric", "go")
        envelope = await self.prometheus_con.receive()
        msg = cast(PrometheusMessage, envelope.message)
        assert msg.performative == PrometheusMessage.Performative.RESPONSE
        assert msg.code == 400
        assert msg.message == "Update function go not found for metric some_metric."

        # test update metric (bad update function: found in getattr, not a method)
        await self.send_update_metric("some_metric", "name")
        envelope = await self.prometheus_con.receive()
        msg = cast(PrometheusMessage, envelope.message)
        assert msg.performative == PrometheusMessage.Performative.RESPONSE
        assert msg.code == 400
        assert (
            msg.message ==
            "Failed to update metric some_metric: name is not a valid update function."
        )

        # Test that invalid message is rejected.
        with pytest.raises(AEAEnforceError):
            envelope = Envelope(
                to="some_address",
                sender="me",
                message=Mock(spec=Message),
            )
            await self.prometheus_con.channel.send(envelope)

        # Test that envelope without dialogue produces warning.
        msg = PrometheusMessage(PrometheusMessage.Performative.RESPONSE,
                                code=0,
                                message="")
        envelope = Envelope(
            to=self.prometheus_address,
            sender=self.agent_address,
            message=msg,
        )
        await self.prometheus_con.channel.send(envelope)

        # Test that envelope with invalid protocol_specification_id raises error.
        with pytest.raises(ValueError):
            msg, _ = self.dialogues.create(
                counterparty=self.prometheus_address,
                performative=PrometheusMessage.Performative.UPDATE_METRIC,
                title="",
                callable="",
                value=1.0,
                labels={},
            )
            envelope = Envelope(
                to=self.prometheus_address,
                sender=self.agent_address,
                message=msg,
            )
            envelope._protocol_specification_id = "bad_id"
            await self.prometheus_con.channel.send(envelope)