Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/workflows/functional-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ jobs:
IOS_MODEL: 'iPhone 17'
- HOST_OS: 'macos-15'
XCODE_VERSION: '16.4'
IOS_VERSION: '18.4'
IOS_VERSION: '18.5'
IOS_MODEL: 'iPhone 16 Plus'
- HOST_OS: 'macos-14'
XCODE_VERSION: '15.4'
Expand Down Expand Up @@ -46,6 +46,7 @@ jobs:
DEVICE_NAME: ${{matrix.test_targets.IOS_MODEL}}
PLATFORM_VERSION: ${{matrix.test_targets.IOS_VERSION}}
run: |
xcrun simctl list devices available
open -Fn "$(xcode-select -p)/Applications/Simulator.app"
udid=$(xcrun simctl list devices available -j | \
node -p "Object.entries(JSON.parse(fs.readFileSync(0)).devices).filter((x) => x[0].includes('$PLATFORM_VERSION'.replace('.', '-'))).reduce((acc, x) => [...acc, ...x[1]], []).find(({name}) => name === '$DEVICE_NAME').udid")
Expand Down
7 changes: 0 additions & 7 deletions lib/appium-ios-device.d.ts

This file was deleted.

2 changes: 1 addition & 1 deletion lib/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export {bundleWDASim} from './check-dependencies';
export {NoSessionProxy} from './no-session-proxy';
export {WebDriverAgent} from './webdriveragent';
export {WDA_BASE_URL, WDA_RUNNER_BUNDLE_ID, PROJECT_FILE} from './constants';
export {WDA_BASE_URL, WDA_RUNNER_APP, WDA_RUNNER_BUNDLE_ID, PROJECT_FILE} from './constants';
export {resetTestProcesses, BOOTSTRAP_PATH} from './utils';

export * from './types';
7 changes: 4 additions & 3 deletions lib/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import {type HTTPHeaders} from '@appium/types';
import type {Simctl} from 'node-simctl';
import type {Devicectl} from 'node-devicectl';

