| 16 | ) |
| 17 | |
| 18 | func TestElection(t *testing.T) { |
| 19 | if os.Getenv("ETCD_ADDR") == "" { |
| 20 | t.Skip("set ETCD_ADDR to run TestElection") |
| 21 | return |
| 22 | } |
| 23 | addrs := strings.Split(os.Getenv("ETCD_ADDR"), ",") |
| 24 | dispatcher := &events.SyncDispatcher{} |
| 25 | var e1, e2 Election |
| 26 | |
| 27 | client, err := clientv3.New(clientv3.Config{Endpoints: addrs, DialTimeout: 2 * time.Second}) |
| 28 | assert.NoError(t, err) |
| 29 | defer client.Close() |
| 30 | |
| 31 | e1 = Election{ |
| 32 | dispatcher: dispatcher, |
| 33 | status: &Status{isLeader: &atomic.Bool{}}, |
| 34 | driver: leaderetcd2.NewEtcdDriver(client, key.New("test")), |
| 35 | } |
| 36 | e2 = Election{ |
| 37 | dispatcher: dispatcher, |
| 38 | status: &Status{isLeader: &atomic.Bool{}}, |
| 39 | driver: leaderetcd2.NewEtcdDriver(client, key.New("test")), |
| 40 | } |
| 41 | ctx, cancel := context.WithCancel(context.Background()) |
| 42 | |
| 43 | e1.Campaign(ctx) |
| 44 | assert.Equal(t, e1.status.IsLeader(), true) |
| 45 | |
| 46 | go e2.Campaign(ctx) |
| 47 | <-time.After(time.Second) |
| 48 | |
| 49 | assert.Equal(t, e1.status.IsLeader(), true) |
| 50 | assert.Equal(t, e2.status.IsLeader(), false) |
| 51 | |
| 52 | e1.Resign(ctx) |
| 53 | time.Sleep(time.Second) |
| 54 | assert.Equal(t, e1.status.IsLeader(), false) |
| 55 | assert.Equal(t, e2.status.IsLeader(), true) |
| 56 | |
| 57 | cancel() |
| 58 | } |