From 310548cda69b834eb40920ed9571b6d828427612 Mon Sep 17 00:00:00 2001 From: Hiram Chirino Date: Sat, 25 Jan 2020 10:46:29 -0500 Subject: [PATCH] fix: error diff was not being show for large values If you were comparing values which when formatted were longer than about 64k then the actual, expected and diff messages were not printed to the console. --- assert/assertions.go | 19 ++++++++++++++++--- assert/assertions_test.go | 16 ++++++++++++++++ 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/assert/assertions.go b/assert/assertions.go index b73b2d5..e0ea9b6 100644 --- a/assert/assertions.go +++ b/assert/assertions.go @@ -429,14 +429,27 @@ func samePointers(first, second interface{}) bool { // to a type conversion in the Go grammar. func formatUnequalValues(expected, actual interface{}) (e string, a string) { if reflect.TypeOf(expected) != reflect.TypeOf(actual) { - return fmt.Sprintf("%T(%#v)", expected, expected), - fmt.Sprintf("%T(%#v)", actual, actual) + return fmt.Sprintf("%T(%s)", expected, truncatingFormat(expected)), + fmt.Sprintf("%T(%s)", actual, truncatingFormat(actual)) } switch expected.(type) { case time.Duration: return fmt.Sprintf("%v", expected), fmt.Sprintf("%v", actual) } - return fmt.Sprintf("%#v", expected), fmt.Sprintf("%#v", actual) + return truncatingFormat(expected), truncatingFormat(actual) +} + +// truncatingFormat formats the data and truncates it if it's too long. +// +// This helps keep formatted error messages lines from exceeding the +// bufio.MaxScanTokenSize max line length that the go testing framework imposes. +func truncatingFormat(data interface{}) string { + value := fmt.Sprintf("%#v", data) + max := bufio.MaxScanTokenSize - 100 // Give us some space the type info too if needed. + if len(value) > max { + value = value[0:max] + "<... truncated>" + } + return value } // EqualValues asserts that two objects are equal or convertable to the same types diff --git a/assert/assertions_test.go b/assert/assertions_test.go index ebcb8c3..29f89da 100644 --- a/assert/assertions_test.go +++ b/assert/assertions_test.go @@ -1,6 +1,7 @@ package assert import ( + "bufio" "bytes" "encoding/json" "errors" @@ -2255,3 +2256,18 @@ func Test_validateEqualArgs(t *testing.T) { t.Error("nil functions are equal") } } + +func Test_truncatingFormat(t *testing.T) { + + original := strings.Repeat("a", bufio.MaxScanTokenSize-102) + result := truncatingFormat(original) + Equal(t, fmt.Sprintf("%#v", original), result, "string should not be truncated") + + original = original + "x" + result = truncatingFormat(original) + NotEqual(t, fmt.Sprintf("%#v", original), result, "string should have been truncated.") + + if !strings.HasSuffix(result, "<... truncated>") { + t.Error("truncated string should have <... truncated> suffix") + } +}