sieobex/tests/cliSuite.ts
2026-10-01 02:46:52 -05:00

559 lines
23 KiB
TypeScript

// The e2e tests of the sieobex CLI, run against one phone.
//
// Everything here goes through the built CLI as a subprocess, the way a user
// drives it: connect starts a real daemon, and the file commands reach the
// phone's own FlexMem server over the serial link. Booting an emulated phone
// takes tens of seconds, so one boot and one daemon are shared by the whole
// suite and the tests run in order.
//
// The phone is a PhoneTarget, which is either an emulator this boots or a
// real one on a cable (tests/device.ts). What the target does not claim to
// know in advance - the model, the platform - is checked for shape instead.
//
// SIEOBEX_HOME points every subprocess at a private directory, so a daemon of
// these tests can never collide with one the developer is using.
import { afterAll, beforeAll, describe, expect, test } from "vitest";
import { spawn } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { setTimeout as delay } from "node:timers/promises";
import type { PhoneTarget, RunningTarget } from "./target.js";
const CLI = path.join(path.dirname(fileURLToPath(import.meta.url)), "../dist/index.js");
// Big enough to cross the CX70's 1030 byte packet limit, so the multi-packet
// transfer paths run at least once per suite, and small enough that a phone on
// a 19200 baud link still gets through it quickly.
const PAYLOAD_SIZE = 1024;
// Over a real cable a single command can take seconds; saying which one is
// running beats a cursor that has not moved in a minute.
const SLOW_COMMAND_MS = 3000;
const VERBOSE = process.env.SIEOBEX_E2E_VERBOSE == "1";
function payload(seed: number, size = PAYLOAD_SIZE): Buffer {
const data = Buffer.alloc(size);
for (let i = 0; i < data.length; i++)
data[i] = (i * 7 + seed) & 0xFF;
return data;
}
export interface CliResult {
status: number;
stdout: string;
stderr: string;
}
// What actually went wrong, out of output that opens with progress notes
// like "connecting to /dev/ttyUSB0...".
function reason(stderr: string): string {
const lines = stderr.split("\n").map((line) => line.trim()).filter(Boolean);
return lines.find((line) => line.startsWith("sieobex:")) ?? lines[lines.length - 1] ?? "no output";
}
export function cliSuite(phone: PhoneTarget): void {
const unavailable = phone.unavailable;
const suite = unavailable ? describe.skip : describe;
if (unavailable)
console.warn(`Skipping the e2e tests on ${phone.name}: ${unavailable}`);
suite(`sieobex on ${phone.name}`, () => {
let running: RunningTarget;
let home: string;
let work: string;
const startedAt = Date.now();
const since = (from = startedAt) => `${((Date.now() - from) / 1000).toFixed(1)}s`;
// Getting the phone ready is minutes of silence otherwise, and over a
// real cable so is many of the commands, so the suite says what it is
// waiting for as it waits.
function step(message: string): void {
console.log(`[${phone.name} +${since()}] ${message}`);
}
// Runs the CLI the way a user would, with its own daemon directory.
function runCli(args: string[], timeoutMS = 120000): Promise<CliResult> {
const began = Date.now();
return new Promise((resolve, reject) => {
const child = spawn(process.execPath, [CLI, ...args], {
cwd: work,
env: { ...process.env, SIEOBEX_HOME: home },
stdio: ["ignore", "pipe", "pipe"],
});
let stdout = "";
let stderr = "";
child.stdout.on("data", (chunk: Buffer) => { stdout += chunk.toString(); });
child.stderr.on("data", (chunk: Buffer) => { stderr += chunk.toString(); });
const timer = setTimeout(() => {
child.kill("SIGKILL");
reject(new Error(`sieobex ${args.join(" ")} did not finish within ${timeoutMS} ms`));
}, timeoutMS);
child.once("error", reject);
child.once("close", (status) => {
clearTimeout(timer);
// Fast commands would only be noise, but one that takes
// seconds is worth naming while the next one runs
if (VERBOSE || Date.now() - began > SLOW_COMMAND_MS)
step(`sieobex ${args.join(" ")} -> exit ${status} in ${since(began)}`);
resolve({ status: status ?? -1, stdout, stderr });
});
});
}
// Mutable: a phone nobody described may send the suite looking for
// a directory that takes files, see checkWritableDir
let writableDir = phone.writableDir;
const phonePath = (...parts: string[]): string => [writableDir, ...parts].join("/");
beforeAll(async () => {
// Short, because a unix socket path is limited to about 107 bytes
home = fs.mkdtempSync(path.join(os.tmpdir(), "sob-"));
work = fs.mkdtempSync(path.join(os.tmpdir(), "sobwork-"));
step("starting the phone");
running = await phone.start();
step(`serial port is ${running.serial}`);
try {
await waitForFlexMem();
await checkWritableDir();
} catch (e) {
const log = running.log();
await running.stop();
throw new Error(`${(e as Error).message}${log ? `\nEmulator output:\n${log}` : ""}`);
}
step("ready");
});
// A listing and a write before the tests start, so a directory this
// phone does not have, or will not take files, is one clear failure
// now rather than a puzzling one eight tests later. It is the thing
// about a phone nobody booted that cannot be discovered: which
// folders it keeps, and which of them are its own.
async function checkWritableDir(): Promise<void> {
step(`checking ${writableDir} is a directory the tests may write into`);
const refusal = await refuses(writableDir);
if (!refusal)
return;
if (!phone.mayPickWritableDir)
throw new Error(`${writableDir} ${refusal}\n${await elsewhere()}`);
// The default only holds for the phones that have /Data. Rather
// than send someone back to the shell to guess a folder name
// their generation uses, try the ones it might.
step(`${writableDir} ${refusal}, looking for a directory that will take files`);
const found = await pickWritableDir();
if (!found)
throw new Error(`no directory on this phone took a file.\n${await elsewhere()}`);
writableDir = found;
step(`writing into ${writableDir} (SIEOBEX_E2E_DIR pins it)`);
}
// Why the directory is no good, or undefined when it is fine.
async function refuses(dir: string): Promise<string | undefined> {
const listing = await runCli(["ls", dir]);
if (listing.status != 0)
return `is not a directory this phone will list: ${reason(listing.stderr)}`;
const probe = path.join(work, "sieobex-e2e-probe.bin");
fs.writeFileSync(probe, payload(9, 32));
const target = [dir, "sieobex-e2e-probe.bin"].join("/");
const push = await runCli(["push", probe, target]);
// Tidy up whatever landed before judging the result
await runCli(["rm", "-f", target]);
return push.status == 0 ? undefined : `will not take a file: ${reason(push.stderr)}`;
}
// Root folders worth trying, likeliest scratch space first. Only
// ones the phone actually lists are tried, and each is offered the
// same 32 byte file that is deleted again either way.
const CANDIDATES = ["tmp", "Misc", "Sounds", "Pictures", "Animations", "Java", "Cache"];
async function pickWritableDir(): Promise<string | undefined> {
const root = await runCli(["ls", "/"]);
const folders = new Set(root.stdout.split("\n").map((line) => line.trim()).filter(Boolean));
for (const name of CANDIDATES) {
if (!folders.has(name))
continue;
const candidate = `/${name}`;
step(`trying ${candidate}`);
if (!await refuses(candidate))
return candidate;
}
return undefined;
}
// The phone's own answer to "then where?", which beats guessing at
// folder names that differ per generation.
async function elsewhere(): Promise<string> {
const root = await runCli(["ls", "/"]);
const folders = root.stdout.split("\n").filter(Boolean).join(" ");
return `Point SIEOBEX_E2E_DIR at another directory. The root holds: ${folders || "(nothing this phone would list)"}`;
}
// The AT interpreter answers long before the file system behind OBEX is
// up: the phone already lists directories while writing into them is
// still refused. How long that takes is wall clock and not guest time -
// QEMU runs the phone on a precise instruction clock, so a busy host
// boots it more slowly - so this waits for a real file operation to
// succeed instead of for a fixed time.
async function waitForFlexMem(): Promise<void> {
const deadline = Date.now() + phone.readyTimeoutMS;
const connectArgs = ["connect", running.serial, ...(phone.connectArgs ?? [])];
let last = "";
for (let attempt = 1; Date.now() < deadline; attempt++) {
step(`connecting${attempt > 1 ? ` (attempt ${attempt})` : ""}`);
const began = Date.now();
const connect = await runCli(connectArgs);
if (connect.status == 0) {
const identity = /phone:\s+(.+)/.exec(connect.stdout);
step(`connected in ${since(began)}: ${identity?.[1] ?? "an unnamed phone"}`);
const probe = await runCli(["ls", phone.smallFilesDir]);
if (probe.status == 0)
return;
last = reason(probe.stderr);
step(`${phone.smallFilesDir} is not listable yet: ${last}`);
// A half-open session is worse than none: start over
await runCli(["disconnect"]);
} else {
last = reason(connect.stderr);
step(`connect failed after ${since(began)}: ${last}`);
// The daemon can be up even when connect reported a failure,
// and then every later attempt just says "already connected"
await runCli(["disconnect"]);
}
if (Date.now() + phone.reconnectWaitMS >= deadline)
break;
// Not a token pause: an emulated phone connected to again too
// soon loses the session for the rest of its boot
step(`waiting ${phone.reconnectWaitMS / 1000}s before trying again`);
await delay(phone.reconnectWaitMS);
}
throw new Error(`${phone.name} was not ready after ${since()}: ${last}`);
}
afterAll(async () => {
// When the phone panics it stops answering, which shows up as a pile
// of timeouts in the tests and only the emulator says why
const log = running?.log() ?? "";
if (log.includes(">>EXIT<<"))
console.error(`The emulated ${phone.name} panicked:\n${log}`);
await runCli(["disconnect"], 30000).catch(() => {});
await running?.stop();
fs.rmSync(home, { recursive: true, force: true });
fs.rmSync(work, { recursive: true, force: true });
});
test("status reports the phone and its free space", async () => {
const result = await runCli(["status"]);
expect(result.status, result.stderr).toBe(0);
expect(result.stdout).toContain(running.serial);
// A known firmware is held to its name; a phone someone plugged in
// only has to be identified as something
if (phone.deviceName)
expect(result.stdout).toContain(phone.deviceName);
if (phone.platform)
expect(result.stdout).toContain(phone.platform);
if (!phone.deviceName || !phone.platform) {
const line = /phone:\s+(.+)/.exec(result.stdout);
expect(line, result.stdout).not.toBeNull();
expect(line![1]).not.toMatch(/^unknown/);
expect(line![1]).toMatch(/\((SGOLD|NewSGOLD|EGOLD),/);
console.log(`${phone.name} identifies itself as ${line![1]}`);
}
const capacity = /capacity:\s+([\d.]+) (\w+)/.exec(result.stdout);
const free = /free:\s+([\d.]+) (\w+)/.exec(result.stdout);
expect(capacity, result.stdout).not.toBeNull();
expect(free, result.stdout).not.toBeNull();
expect(Number(capacity![1])).toBeGreaterThan(0);
// Some of the flash is always in use
expect(result.stdout).toMatch(/% used/);
});
test("a second connect is refused while one is running", async () => {
const result = await runCli(["connect", running.serial]);
expect(result.status).toBe(1);
expect(result.stderr).toMatch(/already connected/);
});
test("the daemon log records the session", async () => {
const result = await runCli(["log"]);
expect(result.status, result.stderr).toBe(0);
expect(result.stdout).toContain("connected to");
});
// Which folders exist differs per phone - the CX70's root holds only
// Data where the x75 phones also show Cache and Config - so this
// checks the one the rest of the suite writes into. It also proves the
// root is listed at all: the phones refuse read permission on every
// top level folder, which marks them hidden, and ls has to show them
// there regardless.
test("the root listing holds the phone's top level folders", async () => {
const result = await runCli(["ls", "/"]);
expect(result.status, result.stderr).toBe(0);
const names = result.stdout.split("\n").filter(Boolean);
expect(names).toContain(writableDir.split("/")[1]);
});
test("the same directory is reachable by drive, by name and by raw path", async () => {
const drive = writableDir.split("/")[1];
const [raw, named] = await Promise.all([
runCli(["ls", writableDir]),
runCli(["ls", writableDir.replace(`/${drive}/`, `${drive}:/`)]),
]);
expect(raw.status, raw.stderr).toBe(0);
expect(named.status, named.stderr).toBe(0);
expect(named.stdout).toBe(raw.stdout);
});
test("the long listing shows type, permissions, size and time", async () => {
const result = await runCli(["ls", "-l", phone.smallFilesDir]);
expect(result.status, result.stderr).toBe(0);
const rows = result.stdout.split("\n").filter(Boolean);
expect(rows.length).toBeGreaterThan(0);
for (const row of rows)
expect(row).toMatch(/^[d-][r-][w-][h-]\s+\d+\s+.{1,12}\s+\S/);
});
test("a missing path is reported and fails", async () => {
const result = await runCli(["ls", phonePath("no-such-dir-e2e")]);
expect(result.status).toBe(1);
expect(result.stderr).toMatch(/no-such-dir-e2e/);
});
test("an upload comes back byte for byte", async () => {
const local = path.join(work, "payload.bin");
const data = payload(1);
fs.writeFileSync(local, data);
const target = phonePath("sieobex-e2e.bin");
const push = await runCli(["push", local, target]);
expect(push.status, push.stderr).toBe(0);
expect(push.stdout).toMatch(/1 file pushed/);
const listing = await runCli(["ls", "-l", target]);
expect(listing.status, listing.stderr).toBe(0);
expect(listing.stdout).toMatch(new RegExp(`\\s${data.length}\\s`));
const back = path.join(work, "payload-back.bin");
const pull = await runCli(["pull", target, back]);
expect(pull.status, pull.stderr).toBe(0);
expect(fs.readFileSync(back)).toEqual(data);
});
// The FlexMem server appends to an existing file, so putFile has to
// delete it first; without that the file would grow instead
test("uploading over an existing file replaces it instead of appending", async () => {
const target = phonePath("sieobex-e2e.bin");
const smaller = payload(2, 100);
const local = path.join(work, "smaller.bin");
fs.writeFileSync(local, smaller);
const push = await runCli(["push", local, target]);
expect(push.status, push.stderr).toBe(0);
const back = path.join(work, "smaller-back.bin");
const pull = await runCli(["pull", target, back]);
expect(pull.status, pull.stderr).toBe(0);
expect(fs.readFileSync(back)).toEqual(smaller);
});
test("pull into an existing directory keeps the file name", async () => {
const into = path.join(work, "into");
fs.mkdirSync(into, { recursive: true });
const result = await runCli(["pull", phonePath("sieobex-e2e.bin"), into]);
expect(result.status, result.stderr).toBe(0);
expect(fs.existsSync(path.join(into, "sieobex-e2e.bin"))).toBe(true);
});
test("a folder is pushed and pulled back with its whole tree", async () => {
const localRoot = path.join(work, "tree");
fs.mkdirSync(path.join(localRoot, "sub"), { recursive: true });
const files = {
"one.bin": payload(3, 300),
"two.bin": payload(4, 200),
"sub/three.bin": payload(5, 150),
};
for (const [name, data] of Object.entries(files))
fs.writeFileSync(path.join(localRoot, name), data);
const target = phonePath("sieobex-tree");
const push = await runCli(["push", localRoot, target]);
expect(push.status, push.stderr).toBe(0);
expect(push.stdout).toMatch(/3 files pushed/);
const back = path.join(work, "tree-back");
const pull = await runCli(["pull", target, back]);
expect(pull.status, pull.stderr).toBe(0);
expect(pull.stdout).toMatch(/3 files pulled/);
for (const [name, data] of Object.entries(files))
expect(fs.readFileSync(path.join(back, name)), name).toEqual(data);
});
test("a directory needs -r to be deleted", async () => {
const target = phonePath("sieobex-tree");
const refused = await runCli(["rm", target]);
expect(refused.status).toBe(1);
expect(refused.stderr).toMatch(/is a directory/);
const removed = await runCli(["rm", "-r", target]);
expect(removed.status, removed.stderr).toBe(0);
const listing = await runCli(["ls", writableDir]);
expect(listing.stdout).not.toContain("sieobex-tree");
});
test("a file is deleted and a missing one only fails without -f", async () => {
const target = phonePath("sieobex-e2e.bin");
const removed = await runCli(["rm", target]);
expect(removed.status, removed.stderr).toBe(0);
const again = await runCli(["rm", target]);
expect(again.status).toBe(1);
expect(again.stderr).toMatch(/No such file or directory/);
const forced = await runCli(["rm", "-f", target]);
expect(forced.status, forced.stderr).toBe(0);
});
test("pulling a file that is not there fails", async () => {
const result = await runCli(["pull", phonePath("missing-e2e.bin"), path.join(work, "nope.bin")]);
expect(result.status).toBe(1);
expect(result.stderr).toMatch(/No such file or directory/);
});
// Completion stays silent on any error, so that a phone which is busy
// cannot spray messages over the user's prompt. That makes an empty
// answer indistinguishable from a stalled phone, and the CX70 does
// stall for about 20 s once per boot, hence the retry.
async function completeWithRetry(args: string[]): Promise<CliResult> {
let result = await runCli(args);
for (let attempt = 0; attempt < 3 && !result.stdout.trim(); attempt++) {
await delay(3000);
result = await runCli(args);
}
return result;
}
test("completion offers drives, directories and local files", async () => {
const drive = writableDir.split("/")[1];
// A raw path, not the drive form: the colon is only completed
// into a word that already has one
const drives = await completeWithRetry(["__complete", "ls", drive.slice(0, 2)]);
expect(drives.status).toBe(0);
expect(drives.stdout.split("\n")).toContain(`/${drive}/`);
// The writable directory itself always exists, unlike whatever the
// earlier tests left inside it
const partial = writableDir.slice(0, writableDir.length - 2);
const dirs = await completeWithRetry(["__complete", "ls", partial]);
expect(dirs.status).toBe(0);
expect(dirs.stdout.split("\n")).toContain(`${writableDir}/`);
const local = await runCli(["__complete", "push", ""]);
expect(local.stdout.trim()).toBe("%files");
});
test("disconnect stops the daemon and leaves nothing behind", async () => {
const result = await runCli(["disconnect"]);
expect(result.status, result.stderr).toBe(0);
expect(fs.existsSync(path.join(home, "daemon.sock"))).toBe(false);
const status = await runCli(["status"]);
expect(status.status).toBe(1);
expect(status.stderr).toMatch(/not connected/);
const again = await runCli(["disconnect"]);
expect(again.status).toBe(1);
});
// From here the suite is disconnected, and -d is what brings the
// session back: these tests are last because the final one ends it.
test("-d connects on its own when nothing is running", async () => {
// The +++ escape hands the wire back to the AT interpreter, but the
// phone needs a few seconds before the next handshake catches it,
// and connecting too early loses the session for the rest of the
// boot rather than just failing once
step(`leaving the phone ${phone.reconnectWaitMS / 1000}s to get back to its AT interpreter`);
await delay(phone.reconnectWaitMS);
const result = await runCli(["ls", "-d", running.serial, "/"]);
expect(result.status, result.stderr).toBe(0);
expect(result.stderr).toMatch(/connecting to/);
expect(result.stdout.split("\n").filter(Boolean)).toContain(writableDir.split("/")[1]);
});
test("-d on the device already held reuses the session", async () => {
const first = await runCli(["status", "-d", running.serial]);
expect(first.status, first.stderr).toBe(0);
// The same socket written the other way is the same device
const second = await runCli(["status", "-d", running.serial.replace("tcp://", "tcp:")]);
expect(second.status, second.stderr).toBe(0);
expect(second.stderr).not.toMatch(/connecting to/);
expect(sessionId(second.stdout)).toBe(sessionId(first.stdout));
});
test("-d on another device gives this one back first", async () => {
// Nothing listens on port 1, so the new session cannot be made -
// but only after the phone has been handed back
const result = await runCli(["ls", "-d", "tcp://127.0.0.1:1", "/"]);
expect(result.status).toBe(1);
expect(result.stderr).toMatch(/disconnecting from/);
const status = await runCli(["status"]);
expect(status.status).toBe(1);
expect(status.stderr).toMatch(/not connected/);
});
// A session each, run last because each one ends in a disconnect.
// On a real cable this is the wire changing speed; against an
// emulator the chardev ignores the host speed, so it shows the
// option reaching the port and coming back in the status.
test.skipIf(!phone.baudRates.length)("connects at each baud rate it is given", async () => {
for (const rate of phone.baudRates) {
step(`pinning ${rate} baud`);
const connect = await runCli(["connect", running.serial, "--baudrate", String(rate)]);
expect(connect.status, `${rate} baud: ${connect.stderr}`).toBe(0);
expect(connect.stdout).toContain(`(${rate} baud)`);
// The speed is no good if the phone cannot be read at it
const listing = await runCli(["ls", "/"]);
expect(listing.status, `${rate} baud: ${listing.stderr}`).toBe(0);
expect(listing.stdout.split("\n").filter(Boolean).length).toBeGreaterThan(0);
await runCli(["disconnect"]);
}
});
test("finds the speed on its own when it is given none", async () => {
const connect = await runCli(["connect", running.serial]);
expect(connect.status, connect.stderr).toBe(0);
const found = /\((\d+) baud\)/.exec(connect.stdout);
expect(found, connect.stdout).not.toBeNull();
expect(AT_PROBE_SPEEDS).toContain(Number(found![1]));
step(`the probe settled on ${found![1]} baud`);
const listing = await runCli(["ls", "/"]);
expect(listing.status, listing.stderr).toBe(0);
});
});
}
// The speeds the handshake walks when it is given none, in the library's
// own order. Autodetection has to come back with one of them.
const AT_PROBE_SPEEDS = [115200, 57600, 19200, 230400, 9600];
// The daemon's pid and the moment it connected, which together say whether
// a session was reused or a new one was started.
function sessionId(stdout: string): string {
return /connected:\s+(.+)/.exec(stdout)?.[1] ?? "";
}