2021-09-18 17:26:11 +00:00
|
|
|
package async_test
|
2019-12-13 23:14:56 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2022-07-12 14:39:18 +00:00
|
|
|
"sync/atomic"
|
2019-12-13 23:14:56 +00:00
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
|
2024-02-15 05:46:47 +00:00
|
|
|
"github.com/prysmaticlabs/prysm/v5/async"
|
2019-12-13 23:14:56 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestEveryRuns(t *testing.T) {
|
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
|
2022-07-12 14:39:18 +00:00
|
|
|
i := int32(0)
|
2021-09-18 17:26:11 +00:00
|
|
|
async.RunEvery(ctx, 100*time.Millisecond, func() {
|
2022-07-12 14:39:18 +00:00
|
|
|
atomic.AddInt32(&i, 1)
|
2019-12-13 23:14:56 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
// Sleep for a bit and ensure the value has increased.
|
2020-01-08 02:36:55 +00:00
|
|
|
time.Sleep(200 * time.Millisecond)
|
2019-12-13 23:14:56 +00:00
|
|
|
|
2022-07-12 14:39:18 +00:00
|
|
|
if atomic.LoadInt32(&i) == 0 {
|
2019-12-13 23:14:56 +00:00
|
|
|
t.Error("Counter failed to increment with ticker")
|
|
|
|
}
|
|
|
|
|
|
|
|
cancel()
|
|
|
|
|
|
|
|
// Sleep for a bit to let the cancel take place.
|
2020-01-08 02:36:55 +00:00
|
|
|
time.Sleep(100 * time.Millisecond)
|
2019-12-13 23:14:56 +00:00
|
|
|
|
2022-07-12 14:39:18 +00:00
|
|
|
last := atomic.LoadInt32(&i)
|
2019-12-13 23:14:56 +00:00
|
|
|
|
|
|
|
// Sleep for a bit and ensure the value has not increased.
|
2020-01-08 02:36:55 +00:00
|
|
|
time.Sleep(200 * time.Millisecond)
|
2019-12-13 23:14:56 +00:00
|
|
|
|
2022-07-12 14:39:18 +00:00
|
|
|
if atomic.LoadInt32(&i) != last {
|
2019-12-13 23:14:56 +00:00
|
|
|
t.Error("Counter incremented after stop")
|
|
|
|
}
|
|
|
|
}
|