package util import ( "context" "errors" "fmt" "testing" "time" ) // mockRegistrar 内存版注册后端:occupied 模拟已占用的 WorkerID。 type mockRegistrar struct { occupied map[int]bool calls int failOn int // 第 failOn 次调用返回错误(0 表示不失败) } func (m *mockRegistrar) TryCreate(_ context.Context, key, _ string, _ time.Duration) (bool, error) { m.calls++ if m.failOn > 0 && m.calls == m.failOn { return false, errors.New("backend down") } var id int _, _ = fmt.Sscanf(key, WorkerKeyPrefix+"%d", &id) if m.occupied[id] { return false, nil } m.occupied[id] = true return true, nil } // TestAcquireWorkerID_MinIdle 验证抢注最小空闲 ID。 func TestAcquireWorkerID_MinIdle(t *testing.T) { reg := &mockRegistrar{occupied: map[int]bool{0: true, 1: true, 3: true}} id, err := AcquireWorkerID(context.Background(), reg, int(MaxWorkerID)) if err != nil || id != 2 { t.Errorf("期望抢到 2, 实际 (%d, %v)", id, err) } } // TestAcquireWorkerID_Sequential 验证顺序分配 0,1,2... func TestAcquireWorkerID_Sequential(t *testing.T) { reg := &mockRegistrar{occupied: map[int]bool{}} for want := 0; want < 5; want++ { id, err := AcquireWorkerID(context.Background(), reg, int(MaxWorkerID)) if err != nil || id != want { t.Fatalf("第 %d 次应得 %d, 实际 (%d, %v)", want+1, want, id, err) } } } // TestAcquireWorkerID_Exhausted 验证全占用时报错。 func TestAcquireWorkerID_Exhausted(t *testing.T) { reg := &mockRegistrar{occupied: map[int]bool{0: true, 1: true, 2: true}} if _, err := AcquireWorkerID(context.Background(), reg, 2); err == nil { t.Error("全部占用应报错") } } // TestAcquireWorkerID_BackendError 验证后端错误透传。 func TestAcquireWorkerID_BackendError(t *testing.T) { reg := &mockRegistrar{occupied: map[int]bool{}, failOn: 1} if _, err := AcquireWorkerID(context.Background(), reg, 3); err == nil { t.Error("后端错误应透传") } }