Skip to content

Commit

Permalink
metadata: make Stringer implementation consistent (#7355)
Browse files Browse the repository at this point in the history
  • Loading branch information
dims authored Jun 27, 2024
1 parent 98e5dee commit 6126383
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 23 deletions.
15 changes: 3 additions & 12 deletions metadata/metadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,19 +90,10 @@ func Pairs(kv ...string) MD {
return md
}

// String implements the Stringer interface for pretty-printing a MD.
// Ordering of the values is non-deterministic as it ranges over a map.
// String implements fmt.Stringer to allow metadata to be printed when stored
// in a context. It returns the metadata map as formatted by Go's fmt package.
func (md MD) String() string {
var sb strings.Builder
fmt.Fprintf(&sb, "MD{")
for k, v := range md {
if sb.Len() > 3 {
fmt.Fprintf(&sb, ", ")
}
fmt.Fprintf(&sb, "%s=[%s]", k, strings.Join(v, ", "))
}
fmt.Fprintf(&sb, "}")
return sb.String()
return fmt.Sprint(map[string][]string(md))
}

// Len returns the number of items in md.
Expand Down
21 changes: 10 additions & 11 deletions metadata/metadata_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import (
"context"
"reflect"
"strconv"
"strings"
"testing"
"time"

Expand Down Expand Up @@ -342,19 +341,19 @@ func (s) TestAppendToOutgoingContext_FromKVSlice(t *testing.T) {
func TestStringerMD(t *testing.T) {
for _, test := range []struct {
md MD
want []string
want string
}{
{MD{}, []string{"MD{}"}},
{MD{"k1": []string{}}, []string{"MD{k1=[]}"}},
{MD{"k1": []string{"v1", "v2"}}, []string{"MD{k1=[v1, v2]}"}},
{MD{"k1": []string{"v1"}}, []string{"MD{k1=[v1]}"}},
{MD{"k1": []string{"v1", "v2"}, "k2": []string{}, "k3": []string{"1", "2", "3"}}, []string{"MD{", "k1=[v1, v2]", "k2=[]", "k3=[1, 2, 3]", "}"}},
{MD{}, "map[]"},
{MD{"k1": []string{}}, "map[k1:[]]"},
{MD{"k1": []string{"v1", "v2"}}, "map[k1:[v1 v2]]"},
{MD{"k1": []string{"v1"}}, "map[k1:[v1]]"},
{MD{"k1": []string{"v1", "v2"}, "k2": []string{}, "k3": []string{"1", "2", "3"}}, "map[k1:[v1 v2] k2:[] k3:[1 2 3]]"},
{MD{"k2": []string{}, "k3": []string{"1", "2", "3"}, "k1": []string{"v1", "v2"}}, "map[k1:[v1 v2] k2:[] k3:[1 2 3]]"},
{MD{"k3": []string{"1", "2", "3"}, "k2": []string{}, "k1": []string{"v1", "v2"}}, "map[k1:[v1 v2] k2:[] k3:[1 2 3]]"},
} {
got := test.md.String()
for _, want := range test.want {
if !strings.Contains(got, want) {
t.Fatalf("Metadata string %q is missing %q", got, want)
}
if got != test.want {
t.Fatalf("Metadata string %q should be %q", got, test.want)
}
}
}
Expand Down

0 comments on commit 6126383

Please sign in to comment.