Skip to content
112 changes: 112 additions & 0 deletions e2e/helpers/test-android-sdk.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";

import { describe, expect, it } from "vitest";

import { MemoryFilesystem } from "../../src/ports/index.js";
import { findAndroidSdk, runSdkTool } from "./test-android-sdk.js";

const SDK = "/Local/Android/Sdk";
const WINDOWS_TOOLS = [
"cmdline-tools/latest/bin/avdmanager.bat",
"cmdline-tools/latest/bin/sdkmanager.bat",
"emulator/emulator.exe",
"platform-tools/adb.exe",
];

async function sdkWith(tools: readonly string[]): Promise<MemoryFilesystem> {
const filesystem = new MemoryFilesystem();
await filesystem.mkdirp(SDK);
for (const tool of tools) {
const path = `${SDK}/${tool}`;
await filesystem.mkdirp(path.slice(0, path.lastIndexOf("/")));
await filesystem.writeFileAtomic(path, "");
}
return filesystem;
}

// why: the lookup's search order and tool names are proven in src/drivers/android/prerequisites.test.ts;
// these prove only what this helper adds: a skip on anything short of a complete SDK, and that a
// tool which fails or runs past its timeout rejects, as `execFile` did.
describe("findAndroidSdk", () => {
it("finds a Windows SDK under %LOCALAPPDATA% with its .exe and .bat tools", async () => {
const sdk = await findAndroidSdk(
{ LOCALAPPDATA: "/Local" },
"/Users/me",
await sdkWith(WINDOWS_TOOLS),
"win32",
);

expect(sdk).toEqual({
adb: "/Local/Android/Sdk/platform-tools/adb.exe",
avdmanager: "/Local/Android/Sdk/cmdline-tools/latest/bin/avdmanager.bat",
emulator: "/Local/Android/Sdk/emulator/emulator.exe",
root: "/Local/Android/Sdk",
sdkmanager: "/Local/Android/Sdk/cmdline-tools/latest/bin/sdkmanager.bat",
});
});

it.each([
[
"an SDK missing its emulator (incomplete)",
WINDOWS_TOOLS.filter((t) => !t.startsWith("emulator/")),
],
[
"an SDK of extensionless tools on Windows (incomplete)",
WINDOWS_TOOLS.map((t) => t.replace(/\.(bat|exe)$/, "")),
],
])("is undefined for %s", async (_case, tools) => {
await expect(
findAndroidSdk({ ANDROID_HOME: SDK }, "/Users/me", await sdkWith(tools), "win32"),
).resolves.toBeUndefined();
});

it("is undefined when no searched root exists (absent)", async () => {
await expect(
findAndroidSdk({ ANDROID_HOME: "/nowhere" }, "/Users/me", new MemoryFilesystem(), "darwin"),
).resolves.toBeUndefined();
});
});

describe("runSdkTool", () => {
it("answers a tool that exits 0 with its output", async () => {
await expect(
runSdkTool(process.execPath, ["-e", 'process.stdout.write("ok")']),
).resolves.toMatchObject({ stdout: "ok" });
});

it("rejects a tool that exits non-zero, not killed", async () => {
await expect(runSdkTool(process.execPath, ["-e", "process.exit(3)"])).rejects.toMatchObject({
killed: false,
});
});

it("rejects a tool its timeout ended, killed", async () => {
await expect(
runSdkTool(process.execPath, ["-e", "setTimeout(() => {}, 60000)"], { timeout: 200 }),
).rejects.toMatchObject({ killed: true });
});

// why: avdmanager on Windows is a .bat under the SDK root, which may hold spaces; the slow tests reach it only through this helper.
it.runIf(process.platform === "win32")(
"runs a .bat under a path with spaces and hands it an argument with spaces intact",
async () => {
const directory = await mkdtemp(join(tmpdir(), "simlock sdk "));
const printer = join(directory, "print-args.cjs");
const tool = join(directory, "avd manager.bat");
await writeFile(printer, "console.log(JSON.stringify(process.argv.slice(2)));\n");
await writeFile(
tool,
["@echo off", `"${process.execPath}" "${printer}" %*`, ""].join("\r\n"),
);
try {
const result = await runSdkTool(tool, ["list", "with space"]);

expect(JSON.parse(result.stdout)).toEqual(["list", "with space"]);
} finally {
await rm(directory, { force: true, recursive: true });
}
},
);
});
57 changes: 57 additions & 0 deletions e2e/helpers/test-android-sdk.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { homedir } from "node:os";

