github.com/weedge/lib@v0.0.0-20230424045628-a36dcc1d90e4/container/queue/priority_queue_test.go (about)

     1  package queue
     2  
     3  import (
     4  	"container/heap"
     5  	"math/rand"
     6  	"path/filepath"
     7  	"reflect"
     8  	"runtime"
     9  	"sort"
    10  	"testing"
    11  )
    12  
    13  func equal(t *testing.T, act, exp interface{}) {
    14  	if !reflect.DeepEqual(exp, act) {
    15  		_, file, line, _ := runtime.Caller(1)
    16  		t.Logf("\033[31m%s:%d:\n\n\texp: %#v\n\n\tgot: %#v\033[39m\n\n",
    17  			filepath.Base(file), line, exp, act)
    18  		t.FailNow()
    19  	}
    20  }
    21  
    22  func TestPriorityQueue_Ops(t *testing.T) {
    23  	c := 100
    24  	pq := NewPriorityQueue(c)
    25  
    26  	ints := make([]int, 0, c)
    27  	for i := 0; i < c; i++ {
    28  		v := rand.Int()
    29  		ints = append(ints, v)
    30  		heap.Push(&pq, &Item{Value: "test", Priority: int64(v)})
    31  	}
    32  	equal(t, len(pq), c)
    33  
    34  	sort.Ints(ints)
    35  
    36  	item := heap.Pop(&pq)
    37  	equal(t, item.(*Item).Priority, int64(ints[0]))
    38  
    39  	for i := 0; i < 10; i++ {
    40  		heap.Remove(&pq, rand.Intn((c-1)-i))
    41  	}
    42  
    43  	lastPriority := heap.Pop(&pq).(*Item).Priority
    44  	for i := 0; i < (c - 10 - 1 - 1); i++ {
    45  		item := heap.Pop(&pq)
    46  		equal(t, lastPriority < item.(*Item).Priority, true)
    47  		lastPriority = item.(*Item).Priority
    48  	}
    49  
    50  	equal(t, len(pq), 0)
    51  }
    52  
    53  func TestPriorityQueue_PeekAndShift(t *testing.T) {
    54  	c := 100
    55  	pq := NewPriorityQueue(c)
    56  
    57  	for i := 0; i < c; i++ {
    58  		heap.Push(&pq, &Item{Value: "test", Priority: int64(i)})
    59  	}
    60  	equal(t, len(pq), c)
    61  
    62  	for i := 0; i < c; i++ {
    63  		item, _ := pq.PeekAndShift(int64(c - 1))
    64  		equal(t, item.Priority, int64(i))
    65  	}
    66  }
    67  
    68  func TestPriorityQueue_Update(t *testing.T) {
    69  	c := 10
    70  	pq := NewPriorityQueue(c)
    71  
    72  	for i := 0; i < c; i++ {
    73  		heap.Push(&pq, &Item{Value: "test", Priority: int64(i)})
    74  	}
    75  	equal(t, len(pq), c)
    76  	equal(t, pq.Top().Priority, int64(0))
    77  
    78  	item := &Item{Value: "test-1", Priority: int64(-1)}
    79  	heap.Push(&pq, item)
    80  	equal(t, pq.Top().Priority, int64(-1))
    81  
    82  	pq.Update(item, "test10", int64(c))
    83  	equal(t, pq.Top().Priority, int64(0))
    84  
    85  	equal(t, len(pq), c+1)
    86  }