priorityq/queue/lib_test.go
Sam Fredrickson 87212466ae
Some checks failed
Build & Test / Main (push) Failing after 5s
Add iterators for a couple queues.
2024-08-22 00:53:48 -07:00

147 lines
2.4 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 TestIter(t *testing.T) {
q := queue.Make[int](4)
q.PushBack(1)
q.PushBack(2)
q.PushBack(3)
q.PushBack(4)
i := 0
for v := range q.Iter() {
expected := i + 1
if v != expected {
t.Errorf("iter %d should have value %d, not %d",
i, expected, v)
}
i++
}
if q.Len() != 4 {
t.Errorf("wrong length")
}
}
func TestIterPop(t *testing.T) {
t.Parallel()
q := queue.Make[int](4)
q.PushBack(1)
q.PushBack(2)
q.PushBack(3)
q.PushBack(4)
i := 0
for v := range q.IterPop() {
expected := i + 1
if v != expected {
t.Errorf("iter %d should have value %d, not %d",
i, expected, v)
}
i++
// to test yield() returning false
if i == 4 {
break
}
}
if q.Len() != 0 {
t.Errorf("wrong length")
}
}
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()
}
}