import { describe, expect, test } from 'bun:test' import { cpuUsageBetween, parseGateway, parseMemAvailable, parseMemTotal, parseNameservers, } from './host-info.ts' describe('parseMemTotal', () => { test('取 MemTotal 并换算成字节', () => { const meminfo = 'MemTotal: 2048000 kB\nMemFree: 100000 kB\nMemAvailable: 512000 kB\n' expect(parseMemTotal(meminfo)).toBe(2048000 * 1024) }) test('读不到 /proc/meminfo(非 Linux 平台)返回 null', () => { expect(parseMemTotal('')).toBeNull() }) }) describe('parseMemAvailable', () => { test('取 MemAvailable 并换算成字节', () => { const meminfo = 'MemTotal: 2048000 kB\nMemFree: 100000 kB\nMemAvailable: 512000 kB\n' expect(parseMemAvailable(meminfo)).toBe(512000 * 1024) }) test('没有这一行(老内核)返回 null', () => { expect(parseMemAvailable('MemTotal: 1 kB\nMemFree: 1 kB\n')).toBeNull() }) }) describe('parseGateway', () => { test('默认路由的网关按小端序倒回来', () => { // 0102A8C0 → c0.a8.02.01 → 192.168.2.1 const table = [ 'Iface\tDestination\tGateway\tFlags\tRefCnt\tUse\tMetric\tMask\t\tMTU\tWindow\tIRTT', 'eth0\t00000000\t0102A8C0\t0003\t0\t0\t0\t00000000\t0\t0\t0', 'eth0\t0002A8C0\t00000000\t0001\t0\t0\t0\t00FFFFFF\t0\t0\t0', ].join('\n') expect(parseGateway(table)).toBe('192.168.2.1') }) test('没有默认路由返回 null', () => { const table = 'Iface\tDestination\tGateway\neth0\t0002A8C0\t00000000' expect(parseGateway(table)).toBeNull() }) }) describe('parseNameservers', () => { test('按出现顺序取 nameserver', () => { const conf = '# comment\nnameserver 223.5.5.5\nsearch lan\nnameserver 114.114.114.114\n' expect(parseNameservers(conf)).toEqual(['223.5.5.5', '114.114.114.114']) }) }) describe('cpuUsageBetween', () => { test('按两次快照的差值算百分比', () => { const usage = cpuUsageBetween({ busy: 100, total: 1000 }, { busy: 350, total: 2000 }) expect(usage).toBe(25) }) test('时间没有前进时返回 null', () => { expect(cpuUsageBetween({ busy: 1, total: 10 }, { busy: 1, total: 10 })).toBeNull() }) })