priorityq/queue/lib_test.go

102 lines
1.7 KiB
Go

package queue_test
import (
"math/rand"
"testing"
"gogs.humancabbage.net/sam/priorityq/queue"
)
func TestRepeatPushPop(t *testing.T) {
t.Parallel()
q := queue.Make[int](4)
if q.Capacity() != 4 {
t.Errorf("wrong capacity")
}
for i := 0; i < 50; i++ {
q.PushBack(1)
q.PushBack(2)
q.PushBack(3)
q.PushBack(4)
if q.Len() != 4 {
t.Errorf("wrong length")
}
checkPop := func(n int) {
if v := q.PopFront(); v != n {
t.Errorf("popped %d, expected %d", v, n)
}
}
checkPop(1)
checkPop(2)
checkPop(3)
checkPop(4)
}
}
func TestInterleavedPushPop(t *testing.T) {
t.Parallel()
q := queue.Make[int](4)
checkPop := func(n int) {
if v := q.PopFront(); v != n {
t.Errorf("popped %d, expected %d", v, n)
}
}
q.PushBack(1)
q.PushBack(2)
q.PushBack(3)
checkPop(1)
q.PushBack(4)
q.PushBack(5)
checkPop(2)
}
func TestEmptyPopPanic(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Errorf("popping empty buffer did not panic")
}
}()
t.Parallel()
q := queue.Make[int](4)
q.PopFront()
}
func TestFullPushPanic(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Errorf("pushing full buffer did not panic")
}
}()
t.Parallel()
q := queue.Make[int](1)
q.PushBack(1)
q.PushBack(2)
}
func BenchmarkPush(b *testing.B) {
q := queue.Make[int](b.N)
rs := rand.NewSource(0)
r := rand.New(rs)
items := make([]int, b.N)
for i := 0; i < b.N; i++ {
items[i] = r.Int()
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
q.PushBack(items[i])
}
}
func BenchmarkPop(b *testing.B) {
q := queue.Make[int](b.N)
rs := rand.NewSource(0)
r := rand.New(rs)
for i := 0; i < b.N; i++ {
q.PushBack(r.Int())
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
q.PopFront()
}
}