cmd/cli: improving loop guard test

We see number of failed test in Github Action, mostly on MacOS or
Windows due to the fact that goroutines are scheduled to be run
consequently.

This commit improves the test, ensuring at least 2 goroutines were
started before increasing the counting.
This commit is contained in:
Cuong Manh Le
2023-12-11 23:17:38 +07:00
committed by Cuong Manh Le
parent 684019c2e3
commit dfbcb1489d

View File

@@ -2,6 +2,7 @@ package cli
import ( import (
"sync" "sync"
"sync/atomic"
"testing" "testing"
) )
@@ -9,16 +10,19 @@ func Test_loopGuard(t *testing.T) {
lg := newLoopGuard() lg := newLoopGuard()
key := "foo" key := "foo"
var mu sync.Mutex var i atomic.Int64
i := 0 var started atomic.Int64
n := 1000 n := 1000
do := func() { do := func() {
locked := lg.TryLock(key) locked := lg.TryLock(key)
defer lg.Unlock(key) defer lg.Unlock(key)
started.Add(1)
for started.Load() < 2 {
// Wait until at least 2 goroutines started, otherwise, on system with heavy load,
// or having only 1 CPU, all goroutines can be scheduled to run consequently.
}
if locked { if locked {
mu.Lock() i.Add(1)
i++
mu.Unlock()
} }
} }
@@ -32,7 +36,7 @@ func Test_loopGuard(t *testing.T) {
} }
wg.Wait() wg.Wait()
if i == n { if i.Load() == int64(n) {
t.Fatalf("i must not be increased %d times", n) t.Fatalf("i must not be increased %d times", n)
} }
} }