github.com/benz9527/xboot@v0.0.0-20240504061247-c23f15593274/dlock/etcd_dlock_test.go (about) 1 //go:build linux 2 // +build linux 3 4 package dlock 5 6 import ( 7 "context" 8 "sync" 9 "testing" 10 "time" 11 12 "github.com/stretchr/testify/require" 13 clientv3 "go.etcd.io/etcd/client/v3" 14 tintegration "go.etcd.io/etcd/tests/v3/integration" 15 ) 16 17 func TestEtcdDLock_DataRace(t *testing.T) { 18 tintegration.BeforeTest(t) 19 clusterv3 := tintegration.NewClusterV3(t, &tintegration.ClusterConfig{ 20 Size: 1, 21 }) 22 clients := make([]*clientv3.Client, 0, 2) 23 cliConstructor := tintegration.MakeSingleNodeClients(t, clusterv3, &clients) 24 cli := cliConstructor() 25 26 wg := sync.WaitGroup{} 27 wg.Add(2) 28 29 go func() { 30 lock1, err := EtcdDLockBuilder(context.TODO(), cli). 31 TTL(2*time.Second). 32 Keys("testKey1", "testKey2"). 33 Retry(DefaultExponentialBackoffRetry()). 34 Build() 35 require.NoError(t, err) 36 err = lock1.Lock() 37 if err != nil { 38 t.Logf("lock1.Lock() err: %v", err) 39 wg.Done() 40 return 41 } 42 require.NoError(t, err) 43 require.Error(t, lock1.Renewal(3*time.Second)) 44 ttl, err := lock1.TTL() 45 require.NoError(t, err) 46 t.Log("lock1 ttl", ttl) 47 err = lock1.Unlock() 48 require.NoError(t, err) 49 wg.Done() 50 }() 51 go func() { 52 lock2, err := EtcdDLock(context.TODO(), cli, 53 WithEtcdDLockTTL(2*time.Second), 54 WithEtcdDLockKeys("testKey1", "testKey2"), 55 WithEtcdDLockRetry(DefaultExponentialBackoffRetry()), 56 ) 57 require.NoError(t, err) 58 err = lock2.Lock() 59 if err != nil { 60 t.Logf("lock2.Lock() err: %v", err) 61 wg.Done() 62 return 63 } 64 require.NoError(t, err) 65 ttl, err := lock2.TTL() 66 require.NoError(t, err) 67 t.Log("lock2 ttl", ttl) 68 err = lock2.Unlock() 69 require.NoError(t, err) 70 wg.Done() 71 }() 72 73 wg.Wait() 74 _ = cli.Close() 75 clusterv3.Terminate(t) 76 }