woj-server/pkg/pool/pool_test.go

109 lines
1.8 KiB
Go
Raw Normal View History

2024-01-06 01:50:20 +08:00
package pool
import (
"errors"
"strconv"
2024-01-06 01:50:20 +08:00
"sync"
"testing"
"time"
)
func TestTaskPool_Stop(t *testing.T) {
pool := NewTaskPool(5, 10)
pool.Start()
lck := sync.Mutex{}
counter := 0
for i := 1; i <= 10; i++ {
f := func(i int) func() error {
return func() error {
2024-01-06 01:50:20 +08:00
lck.Lock()
t.Log("task", i, "locked")
counter += i
t.Log("task", i, "unlocked")
lck.Unlock()
time.Sleep(time.Duration(i*100) * time.Millisecond)
t.Log("task", i, "finished")
return nil
2024-01-06 01:50:20 +08:00
}
}(i)
pool.AddTask(f)
}
pool.Stop()
if counter != 55 {
t.Error("some tasks were not executed")
}
}
func TestTaskPool_WaitForTask(t *testing.T) {
pool := NewTaskPool(10, 10)
pool.Start()
counter := 0
for i := 1; i <= 10; i++ {
f := func(i int) func() error {
return func() error {
2024-01-06 01:50:20 +08:00
counter += 1
t.Log("task", i, "finished")
return errors.New(strconv.Itoa(i))
2024-01-06 01:50:20 +08:00
}
}(i)
id := pool.AddTask(f)
ret := pool.WaitForTask(id)
2024-01-06 01:50:20 +08:00
if counter != 1 {
t.Errorf("Counter mismatch: expected %d, got %d, task %d", 1, counter, id)
}
if ret.Error() != strconv.Itoa(i) {
t.Errorf("Return value mismatch: expected %s, got %s, task %d", strconv.Itoa(i), ret.Error(), id)
}
2024-01-06 01:50:20 +08:00
counter -= 1
}
pool.Stop()
}
2024-01-06 21:03:30 +08:00
func TestTaskPool_One(t *testing.T) {
pool := NewTaskPool(1, 1)
pool.Start()
lck := sync.Mutex{}
counter := 0
ids := make([]int, 0)
for i := 1; i <= 10; i++ {
f := func(i int) func() error {
return func() error {
2024-01-06 21:03:30 +08:00
lck.Lock()
t.Log("task", i, "locked")
counter += i
t.Log("task", i, "unlocked")
lck.Unlock()
time.Sleep(time.Duration(i*10) * time.Millisecond)
t.Log("task", i, "finished")
return nil
2024-01-06 21:03:30 +08:00
}
}(i)
id := pool.AddTask(f)
ids = append(ids, id)
}
for _, id := range ids {
_ = pool.WaitForTask(id)
2024-01-06 21:03:30 +08:00
}
if counter != 55 {
t.Error("some tasks were not executed")
}
pool.Stop()
}