appium-xcuitest-driver
Version:
Appium driver for iOS using XCUITest for backend
327 lines • 14.9 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.mobileInstallApp = mobileInstallApp;
exports.mobileIsAppInstalled = mobileIsAppInstalled;
exports.mobileRemoveApp = mobileRemoveApp;
exports.mobileLaunchApp = mobileLaunchApp;
exports.mobileTerminateApp = mobileTerminateApp;
exports.mobileActivateApp = mobileActivateApp;
exports.mobileKillApp = mobileKillApp;
exports.mobileQueryAppState = mobileQueryAppState;
exports.installApp = installApp;
exports.activateApp = activateApp;
exports.isAppInstalled = isAppInstalled;
exports.terminateApp = terminateApp;
exports.queryAppState = queryAppState;
exports.mobileListApps = mobileListApps;
exports.mobileClearApp = mobileClearApp;
exports.background = background;
const lodash_1 = __importDefault(require("lodash"));
const support_1 = require("appium/support");
const driver_1 = require("appium/driver");
const node_path_1 = __importDefault(require("node:path"));
const utils_1 = require("../utils");
const installation_proxy_client_1 = require("../device/installation-proxy-client");
/**
* Installs the given application to the device under test.
*
* Please ensure the app is built for a correct architecture and is signed with a proper developer signature (for real devices) prior to calling this.
* @param app - See docs for `appium:app` capability
* @param timeoutMs - The maximum time to wait until app install is finished (in ms) on real devices.
* If not provided, then the value of `appium:appPushTimeout` capability is used. If the capability is not provided then the default is 240000ms (4 minutes).
* @param checkVersion - If the application installation follows currently installed application's version status if provided.
* No checking occurs if no this option.
* @privateRemarks Link to capability docs
*/
async function mobileInstallApp(app, timeoutMs, checkVersion) {
const srcAppPath = await this.helpers.configureApp(app, {
onPostProcess: utils_1.onPostConfigureApp.bind(this),
onDownload: utils_1.onDownloadApp.bind(this),
supportedExtensions: utils_1.SUPPORTED_EXTENSIONS,
});
this.log.info(`Installing '${srcAppPath}' to the ${this.isRealDevice() ? 'real device' : 'Simulator'} ` +
`with UDID '${this.device.udid}'`);
if (!(await support_1.fs.exists(srcAppPath))) {
throw this.log.errorWithException(`The application at '${srcAppPath}' does not exist or is not accessible`);
}
const bundleId = await this.appInfosCache.extractBundleId(srcAppPath);
if (checkVersion) {
const { install } = await this.checkAutInstallationState({
enforceAppInstall: false,
fullReset: false,
noReset: false,
bundleId,
app: srcAppPath,
});
if (!install) {
this.log.info(`Skipping the installation of '${bundleId}'`);
return;
}
}
await this.device.installApp(srcAppPath, bundleId, {
timeoutMs: timeoutMs ?? this.opts.appPushTimeout,
});
this.log.info(`Installation of '${srcAppPath}' succeeded`);
}
/**
* Checks whether the given application is installed on the device under test.
* Offload app is handled as not installed.
*
* @param bundleId - The bundle identifier of the application to be checked
* @returns `true` if the application is installed; `false` otherwise
*/
async function mobileIsAppInstalled(bundleId) {
const installed = await this.device.isAppInstalled(bundleId);
this.log.info(`App '${bundleId}' is${installed ? '' : ' not'} installed`);
return installed;
}
/**
* Removes/uninstalls the given application from the device under test.
* Offload app data could also be removed.
*
* @param bundleId - The bundle identifier of the application to be removed
* @returns `true` if the application has been removed successfully; `false` otherwise
*/
async function mobileRemoveApp(bundleId) {
this.log.info(`Uninstalling the application with bundle identifier '${bundleId}' ` +
`from the ${this.isRealDevice() ? 'real device' : 'Simulator'} with UDID '${this.device.udid}'`);
try {
await this.device.removeApp(bundleId);
this.log.info(`Removal of '${bundleId}' succeeded`);
return true;
}
catch (err) {
this.log.warn(`Cannot remove '${bundleId}'. Original error: ${err.message}`);
return false;
}
}
/**
* Executes the given app on the device under test.
*
* If the app is already running it will be activated. If the app is not installed or cannot be launched then an exception is thrown.
* @param bundleId - The bundle identifier of the application to be launched
* @param args - One or more command line arguments for the app. If the app is already running then this argument is ignored.
* @param environment - Environment variables mapping for the app. If the app is already running then this argument is ignored.
*/
async function mobileLaunchApp(bundleId, args, environment) {
const launchOptions = { bundleId };
if (args) {
launchOptions.arguments = Array.isArray(args) ? args : [args];
}
if (environment) {
launchOptions.environment = environment;
}
await this.proxyCommand('/wda/apps/launch', 'POST', launchOptions);
}
/**
* Terminates the given app on the device under test.
*
* This command performs termination via [XCTest's `terminate`](https://developer.apple.com/documentation/xctest/xcuiapplication/1500637-terminate) API. If the app is not installed an exception is thrown. If the app is not running then nothing is done.
* @param bundleId - The bundle identifier of the application to be terminated
* @returns `true` if the app has been terminated successfully; `false` otherwise
*/
async function mobileTerminateApp(bundleId) {
return (await this.proxyCommand('/wda/apps/terminate', 'POST', { bundleId }));
}
/**
* Activate the given app on the device under test.
*
* This pushes the app to the foreground if it is running in the background. An exception is thrown if the app is not install or isn't running. Nothing is done if the app is already in the foreground.
*
* @param bundleId - The bundle identifier of the application to be activated
*/
async function mobileActivateApp(bundleId) {
await this.proxyCommand('/wda/apps/activate', 'POST', { bundleId });
}
/**
* Kill the given app on the real device under test by instruments service.
*
* If the app is not running or kill failed, then nothing is done.
*
* @param bundleId - The bundle identifier of the application to be killed
* @returns `true` if the app has been killed successfully; `false` otherwise
* @group Real Device Only
*/
async function mobileKillApp(bundleId) {
return await (0, utils_1.requireRealDevice)(this, 'Killing app').terminateApp(bundleId);
}
/**
* Queries the state of an installed application from the device under test.
*
* If the app with the given `bundleId` is not installed, an exception will be thrown.
*
* @param bundleId - The bundle identifier of the application to be queried
* @returns The actual application state code
* @see https://developer.apple.com/documentation/xctest/xcuiapplicationstate?language=objc
*/
async function mobileQueryAppState(bundleId) {
return (await this.proxyCommand('/wda/apps/state', 'POST', { bundleId }));
}
/**
* Installs the given application to the device under test.
*
* This is a wrapper around {@linkcode mobileInstallApp mobile: installApp}.
*
* @param appPath - Path to the application bundle or .ipa/.app file
* @param opts - Installation options
* @param opts.timeoutMs - Maximum time to wait for installation to complete (in milliseconds)
* @param opts.strategy - If `true`, checks the version before installing and skips if already installed
*/
async function installApp(appPath, opts = {}) {
await this.mobileInstallApp(appPath, opts.timeoutMs, opts.strategy);
}
/**
* Activates the given app on the device under test.
*
* This is a wrapper around {@linkcode mobileLaunchApp mobile: launchApp}. If the app is already
* running, it will be activated (brought to foreground). If the app is not installed or cannot
* be launched, an exception is thrown.
*
* @param bundleId - The bundle identifier of the application to be activated
* @param opts - Launch options
* @param opts.environment - Environment variables mapping for the app
* @param opts.arguments - Command line arguments for the app
*/
async function activateApp(bundleId, opts = {}) {
const { environment, arguments: args } = opts;
return await this.mobileLaunchApp(bundleId, args, environment);
}
/**
* Checks whether the given application is installed on the device under test.
*
* This is a wrapper around {@linkcode mobileIsAppInstalled mobile: isAppInstalled}.
* Offload apps are treated as not installed.
*
* @param bundleId - The bundle identifier of the application to be checked
* @returns `true` if the application is installed; `false` otherwise
*/
async function isAppInstalled(bundleId) {
return await this.mobileIsAppInstalled(bundleId);
}
/**
* Terminates the given app on the device under test.
*
* This is a wrapper around {@linkcode mobileTerminateApp mobile: terminateApp}.
* The command performs termination via XCTest's `terminate` API. If the app is not installed,
* an exception is thrown. If the app is not running, nothing is done.
*
* @param bundleId - The bundle identifier of the application to be terminated
* @returns `true` if the app has been terminated successfully; `false` otherwise
*/
async function terminateApp(bundleId) {
return await this.mobileTerminateApp(bundleId);
}
/**
* Queries the state of an installed application from the device under test.
*
* This is a wrapper around {@linkcode mobileQueryAppState mobile: queryAppState}.
* If the app with the given `bundleId` is not installed, an exception will be thrown.
*
* @param bundleId - The bundle identifier of the application to be queried
* @returns The actual application state code
* @see https://developer.apple.com/documentation/xctest/xcuiapplicationstate?language=objc
*/
async function queryAppState(bundleId) {
return await this.mobileQueryAppState(bundleId);
}
/**
* List applications installed on the real device under test
*
* Read [Pushing/Pulling files](https://appium.io/docs/en/writing-running-appium/ios/ios-xctest-file-movement/) for more details.
* @param applicationType - The type of applications to list (default: 'User').
* @param returnAttributes - Array of attribute names to return for each app (e.g., ["CFBundleIdentifier", "CFBundleName"]).
* If not provided, all available attributes are returned.
* @returns An object mapping bundle identifiers to app properties (e.g., CFBundleName, CFBundleVersion, etc.).
* @remarks Having `UIFileSharingEnabled` set to `true` in the app properties means the app supports file upload/download in its `documents` container.
* @group Real Device Only
*/
async function mobileListApps(applicationType = 'User', returnAttributes) {
const device = (0, utils_1.requireRealDevice)(this, 'Listing apps');
const useRemoteXPC = (0, utils_1.isIos18OrNewer)(this.opts);
const client = await installation_proxy_client_1.InstallationProxyClient.create(device.udid, useRemoteXPC);
try {
return await client.listApplications({ applicationType, returnAttributes });
}
finally {
await client.close();
}
}
/**
* Deletes application data files, so it could start from the clean state next time
* it is launched.
* This API only works on a Simulator.
*
* @param bundleId Application bundle identifier
* @returns true if any files from the app's data container have been deleted
*/
async function mobileClearApp(bundleId) {
if (this.isRealDevice()) {
throw new driver_1.errors.NotImplementedError(`This extension is only supported on simulators. ` +
`The only known way to clear app data on real devices ` +
`would be to uninstall the app then perform a fresh install of it.`);
}
const simctl = this.device.simctl;
const dataRoot = await simctl.getAppContainer(bundleId, 'data');
this.log.debug(`Got the data container root of ${bundleId} at '${dataRoot}'`);
if (!(await support_1.fs.exists(dataRoot))) {
return false;
}
await this.mobileTerminateApp(bundleId);
const items = await support_1.fs.readdir(dataRoot);
if (!items.length) {
return false;
}
await Promise.all(items.map((item) => support_1.fs.rimraf(node_path_1.default.join(dataRoot, item))));
this.log.info(`Cleaned up ${support_1.util.pluralize('item', items.length, true)} from ${bundleId}'s data container`);
return true;
}
/**
* Closes the app (simulates device home button press).
*
* It is possible to restore the app after a timeout or keep it minimized based on the parameter value.
*
* @param seconds - Timeout configuration. Accepts:
* - A positive number (seconds): app will be restored after the specified number of seconds
* - A negative number or zero: app will not be restored (kept minimized)
* - `undefined` or `null`: app will not be restored (kept minimized)
* - An object with `timeout` property:
* - `{timeout: 5000}`: app will be restored after 5 seconds (timeout in milliseconds)
* - `{timeout: null}` or `{timeout: -2}`: app will not be restored
*/
async function background(seconds) {
const homescreen = '/wda/homescreen';
const deactivateApp = '/wda/deactivateApp';
let endpoint;
let params = {};
const selectEndpoint = (timeoutSeconds) => {
if (!support_1.util.hasValue(timeoutSeconds)) {
endpoint = homescreen;
}
else if (!isNaN(Number(timeoutSeconds))) {
const duration = parseFloat(String(timeoutSeconds));
if (duration >= 0) {
params = { duration };
endpoint = deactivateApp;
}
else {
endpoint = homescreen;
}
}
};
if (seconds && !lodash_1.default.isNumber(seconds) && lodash_1.default.has(seconds, 'timeout')) {
const timeout = seconds.timeout;
selectEndpoint(isNaN(Number(timeout)) ? timeout : parseFloat(String(timeout)) / 1000.0);
}
else {
selectEndpoint(lodash_1.default.isNumber(seconds) ? seconds : undefined);
}
if (!endpoint) {
throw new driver_1.errors.InvalidArgumentError(`Argument value is expected to be a valid number. ` +
`${JSON.stringify(seconds)} has been provided instead`);
}
return await this.proxyCommand(endpoint, 'POST', params, endpoint !== homescreen);
}
//# sourceMappingURL=app-management.js.map