Skip to content

Commit dae8ba6

Browse files
authored
Merge pull request #18311 from mohamedawnallah/backport-3.4-fmtgRPCMetadata
[3.4] client/v3/watch.go: use fmt go pkg for gRPC metadata map printing
2 parents 518accf + 6542146 commit dae8ba6

File tree

2 files changed

+54
-1
lines changed

2 files changed

+54
-1
lines changed

clientv3/watch.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1043,7 +1043,7 @@ func (pr *progressRequest) toPB() *pb.WatchRequest {
10431043

10441044
func streamKeyFromCtx(ctx context.Context) string {
10451045
if md, ok := metadata.FromOutgoingContext(ctx); ok {
1046-
return fmt.Sprintf("%+v", md)
1046+
return fmt.Sprintf("%+v", map[string][]string(md))
10471047
}
10481048
return ""
10491049
}

clientv3/watch_test.go

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,11 @@
1515
package clientv3
1616

1717
import (
18+
"context"
1819
"testing"
1920

21+
"google.golang.org/grpc/metadata"
22+
2023
"go.etcd.io/etcd/mvcc/mvccpb"
2124
)
2225

@@ -53,3 +56,53 @@ func TestEvent(t *testing.T) {
5356
}
5457
}
5558
}
59+
60+
// TestStreamKeyFromCtx tests the streamKeyFromCtx function to ensure it correctly
61+
// formats metadata as a map[string][]string when extracting metadata from the context.
62+
//
63+
// The fmt package in Go guarantees that maps are printed in a consistent order,
64+
// sorted by the keys. This test verifies that the streamKeyFromCtx function
65+
// produces the expected formatted string representation of metadata maps when called with
66+
// various context scenarios.
67+
func TestStreamKeyFromCtx(t *testing.T) {
68+
tests := []struct {
69+
name string
70+
ctx context.Context
71+
expected string
72+
}{
73+
{
74+
name: "multiple keys",
75+
ctx: metadata.NewOutgoingContext(context.Background(), metadata.MD{
76+
"key1": []string{"value1"},
77+
"key2": []string{"value2a", "value2b"},
78+
}),
79+
expected: "map[key1:[value1] key2:[value2a value2b]]",
80+
},
81+
{
82+
name: "no keys",
83+
ctx: metadata.NewOutgoingContext(context.Background(), metadata.MD{}),
84+
expected: "map[]",
85+
},
86+
{
87+
name: "only one key",
88+
ctx: metadata.NewOutgoingContext(context.Background(), metadata.MD{
89+
"key1": []string{"value1", "value1a"},
90+
}),
91+
expected: "map[key1:[value1 value1a]]",
92+
},
93+
{
94+
name: "no metadata",
95+
ctx: context.Background(),
96+
expected: "",
97+
},
98+
}
99+
100+
for _, tt := range tests {
101+
t.Run(tt.name, func(t *testing.T) {
102+
actual := streamKeyFromCtx(tt.ctx)
103+
if actual != tt.expected {
104+
t.Errorf("streamKeyFromCtx() = %v, expected %v", actual, tt.expected)
105+
}
106+
})
107+
}
108+
}

0 commit comments

Comments
 (0)