Пример #1
0
func TestAcquireLeadership(t *testing.T) {
	tests := []struct {
		exist       *leaseMeta
		local       leaseMeta
		wantAcquire bool
	}{
		// able to acquire if lease does not already exist
		{
			exist:       nil,
			local:       leaseMeta{machID: "XXX", ver: 12},
			wantAcquire: true,
		},

		// steal if lease exists at lower version
		{
			exist:       &leaseMeta{machID: "YYY", ver: 0},
			local:       leaseMeta{machID: "XXX", ver: 1},
			wantAcquire: true,
		},

		// unable to acquire if lease exists at higher version
		{
			exist:       &leaseMeta{machID: "YYY", ver: 10},
			local:       leaseMeta{machID: "XXX", ver: 2},
			wantAcquire: false,
		},

		// unable to acquire if lease exists at same version
		{
			exist:       &leaseMeta{machID: "YYY", ver: 2},
			local:       leaseMeta{machID: "XXX", ver: 2},
			wantAcquire: false,
		},
	}

	for i, tt := range tests {
		lReg := registry.NewFakeLeaseRegistry()

		if tt.exist != nil {
			lReg.SetLease(engineLeaseName, tt.exist.machID, tt.exist.ver, time.Millisecond)
		}

		got := acquireLeadership(lReg, tt.local.machID, tt.local.ver, time.Millisecond)

		if tt.wantAcquire != (isLeader(got, tt.local.machID)) {
			t.Errorf("case %d: wantAcquire=%t but got %#v", i, tt.wantAcquire, got)
		}
	}
}
Пример #2
0
func TestIsLeader(t *testing.T) {
	tests := []struct {
		lease      *leaseMeta
		machID     string
		wantLeader bool
	}{
		// not a leader if lease is null
		{
			lease:      nil,
			machID:     "XXX",
			wantLeader: false,
		},

		// not a leader if lease is held by a different machines
		{
			lease:      &leaseMeta{machID: "YYY"},
			machID:     "XXX",
			wantLeader: false,
		},

		// leader if lease is valid and held by current machine
		{
			lease:      &leaseMeta{machID: "XXX"},
			machID:     "XXX",
			wantLeader: true,
		},
	}

	for i, tt := range tests {
		lReg := registry.NewFakeLeaseRegistry()

		if tt.lease != nil {
			lReg.SetLease(engineLeaseName, tt.lease.machID, tt.lease.ver, time.Millisecond)
		}

		lease, _ := lReg.GetLease(engineLeaseName)

		got := isLeader(lease, tt.machID)
		if tt.wantLeader != got {
			t.Errorf("case %d: wantLeader=%t but got %t", i, tt.wantLeader, got)
		}
	}
}