Files
2026-06-28 14:23:13 +08:00

49 lines
1.4 KiB
TypeScript

import { test } from 'node:test';
import assert from 'node:assert/strict';
import { HeartbeatWatchdog, type Clock } from '../../YouleNexus/assets/framework/net/heartbeat.ts';
function fakeClock() {
let seq = 0;
const timers = new Map<number, { fn: () => void; at: number }>();
let now = 0;
const clock: Clock = {
setTimeout: (fn, ms) => { const id = ++seq; timers.set(id, { fn, at: now + ms }); return id; },
clearTimeout: (id: any) => { timers.delete(id); },
};
const advance = (ms: number) => {
now += ms;
for (const [id, t] of [...timers]) if (t.at <= now) { timers.delete(id); t.fn(); }
};
return { clock, advance };
}
test('超时未 feed 触发回调', () => {
const { clock, advance } = fakeClock();
let fired = 0;
const wd = new HeartbeatWatchdog(30000, () => { fired++; }, clock);
wd.feed();
advance(30000);
assert.equal(fired, 1);
});
test('feed 重置计时,未到阈值不触发', () => {
const { clock, advance } = fakeClock();
let fired = 0;
const wd = new HeartbeatWatchdog(30000, () => { fired++; }, clock);
wd.feed();
advance(20000);
wd.feed(); // 重置
advance(20000); // 距上次 feed 仅 20s
assert.equal(fired, 0);
});
test('stop 后不再触发', () => {
const { clock, advance } = fakeClock();
let fired = 0;
const wd = new HeartbeatWatchdog(30000, () => { fired++; }, clock);
wd.feed();
wd.stop();
advance(30000);
assert.equal(fired, 0);
});