import { type AndroidSdkPaths, locateSdk } from "../../src/drivers/android/testing.js";
import { type Filesystem, NodeFilesystem, NodeProcessRunner } from "../../src/ports/index.js";

const runner = new NodeProcessRunner();

/**
* why: the slow Android tests skip exactly when the real driver could not start, so they ask the
* driver's own `locateSdk` (which knows `%LOCALAPPDATA%` and the `.exe`/`.bat` tools on Windows)
* rather than a lookup of their own that silently skips on a host it does not know.
*/
export async function findAndroidSdk(
env: Readonly<Record<string, string | undefined>>,
homeDirectory: string,
filesystem: Filesystem,
platform: NodeJS.Platform,
): Promise<AndroidSdkPaths | undefined> {
const location = await locateSdk(env, homeDirectory, filesystem, platform);
return location.kind === "complete" ? location.paths : undefined;
}

export const ANDROID_SDK: AndroidSdkPaths | undefined = await findAndroidSdk(
process.env,
homedir(),
new NodeFilesystem(),
process.platform,
);

export function requireAndroidSdk(): AndroidSdkPaths {
if (ANDROID_SDK === undefined) {
throw new Error("no complete Android SDK on this host: the test should have been skipped");
}
return ANDROID_SDK;
}

/**
* why: a `.bat` tool (`avdmanager` on Windows) runs through the ports' process runner, which owns
* how a batch file runs under cmd.exe and which arguments it refuses. As `execFile` did, a non-zero
* exit rejects, and a run its timeout ended rejects with `killed: true`.
*/
export async function runSdkTool(
tool: string,
args: readonly string[],
options: { readonly timeout?: number } = {},
): Promise<{ readonly stdout: string; readonly stderr: string }> {
const result = await runner.run(
tool,
args,
options.timeout === undefined ? {} : { timeoutMs: options.timeout },
);
if (result.code === 0) return result;
throw Object.assign(
new Error(`${tool} ${args.join(" ")} exited ${String(result.code)}: ${result.stderr}`),
{ killed: result.code === null },
);
}
13 changes: 2 additions & 11 deletions e2e/slow-android-lease-files.test.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,7 @@
import { existsSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";

import { DEVICE_READY_MS, waitFor, withHttpDaemon } from "./helpers/index.js";

const ANDROID_HOME =
process.env.ANDROID_HOME ??
process.env.ANDROID_SDK_ROOT ??
join(homedir(), "Library/Android/sdk");
const hasAndroidSdk =
existsSync(ANDROID_HOME) && existsSync(join(ANDROID_HOME, "platform-tools", "adb"));
import { ANDROID_SDK } from "./helpers/test-android-sdk.js";

const FILE_BYTES = 70_000_000;

Expand All @@ -35,7 +26,7 @@ async function readSse(response: Response): Promise<SseFrame[]> {
}

// why: only a real emulator proves that the folder a lease's upload went to is the folder `adb push` reads from, and that `adb pull` leaves a file the GET route serves, at a size no fake pipe is asked to carry.
describe.skipIf(!hasAndroidSdk)(
describe.skipIf(ANDROID_SDK === undefined)(
"a lease's files on a real emulator",
{ tags: ["slow", "android"] },
() => {
Expand Down
Loading
Loading