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
19 changes: 16 additions & 3 deletions assert/assertions.go
Original file line number Diff line number Diff line change
Expand Up @@ -596,6 +596,19 @@ func samePointers(first, second interface{}) (same bool, ok bool) {
return first == second, true
}

// formatValue formats a value for display in error messages. It uses %v for
// unsigned integers to avoid the hex representation that %#v produces, and
// %#v for all other types to preserve struct field names and string quotes.
func formatValue(value interface{}) string {
if value != nil {
kind := reflect.TypeOf(value).Kind()
if kind >= reflect.Uint && kind <= reflect.Uintptr {
return truncatingFormat("%v", value)
}
}
return truncatingFormat("%#v", value)
}

// formatUnequalValues takes two values of arbitrary types and returns string
// representations appropriate to be presented to the user.
//
Expand All @@ -604,14 +617,14 @@ func samePointers(first, second interface{}) (same bool, ok 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(%s)", expected, truncatingFormat("%#v", expected)),
fmt.Sprintf("%T(%s)", actual, truncatingFormat("%#v", actual))
return fmt.Sprintf("%T(%s)", expected, formatValue(expected)),
fmt.Sprintf("%T(%s)", actual, formatValue(actual))
}
switch expected.(type) {
case time.Duration:
return fmt.Sprintf("%v", expected), fmt.Sprintf("%v", actual)
}
return truncatingFormat("%#v", expected), truncatingFormat("%#v", actual)
return formatValue(expected), formatValue(actual)
}

// truncatingFormat formats the data and truncates it if it's too long.
Expand Down
9 changes: 9 additions & 0 deletions assert/assertions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -863,6 +863,15 @@ func TestFormatUnequalValues(t *testing.T) {
expected, actual = formatUnequalValues(&testStructType{Val: "test"}, &testStructType{Val: "test"})
Equal(t, `&assert.testStructType{Val:"test"}`, expected, "value should not include type annotation")
Equal(t, `&assert.testStructType{Val:"test"}`, actual, "value should not include type annotation")

// Unsigned integers should print as decimal, not hex (issue #400).
expected, actual = formatUnequalValues(uint(1700), uint(1701))
Equal(t, `1700`, expected, "uint should print as decimal")
Equal(t, `1701`, actual, "uint should print as decimal")

expected, actual = formatUnequalValues(uint(1700), int(1701))
Equal(t, `uint(1700)`, expected, "uint should print as decimal with type prefix")
Equal(t, `int(1701)`, actual, "int should print as decimal with type prefix")
}

func TestNotNil(t *testing.T) {
Expand Down
Loading