github.com/haraldrudell/parl@v0.4.176/pqs/priority-queue-thread-safe_test.go (about)

     1  /*
     2  © 2022–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
     3  ISC License
     4  */
     5  
     6  package pqs
     7  
     8  import (
     9  	"strconv"
    10  	"testing"
    11  
    12  	"github.com/haraldrudell/parl"
    13  )
    14  
    15  func TestNewOrderedThreadSafe(t *testing.T) {
    16  	type entity struct{ value int }
    17  	value1 := 1
    18  	value2 := 2
    19  	entity1 := entity{value: value1}
    20  	entity2 := entity{value: value2}
    21  	entityStringMap := map[*entity]string{
    22  		&entity1: "entity1",
    23  		&entity2: "entity2",
    24  	}
    25  	ranker := func(entityN *entity) (rank int) {
    26  		return entityN.value
    27  	}
    28  	exp1 := []*entity{&entity2, &entity1}
    29  	expLength := 2
    30  
    31  	var ranking parl.PriorityQueue[entity, int]
    32  	var pmapsRankingThreadSafe *PriorityQueueThreadSafe[entity, int]
    33  	var pmapsRanking *PriorityQueue[entity, int]
    34  	var ok bool
    35  	var rankList []*entity
    36  	var length int
    37  	isSameRanking := func(a, b []*entity) (isSame bool) {
    38  		if len(a) != len(b) {
    39  			return
    40  		}
    41  		for i, entityp := range a {
    42  			if entityp != b[i] {
    43  				return
    44  			}
    45  		}
    46  		return true
    47  	}
    48  	makeListPrintable := func(entities []*entity) (result []string) {
    49  		result = make([]string, len(entities))
    50  		for i, entityp := range entities {
    51  			result[i] = strconv.Quote(entityStringMap[entityp])
    52  		}
    53  		return
    54  	}
    55  
    56  	ranking = NewPriorityQueueThreadSafe(ranker)
    57  	ranking.AddOrUpdate(&entity1)
    58  	ranking.AddOrUpdate(&entity2)
    59  	pmapsRankingThreadSafe, ok = ranking.(*PriorityQueueThreadSafe[entity, int])
    60  	if !ok {
    61  		t.Errorf("type assertion failed: ranking.(*RankingThreadSafe[entity, int])")
    62  		t.FailNow()
    63  	}
    64  	pmapsRanking, ok = pmapsRankingThreadSafe.PriorityQueue.(*PriorityQueue[entity, int])
    65  	if !ok {
    66  		t.Errorf("type assertion failed: pmapsRankingThreadSafe.Ranking.(*Ranking[entity, int])")
    67  		t.FailNow()
    68  	}
    69  	length = pmapsRanking.queue.Length()
    70  	if length != expLength {
    71  		t.Errorf("bad Length1 %d exp %d", length, expLength)
    72  	}
    73  	if rankList = ranking.List(); !isSameRanking(rankList, exp1) {
    74  		t.Errorf("bad list1 %v exp %v", makeListPrintable(rankList), makeListPrintable(exp1))
    75  	}
    76  }