github.com/FISCO-BCOS/crypto@v0.0.0-20200202032121-bd8ab0b5d4f1/internal/fmtsort/sort_test.go (about)

     1  // Copyright 2018 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package fmtsort_test
     6  
     7  import (
     8  	"fmt"
     9  	"internal/fmtsort"
    10  	"math"
    11  	"reflect"
    12  	"strings"
    13  	"testing"
    14  )
    15  
    16  var compareTests = [][]reflect.Value{
    17  	ct(reflect.TypeOf(int(0)), -1, 0, 1),
    18  	ct(reflect.TypeOf(int8(0)), -1, 0, 1),
    19  	ct(reflect.TypeOf(int16(0)), -1, 0, 1),
    20  	ct(reflect.TypeOf(int32(0)), -1, 0, 1),
    21  	ct(reflect.TypeOf(int64(0)), -1, 0, 1),
    22  	ct(reflect.TypeOf(uint(0)), 0, 1, 5),
    23  	ct(reflect.TypeOf(uint8(0)), 0, 1, 5),
    24  	ct(reflect.TypeOf(uint16(0)), 0, 1, 5),
    25  	ct(reflect.TypeOf(uint32(0)), 0, 1, 5),
    26  	ct(reflect.TypeOf(uint64(0)), 0, 1, 5),
    27  	ct(reflect.TypeOf(uintptr(0)), 0, 1, 5),
    28  	ct(reflect.TypeOf(string("")), "", "a", "ab"),
    29  	ct(reflect.TypeOf(float32(0)), math.NaN(), math.Inf(-1), -1e10, 0, 1e10, math.Inf(1)),
    30  	ct(reflect.TypeOf(float64(0)), math.NaN(), math.Inf(-1), -1e10, 0, 1e10, math.Inf(1)),
    31  	ct(reflect.TypeOf(complex64(0+1i)), -1-1i, -1+0i, -1+1i, 0-1i, 0+0i, 0+1i, 1-1i, 1+0i, 1+1i),
    32  	ct(reflect.TypeOf(complex128(0+1i)), -1-1i, -1+0i, -1+1i, 0-1i, 0+0i, 0+1i, 1-1i, 1+0i, 1+1i),
    33  	ct(reflect.TypeOf(false), false, true),
    34  	ct(reflect.TypeOf(&ints[0]), &ints[0], &ints[1], &ints[2]),
    35  	ct(reflect.TypeOf(chans[0]), chans[0], chans[1], chans[2]),
    36  	ct(reflect.TypeOf(toy{}), toy{0, 1}, toy{0, 2}, toy{1, -1}, toy{1, 1}),
    37  	ct(reflect.TypeOf([2]int{}), [2]int{1, 1}, [2]int{1, 2}, [2]int{2, 0}),
    38  	ct(reflect.TypeOf(interface{}(interface{}(0))), iFace, 1, 2, 3),
    39  }
    40  
    41  var iFace interface{}
    42  
    43  func ct(typ reflect.Type, args ...interface{}) []reflect.Value {
    44  	value := make([]reflect.Value, len(args))
    45  	for i, v := range args {
    46  		x := reflect.ValueOf(v)
    47  		if !x.IsValid() { // Make it a typed nil.
    48  			x = reflect.Zero(typ)
    49  		} else {
    50  			x = x.Convert(typ)
    51  		}
    52  		value[i] = x
    53  	}
    54  	return value
    55  }
    56  
    57  func TestCompare(t *testing.T) {
    58  	for _, test := range compareTests {
    59  		for i, v0 := range test {
    60  			for j, v1 := range test {
    61  				c := fmtsort.Compare(v0, v1)
    62  				var expect int
    63  				switch {
    64  				case i == j:
    65  					expect = 0
    66  					// NaNs are tricky.
    67  					if typ := v0.Type(); (typ.Kind() == reflect.Float32 || typ.Kind() == reflect.Float64) && math.IsNaN(v0.Float()) {
    68  						expect = -1
    69  					}
    70  				case i < j:
    71  					expect = -1
    72  				case i > j:
    73  					expect = 1
    74  				}
    75  				if c != expect {
    76  					t.Errorf("%s: compare(%v,%v)=%d; expect %d", v0.Type(), v0, v1, c, expect)
    77  				}
    78  			}
    79  		}
    80  	}
    81  }
    82  
    83  type sortTest struct {
    84  	data  interface{} // Always a map.
    85  	print string      // Printed result using our custom printer.
    86  }
    87  
    88  var sortTests = []sortTest{
    89  	{
    90  		map[int]string{7: "bar", -3: "foo"},
    91  		"-3:foo 7:bar",
    92  	},
    93  	{
    94  		map[uint8]string{7: "bar", 3: "foo"},
    95  		"3:foo 7:bar",
    96  	},
    97  	{
    98  		map[string]string{"7": "bar", "3": "foo"},
    99  		"3:foo 7:bar",
   100  	},
   101  	{
   102  		map[float64]string{7: "bar", -3: "foo", math.NaN(): "nan", math.Inf(0): "inf"},
   103  		"NaN:nan -3:foo 7:bar +Inf:inf",
   104  	},
   105  	{
   106  		map[complex128]string{7 + 2i: "bar2", 7 + 1i: "bar", -3: "foo", complex(math.NaN(), 0i): "nan", complex(math.Inf(0), 0i): "inf"},
   107  		"(NaN+0i):nan (-3+0i):foo (7+1i):bar (7+2i):bar2 (+Inf+0i):inf",
   108  	},
   109  	{
   110  		map[bool]string{true: "true", false: "false"},
   111  		"false:false true:true",
   112  	},
   113  	{
   114  		chanMap(),
   115  		"CHAN0:0 CHAN1:1 CHAN2:2",
   116  	},
   117  	{
   118  		pointerMap(),
   119  		"PTR0:0 PTR1:1 PTR2:2",
   120  	},
   121  	{
   122  		map[toy]string{toy{7, 2}: "72", toy{7, 1}: "71", toy{3, 4}: "34"},
   123  		"{3 4}:34 {7 1}:71 {7 2}:72",
   124  	},
   125  	{
   126  		map[[2]int]string{{7, 2}: "72", {7, 1}: "71", {3, 4}: "34"},
   127  		"[3 4]:34 [7 1]:71 [7 2]:72",
   128  	},
   129  }
   130  
   131  func sprint(data interface{}) string {
   132  	om := fmtsort.Sort(reflect.ValueOf(data))
   133  	if om == nil {
   134  		return "nil"
   135  	}
   136  	b := new(strings.Builder)
   137  	for i, key := range om.Key {
   138  		if i > 0 {
   139  			b.WriteRune(' ')
   140  		}
   141  		b.WriteString(sprintKey(key))
   142  		b.WriteRune(':')
   143  		b.WriteString(fmt.Sprint(om.Value[i]))
   144  	}
   145  	return b.String()
   146  }
   147  
   148  // sprintKey formats a reflect.Value but gives reproducible values for some
   149  // problematic types such as pointers. Note that it only does special handling
   150  // for the troublesome types used in the test cases; it is not a general
   151  // printer.
   152  func sprintKey(key reflect.Value) string {
   153  	switch str := key.Type().String(); str {
   154  	case "*int":
   155  		ptr := key.Interface().(*int)
   156  		for i := range ints {
   157  			if ptr == &ints[i] {
   158  				return fmt.Sprintf("PTR%d", i)
   159  			}
   160  		}
   161  		return "PTR???"
   162  	case "chan int":
   163  		c := key.Interface().(chan int)
   164  		for i := range chans {
   165  			if c == chans[i] {
   166  				return fmt.Sprintf("CHAN%d", i)
   167  			}
   168  		}
   169  		return "CHAN???"
   170  	default:
   171  		return fmt.Sprint(key)
   172  	}
   173  }
   174  
   175  var (
   176  	ints  [3]int
   177  	chans = [3]chan int{make(chan int), make(chan int), make(chan int)}
   178  )
   179  
   180  func pointerMap() map[*int]string {
   181  	m := make(map[*int]string)
   182  	for i := 2; i >= 0; i-- {
   183  		m[&ints[i]] = fmt.Sprint(i)
   184  	}
   185  	return m
   186  }
   187  
   188  func chanMap() map[chan int]string {
   189  	m := make(map[chan int]string)
   190  	for i := 2; i >= 0; i-- {
   191  		m[chans[i]] = fmt.Sprint(i)
   192  	}
   193  	return m
   194  }
   195  
   196  type toy struct {
   197  	A int // Exported.
   198  	b int // Unexported.
   199  }
   200  
   201  func TestOrder(t *testing.T) {
   202  	for _, test := range sortTests {
   203  		got := sprint(test.data)
   204  		if got != test.print {
   205  			t.Errorf("%s: got %q, want %q", reflect.TypeOf(test.data), got, test.print)
   206  		}
   207  	}
   208  }
   209  
   210  func TestInterface(t *testing.T) {
   211  	// A map containing multiple concrete types should be sorted by type,
   212  	// then value. However, the relative ordering of types is unspecified,
   213  	// so test this by checking the presence of sorted subgroups.
   214  	m := map[interface{}]string{
   215  		[2]int{1, 0}:             "",
   216  		[2]int{0, 1}:             "",
   217  		true:                     "",
   218  		false:                    "",
   219  		3.1:                      "",
   220  		2.1:                      "",
   221  		1.1:                      "",
   222  		math.NaN():               "",
   223  		3:                        "",
   224  		2:                        "",
   225  		1:                        "",
   226  		"c":                      "",
   227  		"b":                      "",
   228  		"a":                      "",
   229  		struct{ x, y int }{1, 0}: "",
   230  		struct{ x, y int }{0, 1}: "",
   231  	}
   232  	got := sprint(m)
   233  	typeGroups := []string{
   234  		"NaN: 1.1: 2.1: 3.1:", // float64
   235  		"false: true:",        // bool
   236  		"1: 2: 3:",            // int
   237  		"a: b: c:",            // string
   238  		"[0 1]: [1 0]:",       // [2]int
   239  		"{0 1}: {1 0}:",       // struct{ x int; y int }
   240  	}
   241  	for _, g := range typeGroups {
   242  		if !strings.Contains(got, g) {
   243  			t.Errorf("sorted map should contain %q", g)
   244  		}
   245  	}
   246  }