mihomo/common/singledo/singledo_test.go

71 lines
1.1 KiB
Go
Raw Permalink Normal View History

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