adb_cli/tests/streamPanel.test.tsx
2026-09-07 16:16:22 +08:00

356 lines
12 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { Device } from '../src/adb/deviceParser.js';
import { DevicePoller } from '../src/adb/devicePoller.js';
import { App } from '../src/components/App.js';
import { renderHarness } from './harness.js';
const { execAdbMock, startStreamMock, fakeDevices } = vi.hoisted(() => ({
execAdbMock: vi.fn(),
startStreamMock: vi.fn(),
fakeDevices: [{ serial: 'serial-1', state: 'device', model: 'Pixel_7' }] as Device[],
}));
vi.mock('../src/adb/adbClient.js', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/adb/adbClient.js')>();
return { ...actual, execAdb: (args: string[], timeoutMs?: number) => execAdbMock(args, timeoutMs) };
});
vi.mock('../src/adb/streamRunner.js', () => ({
startStream: startStreamMock,
}));
const sleep = (ms = 150) => new Promise((resolve) => setTimeout(resolve, ms));
function makeApp() {
const poller = new DevicePoller(() => Promise.resolve(structuredClone(fakeDevices)));
return renderHarness(<App adbVersion="1.0.41" poller={poller} />);
}
/** 可控的假流:捕获回调后由测试驱动 emit/exit。 */
function fakeStream() {
const stop = vi.fn();
let callbacks: { onLines: (lines: string[]) => void; onExit: () => void } | null = null;
const callbackHistory: Array<{ onLines: (lines: string[]) => void; onExit: () => void }> = [];
startStreamMock.mockImplementation((_args: string[], cb: typeof callbacks) => {
callbacks = cb;
if (cb) callbackHistory.push(cb);
return { stop };
});
return {
stop,
emit: (lines: string[]) => callbacks?.onLines(lines),
exit: () => callbacks?.onExit(),
exitAt: (index: number) => callbackHistory[index]?.onExit(),
args: () => startStreamMock.mock.calls.at(-1)?.[0] as string[],
};
}
/** 测量最后一个带边框面板的高度(╭ 到 ╰)。 */
function panelHeight(output: string): number {
const lines = output.split('\n');
let top = -1;
for (let i = lines.length - 1; i >= 0; i--) {
if (lines[i]!.includes('╭')) {
top = i;
break;
}
}
if (top < 0) return -1;
for (let j = top + 1; j < lines.length; j++) {
if (lines[j]!.includes('╰')) return j - top + 1;
}
return -1;
}
/** 最后一次渲染出的面板上边框宽度(忽略居中产生的左侧空格)。 */
function panelWidth(output: string): number {
const top = output
.split('\n')
.filter((line) => line.includes('╭'))
.at(-1);
return top?.trimStart().length ?? -1;
}
describe('流式命令与窗口面板(spec v1.2 A12-A14)', () => {
beforeEach(() => {
execAdbMock.mockReset();
execAdbMock.mockResolvedValue({ code: 0, stdout: 'ok', stderr: '' });
startStreamMock.mockReset();
});
it('/shell logcat 进入监听模式:右侧分栏,设备列表缩至 1/4 高', async () => {
const stream = fakeStream();
const app = makeApp();
await sleep(300);
// 无监听时设备面板为终端一半(harness rows=40 → 20 行)
expect(panelHeight(app.output())).toBe(20);
app.write('/shell logcat -v brief\r');
await sleep(400);
expect(stream.args()).toEqual(['-s', 'serial-1', 'shell', 'logcat', '-v', 'brief']);
// 监听面板出现且显示命令与中断提示
expect(app.output()).toContain('$ /shell logcat -v brief');
expect(app.output()).toContain('Ctrl+Q 中断');
// 设备面板缩至 1/4(10 行),监听面板补齐(10 行)
expect(panelHeight(app.output())).toBe(10);
expect(app.output()).not.toContain('已结束');
await app.stop();
});
it('流式输出逐批渲染到监听面板', async () => {
const stream = fakeStream();
const app = makeApp();
await sleep(300);
app.write('/shell logcat\r');
await sleep(400);
stream.emit(['line-1', 'line-2']);
await sleep(300);
stream.emit(['line-3']);
await sleep(300);
const out = app.output();
expect(out).toContain('line-1');
expect(out).toContain('line-2');
expect(out).toContain('line-3');
await app.stop();
});
it('普通布局 Ctrl+Q 中断当前监听并移除面板', async () => {
const stream = fakeStream();
const app = makeApp();
await sleep(300);
app.write('/shell logcat\r');
await sleep(400);
stream.emit(['hello-log']);
await sleep(300);
// Ctrl+Q = \x11(raw mode 下正常送达)
app.writeRaw('\x11');
await sleep(300);
expect(stream.stop).toHaveBeenCalled();
// output 是全历史帧累积:最新设备标题晚于旧监听标题,说明当前帧已无监听框。
let out = app.output();
expect(out.lastIndexOf('#0 Devices')).toBeGreaterThan(out.lastIndexOf('#1 $ /shell logcat'));
// 迟到的 close 回调不能把已移除窗口重新带回来。
stream.exit();
await sleep(300);
out = app.output();
expect(out.lastIndexOf('#0 Devices')).toBeGreaterThan(out.lastIndexOf('#1 $ /shell logcat'));
await app.stop();
});
it('单监听:启动新监听自动中断旧的', async () => {
const stream = fakeStream();
const app = makeApp();
await sleep(300);
app.write('/shell logcat\r');
await sleep(400);
app.write('/shell top -m 10\r');
await sleep(400);
expect(stream.stop).toHaveBeenCalledTimes(1);
expect(stream.args()).toEqual(['-s', 'serial-1', 'shell', 'top', '-m', '10']);
await app.stop();
});
it('非流式 /shell 命令仍走批处理路径', async () => {
const stream = fakeStream();
const app = makeApp();
await sleep(300);
app.write('/shell ls -l\r');
await sleep(400);
expect(startStreamMock).not.toHaveBeenCalled();
expect(execAdbMock).toHaveBeenCalledWith(['-s', 'serial-1', 'shell', 'ls', '-l'], undefined);
// 无监听面板
expect(app.output()).not.toContain('Ctrl+Q 中断');
await app.stop();
});
it('监听中设备断开后监听框占满右半(1/2)', async () => {
const stream = fakeStream();
let currentDevices: Device[] = structuredClone(fakeDevices);
const poller = new DevicePoller(() => Promise.resolve(structuredClone(currentDevices)));
const app = renderHarness(<App adbVersion="1.0.41" poller={poller} />);
await sleep(300);
// 有设备时启动监听:设备面板 1/4 + 监听框 1/4
app.write('/shell logcat\r');
await sleep(400);
expect(panelHeight(app.output())).toBe(10);
// 设备断开(下一个轮询周期生效,间隔 1 秒):监听继续,监听框占满 1/2
currentDevices = [];
await sleep(1400);
expect(panelHeight(app.output())).toBe(20);
expect(app.output()).toContain('Ctrl+Q 中断');
await app.stop();
});
it('存活窗口编号不重排,设备重连复用最小空闲编号', async () => {
fakeStream();
let currentDevices: Device[] = structuredClone(fakeDevices);
const poller = new DevicePoller(() => Promise.resolve(structuredClone(currentDevices)));
const app = renderHarness(<App adbVersion="1.0.41" poller={poller} />);
await sleep(300);
app.write('/shell logcat\r');
await sleep(400);
expect(app.output()).toContain('#0 Devices (1)');
expect(app.output()).toContain('#1 $ /shell logcat');
currentDevices = [];
await sleep(1400);
const beforeReconnectLength = app.output().length;
currentDevices = structuredClone(fakeDevices);
await sleep(1400);
const reconnectFrames = app.output().slice(beforeReconnectLength);
expect(reconnectFrames).toContain('#0 Devices (1)');
expect(reconnectFrames).toContain('#1 $ /shell logcat');
await app.stop();
});
it('关闭窗口后复用最小空闲编号', async () => {
const stream = fakeStream();
const app = makeApp();
await sleep(300);
expect(app.output()).toContain('#0 Devices (1)');
app.write('/shell logcat\r');
await sleep(400);
expect(app.output()).toContain('#1 $ /shell logcat');
app.writeRaw('\x11');
await sleep(300);
app.write('/shell top -m 10\r');
await sleep(400);
expect(app.output()).toContain('#1 $ /shell top -m 10');
expect(stream.stop).toHaveBeenCalledTimes(1);
// 旧 #1 的迟到退出回调不能把复用 #1 的新监听标记为结束。
stream.exitAt(0);
await sleep(300);
const out = app.output();
expect(out.lastIndexOf('Ctrl+Q 中断')).toBeGreaterThan(out.lastIndexOf('已结束'));
await app.stop();
});
it('/window 0 放大设备框至 90%×60%,隐藏监听但监听继续收集', async () => {
const stream = fakeStream();
const app = makeApp();
await sleep(300);
app.write('/shell logcat\r');
await sleep(400);
app.write('/window 0\r');
await sleep(400);
expect(panelWidth(app.output())).toBe(108); // harness 120 列 × 90%
expect(panelHeight(app.output())).toBe(24); // harness 40 行 × 60%
expect(app.output().lastIndexOf('#0 Devices')).toBeGreaterThan(
app.output().lastIndexOf('#1 $ /shell logcat'),
);
expect(app.output().lastIndexOf('#0 Devices')).toBeGreaterThan(
app.output().lastIndexOf('切换命令'),
);
stream.emit(['during-zoom']);
await sleep(300);
expect(app.output()).not.toContain('during-zoom');
expect(stream.stop).not.toHaveBeenCalled();
// 第一次 Ctrl+Q 只恢复布局;隐藏期间收集的输出重新可见。
app.writeRaw('\x11');
await sleep(400);
expect(stream.stop).not.toHaveBeenCalled();
expect(app.output()).toContain('during-zoom');
expect(app.output().lastIndexOf('#1 $ /shell logcat')).toBeGreaterThan(
app.output().lastIndexOf('#0 Devices'),
);
await app.stop();
});
it('放大监听框时第一次 Ctrl+Q 恢复,第二次停止并移除窗口', async () => {
const stream = fakeStream();
const app = makeApp();
await sleep(300);
app.write('/shell logcat\r');
await sleep(400);
app.write('/window 1\r');
await sleep(400);
expect(panelWidth(app.output())).toBe(108);
expect(panelHeight(app.output())).toBe(24);
expect(app.output().lastIndexOf('#1 $ /shell logcat')).toBeGreaterThan(
app.output().lastIndexOf('#0 Devices'),
);
app.writeRaw('\x11');
await sleep(400);
expect(stream.stop).not.toHaveBeenCalled();
app.writeRaw('\x11');
await sleep(400);
expect(stream.stop).toHaveBeenCalledTimes(1);
expect(app.output().lastIndexOf('#0 Devices')).toBeGreaterThan(
app.output().lastIndexOf('#1 $ /shell logcat'),
);
await app.stop();
});
it('/window 目标不存在时提示错误且保持普通布局', async () => {
const app = makeApp();
await sleep(300);
app.write('/window 99\r');
await sleep(400);
const out = app.output();
expect(out).toContain('窗口 #99 不存在');
expect(out.lastIndexOf('切换命令')).toBeGreaterThan(out.lastIndexOf('#0 Devices'));
await app.stop();
});
it('放大的设备窗口消失时自动恢复普通布局,重新生成复用最小空闲编号', async () => {
let currentDevices: Device[] = structuredClone(fakeDevices);
const poller = new DevicePoller(() => Promise.resolve(structuredClone(currentDevices)));
const app = renderHarness(<App adbVersion="1.0.41" poller={poller} />);
await sleep(300);
app.write('/window 0\r');
await sleep(400);
expect(panelHeight(app.output())).toBe(24);
currentDevices = [];
await sleep(1400);
expect(app.output()).toContain('目标设备已断开连接');
expect(app.output().lastIndexOf('切换命令')).toBeGreaterThan(
app.output().lastIndexOf('#0 Devices'),
);
currentDevices = structuredClone(fakeDevices);
await sleep(1400);
expect(app.output()).toContain('#0 Devices (1)');
await app.stop();
});
});