58 lines
2.3 KiB
TypeScript
58 lines
2.3 KiB
TypeScript
import type { CpuInfo } from 'node:os';
|
|
import { describe, expect, it } from 'vitest';
|
|
import { busyPercent, decide, DEFAULT_MAX, DEFAULT_WAIT_SECONDS, limitsFrom } from '../src/guard.js';
|
|
|
|
const core = (user: number, idle: number, sys = 0): CpuInfo => ({ model: 'test', speed: 1, times: { user, nice: 0, sys, idle, irq: 0 } });
|
|
|
|
describe('busyPercent', () => {
|
|
it('measures the whole machine between two readings, not since boot', () => {
|
|
// Since boot both cores look idle; between the readings one is full and one is idle.
|
|
const before = [core(1_000, 99_000), core(1_000, 99_000)];
|
|
const after = [core(2_000, 99_000), core(1_000, 100_000)];
|
|
expect(busyPercent(before, after)).toBe(50);
|
|
});
|
|
|
|
it('counts system time as busy, and an idle machine as 0', () => {
|
|
expect(busyPercent([core(0, 0)], [core(300, 100, 600)])).toBe(90);
|
|
expect(busyPercent([core(5, 5)], [core(5, 1005)])).toBe(0);
|
|
});
|
|
|
|
it('two readings with no time between them are 0, never NaN', () => {
|
|
expect(busyPercent([core(1, 1)], [core(1, 1)])).toBe(0);
|
|
});
|
|
});
|
|
|
|
describe('limitsFrom', () => {
|
|
it('defaults to CLAUDE.md §5.7: 80 %, waiting three minutes', () => {
|
|
expect(limitsFrom({})).toEqual({ max: DEFAULT_MAX, waitSeconds: DEFAULT_WAIT_SECONDS });
|
|
expect(DEFAULT_MAX).toBe(80);
|
|
});
|
|
|
|
it('reads a dedicated machine\'s limit and wait', () => {
|
|
expect(limitsFrom({ ROSEA_CPU_MAX: '100', ROSEA_CPU_WAIT_SECONDS: '0' })).toEqual({ max: 100, waitSeconds: 0 });
|
|
});
|
|
|
|
it.each(['abc', '0', '101', '80.5', '-5'])('refuses ROSEA_CPU_MAX=%s rather than quietly using the default', (raw) => {
|
|
expect(() => limitsFrom({ ROSEA_CPU_MAX: raw })).toThrow(/ROSEA_CPU_MAX must be a whole number from 1 to 100/);
|
|
});
|
|
});
|
|
|
|
describe('decide', () => {
|
|
const limits = { max: 80, waitSeconds: 180 };
|
|
|
|
it('starts at or under the limit', () => {
|
|
expect(decide(80, 0, limits)).toBe('start');
|
|
expect(decide(12, 500, limits)).toBe('start');
|
|
});
|
|
|
|
it('waits while busy, then refuses once the wait is used up', () => {
|
|
expect(decide(81, 0, limits)).toBe('wait');
|
|
expect(decide(100, 179, limits)).toBe('wait');
|
|
expect(decide(100, 180, limits)).toBe('refuse');
|
|
});
|
|
|
|
it('with no wait, refuses at once', () => {
|
|
expect(decide(95, 0, { max: 80, waitSeconds: 0 })).toBe('refuse');
|
|
});
|
|
});
|