Debian Codegraph @

pdata/ptrace/ptraceotlp/request_test.go

raw symbols SCIP
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package ptraceotlp
5
6 import (
7 "encoding/json"
8 "strings"
9 "testing"
10
11 "github.com/stretchr/testify/assert"
12 "github.com/stretchr/testify/require"
13 gootlpcollectortrace "go.opentelemetry.io/proto/slim/otlp/collector/trace/v1"
14 goproto "google.golang.org/protobuf/proto"
15
16 "go.opentelemetry.io/collector/pdata/internal"
17 "go.opentelemetry.io/collector/pdata/internal/otlp"
18 "go.opentelemetry.io/collector/pdata/ptrace"
19 )
20
21 var (
22 _ json.Unmarshaler = ExportRequest{}
23 _ json.Marshaler = ExportRequest{}
24 )
25
26 var tracesRequestJSON = []byte(`
27 {
28 "resourceSpans": [
29 {
30 "resource": {},
31 "scopeSpans": [
32 {
33 "scope": {},
34 "spans": [
35 {
36 "name": "test_span",
37 "status": {}
38 }
39 ]
40 }
41 ]
42 }
43 ]
44 }`)
45
46 func TestRequestToPData(t *testing.T) {
47 tr := NewExportRequest()
48 assert.Equal(t, 0, tr.Traces().SpanCount())
49 tr.Traces().ResourceSpans().AppendEmpty().ScopeSpans().AppendEmpty().Spans().AppendEmpty()
50 assert.Equal(t, 1, tr.Traces().SpanCount())
51 }
52
53 func TestRequestJSON(t *testing.T) {
54 tr := NewExportRequest()
55 require.NoError(t, tr.UnmarshalJSON(tracesRequestJSON))
56 assert.Equal(t, "test_span", tr.Traces().ResourceSpans().At(0).ScopeSpans().At(0).Spans().At(0).Name())
57
58 got, err := tr.MarshalJSON()
59 require.NoError(t, err)
60 assert.Equal(t, strings.Join(strings.Fields(string(tracesRequestJSON)), ""), string(got))
61 }
62
63 func TestTracesProtoWireCompatibility(t *testing.T) {
64 // This test verifies that OTLP ProtoBufs generated using goproto lib in
65 // opentelemetry-proto repository OTLP ProtoBufs generated using gogoproto lib in
66 // this repository are wire compatible.
67
68 // Generate Traces as pdata struct.
69 td := NewExportRequestFromTraces(ptrace.Traces(internal.GenTestTracesWrapper()))
70
71 // Marshal its underlying ProtoBuf to wire.
72 wire1, err := td.MarshalProto()
73 require.NoError(t, err)
74 assert.NotNil(t, wire1)
75
76 // Unmarshal from the wire to OTLP Protobuf in goproto's representation.
77 var goprotoMessage gootlpcollectortrace.ExportTraceServiceRequest
78 err = goproto.Unmarshal(wire1, &goprotoMessage)
79 require.NoError(t, err)
80
81 // Marshal to the wire again.
82 wire2, err := goproto.Marshal(&goprotoMessage)
83 require.NoError(t, err)
84 assert.NotNil(t, wire2)
85
86 // Unmarshal from the wire into gogoproto's representation.
87 td2 := NewExportRequest()
88 err = td2.UnmarshalProto(wire2)
89 require.NoError(t, err)
90
91 // Now compare that the original and final ProtoBuf messages are the same.
92 // This proves that goproto and gogoproto marshaling/unmarshaling are wire compatible.
93 // Migration logic will run, so run it on the original message as well.
94 otlp.MigrateTraces(td.orig.ResourceSpans)
95 assert.Equal(t, td, td2)
96 }