import { EventEmitter } from 'node:events'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { createLineSplitter, prepareStreamAdbArgs, startStream, stripAnsi, } from '../src/adb/streamRunner.js'; const { spawnMock } = vi.hoisted(() => ({ spawnMock: vi.fn() })); vi.mock('node:child_process', () => ({ spawn: spawnMock })); /** 每次 spawn 返回新的可控假子进程(避免跨 launch 的 handler 闭包混淆)。 */ function fakeChildren() { const children: { stdout: EventEmitter; stderr: EventEmitter; kill: ReturnType; on: ReturnType; }[] = []; spawnMock.mockImplementation(() => { const child = { stdout: new EventEmitter(), stderr: new EventEmitter(), kill: vi.fn(), on: vi.fn() }; children.push(child); return child; }); return { count: () => children.length, emitStderr: (i: number, text: string) => children[i]!.stderr.emit('data', Buffer.from(text)), emitStdout: (i: number, text: string) => children[i]!.stdout.emit('data', Buffer.from(text)), /** 手动触发第 i 次子进程的 close 回调。 */ close: (i: number) => children[i]!.on.mock.calls.find(([event]) => event === 'close')?.[1] as (() => void) | undefined, killCalls: (i: number) => children[i]!.kill, }; } const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); // 快速重试间隔,避免测试真等 1 秒 const FAST_RETRY = { retryDelayMs: 30 }; beforeEach(() => { spawnMock.mockReset(); }); afterEach(() => { vi.restoreAllMocks(); }); describe('stripAnsi(监听框输出净化)', () => { it('剥离 CSI 转义序列与 \\r(top 全屏重绘)', () => { expect(stripAnsi('\x1b[H\x1b[JTasks: 100\r\n')).toBe('Tasks: 100\n'); expect(stripAnsi('\x1b[30;80R\x1b[?25labc')).toBe('abc'); }); it('剥离 OSC 与字符集序列', () => { expect(stripAnsi('\x1b]0;title\x07text')).toBe('text'); expect(stripAnsi('\x1b(Bok')).toBe('ok'); expect(stripAnsi('\x1b=\x1b>ok')).toBe('ok'); // 键盘模式序列(\x1b=> 实为 \x1b= + 字面 >) }); it('普通文本不受影响', () => { expect(stripAnsi('09-02 15:00:00.123 1234 5678 I Tag: msg')).toBe( '09-02 15:00:00.123 1234 5678 I Tag: msg', ); }); }); describe('createLineSplitter(跨数据块行分割)', () => { it('按 \\n 分割完整行', () => { const lines: string[] = []; const splitter = createLineSplitter((line) => lines.push(line)); splitter.push('a\nb\nc\n'); expect(lines).toEqual(['a', 'b', 'c']); }); it('行在数据块中间截断时缓冲到下一块(logcat 高频流场景)', () => { const lines: string[] = []; const splitter = createLineSplitter((line) => lines.push(line)); splitter.push('09-02 15:00:00.123 1234 5678 I Tag: ms'); expect(lines).toEqual([]); splitter.push('g end\n09-02 15:00:00.124 1234 567'); expect(lines).toEqual(['09-02 15:00:00.123 1234 5678 I Tag: msg end']); splitter.push('8 I Tag: next\n'); expect(lines).toEqual([ '09-02 15:00:00.123 1234 5678 I Tag: msg end', '09-02 15:00:00.124 1234 5678 I Tag: next', ]); }); it('flush 冲刷末尾不完整行(流结束时)', () => { const lines: string[] = []; const splitter = createLineSplitter((line) => lines.push(line)); splitter.push('partial'); expect(lines).toEqual([]); splitter.flush(); expect(lines).toEqual(['partial']); }); }); describe('prepareStreamAdbArgs(top 强制远端 PTY)', () => { it('有目标设备时在 shell 后注入 -tt', () => { expect(prepareStreamAdbArgs(['-s', 'serial-1', 'shell', 'top', '-m', '10'])).toEqual([ '-s', 'serial-1', 'shell', '-tt', 'top', '-m', '10', ]); }); it('无目标设备时仍在 shell 后注入 -tt', () => { expect(prepareStreamAdbArgs(['shell', 'top'])).toEqual(['shell', '-tt', 'top']); }); it('logcat 与非 shell 参数保持不变', () => { const logcat = ['-s', 'serial-1', 'shell', 'logcat', '-v', 'brief']; const devices = ['devices', '-l']; expect(prepareStreamAdbArgs(logcat)).toBe(logcat); expect(prepareStreamAdbArgs(devices)).toBe(devices); }); }); describe('startStream 闪断自动重试(spec v0.9)', () => { it('spawn top 时使用强制 PTY 参数', () => { const fake = fakeChildren(); const handle = startStream( ['-s', 'serial-1', 'shell', 'top', '-m', '10'], { onLines: vi.fn(), onExit: vi.fn() }, FAST_RETRY, ); expect(spawnMock).toHaveBeenCalledWith( 'adb', ['-s', 'serial-1', 'shell', '-tt', 'top', '-m', '10'], { stdio: ['ignore', 'pipe', 'pipe'] }, ); handle.stop(); expect(fake.killCalls(0)).toHaveBeenCalledWith('SIGKILL'); }); it('stderr 出现 error: closed 时自动重试,提示行经 onLines 展示', async () => { const fake = fakeChildren(); const onLines = vi.fn(); const onExit = vi.fn(); const handle = startStream(['shell', 'logcat'], { onLines, onExit }, FAST_RETRY); // 第一次:闪断退出 fake.emitStderr(0, 'error: closed\n'); fake.close(0)?.(); await sleep(80); // 重试提示行 + 已重新 spawn(新子进程),onExit 未触发(面板保持运行态) expect(onLines.mock.calls.some((call) => call[0].some((l: string) => l.includes('自动重试 1/2')))).toBe(true); expect(fake.count()).toBe(2); expect(onExit).not.toHaveBeenCalled(); // 第二次:正常结束 → onExit fake.close(1)?.(); expect(onExit).toHaveBeenCalledTimes(1); handle.stop(); }); it('重试次数用尽后不再重试(上限 2 次)', async () => { const fake = fakeChildren(); const onExit = vi.fn(); const handle = startStream(['shell', 'logcat'], { onLines: vi.fn(), onExit }, FAST_RETRY); for (let i = 0; i < 3; i++) { fake.emitStderr(i, 'error: closed\n'); fake.close(i)?.(); await sleep(80); } // 共 spawn 3 次(首发 + 2 次重试),之后放弃并 onExit expect(fake.count()).toBe(3); expect(onExit).toHaveBeenCalledTimes(1); handle.stop(); }); it('用户 stop() 后不再重试(含重试等待期内 stop)', async () => { const fake = fakeChildren(); const onExit = vi.fn(); const handle = startStream(['shell', 'logcat'], { onLines: vi.fn(), onExit }, FAST_RETRY); // 闪断 → 进入重试等待期 fake.emitStderr(0, 'error: closed\n'); fake.close(0)?.(); await sleep(10); // 等待期内用户中断:直接 onExit,不 respawn handle.stop(); expect(onExit).toHaveBeenCalledTimes(1); await sleep(80); expect(fake.count()).toBe(1); }); it('正常结束(无 error: closed)不重试', async () => { const fake = fakeChildren(); const onExit = vi.fn(); const handle = startStream(['shell', 'top', '-n', '1'], { onLines: vi.fn(), onExit }, FAST_RETRY); fake.emitStdout(0, 'Tasks: 100\n'); fake.close(0)?.(); await sleep(80); expect(fake.count()).toBe(1); expect(onExit).toHaveBeenCalledTimes(1); handle.stop(); }); it('stop() 杀掉运行中的子进程(kill)且不重试', async () => { const fake = fakeChildren(); const onExit = vi.fn(); const handle = startStream(['shell', 'logcat'], { onLines: vi.fn(), onExit }, FAST_RETRY); handle.stop(); expect(fake.killCalls(0)).toHaveBeenCalledWith('SIGKILL'); // kill 后 close 触发:无闪断错误,正常 onExit,不 respawn fake.close(0)?.(); await sleep(80); expect(fake.count()).toBe(1); expect(onExit).toHaveBeenCalledTimes(1); }); });