Debian Codegraph @

pdata/xpdata/request/context_test.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package request // import "go.opentelemetry.io/collector/pdata/xpdata/request"
5
6 import (
7 "context"
8 "net"
9 "testing"
10
11 "github.com/stretchr/testify/assert"
12 "github.com/stretchr/testify/require"
13 "go.opentelemetry.io/otel/trace"
14
15 "go.opentelemetry.io/collector/client"
16 "go.opentelemetry.io/collector/pdata/internal"
17 )
18
19 func TestEncodeDecodeContext(t *testing.T) {
20 spanCtx := fakeSpanContext(t)
21 clientMetadata := client.NewMetadata(map[string][]string{
22 "key1": {"value1"},
23 "key2": {"value2", "value3"},
24 })
25 tests := []struct {
26 name string
27 clientInfo client.Info
28 }{
29 {
30 name: "without_client_address",
31 clientInfo: client.Info{Metadata: clientMetadata},
32 },
33 {
34 name: "with_client_IP_address",
35 clientInfo: client.Info{
36 Metadata: clientMetadata,
37 Addr: &net.IPAddr{
38 IP: net.IPv6loopback,
39 Zone: "eth0",
40 },
41 },
42 },
43 {
44 name: "with_client_TCP_address",
45 clientInfo: client.Info{
46 Metadata: clientMetadata,
47 Addr: &net.TCPAddr{
48 IP: net.IPv4(127, 0, 0, 1),
49 Port: 8080,
50 },
51 },
52 },
53 {
54 name: "with_client_UDP_address",
55 clientInfo: client.Info{
56 Metadata: clientMetadata,
57 Addr: &net.UDPAddr{
58 IP: net.IPv4(127, 0, 0, 1),
59 Port: 8080,
60 },
61 },
62 },
63 {
64 name: "with_client_unix_address",
65 clientInfo: client.Info{
66 Metadata: clientMetadata,
67 Addr: &net.UnixAddr{
68 Name: "/var/run/test.sock",
69 Net: "unixpacket",
70 },
71 },
72 },
73 }
74 for _, tt := range tests {
75 t.Run(tt.name, func(t *testing.T) {
76 // Encode a context with a span and client metadata
77 ctx := trace.ContextWithSpanContext(context.Background(), spanCtx)
78 ctx = client.NewContext(ctx, tt.clientInfo)
79 reqCtx := encodeContext(ctx)
80 buf := make([]byte, reqCtx.SizeProto())
81 reqCtx.MarshalProto(buf)
82
83 // Decode the context
84 gotReqCtx := internal.RequestContext{}
85 require.NoError(t, gotReqCtx.UnmarshalProto(buf))
86 gotCtx := decodeContext(context.Background(), &gotReqCtx)
87 assert.Equal(t, spanCtx, trace.SpanContextFromContext(gotCtx))
88 assert.Equal(t, tt.clientInfo, client.FromContext(gotCtx))
89 })
90 }
91
92 // Decode a nil context
93 assert.Equal(t, context.Background(), decodeContext(context.Background(), nil))
94 }