apiserverspanexporter_test.go
Overview
This file contains unit tests for the APIServerSpanExporter component, which is responsible for exporting OpenTelemetry spans in the context of API server telemetry. The tests ensure that spans are correctly captured, filtered, and stored based on event IDs and span names. It also verifies the correct initialization and shutdown behavior of the exporter. The file includes a custom in-memory span exporter used to capture spans during tests.
Detailed Explanation of Components
capturingExporter
A test utility type implementing the OpenTelemetry SpanExporter interface to capture spans in memory for assertions.
type capturingExporter struct {
spans []sdktrace.ReadOnlySpan
}
Fields:
spans []sdktrace.ReadOnlySpan: Stores the spans exported during test execution.
Methods:
ExportSpans(ctx context.Context, spans []sdktrace.ReadOnlySpan) error: Appends the received spans tospans.Shutdown(ctx context.Context) error: No operation, returns nil.
Usage:
Used within tests to intercept spans created by a tracer provider, allowing verification of span export behavior without external dependencies.
TestNewAPIServerSpanExporter
Tests the creation of a new APIServerSpanExporter instance.
Purpose: Verify that the exporter is successfully instantiated and its internal trace dictionary (
traceDict) is initialized properly.Assertions:
The returned exporter is not
nil.The
traceDictis notnil.
Example:
exporter := NewAPIServerSpanExporter()
if exporter == nil {
t.Fatal("NewAPIServerSpanExporter returned nil")
}
if exporter.GetTraceDict() == nil {
t.Error("traceDict should be non-nil")
}
TestAPIServerSpanExporterExportSpans
Tests the span export functionality of the APIServerSpanExporter using various scenarios.
Test Cases:
Each test case defines:spanName: Name of the span.attributes: Span attributes, particularly checking for"gcp.vertex.agent.event_id".expectedEvent: Whether the span should be recorded in the exporter's trace dictionary.
Test Workflow:
Create a tracer provider with
capturingExporteras the span syncer.Start and end a span with the given name and attributes.
Shutdown the tracer provider to flush spans.
Instantiate
APIServerSpanExporterand callExportSpanswith captured spans.Validate the contents of the exporter's
traceDictbased on expectations.
Key Logic Tested:
Only spans with certain names (
call_llm,send_data,execute_tool_test) and with an"event_id"attribute are captured intraceDict.Spans without
"event_id"or with irrelevant names are ignored.The
traceDictentries contain required keys:"span_id"and"trace_id".
Example Test Case:
{
name: "call_llm-with-event-id-saved",
spanName: "call_llm",
attributes: []attribute.KeyValue{
attribute.String("gcp.vertex.agent.event_id", "event-id"),
},
expectedEvent: true,
}
TestAPIServerSpanExporterShutdown
Tests that the Shutdown method of APIServerSpanExporter executes without error.
Purpose: Confirm that calling
Shutdownreturnsnilerror, ensuring graceful cleanup.
Example:
exporter := NewAPIServerSpanExporter()
if err := exporter.Shutdown(context.Background()); err != nil {
t.Errorf("Shutdown() error = %v, wantErr nil", err)
}
Important Implementation Details
The
capturingExporterfacilitates in-memory span capturing, avoiding external dependencies during tests.Span filtering logic is exercised indirectly via test cases by checking span names and event ID attributes.
The tests simulate realistic tracing flows by using an OpenTelemetry tracer provider and spans.
The exporter under test is expected to maintain a dictionary keyed by event IDs, storing span metadata for observability and downstream processing.
The shutdown tests ensure that the exporter cleans up resources without errors.
Interaction with Other Parts of the System
This test file interacts primarily with the tracing system via OpenTelemetry SDK (
go.opentelemetry.io/otel/sdk/trace).It verifies the behavior of
APIServerSpanExporter, a component that processes spans post-collection, presumably part of the overall telemetry and observability frameworkTelemetry and Observability.The exporter likely integrates with API server telemetry collection and event processing workflows in the service layer.
Span attributes like
"gcp.vertex.agent.event_id"suggest integration with Google Cloud Platform telemetry conventions or custom event tracking.
Visual Diagram: Flowchart of Test Relationships and Span Export Flow
flowchart TD
A[Start Test] --> B[Create capturingExporter]
B --> C[Initialize TracerProvider with capturingExporter]
C --> D[Start Span with name & attributes]
D --> E[End Span]
E --> F["Shutdown TracerProvider (flush spans)"]
F --> G[Create APIServerSpanExporter]
G --> H[Call ExportSpans with captured spans]
H --> I[Check traceDict contents]
I --> J{Expected Event?}
J -- Yes --> K[Assert traceDict has 1 item with event ID]
J -- No --> L[Assert traceDict is empty]
K & L --> M[End Test]
Summary of Provided Functions and Methods
Function/Method | Parameters | Returns | Description |
|---|---|---|---|
|
|
| Stores spans into internal slice for inspection. |
|
|
| No-op shutdown method. |
|
| Tests creation and initialization of the API server exporter. | |
|
| Tests span export behavior with various span names and attributes. | |
|
| Tests shutdown method completes without error. |
Usage Examples
Although this is a test file and not intended for direct usage outside testing, the test cases provide usage patterns for how to:
Create a tracer provider with a custom exporter.
Start and end spans with specific attributes.
Use the
APIServerSpanExporterto export spans and inspect its internal state.
This aligns with typical OpenTelemetry span capturing and exporting workflows found in telemetry systems [OpenTelemetry Integration](80596).