2
0
mirror of https://github.com/hibiken/asynq.git synced 2024-12-26 07:42:17 +08:00

Fix data race in syncer test

This commit is contained in:
Ken Hibino 2020-02-16 21:09:16 -08:00
parent 906f231e6c
commit 0cc486a975

View File

@ -5,11 +5,11 @@
package asynq package asynq
import ( import (
"fmt"
"sync" "sync"
"testing" "testing"
"time" "time"
"github.com/go-redis/redis/v7"
h "github.com/hibiken/asynq/internal/asynqtest" h "github.com/hibiken/asynq/internal/asynqtest"
"github.com/hibiken/asynq/internal/base" "github.com/hibiken/asynq/internal/base"
"github.com/hibiken/asynq/internal/rdb" "github.com/hibiken/asynq/internal/rdb"
@ -50,54 +50,43 @@ func TestSyncer(t *testing.T) {
} }
func TestSyncerRetry(t *testing.T) { func TestSyncerRetry(t *testing.T) {
inProgress := []*base.TaskMessage{
h.NewTaskMessage("send_email", nil),
h.NewTaskMessage("reindex", nil),
h.NewTaskMessage("gen_thumbnail", nil),
}
goodClient := setup(t)
h.SeedInProgressQueue(t, goodClient, inProgress)
// Simulate the situation where redis server is down
// by connecting to a wrong port.
badClient := redis.NewClient(&redis.Options{
Addr: "localhost:6390",
})
rdbClient := rdb.NewRDB(badClient)
const interval = time.Second const interval = time.Second
syncRequestCh := make(chan *syncRequest) syncRequestCh := make(chan *syncRequest)
syncer := newSyncer(syncRequestCh, interval) syncer := newSyncer(syncRequestCh, interval)
var wg sync.WaitGroup var wg sync.WaitGroup
syncer.start(&wg) syncer.start(&wg)
defer syncer.terminate() defer syncer.terminate()
for _, msg := range inProgress { var (
m := msg mu sync.Mutex
counter int
)
// Increment the counter for each call.
// Initial call will fail and second call will succeed.
requestFunc := func() error {
mu.Lock()
defer mu.Unlock()
if counter == 0 {
counter++
return fmt.Errorf("zero")
}
counter++
return nil
}
syncRequestCh <- &syncRequest{ syncRequestCh <- &syncRequest{
fn: func() error { fn: requestFunc,
return rdbClient.Done(m) errMsg: "error",
},
}
} }
time.Sleep(2 * interval) // ensure that syncer runs at least once // allow syncer to retry
time.Sleep(3 * interval)
// Sanity check to ensure that message was not successfully deleted mu.Lock()
// from in-progress list. if counter != 2 {
gotInProgress := h.GetInProgressMessages(t, goodClient) t.Errorf("counter = %d, want 2", counter)
if l := len(gotInProgress); l != len(inProgress) {
t.Errorf("%q has length %d; want %d", base.InProgressQueue, l, len(inProgress))
}
// FIXME: This assignment introduces data race and running the test with -race will fail.
// simualate failover.
rdbClient = rdb.NewRDB(goodClient)
time.Sleep(2 * interval) // ensure that syncer runs at least once
gotInProgress = h.GetInProgressMessages(t, goodClient)
if l := len(gotInProgress); l != 0 {
t.Errorf("%q has length %d; want 0", base.InProgressQueue, l)
} }
mu.Unlock()
} }