import { test, expect } from '@playwright/test'; import { writeFileSync, mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join, relative, resolve } from 'node:path'; import { MobilecliDriver } from './driver.js'; import { NoDeviceAvailableError, type DeviceInfo } from '@mobilewright/protocol'; const ZIP_MAGIC = Buffer.from([0x50, 0x4B, 0x03, 0x04]); const tmpDir = mkdtempSync(join(tmpdir(), 'mw-driver-test-')); test.afterAll(() => { rmSync(tmpDir, { recursive: true }); }); function createValidZipFile(name: string): string { const path = join(tmpDir, name); writeFileSync(path, ZIP_MAGIC); return path; } function createCorruptZipFile(name: string): string { const path = join(tmpDir, name); writeFileSync(path, Buffer.from([0x00, 0x00, 0x00, 0x00])); return path; } const SIMULATOR_DEVICE_ID = 'sim-iphone-15'; const SIMULATOR_DEVICE_NAME = 'iPhone 15'; /** * Patch a MobilecliDriver instance so it has a pre-established session and * its `listDevices` call returns a controlled list — no real mobilecli binary * or WebSocket server needed. */ function createDriverWithSession(opts?: { platform?: 'ios' | 'android'; deviceType?: 'simulator' | 'real' | 'emulator'; }): MobilecliDriver { const platform = opts?.platform ?? 'ios'; const deviceType = opts?.deviceType ?? 'simulator'; const driver = new MobilecliDriver(); // Inject a fake active session directly into the private field. (driver as any).session = { deviceId: SIMULATOR_DEVICE_ID, deviceName: SIMULATOR_DEVICE_NAME, platform, deviceType, rpc: { call: async () => { throw new Error('RPC call should not have been made'); }, disconnect: async () => { }, }, }; // Stub listDevices to return the simulated device list. driver.listDevices = async () => [ { id: SIMULATOR_DEVICE_ID, name: SIMULATOR_DEVICE_NAME, platform, type: deviceType, state: 'online', }, ]; return driver; } function allowRpc(driver: MobilecliDriver): void { (driver as any).session.rpc.call = async () => ({}); } interface RecordedCall { method: string; params: Record; } // Replace the session's RPC transport with a recorder that returns canned // responses keyed by method name, capturing every (method, params) pair. function recordRpc( driver: MobilecliDriver, responses: Record, ): RecordedCall[] { const calls: RecordedCall[] = []; (driver as any).session.rpc.call = async (method: string, params: Record) => { calls.push({ method, params }); return responses[method]; }; return calls; } test.describe('MobilecliDriver.installApp()', () => { test.describe('iOS simulator', () => { test('accepts a .zip file', async () => { const driver = createDriverWithSession({ platform: 'ios', deviceType: 'simulator' }); allowRpc(driver); await expect(driver.installApp(createValidZipFile('MyApp.zip'))).resolves.toBeUndefined(); }); test('rejects a .zip file that is not a valid ZIP', async () => { const driver = createDriverWithSession({ platform: 'ios', deviceType: 'simulator' }); await expect(driver.installApp(createCorruptZipFile('corrupt-sim.zip'))).rejects.toThrow( 'is not a valid ZIP file', ); }); test('rejects a .ipa file with instructions for building a .zip', async () => { const driver = createDriverWithSession({ platform: 'ios', deviceType: 'simulator' }); let error: Error | undefined; try { await driver.installApp('/path/to/MyApp.ipa'); } catch (e) { error = e as Error; } expect(error).toBeDefined(); expect(error!.message).toContain(`iOS simulator "${SIMULATOR_DEVICE_NAME}" requires a .zip`); expect(error!.message).toContain('xcodebuild'); expect(error!.message).toContain('zip -r MyApp.zip MyApp.app'); expect(error!.message).toContain('installApps config'); }); test('rejects a .apk file', async () => { const driver = createDriverWithSession({ platform: 'ios', deviceType: 'simulator' }); await expect(driver.installApp('/path/to/app.apk')).rejects.toThrow( `iOS simulator "${SIMULATOR_DEVICE_NAME}" requires a .zip`, ); }); test('is case-insensitive for extension check', async () => { const driver = createDriverWithSession({ platform: 'ios', deviceType: 'simulator' }); await expect(driver.installApp('/path/to/MyApp.IPA')).rejects.toThrow( `iOS simulator "${SIMULATOR_DEVICE_NAME}" requires a .zip`, ); }); test('does not make an RPC call when rejected', async () => { const driver = createDriverWithSession({ platform: 'ios', deviceType: 'simulator' }); let error: Error | undefined; try { await driver.installApp('/path/to/app.ipa'); } catch (e) { error = e as Error; } expect(error).toBeDefined(); expect(error!.message).not.toContain('RPC call should not have been made'); }); }); test.describe('iOS real device', () => { test('accepts a .ipa file', async () => { const driver = createDriverWithSession({ platform: 'ios', deviceType: 'real' }); allowRpc(driver); await expect(driver.installApp(createValidZipFile('MyApp.ipa'))).resolves.toBeUndefined(); }); test('rejects an .ipa file that is not a valid ZIP', async () => { const driver = createDriverWithSession({ platform: 'ios', deviceType: 'real' }); await expect(driver.installApp(createCorruptZipFile('corrupt-real.ipa'))).rejects.toThrow( 'is not a valid ZIP file', ); }); test('rejects a .zip file', async () => { const driver = createDriverWithSession({ platform: 'ios', deviceType: 'real' }); await expect(driver.installApp('/path/to/MyApp.zip')).rejects.toThrow( 'iOS real device requires a .ipa file', ); }); test('rejects a .apk file', async () => { const driver = createDriverWithSession({ platform: 'ios', deviceType: 'real' }); await expect(driver.installApp('/path/to/app.apk')).rejects.toThrow( 'iOS real device requires a .ipa file', ); }); test('is case-insensitive for extension check', async () => { const driver = createDriverWithSession({ platform: 'ios', deviceType: 'real' }); allowRpc(driver); await expect(driver.installApp(createValidZipFile('MyApp.IPA'))).resolves.toBeUndefined(); }); }); test.describe('Android', () => { test('accepts a .apk file', async () => { const driver = createDriverWithSession({ platform: 'android', deviceType: 'emulator' }); allowRpc(driver); await expect(driver.installApp(createValidZipFile('app.apk'))).resolves.toBeUndefined(); }); test('rejects an .apk file that is not a valid ZIP', async () => { const driver = createDriverWithSession({ platform: 'android', deviceType: 'emulator' }); await expect(driver.installApp(createCorruptZipFile('corrupt.apk'))).rejects.toThrow( 'is not a valid ZIP file', ); }); test('rejects a .ipa file', async () => { const driver = createDriverWithSession({ platform: 'android', deviceType: 'emulator' }); await expect(driver.installApp('/path/to/MyApp.ipa')).rejects.toThrow( 'Android requires a .apk file', ); }); test('rejects a .zip file', async () => { const driver = createDriverWithSession({ platform: 'android', deviceType: 'emulator' }); await expect(driver.installApp('/path/to/app.zip')).rejects.toThrow( 'Android requires a .apk file', ); }); test('is case-insensitive for extension check', async () => { const driver = createDriverWithSession({ platform: 'android', deviceType: 'emulator' }); allowRpc(driver); await expect(driver.installApp(createValidZipFile('app.APK'))).resolves.toBeUndefined(); }); }); }); test.describe('MobilecliDriver.launchApp()', () => { function launchCallParams(calls: RecordedCall[]): Record { const launch = calls.find((c) => c.method === 'device.apps.launch'); if (!launch) { throw new Error('device.apps.launch was never called'); } return launch.params; } test('forwards an explicit activity to device.apps.launch', async () => { const driver = createDriverWithSession({ platform: 'android', deviceType: 'emulator' }); const calls = recordRpc(driver, {}); await driver.launchApp('com.example.app', { activity: '.DebugActivity' }); expect(launchCallParams(calls)).toEqual({ deviceId: SIMULATOR_DEVICE_ID, bundleId: 'com.example.app', activity: '.DebugActivity', }); }); test('omits activity from device.apps.launch when not provided', async () => { const driver = createDriverWithSession({ platform: 'android', deviceType: 'emulator' }); const calls = recordRpc(driver, {}); await driver.launchApp('com.example.app'); expect(launchCallParams(calls)).toEqual({ deviceId: SIMULATOR_DEVICE_ID, bundleId: 'com.example.app', }); }); }); test.describe('MobilecliDriver.webViewBridge', () => { test('listWebViews maps device.webview.list entries to WebViewInfo', async () => { const driver = createDriverWithSession(); recordRpc(driver, { 'device.webview.list': [ { id: 'wv-1', url: 'https://example.com/', title: 'Example', bundleId: 'com.example.app', bounds: { x: 0, y: 100, width: 390, height: 700 }, isVisible: true, }, ], }); const webviews = await driver.webViewBridge.listWebViews(); expect(webviews).toEqual([ { id: 'wv-1', url: 'https://example.com/', title: 'Example', nativeBounds: { x: 0, y: 100, width: 390, height: 700 }, }, ]); }); test('navigation methods call the matching RPC with the device and webview ids', async () => { const driver = createDriverWithSession(); const calls = recordRpc(driver, {}); const session = await driver.webViewBridge.attachWebView('wv-1'); await session.goto('https://example.com/'); await session.goBack(); await session.goForward(); await session.reload(); expect(calls.map((c) => c.method)).toEqual([ 'device.webview.goto', 'device.webview.goBack', 'device.webview.goForward', 'device.webview.reload', ]); // deviceId is injected by the driver, id by the session. expect(calls[0].params).toEqual({ deviceId: SIMULATOR_DEVICE_ID, id: 'wv-1', url: 'https://example.com/' }); expect(calls[1].params).toEqual({ deviceId: SIMULATOR_DEVICE_ID, id: 'wv-1' }); }); test('evaluate forwards the expression and returns the value directly', async () => { const driver = createDriverWithSession(); const calls = recordRpc(driver, { 'device.webview.evaluate': 42 }); const session = await driver.webViewBridge.attachWebView('wv-1'); const value = await session.evaluate('6 * 7'); expect(value).toBe(42); expect(calls[0]).toEqual({ method: 'device.webview.evaluate', params: { deviceId: SIMULATOR_DEVICE_ID, id: 'wv-1', expression: '6 * 7' }, }); }); test('url and title return the raw RPC string results', async () => { const driver = createDriverWithSession(); recordRpc(driver, { 'device.webview.url': 'https://example.com/page', 'device.webview.title': 'Page Title', }); const session = await driver.webViewBridge.attachWebView('wv-1'); expect(await session.url()).toBe('https://example.com/page'); expect(await session.title()).toBe('Page Title'); }); }); test.describe('MobilecliDriver.fill()', () => { for (const platform of ['ios', 'android'] as const) { test(`asks mobilecli to fill the focused field on ${platform}`, async () => { const driver = createDriverWithSession({ platform }); const calls = recordRpc(driver, { 'device.io.fill': {} }); await driver.fill('Zaphod'); expect(calls).toEqual([ { method: 'device.io.fill', params: { deviceId: SIMULATOR_DEVICE_ID, text: 'Zaphod' } }, ]); }); } test('fills with an empty string to clear', async () => { const driver = createDriverWithSession({ platform: 'android' }); const calls = recordRpc(driver, { 'device.io.fill': {} }); await driver.fill(''); expect(calls).toEqual([ { method: 'device.io.fill', params: { deviceId: SIMULATOR_DEVICE_ID, text: '' } }, ]); }); }); test.describe('MobilecliDriver.applyDeviceSettings()', () => { test('sends device.settings.apply with the settings and deviceId', async () => { const driver = createDriverWithSession({ platform: 'android' }); const calls = recordRpc(driver, { 'device.settings.apply': {} }); await driver.applyDeviceSettings({ animations: 'off' }); expect(calls).toEqual([ { method: 'device.settings.apply', params: { deviceId: SIMULATOR_DEVICE_ID, animations: 'off' } }, ]); }); }); test.describe('MobilecliDriver.allocate()', () => { function createDriverWithDevices(devices: Partial[]): MobilecliDriver { const driver = new MobilecliDriver(); driver.listDevices = async () => devices.map((d, i) => ({ id: d.id ?? `device-${i}`, name: d.name ?? `Device ${i}`, platform: d.platform ?? 'ios', type: d.type ?? 'simulator', state: d.state ?? 'online', model: d.model, osVersion: d.osVersion, })); return driver; } test('picks a real device over a simulator when deviceType is "real"', async () => { const driver = createDriverWithDevices([ { id: 'sim-1', type: 'simulator' }, { id: 'real-1', type: 'real' }, ]); const allocated = await driver.allocate({ platform: 'ios', deviceType: 'real' }, new Set()); expect(allocated.deviceId).toBe('real-1'); }); test('throws a non-retriable error when no device matches the deviceType', async () => { const driver = createDriverWithDevices([{ id: 'sim-1', type: 'simulator' }]); const error = await driver.allocate({ platform: 'ios', deviceType: 'real' }, new Set()).catch((e: Error) => e); expect(error).not.toBeInstanceOf(NoDeviceAvailableError); expect((error as Error).message).toContain('sim-1'); }); test('throws NoDeviceAvailableError when the only matching device is taken', async () => { const driver = createDriverWithDevices([{ id: 'sim-1', type: 'simulator' }]); await expect(driver.allocate({ platform: 'ios' }, new Set(['sim-1']))).rejects.toThrow( NoDeviceAvailableError, ); }); test('a deviceNamePattern that matches nothing fails immediately, listing the devices it saw', async () => { const driver = createDriverWithDevices([{ id: 'PixelPro_AVD', name: 'PixelPro AVD' }]); const error = await driver .allocate({ platform: 'ios', deviceNamePattern: 'PixelPro_AVD' }, new Set()) .catch((e: Error) => e); expect(error).not.toBeInstanceOf(NoDeviceAvailableError); expect((error as Error).message).toContain('PixelPro AVD (PixelPro_AVD, online)'); }); test('picks the device whose OS version satisfies the expression', async () => { const driver = createDriverWithDevices([ { id: 'old', osVersion: '16.4' }, { id: 'wanted', osVersion: '17.5' }, { id: 'too-new', osVersion: '18.0' }, ]); const allocated = await driver.allocate({ platform: 'ios', osVersion: '17' }, new Set()); expect(allocated.deviceId).toBe('wanted'); }); test('a device that does not report an OS version never matches an osVersion filter', async () => { const driver = createDriverWithDevices([{ id: 'unknown-version', osVersion: undefined }]); await expect(driver.allocate({ platform: 'ios', osVersion: '17' }, new Set())).rejects.toThrow( /no device matches criteria/, ); }); }); test('an invalid osVersion expression throws a parse error even when no devices are eligible', async () => { const driver = new MobilecliDriver(); driver.listDevices = async () => []; await expect(driver.allocate({ platform: 'ios', osVersion: 'latest' }, new Set())).rejects.toThrow( /invalid OS version/, ); }); test.describe('MobilecliDriver.screenshot()', () => { function screenshotCallParams(calls: RecordedCall[]): Record | undefined { return calls.find(c => c.method === 'device.screenshot')?.params; } test('asks mobilecli for a downscaled screenshot when scale is given', async () => { const driver = createDriverWithSession(); const calls = recordRpc(driver, { 'device.screenshot': { data: '' } }); await driver.screenshot({ scale: 0.5 }); expect(screenshotCallParams(calls)).toEqual({ deviceId: SIMULATOR_DEVICE_ID, scale: 0.5 }); }); test('sends no scale when none is given', async () => { const driver = createDriverWithSession(); const calls = recordRpc(driver, { 'device.screenshot': { data: '' } }); await driver.screenshot(); expect(screenshotCallParams(calls)).toEqual({ deviceId: SIMULATOR_DEVICE_ID }); }); }); // mobilecli's device.io.tap / device.io.longpress params are Go ints: a // fractional coordinate is rejected with "cannot unmarshal number 10.4 into // Go struct field IoTapParams.x of type int". tap() already rounds; the other // pointer actions must do the same. test.describe('pointer coordinates are sent to mobilecli as integers', () => { function sentCoordinates(calls: RecordedCall[]): Array<{ x: unknown; y: unknown }> { return calls.map(({ params }) => ({ x: params.x, y: params.y })); } test('doubleTap() rounds fractional coordinates for both taps', async () => { const driver = createDriverWithSession(); const calls = recordRpc(driver, { 'device.io.tap': {} }); await driver.doubleTap(10.4, 20.6); expect(calls.map((c) => c.method)).toEqual(['device.io.tap', 'device.io.tap']); expect(sentCoordinates(calls)).toEqual([{ x: 10, y: 21 }, { x: 10, y: 21 }]); }); test('longPress() rounds fractional coordinates', async () => { const driver = createDriverWithSession(); const calls = recordRpc(driver, { 'device.io.longpress': {} }); await driver.longPress(10.4, 20.6, 300); expect(calls[0].method).toBe('device.io.longpress'); expect(sentCoordinates(calls)).toEqual([{ x: 10, y: 21 }]); expect(calls[0].params.duration).toBe(300); }); }); // The mobilecli server resolves a relative `path` against ITS cwd, which is // not the test's cwd when the server was started elsewhere. Always hand it an // absolute path. test('installApp() sends an absolute path to mobilecli even when given a relative one', async () => { const driver = createDriverWithSession({ platform: 'android', deviceType: 'emulator' }); const calls = recordRpc(driver, { 'device.apps.install': {} }); const absolutePath = createValidZipFile('relative-install.apk'); const relativePath = relative(process.cwd(), absolutePath); expect(relativePath.startsWith('/')).toBe(false); await driver.installApp(relativePath); expect(calls[0].method).toBe('device.apps.install'); expect(calls[0].params.path).toBe(resolve(absolutePath)); }); // Removing an app that is not there is not an error (real iOS already behaves // this way; Android answered `Failure [DELETE_FAILED_INTERNAL_ERROR]`). test.describe('uninstallApp() when the app is not installed', () => { function driverWithInstalledApps(installed: string[]) { const driver = createDriverWithSession({ platform: 'android', deviceType: 'emulator' }); const calls = recordRpc(driver, { 'device.apps.uninstall': {}, 'device.apps.list': { apps: installed.map((packageName) => ({ packageName })) } }); return { driver, calls }; } test('is a no-op and never sends the uninstall RPC', async () => { const { driver, calls } = driverWithInstalledApps(['com.other.app']); await expect(driver.uninstallApp('com.example.app')).resolves.toBeUndefined(); expect(calls.map((c) => c.method)).toEqual(['device.apps.list']); }); test('still uninstalls an installed app', async () => { const { driver, calls } = driverWithInstalledApps(['com.example.app']); await driver.uninstallApp('com.example.app'); expect(calls.map((c) => c.method)).toEqual(['device.apps.list', 'device.apps.uninstall']); expect(calls[1].params.bundleId).toBe('com.example.app'); }); }); test('installApp() with a path that does not exist reports the path instead of a raw ENOENT', async () => { const driver = createDriverWithSession({ platform: 'android', deviceType: 'emulator' }); await expect(driver.installApp('/no/such/dir/app.apk')).rejects.toThrow(`App file not found: ${resolve('/no/such/dir/app.apk')}`); }); test.describe('keyboard RPC calls', () => { function timeoutsOfRpcCalls(driver: MobilecliDriver): Array { const timeouts: Array = []; (driver as any).session.rpc.call = async (_method: string, _params: unknown, timeoutMs?: number) => { timeouts.push(timeoutMs); }; return timeouts; } test('isKeyboardVisible asks device.io.keyboard.status and returns visible', async () => { const driver = createDriverWithSession({ platform: 'ios', deviceType: 'simulator' }); const calls = recordRpc(driver, { 'device.io.keyboard.status': { visible: true } }); const visible = await driver.isKeyboardVisible(); expect(visible).toBe(true); expect(calls).toEqual([{ method: 'device.io.keyboard.status', params: { deviceId: SIMULATOR_DEVICE_ID } }]); }); test('hideKeyboard calls device.io.keyboard.hide', async () => { const driver = createDriverWithSession({ platform: 'ios', deviceType: 'simulator' }); const calls = recordRpc(driver, {}); await driver.hideKeyboard(); expect(calls).toEqual([{ method: 'device.io.keyboard.hide', params: { deviceId: SIMULATOR_DEVICE_ID } }]); }); test('hideKeyboard allows longer than the default request timeout', async () => { const driver = createDriverWithSession({ platform: 'ios', deviceType: 'simulator' }); const timeouts = timeoutsOfRpcCalls(driver); await driver.hideKeyboard(); expect(timeouts).toEqual([60_000]); }); });