Skip to content

Commit

Permalink
chore: Replace occurrences of the deprecated errorAndThrow API (#2501)
Browse files Browse the repository at this point in the history
  • Loading branch information
mykola-mokhnach authored Dec 12, 2024
1 parent 7b29376 commit d2122eb
Show file tree
Hide file tree
Showing 10 changed files with 142 additions and 104 deletions.
24 changes: 13 additions & 11 deletions lib/commands/condition.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import {INSTRUMENT_CHANNEL, services} from 'appium-ios-device';
import _ from 'lodash';
import {util} from 'appium/support';

function requireConditionInducerCompatibleDevice(driver) {
if (driver.isSimulator()) {
driver.log.errorAndThrow('Condition inducer only works on real devices');
}
if (util.compareVersions(driver.opts.platformVersion, '<', '13.0')) {
driver.log.errorAndThrow('Condition inducer is only supported since iOS 13+');
/**
* @this {XCUITestDriver}
* @returns {void}
*/
function requireConditionInducerCompatibleDevice() {
if (this.isSimulator()) {
throw this.log.errorWithException('Condition inducer only works on real devices');
}
}

Expand Down Expand Up @@ -62,7 +62,7 @@ export default {
* @this {XCUITestDriver}
*/
async listConditionInducers() {
requireConditionInducerCompatibleDevice(this);
requireConditionInducerCompatibleDevice.bind(this);
const conditionInducerService = await services.startInstrumentService(this.device.udid);
try {
const ret = await conditionInducerService.callChannel(
Expand Down Expand Up @@ -95,9 +95,11 @@ export default {
* @this {XCUITestDriver}
*/
async enableConditionInducer(conditionID, profileID) {
requireConditionInducerCompatibleDevice(this);
requireConditionInducerCompatibleDevice.bind(this);
if (this._conditionInducerService && !this._conditionInducerService._socketClient.destroyed) {
this.log.errorAndThrow(`Condition inducer has been started. A condition is already active.`);
throw this.log.errorWithException(
`Condition inducer has been started. A condition is already active.`
);
}
this._conditionInducerService = await services.startInstrumentService(this.device.udid);
const ret = await this._conditionInducerService.callChannel(
Expand All @@ -109,7 +111,7 @@ export default {
if (!_.isBoolean(ret.selector)) {
this._conditionInducerService.close();
this._conditionInducerService = null;
this.log.errorAndThrow(`Enable condition inducer error: '${JSON.stringify(ret.selector)}'`);
throw this.log.errorWithException(`Enable condition inducer error: '${JSON.stringify(ret.selector)}'`);
}
return ret.selector;
},
Expand Down
137 changes: 80 additions & 57 deletions lib/commands/file-movement.js

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions lib/commands/pcap.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export default {
*/
async mobileStartPcap(timeLimitSec = 180, forceRestart = false) {
if (this.isSimulator()) {
this.log.errorAndThrow('Network traffic capture only works on real devices');
throw this.log.errorWithException('Network traffic capture only works on real devices');
}

if (this._trafficCapture?.isCapturing()) {
Expand Down Expand Up @@ -150,7 +150,7 @@ export default {
try {
resultPath = await this._trafficCapture.finish();
if (!(await fs.exists(resultPath))) {
this.log.errorAndThrow(
throw this.log.errorWithException(
`The network traffic capture utility has failed ` +
`to store the actual traffic capture at '${resultPath}'`,
);
Expand Down
12 changes: 6 additions & 6 deletions lib/commands/performance.js
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ export class PerfRecorder {
await this._enforceTermination();
const listProfilesCommand =
toolName === XCTRACE ? `${XCRUN} ${XCTRACE} list templates` : `${INSTRUMENTS} -s`;
this._logger.errorAndThrow(
throw this._logger.errorWithException(
`There is no ${DEFAULT_EXT} file found for performance profile ` +
`'${this._profileName}'. Make sure the profile is supported on this device. ` +
`You could use '${listProfilesCommand}' command to see the list of all available profiles. ` +
Expand All @@ -246,7 +246,7 @@ export class PerfRecorder {
try {
await this._process?.stop('SIGINT', STOP_TIMEOUT_MS);
} catch (e) {
this._logger.errorAndThrow(
throw this._logger.errorWithException(
`Performance recording has failed to exit after ${STOP_TIMEOUT_MS}ms`,
);
}
Expand Down Expand Up @@ -279,7 +279,7 @@ export default {
pid,
) {
if (!this.isFeatureEnabled(PERF_RECORD_FEAT_NAME) && !this.isRealDevice()) {
this.log.errorAndThrow(PERF_RECORD_SECURITY_MESSAGE);
throw this.log.errorWithException(PERF_RECORD_SECURITY_MESSAGE);
}

if (!_.isEmpty(this._perfRecorders)) {
Expand Down Expand Up @@ -348,7 +348,7 @@ export default {
formFields,
) {
if (!this.isFeatureEnabled(PERF_RECORD_FEAT_NAME) && !this.isRealDevice()) {
this.log.errorAndThrow(PERF_RECORD_SECURITY_MESSAGE);
throw this.log.errorWithException(PERF_RECORD_SECURITY_MESSAGE);
}

if (_.isEmpty(this._perfRecorders)) {
Expand All @@ -358,7 +358,7 @@ export default {

const recorders = this._perfRecorders.filter((x) => x.profileName === profileName);
if (_.isEmpty(recorders)) {
this.log.errorAndThrow(
throw this.log.errorWithException(
`There are no records for performance profile '${profileName}' ` +
`and device ${this.device.udid}. Have you started the profiling before?`,
);
Expand All @@ -367,7 +367,7 @@ export default {
const recorder = _.first(recorders);
const resultPath = await /** @type {PerfRecorder} */ (recorder).stop();
if (!(await fs.exists(resultPath))) {
this.log.errorAndThrow(
throw this.log.errorWithException(
`There is no ${DEFAULT_EXT} file found for performance profile '${profileName}' ` +
`and device ${this.device.udid}. Make sure the selected profile is supported on this device`,
);
Expand Down
4 changes: 2 additions & 2 deletions lib/commands/proxy-helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,9 @@ export default {
}

if (!url) {
this.log.errorAndThrow('Proxying requires an endpoint');
throw this.log.errorWithException('Proxying requires an endpoint');
} else if (!SUPPORTED_METHODS.has(method)) {
this.log.errorAndThrow(
throw this.log.errorWithException(
`Proxying only works for the following HTTP methods: ${[...SUPPORTED_METHODS].join(', ')}`,
);
}
Expand Down
8 changes: 4 additions & 4 deletions lib/commands/record-audio.js
Original file line number Diff line number Diff line change
Expand Up @@ -166,14 +166,14 @@ export default {
forceRestart = false,
) {
if (!this.isFeatureEnabled(AUDIO_RECORD_FEAT_NAME)) {
this.log.errorAndThrow(
throw this.log.errorWithException(
`Audio capture feature must be enabled on the server side. ` +
`Please set '--relaxed-security' or '--allow-insecure' with '${AUDIO_RECORD_FEAT_NAME}' option. ` +
`Read https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/security.md for more details.`,
);
}
if (!audioInput) {
this.log.errorAndThrow(
throw this.log.errorWithException(
`The mandatory audioInput option is not provided. Please set it ` +
`to a correct value (e. g. ':1'). Use 'ffmpeg -f avfoundation -list_devices true -i ""' ` +
`command to list available input sources`,
Expand Down Expand Up @@ -213,7 +213,7 @@ export default {

const timeoutSeconds = parseInt(String(timeLimit), 10);
if (isNaN(timeoutSeconds) || timeoutSeconds > MAX_RECORDING_TIME_SEC || timeoutSeconds <= 0) {
this.log.errorAndThrow(
throw this.log.errorWithException(
`The timeLimit value must be in range [1, ${MAX_RECORDING_TIME_SEC}] seconds. ` +
`The value of '${timeLimit}' has been passed instead.`,
);
Expand Down Expand Up @@ -250,7 +250,7 @@ export default {
try {
resultPath = await this._audioRecorder.finish();
if (!(await fs.exists(resultPath))) {
this.log.errorAndThrow(
throw this.log.errorWithException(
`${FFMPEG_BINARY} has failed ` + `to store the actual audio recording at '${resultPath}'`,
);
}
Expand Down
6 changes: 3 additions & 3 deletions lib/commands/recordscreen.js
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ export default {
pixelFormat,
});
if (!(await screenRecorder.interrupt(true))) {
this.log.errorAndThrow('Unable to stop screen recording process');
throw this.log.errorWithException('Unable to stop screen recording process');
}
if (this._recentScreenRecorder) {
await this._recentScreenRecorder.cleanup();
Expand All @@ -249,7 +249,7 @@ export default {

const timeoutSeconds = parseFloat(String(timeLimit));
if (isNaN(timeoutSeconds) || timeoutSeconds > MAX_RECORDING_TIME_SEC || timeoutSeconds <= 0) {
this.log.errorAndThrow(
throw this.log.errorWithException(
`The timeLimit value must be in range [1, ${MAX_RECORDING_TIME_SEC}] seconds. ` +
`The value of '${timeLimit}' has been passed instead.`,
);
Expand Down Expand Up @@ -333,7 +333,7 @@ export default {
try {
const videoPath = await this._recentScreenRecorder.finish();
if (!(await fs.exists(videoPath))) {
this.log.errorAndThrow(
throw this.log.errorWithException(
`The screen recorder utility has failed ` +
`to store the actual screen recording at '${videoPath}'`,
);
Expand Down
24 changes: 13 additions & 11 deletions lib/driver.js
Original file line number Diff line number Diff line change
Expand Up @@ -628,7 +628,7 @@ export class XCUITestDriver extends BaseDriver {
!this.isSafari() &&
!(await this.device.isAppInstalled(this.opts.bundleId))
) {
this.log.errorAndThrow(`App with bundle identifier '${this.opts.bundleId}' unknown`);
throw this.log.errorWithException(`App with bundle identifier '${this.opts.bundleId}' unknown`);
}

if (this.isSimulator()) {
Expand Down Expand Up @@ -1385,10 +1385,10 @@ export class XCUITestDriver extends BaseDriver {
let verifyProcessArgument = (processArguments) => {
const {args, env} = processArguments;
if (!_.isNil(args) && !_.isArray(args)) {
this.log.errorAndThrow('processArguments.args must be an array of strings');
throw this.log.errorWithException('processArguments.args must be an array of strings');
}
if (!_.isNil(env) && !_.isPlainObject(env)) {
this.log.errorAndThrow(
throw this.log.errorWithException(
'processArguments.env must be an object <key,value> pair {a:b, c:d}',
);
}
Expand All @@ -1402,15 +1402,15 @@ export class XCUITestDriver extends BaseDriver {
caps.processArguments = JSON.parse(caps.processArguments);
verifyProcessArgument(caps.processArguments);
} catch (err) {
this.log.errorAndThrow(
throw this.log.errorWithException(
`processArguments must be a JSON format or an object with format {args : [], env : {a:b, c:d}}. ` +
`Both environment and argument can be null. Error: ${err}`,
);
}
} else if (_.isPlainObject(caps.processArguments)) {
verifyProcessArgument(caps.processArguments);
} else {
this.log.errorAndThrow(
throw this.log.errorWithException(
`'processArguments must be an object, or a string JSON object with format {args : [], env : {a:b, c:d}}. ` +
`Both environment and argument can be null.`,
);
Expand All @@ -1422,7 +1422,7 @@ export class XCUITestDriver extends BaseDriver {
(caps.keychainPath && !caps.keychainPassword) ||
(!caps.keychainPath && caps.keychainPassword)
) {
this.log.errorAndThrow(
throw this.log.errorWithException(
`If 'keychainPath' is set, 'keychainPassword' must also be set (and vice versa).`,
);
}
Expand All @@ -1439,7 +1439,7 @@ export class XCUITestDriver extends BaseDriver {
if (_.isString(caps.webDriverAgentUrl)) {
const {protocol, host} = url.parse(caps.webDriverAgentUrl);
if (_.isEmpty(protocol) || _.isEmpty(host)) {
this.log.errorAndThrow(
throw this.log.errorWithException(
`'webDriverAgentUrl' capability is expected to contain a valid WebDriverAgent server URL. ` +
`'${caps.webDriverAgentUrl}' is given instead`,
);
Expand All @@ -1448,7 +1448,9 @@ export class XCUITestDriver extends BaseDriver {

if (caps.browserName) {
if (caps.bundleId) {
this.log.errorAndThrow(`'browserName' cannot be set together with 'bundleId' capability`);
throw this.log.errorWithException(
`'browserName' cannot be set together with 'bundleId' capability`
);
}
// warn if the capabilities have both `app` and `browser, although this
// is common with selenium grid
Expand All @@ -1470,15 +1472,15 @@ export class XCUITestDriver extends BaseDriver {
}
}
} catch (e) {
this.log.errorAndThrow(
throw this.log.errorWithException(
`'${caps.permissions}' is expected to be a valid object with format ` +
`{"<bundleId1>": {"<serviceName1>": "<serviceStatus1>", ...}, ...}. Original error: ${e.message}`,
);
}
}

if (caps.platformVersion && !util.coerceVersion(caps.platformVersion, false)) {
this.log.errorAndThrow(
throw this.log.errorWithException(
`'platformVersion' must be a valid version number. ` +
`'${caps.platformVersion}' is given instead.`,
);
Expand Down Expand Up @@ -1617,7 +1619,7 @@ export class XCUITestDriver extends BaseDriver {
try {
appsList = this.helpers.parseCapsArray(otherApps);
} catch (e) {
this.log.errorAndThrow(`Could not parse "otherApps" capability: ${e.message}`);
throw this.log.errorWithException(`Could not parse "otherApps" capability: ${e.message}`);
}
if (!appsList || !appsList.length) {
this.log.info(`Got zero apps from 'otherApps' capability value. Doing nothing`);
Expand Down
8 changes: 4 additions & 4 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ async function clearSystemFiles(wda) {
async function checkAppPresent(app) {
log.debug(`Checking whether app '${app}' is actually present on file system`);
if (!(await fs.exists(app))) {
log.errorAndThrow(`Could not find app at '${app}'`);
throw log.errorWithException(`Could not find app at '${app}'`);
}
log.debug('App is present');
}
Expand Down Expand Up @@ -295,13 +295,13 @@ function normalizeCommandTimeouts(value) {
throw new Error();
}
} catch (err) {
log.errorAndThrow(
throw log.errorWithException(
`"commandTimeouts" capability should be a valid JSON object. "${value}" was given instead`,
);
}
for (let [cmd, timeout] of _.toPairs(result)) {
if (!_.isInteger(timeout) || timeout <= 0) {
log.errorAndThrow(
throw log.errorWithException(
`The timeout for "${cmd}" should be a valid natural number of milliseconds. "${timeout}" was given instead`,
);
}
Expand Down Expand Up @@ -377,7 +377,7 @@ async function getPIDsListeningOnPort(port, filteringFunc = null) {
*/
async function encodeBase64OrUpload(localPath, remotePath = null, uploadOptions = {}) {
if (!(await fs.exists(localPath))) {
log.errorAndThrow(`The file at '${localPath}' does not exist or is not accessible`);
throw log.errorWithException(`The file at '${localPath}' does not exist or is not accessible`);
}

if (_.isEmpty(remotePath)) {
Expand Down
19 changes: 15 additions & 4 deletions test/unit/commands/file-movement-specs.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {parseContainerPath} from '../../../lib/commands/file-movement';
import {tempDir} from 'appium/support';
import XCUITestDriver from '../../../lib/driver';


describe('file-movement', function () {
Expand All @@ -16,9 +17,19 @@ describe('file-movement', function () {
});

describe('parseContainerPath', function () {
let driver;

beforeEach(function () {
driver = new XCUITestDriver();
});

afterEach(function () {
driver = null;
});

it('should parse with container', async function () {
const mntRoot = await tempDir.openDir();
const {bundleId, pathInContainer, containerType} = await parseContainerPath(
const {bundleId, pathInContainer, containerType} = await parseContainerPath.bind(driver)(
'@io.appium.example:app/Documents/file.txt',
mntRoot,
);
Expand All @@ -29,7 +40,7 @@ describe('file-movement', function () {
});
it('should parse with container root', async function () {
const mntRoot = await tempDir.openDir();
const {bundleId, pathInContainer, containerType} = await parseContainerPath(
const {bundleId, pathInContainer, containerType} = await parseContainerPath.bind(driver)(
'@io.appium.example:documents/',
mntRoot,
);
Expand All @@ -40,7 +51,7 @@ describe('file-movement', function () {
});
it('should parse without container', async function () {
const mntRoot = await tempDir.openDir();
const {bundleId, pathInContainer, containerType} = await parseContainerPath(
const {bundleId, pathInContainer, containerType} = await parseContainerPath.bind(driver)(
'@io.appium.example/Documents/file.txt',
mntRoot,
);
Expand All @@ -51,7 +62,7 @@ describe('file-movement', function () {
});
it('should raise an error if no container path', async function () {
const mntRoot = await tempDir.openDir();
await parseContainerPath('@io.appium.example:documents', mntRoot).should.be.rejected;
await parseContainerPath.bind(driver)('@io.appium.example:documents', mntRoot).should.be.rejected;
});
});
});

0 comments on commit d2122eb

Please sign in to comment.