package pool import ( "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() { return func() { 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") } }(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() { return func() { counter += 1 t.Log("task", i, "finished") } }(i) id := pool.AddTask(f) pool.WaitForTask(id) if counter != 1 { t.Errorf("Counter mismatch: expected %d, got %d, task %d", 1, counter, id) } counter -= 1 } pool.Stop() } 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() { return func() { 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") } }(i) id := pool.AddTask(f) ids = append(ids, id) } for _, id := range ids { pool.WaitForTask(id) } if counter != 55 { t.Error("some tasks were not executed") } pool.Stop() }