Skip to content

Commit 0677c44

Browse files
committed
[config] fix flaky test in leader_elector_test
1 parent e9995dd commit 0677c44

File tree

1 file changed

+29
-9
lines changed

1 file changed

+29
-9
lines changed

kv_cache_manager/config/test/leader_elector_test.cc

Lines changed: 29 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ class LeaderElectorTest : public TESTBASE {
3232
// 准备选举器参数
3333
lock_key_ = "test_lock_key";
3434
lock_value_ = "127.0.0.1-" + std::to_string(getpid());
35-
lease_ms_ = 100; // 较短的租约时间以便测试
35+
lease_ms_ = 1000; // 较短的租约时间以便测试
3636
loop_interval_ms_ = 10;
3737
}
3838

@@ -118,8 +118,13 @@ TEST_F(LeaderElectorTest, SingleElectorBecomesLeader) {
118118

119119
EXPECT_TRUE(elector->Start());
120120

121-
// 等待足够时间让选举器有机会成为领导者
122-
std::this_thread::sleep_for(std::chrono::milliseconds(200));
121+
for (int i = 0; i < 100; i++) {
122+
// 等待足够时间让选举发生
123+
if (become_leader_called) {
124+
break;
125+
}
126+
std::this_thread::sleep_for(std::chrono::milliseconds(100));
127+
}
123128

124129
// 应该成为领导者
125130
EXPECT_TRUE(become_leader_called);
@@ -145,8 +150,13 @@ TEST_F(LeaderElectorTest, ManualDemote) {
145150

146151
EXPECT_TRUE(elector->Start());
147152

148-
// 等待成为领导者
149-
std::this_thread::sleep_for(std::chrono::milliseconds(200));
153+
for (int i = 0; i < 100; i++) {
154+
// 等待足够时间让选举发生
155+
if (elector->IsLeader()) {
156+
break;
157+
}
158+
std::this_thread::sleep_for(std::chrono::milliseconds(100));
159+
}
150160

151161
ASSERT_TRUE(elector->IsLeader());
152162
ASSERT_TRUE(become_leader_called);
@@ -188,8 +198,13 @@ TEST_F(LeaderElectorTest, TwoElectorsCompetition) {
188198
EXPECT_TRUE(elector1->Start());
189199
EXPECT_TRUE(elector2->Start());
190200

191-
// 等待足够时间让选举发生
192-
std::this_thread::sleep_for(std::chrono::milliseconds(300));
201+
for (int i = 0; i < 100; i++) {
202+
// 等待足够时间让选举发生
203+
if (elector1->IsLeader() || elector2->IsLeader()) {
204+
break;
205+
}
206+
std::this_thread::sleep_for(std::chrono::milliseconds(100));
207+
}
193208

194209
// 检查只有一个选举器成为领导者
195210
const bool is_elector1_first_leader = elector1->IsLeader();
@@ -413,8 +428,13 @@ TEST_F(LeaderElectorTest, MultipleElectorsDifferentKeys) {
413428
EXPECT_TRUE(elector1->Start());
414429
EXPECT_TRUE(elector2->Start());
415430

416-
// 等待足够时间
417-
std::this_thread::sleep_for(std::chrono::milliseconds(300));
431+
for (int i = 0; i < 100; i++) {
432+
// 等待足够时间让选举发生
433+
if (elector1_leader && elector2_leader) {
434+
break;
435+
}
436+
std::this_thread::sleep_for(std::chrono::milliseconds(100));
437+
}
418438

419439
// 两个选举器都应该成为领导者,因为它们使用不同的锁键
420440
EXPECT_TRUE(elector1_leader);

0 commit comments

Comments
 (0)