Skip to content
Open
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
18 changes: 17 additions & 1 deletion assert/assertions.go
Original file line number Diff line number Diff line change
Expand Up @@ -1542,7 +1542,7 @@ func InDeltaMapValues(t TestingT, expected, actual interface{}, delta float64, m
ev.Interface(),
av.Interface(),
delta,
msgAndArgs...,
msgAndArgsWithKey(k, msgAndArgs)...,
) {
return false
}
Expand All @@ -1551,6 +1551,22 @@ func InDeltaMapValues(t TestingT, expected, actual interface{}, delta float64, m
return true
}

// msgAndArgsWithKey prepends "key[<key>]" to the user message in msgAndArgs.
// Nothing is formatted here, so the message is only rendered on failure.
func msgAndArgsWithKey(key interface{}, msgAndArgs []interface{}) []interface{} {
switch len(msgAndArgs) {
case 0:
return []interface{}{"key[%v]", key}
case 1:
return []interface{}{"key[%v]: %+v", key, msgAndArgs[0]}
}
format, ok := msgAndArgs[0].(string)
if !ok {
return msgAndArgs
}
return append([]interface{}{"key[%v]: " + format, key}, msgAndArgs[1:]...)
}

func calcRelativeError(expected, actual interface{}) (float64, error) {
af, aok := toFloat(expected)
bf, bok := toFloat(actual)
Expand Down
45 changes: 45 additions & 0 deletions assert/assertions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2442,6 +2442,51 @@ func TestInDeltaMapValues(t *testing.T) {
}
}

func TestInDeltaMapValues_ErrorIncludesKey(t *testing.T) {
t.Parallel()

for _, tc := range []struct {
title string
expected interface{}
actual interface{}
msgAndArgs []interface{}
wantSub string
}{
{
title: "string key",
expected: map[string]int{"a": 3, "b": 1},
actual: map[string]int{"a": 4, "b": 1},
wantSub: "Messages: \tkey[a]\n",
},
{
title: "int key",
expected: map[int]float64{1: 1.0, 2: 2.0},
actual: map[int]float64{1: 1.0, 2: 5.0},
wantSub: "Messages: \tkey[2]\n",
},
{
title: "single string message is not formatted",
expected: map[string]float64{"x": 1.0},
actual: map[string]float64{"x": math.NaN()},
msgAndArgs: []interface{}{"100%"},
wantSub: "Messages: \tkey[x]: 100%\n",
},
{
title: "formatted message",
expected: map[string]interface{}{"a": "not-a-number"},
actual: map[string]interface{}{"a": "still-not"},
msgAndArgs: []interface{}{"case %d", 7},
wantSub: "Messages: \tkey[a]: case 7\n",
},
} {
t.Run(tc.title, func(t *testing.T) {
mockT := new(mockTestingT)
False(t, InDeltaMapValues(mockT, tc.expected, tc.actual, 0.1, tc.msgAndArgs...))
Contains(t, mockT.errorString(), tc.wantSub)
})
}
}

func TestInEpsilon(t *testing.T) {
t.Parallel()

Expand Down