Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[3.4] client/v3/watch.go: use fmt go pkg for gRPC metadata map printing #18311

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion clientv3/watch.go
Original file line number Diff line number Diff line change
Expand Up @@ -1043,7 +1043,7 @@ func (pr *progressRequest) toPB() *pb.WatchRequest {

func streamKeyFromCtx(ctx context.Context) string {
if md, ok := metadata.FromOutgoingContext(ctx); ok {
return fmt.Sprintf("%+v", md)
return fmt.Sprintf("%+v", map[string][]string(md))
}
return ""
}
53 changes: 53 additions & 0 deletions clientv3/watch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,11 @@
package clientv3

import (
"context"
"testing"

"google.golang.org/grpc/metadata"

"go.etcd.io/etcd/mvcc/mvccpb"
)

Expand Down Expand Up @@ -53,3 +56,53 @@ func TestEvent(t *testing.T) {
}
}
}

// TestStreamKeyFromCtx tests the streamKeyFromCtx function to ensure it correctly
// formats metadata as a map[string][]string when extracting metadata from the context.
//
// The fmt package in Go guarantees that maps are printed in a consistent order,
// sorted by the keys. This test verifies that the streamKeyFromCtx function
// produces the expected formatted string representation of metadata maps when called with
// various context scenarios.
func TestStreamKeyFromCtx(t *testing.T) {
tests := []struct {
name string
ctx context.Context
expected string
}{
{
name: "multiple keys",
ctx: metadata.NewOutgoingContext(context.Background(), metadata.MD{
"key1": []string{"value1"},
"key2": []string{"value2a", "value2b"},
}),
expected: "map[key1:[value1] key2:[value2a value2b]]",
},
{
name: "no keys",
ctx: metadata.NewOutgoingContext(context.Background(), metadata.MD{}),
expected: "map[]",
},
{
name: "only one key",
ctx: metadata.NewOutgoingContext(context.Background(), metadata.MD{
"key1": []string{"value1", "value1a"},
}),
expected: "map[key1:[value1 value1a]]",
},
{
name: "no metadata",
ctx: context.Background(),
expected: "",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
actual := streamKeyFromCtx(tt.ctx)
if actual != tt.expected {
t.Errorf("streamKeyFromCtx() = %v, expected %v", actual, tt.expected)
}
})
}
}
Loading