github.com/arafatk/dataViz@v0.0.0-20190312232637-a92bdc2b62a5/utils/sort_test.go (about)

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