// WebDriverAgentLib/Utilities/FBSettings.h
export interface WDASettings {
Expand Down Expand Up @@ -99,9 +101,8 @@ export interface WebDriverAgentArgs {

export interface AppleDevice {
udid: string;
simctl?: any;
devicectl?: any;
[key: string]: any;
simctl?: Simctl;
devicectl?: Devicectl;
}

/**
Expand Down
137 changes: 31 additions & 106 deletions lib/webdriveragent.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {waitForCondition} from 'asyncbox';
import path from 'node:path';
import {JWProxy} from '@appium/base-driver';
import {fs, util, plist} from '@appium/support';
import {fs, util} from '@appium/support';
import type {AppiumLogger, StringRecord} from '@appium/types';
import {log as defaultLogger} from './logger';
import {NoSessionProxy} from './no-session-proxy';
Expand All @@ -14,21 +14,19 @@ import {
import {XcodeBuild} from './xcodebuild';
import AsyncLock from 'async-lock';
import {exec} from 'teen_process';
import {bundleWDASim} from './check-dependencies';
import {
WDA_RUNNER_BUNDLE_ID,
WDA_RUNNER_APP,
WDA_BASE_URL,
WDA_UPGRADE_TIMESTAMP_PATH,
DEFAULT_TEST_BUNDLE_SUFFIX,
} from './constants';
import {Xctest} from 'appium-ios-device';
import {strongbox} from '@appium/strongbox';
import type {WebDriverAgentArgs, AppleDevice} from './types';
import type {Simctl} from 'node-simctl';
import type {Devicectl} from 'node-devicectl';

const WDA_LAUNCH_TIMEOUT = 60 * 1000;
const WDA_AGENT_PORT = 8100;
const WDA_CF_BUNDLE_NAME = 'WebDriverAgentRunner-Runner';
const SHARED_RESOURCES_GUARD = new AsyncLock();
const RECENT_MODULE_VERSION_ITEM_NAME = 'recentWdaModuleVersion';
const URL_PROTOCOL_SEPARATOR = '://';
Expand Down Expand Up @@ -64,7 +62,6 @@ export class WebDriverAgent {
private readonly wdaLaunchTimeout: number;
private readonly usePreinstalledWDA?: boolean;
private readonly updatedWDABundleIdSuffix: string;
private xctestApiClient?: Xctest | null;
private _xcodebuild?: XcodeBuild | null;
private _url?: URL;

Expand Down Expand Up @@ -112,7 +109,6 @@ export class WebDriverAgent {

this.wdaLaunchTimeout = args.wdaLaunchTimeout || WDA_LAUNCH_TIMEOUT;
this.usePreinstalledWDA = args.usePreinstalledWDA;
this.xctestApiClient = null;
this.updatedWDABundleIdSuffix = args.updatedWDABundleIdSuffix ?? DEFAULT_TEST_BUNDLE_SUFFIX;

this._xcodebuild = this.canSkipXcodebuild
Expand Down Expand Up @@ -366,15 +362,14 @@ export class WebDriverAgent {
async quit(): Promise<void> {
if (this.usePreinstalledWDA) {
this.log.info('Stopping the XCTest session');
if (this.xctestApiClient) {
this.xctestApiClient.stop();
this.xctestApiClient = null;
} else {
try {
try {
if (this.device.simctl) {
await this.device.simctl.terminateApp(this.bundleIdForXctest);
} catch (e: any) {
this.log.warn(e.message);
} else if (this.device.devicectl) {
await this.device.devicectl.terminateApp(this.bundleIdForXctest);
}
} catch (e: any) {
this.log.warn(e.message);
}
} else if (!this.args.webDriverAgentUrl) {
this.log.info('Shutting down sub-processes');
Expand All @@ -383,8 +378,7 @@ export class WebDriverAgent {
}
} else {
this.log.debug(
'Do not stop xcodebuild nor XCTest session ' +
'since the WDA session is managed by outside this driver.',
'Stopping neither xcodebuild nor XCTest session since WDA lifecycle is not managed by this driver',
);
}

Expand Down Expand Up @@ -415,13 +409,14 @@ export class WebDriverAgent {
/**
* Reuse running WDA if it has the same bundle id with updatedWDABundleId.
* Or reuse it if it has the default id without updatedWDABundleId.
* Uninstall it if the method faces an exception for the above situation.
*
* @returns The WDA URL used for caching on success, or `undefined` if caching was skipped.
*/
async setupCaching(): Promise<void> {
async setupCaching(): Promise<string | undefined> {
const status = await this.getStatus(0);
if (!status || !status.build) {
this.log.debug('WDA is currently not running. There is nothing to cache');
return;
return undefined;
}

const {productBundleIdentifier, upgradedAt} = status.build as any;
Expand All @@ -432,9 +427,9 @@ export class WebDriverAgent {
this.updatedWDABundleId !== productBundleIdentifier
) {
this.log.info(
`Will uninstall running WDA since it has different bundle id. The actual value is '${productBundleIdentifier}'.`,
`Will not reuse running WDA since it has different bundle id. The actual value is '${productBundleIdentifier}'.`,
);
return await this.uninstall();
return undefined;
}
// for simulator
if (
Expand All @@ -443,9 +438,9 @@ export class WebDriverAgent {
WDA_RUNNER_BUNDLE_ID !== productBundleIdentifier
) {
this.log.info(
`Will uninstall running WDA since its bundle id is not equal to the default value ${WDA_RUNNER_BUNDLE_ID}`,
`Will not reuse running WDA since its bundle id is not equal to the default value ${WDA_RUNNER_BUNDLE_ID}`,
);
return await this.uninstall();
return undefined;
}

const actualUpgradeTimestamp = await getWDAUpgradeTimestamp();
Expand All @@ -457,51 +452,21 @@ export class WebDriverAgent {
`${actualUpgradeTimestamp}`.toLowerCase() !== `${upgradedAt}`.toLowerCase()
) {
this.log.info(
'Will uninstall running WDA since it has different version in comparison to the one ' +
'Will not reuse running WDA since it has different version in comparison to the one ' +
`which is bundled with appium-xcuitest-driver module (${actualUpgradeTimestamp} != ${upgradedAt})`,
);
return await this.uninstall();
return undefined;
}

const cachedUrl = this.url.href;
const message = util.hasValue(productBundleIdentifier)
? `Will reuse previously cached WDA instance at '${this.url.href}' with '${productBundleIdentifier}'`
: `Will reuse previously cached WDA instance at '${this.url.href}'`;
? `Will reuse previously cached WDA instance at '${cachedUrl}' with '${productBundleIdentifier}'`
: `Will reuse previously cached WDA instance at '${cachedUrl}'`;
this.log.info(
`${message}. Set the wdaLocalPort capability to a value different from ${this.url.port} if this is an undesired behavior.`,
);
this.webDriverAgentUrl = this.url.href;
}

/**
* Quit and uninstall running WDA.
*/
async quitAndUninstall(): Promise<void> {
await this.quit();
await this.uninstall();
}

private async parseBundleId(wdaBundlePath: string): Promise<string> {
const infoPlistPath = path.join(wdaBundlePath, 'Info.plist');
const infoPlist = (await plist.parsePlist(await fs.readFile(infoPlistPath))) as {
CFBundleIdentifier?: string;
};
if (!infoPlist.CFBundleIdentifier) {
throw new Error(`Could not find bundle id in '${infoPlistPath}'`);
}
return infoPlist.CFBundleIdentifier;
}

private async fetchWDABundle(): Promise<string> {
if (!this.derivedDataPath) {
return await bundleWDASim(this.xcodebuild);
}
const wdaBundlePaths = await fs.glob(`${this.derivedDataPath}/**/*${WDA_RUNNER_APP}/`, {
absolute: true,
});
if (wdaBundlePaths.length === 0) {
throw new Error(`Could not find the WDA bundle in '${this.derivedDataPath}'`);
}
return wdaBundlePaths[0];
this.webDriverAgentUrl = cachedUrl;
return cachedUrl;
}

private setupProxies(sessionId: string): void {
Expand Down Expand Up @@ -549,10 +514,6 @@ export class WebDriverAgent {
this.log.info(`Using WDA agent: '${this.agentPath}'`);
}

private async isRunning(): Promise<boolean> {
return !!(await this.getStatus());
}

/**
* Return current running WDA's status like below
* {
Expand Down Expand Up @@ -626,32 +587,6 @@ export class WebDriverAgent {
return status;
}

/**
* Uninstall WDAs from the test device.
* Over Xcode 11, multiple WDA can be in the device since Xcode 11 generates different WDA.
* Appium does not expect multiple WDAs are running on a device.
*/
private async uninstall(): Promise<void> {
try {
const bundleIds = await this.device.getUserInstalledBundleIdsByBundleName(WDA_CF_BUNDLE_NAME);
if (bundleIds.length === 0) {
this.log.debug('No WDAs on the device.');
return;
}

this.log.debug(`Uninstalling WDAs: '${bundleIds}'`);
for (const bundleId of bundleIds) {
await this.device.removeApp(bundleId);
}
} catch (e: any) {
this.log.debug(e);
this.log.warn(
`WebDriverAgent uninstall failed. Perhaps, it is already uninstalled? ` +
`Original error: ${e.message}`,
);
}
}

private async _cleanupProjectIfFresh(): Promise<void> {
if (this.canSkipXcodebuild) {
return;
Expand Down Expand Up @@ -725,17 +660,17 @@ export class WebDriverAgent {
* https://github.com/appium/WebDriverAgent/releases
* with proper sign for this case.
*
* When we implement launching XCTest service via appium-ios-device,
* this implementation can be replaced with it.
*
* @param opts launching WDA with devicectl command options.
*/
private async _launchViaDevicectl(
opts: {env?: Record<string, string | number>} = {},
): Promise<void> {
const {env} = opts;

await this.device.devicectl.launchApp(this.bundleIdForXctest, {env, terminateExisting: true});
await (this.device.devicectl as Devicectl).launchApp(this.bundleIdForXctest, {
env,
terminateExisting: true,
});
}

/**
Expand All @@ -755,19 +690,9 @@ export class WebDriverAgent {
}
this.log.info('Launching WebDriverAgent on the device without xcodebuild');
if (this.isRealDevice) {
// Current method to launch WDA process can be done via 'xcrun devicectl',
// but it has limitation about the WDA preinstalled package.
// https://github.com/appium/appium/issues/19206#issuecomment-2014182674
if (this.platformVersion && util.compareVersions(this.platformVersion, '>=', '17.0')) {
await this._launchViaDevicectl({env: xctestEnv});
} else {
this.xctestApiClient = new Xctest(this.device.udid, this.bundleIdForXctest, null, {
env: xctestEnv,
});
await this.xctestApiClient.start();
}
await this._launchViaDevicectl({env: xctestEnv});
} else {
await this.device.simctl.exec('launch', {
await (this.device.simctl as Simctl).exec('launch', {
args: ['--terminate-running-process', this.device.udid, this.bundleIdForXctest],
env: xctestEnv,
});
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
"chai-as-promised": "^8.0.0",
"conventional-changelog-conventionalcommits": "^9.0.0",
"mocha": "^11.0.1",
"node-devicectl": "^1.4.0",
"node-simctl": "^8.0.0",
"prettier": "^3.0.0",
"semantic-release": "^25.0.2",
Expand All @@ -77,7 +78,6 @@
"@appium/base-driver": "^10.3.0",
"@appium/strongbox": "^1.0.0-rc.1",
"@appium/support": "^7.0.0-rc.1",
"appium-ios-device": "^3.0.0",
"appium-ios-simulator": "^8.0.0",
"async-lock": "^1.0.0",
"asyncbox": "^6.1.0",
Expand Down
2 changes: 1 addition & 1 deletion test/functional/helpers/simulator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export async function killAllSimulators(): Promise<void> {
export async function shutdownSimulator(device: AppleDevice): Promise<void> {
// stop XCTest processes if running to avoid unexpected side effects
await resetTestProcesses(device.udid, true);
await device.shutdown();
await (device.simctl as Simctl).shutdownDevice();
}

export async function deleteDeviceWithRetry(udid: string): Promise<void> {
Expand Down
5 changes: 4 additions & 1 deletion test/functional/webdriveragent-e2e-specs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,10 @@ describe('WebDriverAgent', function () {
this.timeout(6 * 60 * 1000);
beforeEach(async function () {
await killAllSimulators();
await device.run({startupTimeout: SIM_STARTUP_TIMEOUT_MS});
await (device.simctl as Simctl).startBootMonitor({
shouldPreboot: true,
timeout: SIM_STARTUP_TIMEOUT_MS,
});
});
afterEach(async function () {
try {
Expand Down
Loading
Loading