github.com/iqoqo/nomad@v0.11.3-0.20200911112621-d7021c74d101/lib/kheap/score_heap_test.go (about) 1 package kheap 2 3 import ( 4 "container/heap" 5 "testing" 6 7 "github.com/stretchr/testify/require" 8 ) 9 10 type heapItem struct { 11 Value string 12 ScoreVal float64 13 } 14 15 func (h *heapItem) Data() interface{} { 16 return h.Value 17 } 18 19 func (h *heapItem) Score() float64 { 20 return h.ScoreVal 21 } 22 23 func TestScoreHeap(t *testing.T) { 24 type testCase struct { 25 desc string 26 items map[string]float64 27 expected []*heapItem 28 } 29 30 cases := []testCase{ 31 { 32 desc: "More than K elements", 33 items: map[string]float64{ 34 "banana": 3.0, 35 "apple": 2.25, 36 "pear": 2.32, 37 "watermelon": 5.45, 38 "orange": 0.20, 39 "strawberry": 9.03, 40 "blueberry": 0.44, 41 "lemon": 3.9, 42 "cherry": 0.03, 43 }, 44 expected: []*heapItem{ 45 {Value: "pear", ScoreVal: 2.32}, 46 {Value: "banana", ScoreVal: 3.0}, 47 {Value: "lemon", ScoreVal: 3.9}, 48 {Value: "watermelon", ScoreVal: 5.45}, 49 {Value: "strawberry", ScoreVal: 9.03}, 50 }, 51 }, 52 { 53 desc: "Less than K elements", 54 items: map[string]float64{ 55 "eggplant": 9.0, 56 "okra": -1.0, 57 "corn": 0.25, 58 }, 59 expected: []*heapItem{ 60 {Value: "okra", ScoreVal: -1.0}, 61 {Value: "corn", ScoreVal: 0.25}, 62 {Value: "eggplant", ScoreVal: 9.0}, 63 }, 64 }, 65 } 66 67 for _, tc := range cases { 68 t.Run("", func(t *testing.T) { 69 // Create Score heap, push elements into it 70 pq := NewScoreHeap(5) 71 for value, score := range tc.items { 72 heapItem := &heapItem{ 73 Value: value, 74 ScoreVal: score, 75 } 76 heap.Push(pq, heapItem) 77 } 78 79 // Take the items out; they arrive in increasing Score order 80 require := require.New(t) 81 require.Equal(len(tc.expected), pq.Len()) 82 83 i := 0 84 for pq.Len() > 0 { 85 item := heap.Pop(pq).(*heapItem) 86 require.Equal(tc.expected[i], item) 87 i++ 88 } 89 }) 90 } 91 92 }