github.com/angenalZZZ/gofunc@v0.0.0-20210507121333-48ff1be3917b/g/queue_test.go (about) 1 package g_test 2 3 import ( 4 "github.com/angenalZZZ/gofunc/g" 5 "math/rand" 6 "sort" 7 "testing" 8 "time" 9 10 "github.com/stretchr/testify/assert" 11 ) 12 13 type floatValue float64 14 15 func (a floatValue) Less(b g.QueueComparer) bool { 16 return a < b.(floatValue) 17 } 18 19 var queueData, queueSorted = func() ([]g.QueueComparer, []g.QueueComparer) { 20 rand.Seed(time.Now().UnixNano()) 21 var data []g.QueueComparer 22 for i := 0; i < 100; i++ { 23 data = append(data, floatValue(rand.Float64()*100)) 24 } 25 sorted := make([]g.QueueComparer, len(data)) 26 copy(sorted, data) 27 sort.Slice(sorted, func(i, j int) bool { 28 return sorted[i].Less(sorted[j]) 29 }) 30 return data, sorted 31 }() 32 33 func TestMaintainsPriorityQueue(t *testing.T) { 34 q := g.NewQueue(nil) 35 for i := 0; i < len(queueData); i++ { 36 q.Push(queueData[i]) 37 } 38 assert.Equal(t, q.Peek(), queueSorted[0]) 39 var result []g.QueueComparer 40 for q.Len() > 0 { 41 result = append(result, q.Pop()) 42 } 43 assert.Equal(t, result, queueSorted) 44 } 45 46 func TestAcceptsDataInConstructor(t *testing.T) { 47 q := g.NewQueue(queueData) 48 var result []g.QueueComparer 49 for q.Len() > 0 { 50 result = append(result, q.Pop()) 51 } 52 assert.Equal(t, result, queueSorted) 53 } 54 55 func TestHandlesEdgeCasesWithFewElements(t *testing.T) { 56 q := g.NewQueue(nil) 57 q.Push(floatValue(2)) 58 q.Push(floatValue(1)) 59 q.Pop() 60 q.Pop() 61 q.Pop() 62 q.Push(floatValue(2)) 63 q.Push(floatValue(1)) 64 assert.Equal(t, float64(q.Pop().(floatValue)), 1.0) 65 assert.Equal(t, float64(q.Pop().(floatValue)), 2.0) 66 assert.Equal(t, q.Pop(), nil) 67 }