Skip to content

Commit

Permalink
Fix race condition in syncer test
Browse files Browse the repository at this point in the history
Add lock to syncerTest to protect read and write for fields in
syncerTest.
  • Loading branch information
sawsa307 committed Apr 20, 2023
1 parent 34fea07 commit 04ffc02
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions pkg/neg/syncers/syncer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package syncers

import (
"fmt"
"sync"
"testing"
"time"

Expand Down Expand Up @@ -63,10 +64,13 @@ type syncerTester struct {
// blockSync is true, then sync function is blocked on channel
blockSync bool
ch chan interface{}
mu sync.Mutex
}

// sync sleeps for 3 seconds
func (t *syncerTester) sync() error {
t.mu.Lock()
defer t.mu.Unlock()
t.syncCount += 1
if t.syncError {
return fmt.Errorf("sync error")
Expand Down Expand Up @@ -128,7 +132,9 @@ func TestStartAndStopNoopSyncer(t *testing.T) {
}

// blocks sync function
syncerTester.mu.Lock()
syncerTester.blockSync = true
syncerTester.mu.Unlock()
syncerTester.syncer.Stop()
if !syncerTester.syncer.IsShuttingDown() {
// assume syncer needs 5 second for sync
Expand Down Expand Up @@ -174,12 +180,18 @@ func TestRetryOnSyncError(t *testing.T) {

if err := wait.PollImmediate(time.Second, 5*time.Second, func() (bool, error) {
// In 5 seconds, syncer should be able to retry 3 times.
return syncerTester.syncCount == maxRetry+1, nil
syncerTester.mu.Lock()
syncCount := syncerTester.syncCount
syncerTester.mu.Unlock()
return syncCount == maxRetry+1, nil
}); err != nil {
t.Errorf("Syncer failed to retry and record error: %v", err)
}

if syncerTester.syncCount != maxRetry+1 {
t.Errorf("Expect sync count to be %v, but got %v", maxRetry+1, syncerTester.syncCount)
syncerTester.mu.Lock()
syncCount := syncerTester.syncCount
syncerTester.mu.Unlock()
if syncCount != maxRetry+1 {
t.Errorf("Expect sync count to be %v, but got %v", maxRetry+1, syncCount)
}
}

0 comments on commit 04ffc02

Please sign in to comment.