Skip to content

Commit d0f5d49

Browse files
authored
test(android,harmonyos,linux,provision-kit): cover boot-failure and toolchain probe branches (callstack#3433)
* test(android,harmonyos,linux,provision-kit): cover boot-failure and toolchain probe branches Closes callstack#3419 * test(android,harmonyos): cross the boot deadline and cover the command-line-tools root Review follow-ups: make the still-booting poll actually overrun the boot deadline, and assert HARMONYOS_COMMAND_LINE_TOOLS contributes its derived toolchain directory to PATH.
1 parent d154532 commit d0f5d49

5 files changed

Lines changed: 400 additions & 3 deletions

File tree

‎packages/platform-android/src/__tests__/doctor.test.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,53 @@ async function runImeCheck(adb: AndroidAdbExecutor): Promise<DoctorCheck | undef
7474
return checks.find((check) => check.id === 'android-test-ime');
7575
}
7676

77+
function contextWithMetroProbe(
78+
reverse: () => Promise<{ exitCode: number; stdout: string; stderr: string }>,
79+
): HostDiagnosticsContext {
80+
const metroAdb: AndroidAdbExecutor = async (args, options) => {
81+
if (args[0] === 'reverse') {
82+
assert.deepEqual(args, ['reverse', '--list']);
83+
assert.equal(options?.allowFailure, true);
84+
return await reverse();
85+
}
86+
return await fakeAdb(NORMAL_IME)(args, options);
87+
};
88+
return Object.freeze({ ...contextWith(metroAdb), shouldProbeMetro: true });
89+
}
90+
91+
async function runReverseCheck(
92+
reverse: () => Promise<{ exitCode: number; stdout: string; stderr: string }>,
93+
): Promise<DoctorCheck | undefined> {
94+
const checks = await androidDeviceChecks(ANDROID_EMULATOR, contextWithMetroProbe(reverse));
95+
return checks.find((check) => check.id === 'android-reverse');
96+
}
97+
98+
test('reports pass when the Metro reverse mapping already exists', async () => {
99+
const check = await runReverseCheck(async () => ({
100+
exitCode: 0,
101+
stdout: 'tcp:8081 tcp:8081\n',
102+
stderr: '',
103+
}));
104+
assert.equal(check?.status, 'pass');
105+
assert.equal(check?.command, undefined);
106+
assert.match(check?.summary ?? '', /exists for Metro port 8081/);
107+
});
108+
109+
test('reports warn with the reverse command when the Metro mapping is missing', async () => {
110+
const check = await runReverseCheck(async () => ({ exitCode: 0, stdout: '', stderr: '' }));
111+
assert.equal(check?.status, 'warn');
112+
assert.equal(check?.command, `adb -s ${ANDROID_EMULATOR.id} reverse tcp:8081 tcp:8081`);
113+
});
114+
115+
test('reports warn instead of failing the doctor when the reverse probe errors', async () => {
116+
const check = await runReverseCheck(async () => {
117+
throw new Error('adb server died');
118+
});
119+
assert.equal(check?.status, 'warn');
120+
assert.match(check?.summary ?? '', /Could not inspect Android adb reverse/);
121+
assert.match(check?.hint ?? '', /adb server died/);
122+
});
123+
77124
test('reports pass when the normal IME is active', async () => {
78125
const check = await runImeCheck(fakeAdb(NORMAL_IME));
79126
assert.equal(check?.status, 'pass');

‎packages/platform-android/src/__tests__/emulator-lifecycle.test.ts‎

Lines changed: 91 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@ vi.mock('../sdk.ts', () => ({ ensureAndroidSdkPathConfigured: vi.fn(async () =>
1515

1616
import './test-utils/android-host-test-setup.ts';
1717
import { runCmd, runCmdDetached, whichCmd } from '@agent-device/host-kit/command';
18-
import { ensureAndroidEmulatorBooted } from '../emulator-lifecycle.ts';
18+
import { AppError } from '@agent-device/kernel/errors';
19+
import { ensureAndroidEmulatorBooted, waitForAndroidBoot } from '../emulator-lifecycle.ts';
1920

2021
const stopped: DeviceInfo = {
2122
platform: 'android',
@@ -101,3 +102,92 @@ test('emulator boot excludes a running serial outside the resolved Android allow
101102
assert.deepEqual(requests[0]?.androidSerialAllowlist, ['emulator-9999']);
102103
assert.equal(mockRunCmdDetached.mock.calls.length, 0);
103104
});
105+
106+
function bootPropFailure(stdout: string, stderr: string) {
107+
return async () => {
108+
await Promise.resolve();
109+
return { stdout, stderr, exitCode: 1 };
110+
};
111+
}
112+
113+
/** A poll that keeps missing like a real booting device does, and actually burns wall-clock time. */
114+
function slowBootPropFailure(delayMs: number) {
115+
return async () => {
116+
await new Promise((resolve) => setTimeout(resolve, delayMs));
117+
return { stdout: '', stderr: '', exitCode: 1 };
118+
};
119+
}
120+
121+
async function expectBootFailure(
122+
timeoutMs: number,
123+
): Promise<{ code: string; message: string; details: Record<string, unknown> }> {
124+
return await waitForAndroidBoot('emulator-5554', timeoutMs).then(
125+
() => {
126+
throw new Error('expected waitForAndroidBoot to reject');
127+
},
128+
(error: AppError) => ({
129+
code: error.code,
130+
message: error.message,
131+
details: (error.details ?? {}) as Record<string, unknown>,
132+
}),
133+
);
134+
}
135+
136+
test('a boot poll against an offline device fails as an adb transport loss without retrying', async () => {
137+
mockRunCmd.mockImplementation(bootPropFailure('', 'error: device offline'));
138+
139+
const failure = await expectBootFailure(500);
140+
141+
assert.equal(failure.code, 'COMMAND_FAILED');
142+
assert.equal(failure.details.reason, 'ADB_TRANSPORT_UNAVAILABLE');
143+
assert.match(String(failure.details.hint), /adb devices -l/);
144+
assert.equal(failure.details.serial, 'emulator-5554');
145+
assert.equal(failure.details.stderr, 'error: device offline');
146+
assert.equal(failure.details.exitCode, 1);
147+
// shouldRetry refuses the transport loss, so exactly one poll ran.
148+
assert.equal(mockRunCmd.mock.calls.length, 1);
149+
});
150+
151+
test('a still-booting device past its deadline reports an Android boot timeout', async () => {
152+
// 80 ms per poll with a 50 ms retry cadence crosses the 150 ms deadline inside the second
153+
// poll, so the failure is a device that ran out of budget, not three fast poll misses.
154+
mockRunCmd.mockImplementation(slowBootPropFailure(80));
155+
156+
const failure = await expectBootFailure(150);
157+
158+
assert.equal(failure.code, 'COMMAND_FAILED');
159+
assert.equal(failure.message, 'Android device did not finish booting in time');
160+
assert.equal(failure.details.reason, 'ANDROID_BOOT_TIMEOUT');
161+
assert.equal(failure.details.timeoutMs, 150);
162+
assert.equal(Number(failure.details.elapsedMs) >= 150, true);
163+
assert.equal(mockRunCmd.mock.calls.length, 2);
164+
// The classifier sees BOOT_COMMAND_FAILED from the still-booting throw; the caller must
165+
// normalize it to the timeout, not trust the raw classification.
166+
assert.notEqual(failure.details.reason, 'BOOT_COMMAND_FAILED');
167+
});
168+
169+
test('a TOOL_MISSING adb inside the boot loop keeps its error code and hint', async () => {
170+
mockRunCmd.mockRejectedValue(new AppError('TOOL_MISSING', 'adb not found in PATH'));
171+
172+
const failure = await expectBootFailure(500);
173+
174+
assert.equal(failure.code, 'TOOL_MISSING');
175+
assert.equal(failure.message, 'adb not found in PATH');
176+
assert.equal(failure.details.reason, 'ADB_TRANSPORT_UNAVAILABLE');
177+
});
178+
179+
test('boot failure details keep the original error details over the poll evidence', async () => {
180+
mockRunCmd.mockRejectedValue(
181+
new AppError('COMMAND_FAILED', 'error: device not found', {
182+
reason: 'BOOT_COMMAND_FAILED',
183+
diagnosticId: 'adb-x',
184+
}),
185+
);
186+
187+
const failure = await expectBootFailure(500);
188+
189+
assert.equal(failure.code, 'COMMAND_FAILED');
190+
assert.equal(failure.message, 'error: device not found');
191+
assert.equal(failure.details.reason, 'BOOT_COMMAND_FAILED');
192+
assert.equal(failure.details.diagnosticId, 'adb-x');
193+
});

‎packages/platform-harmonyos/src/__tests__/hdc.test.ts‎

Lines changed: 98 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,26 @@
11
import assert from 'node:assert/strict';
2+
import { promises as fs } from 'node:fs';
3+
import path from 'node:path';
24
import { beforeEach, test, vi } from 'vitest';
35

46
vi.mock('@agent-device/host-kit/command', async (importOriginal) => {
57
const actual = await importOriginal<typeof import('@agent-device/host-kit/command')>();
68
return { ...actual, runCmd: vi.fn() };
79
});
10+
vi.mock('@agent-device/host-kit/process', async (importOriginal) => {
11+
const actual = await importOriginal<typeof import('@agent-device/host-kit/process')>();
12+
return { ...actual, hostEnvironment: vi.fn() };
13+
});
814

915
import { runCmd } from '@agent-device/host-kit/command';
10-
import { DEFAULT_HARMONY_HDC_TIMEOUT_MS, runHarmonyHdc, runHarmonyShell } from '../hdc.ts';
16+
import { hostEnvironment } from '@agent-device/host-kit/process';
17+
import {
18+
DEFAULT_HARMONY_HDC_TIMEOUT_MS,
19+
ensureHarmonyToolchainPathConfigured,
20+
runHarmonyHdc,
21+
runHarmonyShell,
22+
} from '../hdc.ts';
23+
import { mkdtempForTestSync } from './tmp-dir.ts';
1124

1225
const mockRunCmd = vi.mocked(runCmd);
1326
const device = { id: '127.0.0.1:5555' };
@@ -53,3 +66,87 @@ test('runHarmonyHdc forwards a binding abort signal to an in-flight HDC command'
5366
await assert.rejects(pending, (error: unknown) => error === aborted);
5467
assert.equal(mockRunCmd.mock.calls[0]?.[2]?.signal, controller.signal);
5568
});
69+
70+
/** HDC_SDK_PATH names the toolchains directory itself, so `HDC_SDK_PATH/hdc` must exist. */
71+
async function seedDirectToolchain(root: string): Promise<string> {
72+
await fs.mkdir(root, { recursive: true });
73+
const hdc = path.join(root, 'hdc');
74+
await fs.writeFile(hdc, '#!/bin/sh\nexit 0\n', 'utf8');
75+
await fs.chmod(hdc, 0o755);
76+
return root;
77+
}
78+
79+
/** DevEco's home joins `default/openharmony/toolchains`; the command-line-tools root adds `sdk` first. */
80+
async function seedNestedToolchain(root: string, ...segments: string[]): Promise<string> {
81+
const toolchains = path.join(root, ...segments, 'default', 'openharmony', 'toolchains');
82+
await fs.mkdir(toolchains, { recursive: true });
83+
const hdc = path.join(toolchains, 'hdc');
84+
await fs.writeFile(hdc, '#!/bin/sh\nexit 0\n', 'utf8');
85+
await fs.chmod(hdc, 0o755);
86+
return root;
87+
}
88+
89+
test('ensureHarmonyToolchainPathConfigured prepends every root holding an hdc binary', async () => {
90+
const hdcSdkRoot = await seedDirectToolchain(mkdtempForTestSync('agent-device-hdc-sdk-'));
91+
const devecoRoot = await seedNestedToolchain(mkdtempForTestSync('agent-device-hdc-deveco-'));
92+
const cmdlineRoot = await seedNestedToolchain(
93+
mkdtempForTestSync('agent-device-hdc-cmdline-'),
94+
'sdk',
95+
);
96+
97+
const env: NodeJS.ProcessEnv = {
98+
PATH: '/usr/bin',
99+
HDC_SDK_PATH: hdcSdkRoot,
100+
DEVECO_SDK_HOME: devecoRoot,
101+
HARMONYOS_COMMAND_LINE_TOOLS: cmdlineRoot,
102+
};
103+
104+
await ensureHarmonyToolchainPathConfigured(env);
105+
106+
assert.deepEqual((env.PATH ?? '').split(path.delimiter), [
107+
hdcSdkRoot,
108+
path.join(devecoRoot, 'default', 'openharmony', 'toolchains'),
109+
path.join(cmdlineRoot, 'sdk', 'default', 'openharmony', 'toolchains'),
110+
'/usr/bin',
111+
]);
112+
});
113+
114+
test('ensureHarmonyToolchainPathConfigured leaves PATH untouched when no root holds hdc', async () => {
115+
const env: NodeJS.ProcessEnv = {
116+
PATH: '/usr/bin',
117+
HDC_SDK_PATH: ' ',
118+
DEVECO_SDK_HOME: mkdtempForTestSync('agent-device-hdc-none-'),
119+
HARMONYOS_COMMAND_LINE_TOOLS: mkdtempForTestSync('agent-device-hdc-none-'),
120+
};
121+
122+
await ensureHarmonyToolchainPathConfigured(env);
123+
124+
assert.equal(env.PATH, '/usr/bin');
125+
});
126+
127+
test('ensureHarmonyToolchainPathConfigured creates PATH and dedupes a root already on it', async () => {
128+
const toolchains = await seedDirectToolchain(mkdtempForTestSync('agent-device-hdc-dup-'));
129+
130+
const env: NodeJS.ProcessEnv = {
131+
PATH: `/usr/bin${path.delimiter}${toolchains}`,
132+
HDC_SDK_PATH: toolchains,
133+
};
134+
await ensureHarmonyToolchainPathConfigured(env);
135+
136+
// The toolchain root moves to the front instead of appearing twice.
137+
assert.equal(env.PATH, [toolchains, '/usr/bin'].join(path.delimiter));
138+
139+
const missingPath: NodeJS.ProcessEnv = { HDC_SDK_PATH: toolchains };
140+
await ensureHarmonyToolchainPathConfigured(missingPath);
141+
assert.equal(missingPath.PATH, toolchains);
142+
});
143+
144+
test('ensureHarmonyToolchainPathConfigured defaults to the host environment', async () => {
145+
const toolchains = await seedDirectToolchain(mkdtempForTestSync('agent-device-hdc-host-'));
146+
const hostEnv: NodeJS.ProcessEnv = { PATH: '/usr/bin', HDC_SDK_PATH: toolchains };
147+
vi.mocked(hostEnvironment).mockReturnValue(hostEnv);
148+
149+
await ensureHarmonyToolchainPathConfigured();
150+
151+
assert.equal(hostEnv.PATH, [toolchains, '/usr/bin'].join(path.delimiter));
152+
});

0 commit comments

Comments
 (0)