From 06ab593f48223371f6108b52190ade0b7f6376a4 Mon Sep 17 00:00:00 2001 From: Tawakalt Date: Fri, 28 Jul 2023 11:51:14 +0200 Subject: [PATCH] add test --- tests/tracing/instrumentation/conftest.py | 23 +++++++++ tests/tracing/instrumentation/test_tracing.py | 48 +++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 tests/tracing/instrumentation/conftest.py create mode 100644 tests/tracing/instrumentation/test_tracing.py diff --git a/tests/tracing/instrumentation/conftest.py b/tests/tracing/instrumentation/conftest.py new file mode 100644 index 000000000..df3a7a166 --- /dev/null +++ b/tests/tracing/instrumentation/conftest.py @@ -0,0 +1,23 @@ +import pytest + +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.export import SimpleSpanProcessor +from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter + + +@pytest.fixture(scope="session") +def tracer_provider() -> TracerProvider: + return TracerProvider() + + +@pytest.fixture(scope="session") +def span_exporter(tracer_provider: TracerProvider) -> InMemorySpanExporter: + exporter = InMemorySpanExporter() # type: ignore + tracer_provider.add_span_processor(SimpleSpanProcessor(exporter)) + return exporter + + +@pytest.fixture(scope="function") +def previous_num_captured_spans(span_exporter: InMemorySpanExporter) -> int: + captured_spans = span_exporter.get_finished_spans() # type: ignore + return len(captured_spans) diff --git a/tests/tracing/instrumentation/test_tracing.py b/tests/tracing/instrumentation/test_tracing.py new file mode 100644 index 000000000..18aaff704 --- /dev/null +++ b/tests/tracing/instrumentation/test_tracing.py @@ -0,0 +1,48 @@ +import json + +import rasa_sdk.endpoint as ep + +from typing import Sequence +from opentelemetry.sdk.trace import ReadableSpan +from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter + + +# noinspection PyTypeChecker +app = ep.create_app(None) + + +def test_server_webhook_custom_action_is_instrumented( + span_exporter: InMemorySpanExporter, + previous_num_captured_spans: int, +): + data = { + "next_action": "custom_action", + "version": "1.0.0", + "tracker": { + "sender_id": "1", + "conversation_id": "default", + "latest_message": {"message_id": "1"}, + }, + } + _, response = app.test_client.post("/webhook", data=json.dumps(data)) + result = response.json + + assert response.status == 200 + + captured_spans: Sequence[ + ReadableSpan + ] = span_exporter.get_finished_spans() # type: ignore + + num_captured_spans = len(captured_spans) - previous_num_captured_spans + assert num_captured_spans == 1 + + captured_span = captured_spans[-1] + + assert captured_span.attributes == { + "http.method": "POST", + "http.route": "/webhook", + "next_action": result.get("next_action"), + "version": result.get("version"), + "sender_id": result.get("sender_id"), + "message_id": result.get("latest_message", {}).get("message_id"), + }