bitbucket.org/espinpro/espincore/v2@v2.0.20/registry/utils/sort_test.go (about)

     1  package utils
     2  
     3  import (
     4  	"math/rand"
     5  	"testing"
     6  
     7  	"bitbucket.org/espinpro/espincore/v2/registry/comparator"
     8  )
     9  
    10  func TestSortInts(t *testing.T) {
    11  	ints := []interface{}{}
    12  	ints = append(ints, 4)
    13  	ints = append(ints, 1)
    14  	ints = append(ints, 2)
    15  	ints = append(ints, 3)
    16  
    17  	Sort(ints, comparator.IntComparator)
    18  
    19  	for i := 1; i < len(ints); i++ {
    20  		if ints[i-1].(int) > ints[i].(int) {
    21  			t.Errorf("Not sorted!")
    22  		}
    23  	}
    24  }
    25  
    26  func TestSortStrings(t *testing.T) {
    27  	strings := []interface{}{}
    28  	strings = append(strings, "d")
    29  	strings = append(strings, "a")
    30  	strings = append(strings, "b")
    31  	strings = append(strings, "c")
    32  
    33  	Sort(strings, comparator.StringComparator)
    34  
    35  	for i := 1; i < len(strings); i++ {
    36  		if strings[i-1].(string) > strings[i].(string) {
    37  			t.Errorf("Not sorted!")
    38  		}
    39  	}
    40  }
    41  
    42  func TestSortStructs(t *testing.T) {
    43  	type User struct {
    44  		id   int
    45  		name string
    46  	}
    47  
    48  	byID := func(a, b interface{}) int {
    49  		c1 := a.(User)
    50  		c2 := b.(User)
    51  		switch {
    52  		case c1.id > c2.id:
    53  			return 1
    54  		case c1.id < c2.id:
    55  			return -1
    56  		default:
    57  			return 0
    58  		}
    59  	}
    60  
    61  	// o1,o2,expected
    62  	users := []interface{}{
    63  		User{4, "d"},
    64  		User{1, "a"},
    65  		User{3, "c"},
    66  		User{2, "b"},
    67  	}
    68  
    69  	Sort(users, byID)
    70  
    71  	for i := 1; i < len(users); i++ {
    72  		if users[i-1].(User).id > users[i].(User).id {
    73  			t.Errorf("Not sorted!")
    74  		}
    75  	}
    76  }
    77  
    78  func TestSortRandom(t *testing.T) {
    79  	ints := []interface{}{}
    80  	for i := 0; i < 10000; i++ {
    81  		ints = append(ints, rand.Int()) //nolint:gosec
    82  	}
    83  	Sort(ints, comparator.IntComparator)
    84  	for i := 1; i < len(ints); i++ {
    85  		if ints[i-1].(int) > ints[i].(int) {
    86  			t.Errorf("Not sorted!")
    87  		}
    88  	}
    89  }
    90  
    91  func BenchmarkGoSortRandom(b *testing.B) {
    92  	b.StopTimer()
    93  	ints := []interface{}{}
    94  	for i := 0; i < 100000; i++ {
    95  		ints = append(ints, rand.Int()) //nolint:gosec
    96  	}
    97  	b.StartTimer()
    98  	Sort(ints, comparator.IntComparator)
    99  	b.StopTimer()
   100  }