2019-12-10 07:04:22 +00:00
|
|
|
package singledo
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
|
2023-11-03 13:01:45 +00:00
|
|
|
"github.com/metacubex/mihomo/common/atomic"
|
2023-04-22 07:37:57 +00:00
|
|
|
|
2019-12-10 07:04:22 +00:00
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestBasic(t *testing.T) {
|
2022-04-23 18:07:57 +00:00
|
|
|
single := NewSingle[int](time.Millisecond * 30)
|
2019-12-10 07:04:22 +00:00
|
|
|
foo := 0
|
2021-10-10 15:44:09 +00:00
|
|
|
shardCount := atomic.NewInt32(0)
|
2022-04-23 18:07:57 +00:00
|
|
|
call := func() (int, error) {
|
2019-12-10 07:04:22 +00:00
|
|
|
foo++
|
2019-12-10 08:26:15 +00:00
|
|
|
time.Sleep(time.Millisecond * 5)
|
2022-04-23 18:07:57 +00:00
|
|
|
return 0, nil
|
2019-12-10 07:04:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var wg sync.WaitGroup
|
2020-04-30 12:13:27 +00:00
|
|
|
const n = 5
|
2019-12-10 07:04:22 +00:00
|
|
|
wg.Add(n)
|
|
|
|
for i := 0; i < n; i++ {
|
|
|
|
go func() {
|
|
|
|
_, _, shard := single.Do(call)
|
|
|
|
if shard {
|
2023-04-22 07:37:57 +00:00
|
|
|
shardCount.Add(1)
|
2019-12-10 07:04:22 +00:00
|
|
|
}
|
|
|
|
wg.Done()
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
|
|
|
|
wg.Wait()
|
|
|
|
assert.Equal(t, 1, foo)
|
2020-10-29 09:51:14 +00:00
|
|
|
assert.Equal(t, int32(4), shardCount.Load())
|
2019-12-10 07:04:22 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func TestTimer(t *testing.T) {
|
2022-04-23 18:07:57 +00:00
|
|
|
single := NewSingle[int](time.Millisecond * 30)
|
2019-12-10 07:04:22 +00:00
|
|
|
foo := 0
|
2022-04-23 18:07:57 +00:00
|
|
|
callM := func() (int, error) {
|
2019-12-10 07:04:22 +00:00
|
|
|
foo++
|
2022-04-23 18:07:57 +00:00
|
|
|
return 0, nil
|
2019-12-10 07:04:22 +00:00
|
|
|
}
|
|
|
|
|
2022-04-23 18:07:57 +00:00
|
|
|
_, _, _ = single.Do(callM)
|
2019-12-10 07:04:22 +00:00
|
|
|
time.Sleep(10 * time.Millisecond)
|
2022-04-23 18:07:57 +00:00
|
|
|
_, _, shard := single.Do(callM)
|
2019-12-10 07:04:22 +00:00
|
|
|
|
|
|
|
assert.Equal(t, 1, foo)
|
|
|
|
assert.True(t, shard)
|
|
|
|
}
|
2020-04-30 12:13:27 +00:00
|
|
|
|
|
|
|
func TestReset(t *testing.T) {
|
2022-04-23 18:07:57 +00:00
|
|
|
single := NewSingle[int](time.Millisecond * 30)
|
2020-04-30 12:13:27 +00:00
|
|
|
foo := 0
|
2022-04-23 18:07:57 +00:00
|
|
|
callM := func() (int, error) {
|
2020-04-30 12:13:27 +00:00
|
|
|
foo++
|
2022-04-23 18:07:57 +00:00
|
|
|
return 0, nil
|
2020-04-30 12:13:27 +00:00
|
|
|
}
|
|
|
|
|
2022-04-23 18:07:57 +00:00
|
|
|
_, _, _ = single.Do(callM)
|
2020-04-30 12:13:27 +00:00
|
|
|
single.Reset()
|
2022-04-23 18:07:57 +00:00
|
|
|
_, _, _ = single.Do(callM)
|
2020-04-30 12:13:27 +00:00
|
|
|
|
|
|
|
assert.Equal(t, 2, foo)
|
|
|
|
}
|