From ed6b76a483ba1d5764c34fdf31fac41f6eb52604 Mon Sep 17 00:00:00 2001 From: Mohamed Awnallah Date: Wed, 10 Jul 2024 12:45:14 +0300 Subject: [PATCH] client/v3/watch_test.go: test fmt metadata print Signed-off-by: Mohamed Awnallah --- client/v3/watch_test.go | 52 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/client/v3/watch_test.go b/client/v3/watch_test.go index 2a56ca4a9383..1ecfd9a25f00 100644 --- a/client/v3/watch_test.go +++ b/client/v3/watch_test.go @@ -15,9 +15,11 @@ package clientv3 import ( + "context" "testing" "go.etcd.io/etcd/api/v3/mvccpb" + "google.golang.org/grpc/metadata" ) func TestEvent(t *testing.T) { @@ -53,3 +55,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 { + md metadata.MD + expected string + }{ + { + md: metadata.MD{ + "key1": []string{"value1"}, + "key2": []string{"value2a", "value2b"}, + }, + expected: "map[key1:[value1] key2:[value2a value2b]]", + }, + { + md: metadata.MD{}, + expected: "map[]", + }, + { + md: metadata.MD{ + "key1": []string{"value1", "value1a"}, + }, + expected: "map[key1:[value1 value1a]]", + }, + } + + // Iterate through each test case and verify the function's output matches + // the expected result. + for i, tt := range tests { + ctx := metadata.NewOutgoingContext(context.Background(), tt.md) + actual := streamKeyFromCtx(ctx) + if actual != tt.expected { + t.Errorf("#%d: streamKeyFromCtx() = %v, want %v", i, actual, tt.expected) + } + } + + // Test with no metadata in context to ensure it returns an empty string. + ctx := context.Background() + expected := "" + actual := streamKeyFromCtx(ctx) + if actual != expected { + t.Errorf("streamKeyFromCtx() = %v, want %v", actual, expected) + } +}