From 3e6e67c4dcea3ac2f25fd4731abc0e1deaf36216 Mon Sep 17 00:00:00 2001 From: Tim Hockin Date: Tue, 31 Mar 2015 13:55:04 -0700 Subject: Enable methods to sort map keys and spew itself as last resort If enabled by flags, try to use methods to stringify map keys and sort on that. If we can't use primitive sorting and we can't use methods, we can still fall back on spew itself. If SpewKeys is enabled, use Sprintf("%#v") to generate a string and sort by that. --- spew/format_test.go | 49 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) (limited to 'spew/format_test.go') diff --git a/spew/format_test.go b/spew/format_test.go index 4dd0ac2..b0f9761 100644 --- a/spew/format_test.go +++ b/spew/format_test.go @@ -69,9 +69,10 @@ package spew_test import ( "bytes" "fmt" - "github.com/davecgh/go-spew/spew" "testing" "unsafe" + + "github.com/davecgh/go-spew/spew" ) // formatterTest is used to describe a test to be perfomed against NewFormatter. @@ -1478,6 +1479,22 @@ func TestFormatter(t *testing.T) { } } +type testStruct struct { + x int +} + +func (ts testStruct) String() string { + return fmt.Sprintf("ts.%d", ts.x) +} + +type testStructP struct { + x int +} + +func (ts *testStructP) String() string { + return fmt.Sprintf("ts.%d", ts.x) +} + func TestPrintSortedKeys(t *testing.T) { cfg := spew.ConfigState{SortKeys: true} s := cfg.Sprint(map[int]string{1: "1", 3: "3", 2: "2"}) @@ -1485,4 +1502,34 @@ func TestPrintSortedKeys(t *testing.T) { if s != expected { t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) } + + s = cfg.Sprint(map[stringer]int{"1": 1, "3": 3, "2": 2}) + expected = "map[stringer 1:1 stringer 2:2 stringer 3:3]" + if s != expected { + t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) + } + + s = cfg.Sprint(map[pstringer]int{pstringer("1"): 1, pstringer("3"): 3, pstringer("2"): 2}) + expected = "map[stringer 1:1 stringer 2:2 stringer 3:3]" + if s != expected { + t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) + } + + s = cfg.Sprint(map[testStruct]int{testStruct{1}: 1, testStruct{3}: 3, testStruct{2}: 2}) + expected = "map[ts.1:1 ts.2:2 ts.3:3]" + if s != expected { + t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) + } + + s = cfg.Sprint(map[testStructP]int{testStructP{1}: 1, testStructP{3}: 3, testStructP{2}: 2}) + expected = "map[ts.1:1 ts.2:2 ts.3:3]" + if s != expected { + t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) + } + + s = cfg.Sprint(map[customError]int{customError(1): 1, customError(3): 3, customError(2): 2}) + expected = "map[error: 1:1 error: 2:2 error: 3:3]" + if s != expected { + t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) + } } -- cgit v1.2.3