From dfbcb1489d78fb83a9c550f92e33bb6ed3c2d711 Mon Sep 17 00:00:00 2001 From: Cuong Manh Le Date: Mon, 11 Dec 2023 23:17:38 +0700 Subject: [PATCH] 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. --- cmd/cli/loop_test.go | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/cmd/cli/loop_test.go b/cmd/cli/loop_test.go index e8cfb2a..b2c8404 100644 --- a/cmd/cli/loop_test.go +++ b/cmd/cli/loop_test.go @@ -2,6 +2,7 @@ package cli import ( "sync" + "sync/atomic" "testing" ) @@ -9,16 +10,19 @@ func Test_loopGuard(t *testing.T) { lg := newLoopGuard() key := "foo" - var mu sync.Mutex - i := 0 + var i atomic.Int64 + var started atomic.Int64 n := 1000 do := func() { locked := lg.TryLock(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 { - mu.Lock() - i++ - mu.Unlock() + i.Add(1) } } @@ -32,7 +36,7 @@ func Test_loopGuard(t *testing.T) { } wg.Wait() - if i == n { + if i.Load() == int64(n) { t.Fatalf("i must not be increased %d times", n) } }