Skip to content

Commit

Permalink
refactor: Use built-in driver logger (#762)
Browse files Browse the repository at this point in the history
  • Loading branch information
mykola-mokhnach authored Mar 28, 2022
1 parent e0f1b37 commit 2d78337
Show file tree
Hide file tree
Showing 7 changed files with 103 additions and 106 deletions.
15 changes: 6 additions & 9 deletions lib/commands/general.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import _ from 'lodash';
import { util } from '@appium/support';
import logger from '../logger';
import validate from 'validate.js';
import { errors } from '@appium/base-driver';
import { qualifyActivityName } from '../utils';

let commands = {}, helpers = {}, extensions = {};
const commands = {}, helpers = {}, extensions = {};

function assertRequiredOptions (options, requiredOptionNames) {
if (!_.isArray(requiredOptionNames)) {
Expand Down Expand Up @@ -62,7 +61,7 @@ commands.mobileGetDeviceInfo = async function mobileGetDeviceInfo () {
commands.mobileIsToastVisible = async function mobileIsToastVisible (opts = {}) {
const {text, isRegexp} = opts;
if (!util.hasValue(text)) {
logger.errorAndThrow(`'text' argument is mandatory`);
throw new errors.InvalidArgumentError(`'text' argument is mandatory`);
}
return await this.espresso.jwproxy.command('/appium/execute_mobile/is_toast_displayed', 'POST', {
text,
Expand Down Expand Up @@ -110,8 +109,7 @@ commands.mobileNavigateTo = async function mobileNavigateTo (opts = {}) {

let menuItemIdAsNumber = parseInt(menuItemId, 10);
if (_.isNaN(menuItemIdAsNumber) || menuItemIdAsNumber < 0) {
logger.errorAndThrow(`'menuItemId' must be a non-negative number. Found ${menuItemId}`);
menuItemId = menuItemIdAsNumber;
throw new errors.InvalidArgumentError(`'menuItemId' must be a non-negative number. Found ${menuItemId}`);
}

return await this.espresso.jwproxy.command(`/appium/execute_mobile/${util.unwrapElement(element)}/navigate_to`, 'POST', {
Expand Down Expand Up @@ -163,15 +161,14 @@ commands.mobileScrollToPage = async function mobileScrollToPage (opts = {}) {
},
},
});

if (util.hasValue(res)) {
logger.errorAndThrow(`Invalid scrollTo parameters: ${JSON.stringify(res)}`);
throw new errors.InvalidArgumentError(`Invalid scrollTo parameters: ${JSON.stringify(res)}`);
}

const {element, scrollTo, scrollToPage, smoothScroll} = opts;

if (util.hasValue(scrollTo) && util.hasValue(scrollToPage)) {
logger.warn(`'scrollTo' and 'scrollToPage' where both provided. Defaulting to 'scrollTo'`);
this.log.warn(`'scrollTo' and 'scrollToPage' where both provided. Defaulting to 'scrollTo'`);
}

return await this.espresso.jwproxy.command(`/appium/execute_mobile/${util.unwrapElement(element)}/scroll_to_page`, 'POST', {
Expand Down Expand Up @@ -307,7 +304,7 @@ commands.startActivity = async function startActivity (appPackage, appActivity,
appWaitPackage = appWaitPackage || appPackage;
appActivity = qualifyActivityName(appActivity, appPackage);
appWaitActivity = qualifyActivityName(appWaitActivity || appActivity, appWaitPackage);
logger.debug(`Starting activity '${appActivity}' for package '${appPackage}'`);
this.log.debug(`Starting activity '${appActivity}' for package '${appPackage}'`);
await this.espresso.jwproxy.command(`/appium/device/start_activity`, 'POST', {
appPackage,
appActivity,
Expand Down
63 changes: 31 additions & 32 deletions lib/driver.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import path from 'path';
import { BaseDriver, errors, isErrorType, DeviceSettings} from '@appium/base-driver';
import { EspressoRunner, TEST_APK_PKG } from './espresso-runner';
import { fs, tempDir, zip } from '@appium/support';
import logger from './logger';
import commands from './commands';
import { DEFAULT_ADB_PORT } from 'appium-adb';
import { androidHelpers, androidCommands, SETTINGS_HELPER_PKG_ID } from 'appium-android-driver';
Expand Down Expand Up @@ -180,11 +179,11 @@ class EspressoDriver extends BaseDriver {

if (this.isChromeSession) {
if (this.opts.app) {
logger.warn(`'browserName' capability will be ignored`);
logger.warn(`Chrome browser cannot be run in Espresso sessions because Espresso automation doesn't ` +
this.log.warn(`'browserName' capability will be ignored`);
this.log.warn(`Chrome browser cannot be run in Espresso sessions because Espresso automation doesn't ` +
`have permission to access Chrome`);
} else {
logger.errorAndThrow(`Chrome browser sessions cannot be run in Espresso because Espresso ` +
this.log.errorAndThrow(`Chrome browser sessions cannot be run in Espresso because Espresso ` +
`automation doesn't have permission to access Chrome`);
}
}
Expand Down Expand Up @@ -214,10 +213,10 @@ class EspressoDriver extends BaseDriver {
} else if (this.appOnDevice) {
// the app isn't an actual app file but rather something we want to
// assume is on the device and just launch via the appPackage
logger.info(`App file was not listed, instead we're going to run ` +
this.log.info(`App file was not listed, instead we're going to run ` +
`${this.opts.appPackage} directly on the device`);
if (!await this.adb.isAppInstalled(this.opts.appPackage)) {
logger.errorAndThrow(`Could not find the package '${this.opts.appPackage}' ` +
this.log.errorAndThrow(`Could not find the package '${this.opts.appPackage}' ` +
`installed on the device`);
}
}
Expand Down Expand Up @@ -260,18 +259,18 @@ class EspressoDriver extends BaseDriver {
})).sort((a, b) => a.split(path.sep).length - b.split(path.sep).length);
if (sortedBundleItems.length === 0) {
// no expected packages in the zip
logger.errorAndThrow(`${this.opts.app} did not have any of '${SUPPORTED_EXTENSIONS.join(', ')}' ` +
this.log.errorAndThrow(`${this.opts.app} did not have any of '${SUPPORTED_EXTENSIONS.join(', ')}' ` +
`extension packages. Please make sure the provided .zip archive contains at least one valid application package.`);
}
const unzippedAppPath = path.join(tmpRoot, _.first(sortedBundleItems));
logger.debug(`'${unzippedAppPath}' is the unzipped file from '${appPath}'`);
this.log.debug(`'${unzippedAppPath}' is the unzipped file from '${appPath}'`);
return unzippedAppPath;
}

async onPostConfigureApp ({cachedAppInfo, isUrl, appPath}) {
const presignApp = async (appLocation) => {
if (this.opts.noSign) {
logger.info('Skipping application signing because noSign capability is set to true. ' +
this.log.info('Skipping application signing because noSign capability is set to true. ' +
'Having the application under test with improper signature/non-signed will cause ' +
'Espresso automation startup failure.');
} else if (!await this.adb.checkApkCert(appLocation, this.opts.appPackage)) {
Expand All @@ -289,7 +288,7 @@ class EspressoDriver extends BaseDriver {
if (_.isPlainObject(cachedAppInfo)) {
const packageHash = await fs.hash(appPath);
if (packageHash === cachedAppInfo.packageHash && await fs.exists(cachedAppInfo.fullPath)) {
logger.info(`Using '${cachedAppInfo.fullPath}' which is cached from '${appPath}'`);
this.log.info(`Using '${cachedAppInfo.fullPath}' which is cached from '${appPath}'`);
isResultAppPathAlreadyCached = true;
pathInCache = cachedAppInfo.fullPath;
}
Expand Down Expand Up @@ -346,13 +345,13 @@ class EspressoDriver extends BaseDriver {
// TODO this method is duplicated from uiautomator2-driver; consolidate
setAvdFromCapabilities (caps) {
if (this.opts.avd) {
logger.info('avd name defined, ignoring device name and platform version');
this.log.info('avd name defined, ignoring device name and platform version');
} else {
if (!caps.deviceName) {
logger.errorAndThrow('avd or deviceName should be specified when reboot option is enables');
this.log.errorAndThrow('avd or deviceName should be specified when reboot option is enables');
}
if (!caps.platformVersion) {
logger.errorAndThrow('avd or platformVersion should be specified when reboot option is enabled');
this.log.errorAndThrow('avd or platformVersion should be specified when reboot option is enabled');
}
let avdDevice = caps.deviceName.replace(/[^a-zA-Z0-9_.]/g, '-');
this.opts.avd = `${avdDevice}__${caps.platformVersion}`;
Expand All @@ -370,11 +369,11 @@ class EspressoDriver extends BaseDriver {

// TODO much of this logic is duplicated from uiautomator2
async startEspressoSession () {
logger.info(`EspressoDriver version: ${version}`);
this.log.info(`EspressoDriver version: ${version}`);

// Read https://github.com/appium/appium-android-driver/pull/461 what happens if ther is no setHiddenApiPolicy for Android P+
if (await this.adb.getApiLevel() >= 28) { // Android P
logger.warn('Relaxing hidden api policy');
this.log.warn('Relaxing hidden api policy');
await this.adb.setHiddenApiPolicy('1', !!this.opts.ignoreHiddenApiPolicyError);
}

Expand All @@ -396,7 +395,7 @@ class EspressoDriver extends BaseDriver {
await this.adb.setAnimationState(false);
this.wasAnimationEnabled = true;
} catch (err) {
logger.warn(`Unable to turn off animations: ${err.message}`);
this.log.warn(`Unable to turn off animations: ${err.message}`);
}
}

Expand All @@ -407,14 +406,14 @@ class EspressoDriver extends BaseDriver {
// set up the modified espresso server etc
this.initEspressoServer();
// Further prepare the device by forwarding the espresso port
logger.debug(`Forwarding Espresso Server port ${DEVICE_PORT} to ${this.opts.systemPort}`);
this.log.debug(`Forwarding Espresso Server port ${DEVICE_PORT} to ${this.opts.systemPort}`);
await this.adb.forwardPort(this.opts.systemPort, DEVICE_PORT);

if (!this.opts.skipUnlock) {
// unlock the device to prepare it for testing
await helpers.unlock(this, this.adb, this.caps);
} else {
logger.debug(`'skipUnlock' capability set, so skipping device unlock`);
this.log.debug(`'skipUnlock' capability set, so skipping device unlock`);
}

// set up app under test
Expand Down Expand Up @@ -443,7 +442,7 @@ class EspressoDriver extends BaseDriver {
// launch espresso and wait till its online and we have a session
await this.espresso.startSession(this.caps);
if (this.caps.autoLaunch === false) {
logger.info(`Not waiting for the application activity to start because 'autoLaunch' is disabled`);
this.log.info(`Not waiting for the application activity to start because 'autoLaunch' is disabled`);
} else {
await this.adb.waitForActivity(this.caps.appWaitPackage, this.caps.appWaitActivity, this.opts.appWaitDuration);
}
Expand All @@ -463,7 +462,7 @@ class EspressoDriver extends BaseDriver {
async initWebview () {
const viewName = androidCommands.defaultWebviewName.call(this);
const timeout = this.opts.autoWebviewTimeout || 2000;
logger.info(`Setting webview to context '${viewName}' with timeout ${timeout}ms`);
this.log.info(`Setting webview to context '${viewName}' with timeout ${timeout}ms`);
await retryInterval(timeout / 500, 500, this.setContext.bind(this), viewName);
}

Expand All @@ -487,7 +486,7 @@ class EspressoDriver extends BaseDriver {
initEspressoServer () {
// now that we have package and activity, we can create an instance of
// espresso with the appropriate data
this.espresso = new EspressoRunner({
this.espresso = new EspressoRunner(this.log, {
host: this.opts.remoteAdbHost || this.opts.host || '127.0.0.1',
systemPort: this.opts.systemPort,
devicePort: DEVICE_PORT,
Expand Down Expand Up @@ -532,9 +531,9 @@ class EspressoDriver extends BaseDriver {

if (!this.opts.app) {
if (this.opts.fullReset) {
logger.errorAndThrow('Full reset requires an app capability, use fastReset if app is not provided');
this.log.errorAndThrow('Full reset requires an app capability, use fastReset if app is not provided');
}
logger.debug('No app capability. Assuming it is already on the device');
this.log.debug('No app capability. Assuming it is already on the device');
if (this.opts.fastReset) {
await helpers.resetApp(this.adb, this.opts);
}
Expand All @@ -547,20 +546,20 @@ class EspressoDriver extends BaseDriver {
await helpers.installApk(this.adb, this.opts);
}
if (this.opts.skipServerInstallation) {
logger.debug('skipServerInstallation capability is set. Not installig espresso-server ');
this.log.debug('skipServerInstallation capability is set. Not installig espresso-server ');
} else {
await this.espresso.installTestApk();
try {
await this.adb.addToDeviceIdleWhitelist(SETTINGS_HELPER_PKG_ID, TEST_APK_PKG);
} catch (e) {
logger.warn(`Cannot add server packages to the Doze whitelist. Original error: ` +
this.log.warn(`Cannot add server packages to the Doze whitelist. Original error: ` +
(e.stderr || e.message));
}
}
}

async deleteSession () {
logger.debug('Deleting espresso session');
this.log.debug('Deleting espresso session');

try {
if (!_.isEmpty(this._screenRecordingProperties)) {
Expand All @@ -586,29 +585,29 @@ class EspressoDriver extends BaseDriver {
try {
await this.adb.setAnimationState(true);
} catch (err) {
logger.warn(`Unable to reset animation: ${err.message}`);
this.log.warn(`Unable to reset animation: ${err.message}`);
}
}
if (this.opts.unicodeKeyboard && this.opts.resetKeyboard &&
this.defaultIME) {
logger.debug(`Resetting IME to '${this.defaultIME}'`);
this.log.debug(`Resetting IME to '${this.defaultIME}'`);
await this.adb.setIME(this.defaultIME);
}
if (!this.isChromeSession && this.opts.appPackage && !this.opts.dontStopAppOnReset) {
await this.adb.forceStop(this.opts.appPackage);
}
if (this.opts.fullReset && !this.opts.skipUninstall && !this.appOnDevice) {
logger.debug(`FULL_RESET set to 'true', Uninstalling '${this.opts.appPackage}'`);
this.log.debug(`FULL_RESET set to 'true', Uninstalling '${this.opts.appPackage}'`);
await this.adb.uninstallApk(this.opts.appPackage);
}
await this.adb.stopLogcat();
if (this.opts.reboot) {
let avdName = this.opts.avd.replace('@', '');
logger.debug(`closing emulator '${avdName}'`);
this.log.debug(`closing emulator '${avdName}'`);
await this.adb.killEmulator(avdName);
}
if (await this.adb.getApiLevel() >= 28) { // Android P
logger.info('Restoring hidden api policy to the device default configuration');
this.log.info('Restoring hidden api policy to the device default configuration');
await this.adb.setDefaultHiddenApiPolicy(!!this.opts.ignoreHiddenApiPolicyError);
}
}
Expand All @@ -617,7 +616,7 @@ class EspressoDriver extends BaseDriver {
try {
await this.adb.removePortForward(this.opts.systemPort);
} catch (error) {
logger.warn(`Unable to remove port forward '${error.message}'`);
this.log.warn(`Unable to remove port forward '${error.message}'`);
//Ignore, this block will also be called when we fall in catch block
// and before even port forward.
}
Expand Down
Loading

0 comments on commit 2d78337

Please sign in to comment.