priorityq/circ/lib_test.go
Sam Fredrickson b00fe25128 Various improvements.
* Expand README.md, provide benchmark results.
* Add docs, benchmarks for binheap and circ packages.
* Add methods Len() and Capacity().
* Change *sync.Cond to sync.Cond.
* TryRecv() and TrySend() distinguish empty and closed errors.
* Improve test coverage.
* Add basic Makefile.
* Fix documentation mistakes.
2023-03-03 15:35:49 -08:00

102 lines
1.7 KiB
Go

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