Skip to content

Commit

Permalink
Fix flaky test TestField_Map (#47)
Browse files Browse the repository at this point in the history
  • Loading branch information
hanzei authored Nov 23, 2023
1 parent 1d340b9 commit 35caf63
Showing 1 changed file with 23 additions and 9 deletions.
32 changes: 23 additions & 9 deletions field_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ package logr

import (
"bytes"
"strings"
"testing"

"github.com/stretchr/testify/assert"
)

/*
Expand Down Expand Up @@ -111,17 +114,17 @@ func TestField_Array(t *testing.T) {

func TestField_Map(t *testing.T) {
tests := []struct {
name string
field Field
wantW string
wantErr bool
name string
field Field
wantW string
wantCommas int
wantErr bool
}{
{name: "nil", field: Map[map[string]any]("map", nil), wantW: "", wantErr: false},

{name: "empty", field: Map("map", map[string]any{}), wantW: "", wantErr: false},
{name: "one elements", field: Map("map", map[string]int{"foo": 0}), wantW: "foo=0", wantErr: false},
{name: "two elements", field: Map("map", map[string]int{"foo": 0, "bar": 1}), wantW: "foo=0,bar=1", wantErr: false},
{name: "three elements", field: Map("map", map[string]int{"foo": 0, "bar": 1, "xyz": 2}), wantW: "foo=0,bar=1,xyz=2", wantErr: false},
{name: "two elements", field: Map("map", map[string]int{"foo": 0, "bar": 1}), wantW: "foo=0,bar=1", wantCommas: 1, wantErr: false},
{name: "three elements", field: Map("map", map[string]int{"foo": 0, "bar": 1, "xyz": 2}), wantW: "foo=0,bar=1,xyz=2", wantCommas: 2, wantErr: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand All @@ -130,8 +133,19 @@ func TestField_Map(t *testing.T) {
t.Errorf("Field.ValueString() error = %v, wantErr %v", err, tt.wantErr)
return
}
if gotW := w.String(); gotW != tt.wantW {
t.Errorf("Field.ValueString() = %v, want %v", gotW, tt.wantW)
if tt.wantCommas == 0 {
if gotW := w.String(); gotW != tt.wantW {
t.Errorf("Field.ValueString() = %v, want %v", gotW, tt.wantW)
}
} else {
gotW := w.String()
if commas := strings.Count(gotW, ","); commas != tt.wantCommas {
t.Errorf("Got %d commas in %s, want %d", commas, gotW, tt.wantCommas)
}

gotElems := strings.Split(gotW, ",")
wantElems := strings.Split(tt.wantW, ",")
assert.ElementsMatch(t, gotElems, wantElems)
}
})
}
Expand Down

0 comments on commit 35caf63

Please sign in to comment.