How to use adb.install method in Appium Android Driver

Best JavaScript code snippet using appium-android-driver

composeDeviceConfig.test.js

Source:composeDeviceConfig.test.js Github

copy

Full Screen

1// @ts-nocheck2const _ = require('lodash');3const DetoxConfigErrorComposer = require('../errors/DetoxConfigErrorComposer');4describe('composeDeviceConfig', () => {5 /** @type {Function} */6 let composeDeviceConfig;7 /** @type {*} */8 let cliConfig;9 /** @type {Detox.DetoxConfiguration} */10 let localConfig;11 /** @type {Detox.DetoxDeviceConfig} */12 let deviceConfig;13 /** @type {Detox.DetoxConfig} */14 let globalConfig;15 /** @type {DetoxConfigErrorComposer} */16 let errorComposer;17 /** @type { { validateConfig: Function } */18 let environmentFactory;19 /** @type {Logger} */20 let logger;21 const compose = () => composeDeviceConfig({22 errorComposer,23 globalConfig,24 localConfig,25 cliConfig,26 });27 const givenConfigValidationSuccess = () => environmentFactory.validateConfig.mockReturnValue(undefined);28 const givenConfigValidationError = (error) => environmentFactory.validateConfig.mockImplementation(() => { throw error; });29 const KNOWN_CONFIGURATIONS = [['plain'], ['inline'], ['aliased']];30 const KNOWN_DEVICES = [31 'ios.none',32 'ios.simulator',33 'android.attached',34 'android.emulator',35 'android.genycloud',36 './customDriver'37 ];38 const KNOWN_GPU_MODES = ['auto', 'host', 'swiftshader_indirect', 'angle_indirect', 'guest'];39 /**40 * @param {'ios.none' | 'ios.simulator' | 'android.attached' | 'android.emulator' | 'android.genycloud' | './customDriver'} deviceType41 * @param {'plain' | 'inline' | 'aliased' } configType42 */43 function setConfig(deviceType, configType = 'aliased') {44 const mixins = {45 bootArgs: { bootArgs: '--someArg' },46 forceAdbInstall: { forceAdbInstall: false },47 utilBinaryPaths: { utilBinaryPaths: ['/path/to/apk'] },48 iosDevice: {49 device: {50 type: 'iPhone 7 Plus',51 os: 'iOS 10.2',52 },53 },54 };55 const deviceTemplates = {56 'ios.none': {57 type: 'ios.none',58 ...mixins.iosDevice,59 },60 'ios.simulator': {61 type: 'ios.simulator',62 ...mixins.iosDevice,63 ...mixins.bootArgs,64 },65 'android.attached': {66 type: 'android.attached',67 device: { adbName: 'emulator-5554' },68 ...mixins.utilBinaryPaths,69 ...mixins.forceAdbInstall,70 },71 'android.emulator': {72 type: 'android.emulator',73 device: { avdName: 'Pixel_API_28' },74 gpu: 'auto',75 headless: true,76 readonly: true,77 ...mixins.bootArgs,78 ...mixins.utilBinaryPaths,79 ...mixins.forceAdbInstall,80 },81 'android.genycloud': {82 type: 'android.genycloud',83 device: { recipeName: 'myRecipe' },84 ...mixins.utilBinaryPaths,85 ...mixins.forceAdbInstall,86 },87 './customDriver': {88 type: './customDriver',89 device: 'firefox',90 binaryPath: 'https://example.com',91 },92 };93 const deviceId = _.uniqueId('device');94 deviceConfig = _.cloneDeep(deviceTemplates[deviceType] || deviceTemplates[undefined]);95 switch (configType) {96 case 'plain':97 Object.assign(localConfig, deviceConfig);98 localConfig.binaryPath = deviceConfig.binaryPath || _.uniqueId('/path/to/app');99 break;100 case 'inline':101 localConfig.device = deviceConfig;102 break;103 case 'aliased':104 localConfig.device = deviceId;105 globalConfig.devices = { [deviceId]: deviceConfig };106 break;107 }108 }109 beforeEach(() => {110 jest.mock('../utils/logger');111 logger = require('../utils/logger');112 jest.mock('../environmentFactory');113 environmentFactory = require('../environmentFactory');114 givenConfigValidationSuccess();115 cliConfig = {};116 localConfig = {};117 deviceConfig = null;118 globalConfig = {119 configurations: {120 someConfig: localConfig,121 },122 };123 errorComposer = new DetoxConfigErrorComposer()124 .setDetoxConfig(globalConfig)125 .setConfigurationName('someConfig');126 composeDeviceConfig = require('./composeDeviceConfig');127 });128 describe('by config type', () => {129 describe.each(KNOWN_DEVICES)('given a device (%j)', (deviceType) => {130 describe('plain', () => {131 beforeEach(() => {132 setConfig(deviceType, 'plain');133 // NOTE: these properties are ignored for plain configurations134 delete deviceConfig.bootArgs;135 delete deviceConfig.forceAdbInstall;136 delete deviceConfig.gpu;137 delete deviceConfig.headless;138 delete deviceConfig.readonly;139 });140 it('should extract type and device', () =>141 expect(compose()).toEqual(deviceConfig));142 // region supported devices143 if (deviceType === './customDriver') return;144 it('should have a fallback for known devices: .name -> .device', () => {145 const expected = compose();146 localConfig.name = localConfig.device;147 delete localConfig.device;148 const actual = compose();149 expect(actual).toEqual(expected);150 });151 it('should extract type, utilBinaryPaths and unpack device query', () => {152 localConfig.device = Object.values(deviceConfig.device).join(', ');153 expect(compose()).toEqual({154 type: deviceConfig.type,155 device: deviceConfig.device,156 utilBinaryPaths: deviceConfig.utilBinaryPaths,157 });158 });159 // endregion160 });161 describe('inlined', () => {162 beforeEach(() => setConfig(deviceType, 'inline'));163 it('should extract type and device', () =>164 expect(compose()).toEqual(deviceConfig));165 describe('unhappy scenarios', () => {166 test('should throw if device config is not found', () => {167 delete localConfig.device;168 expect(compose).toThrow(errorComposer.deviceConfigIsUndefined());169 });170 test('should throw on no .type in device config', () => {171 delete deviceConfig.type;172 expect(compose).toThrow(errorComposer.missingDeviceType(undefined));173 });174 });175 });176 describe('aliased', () => {177 beforeEach(() => setConfig(deviceType, 'aliased'));178 it('should extract type and device', () =>179 expect(compose()).toEqual(deviceConfig));180 describe('unhappy scenarios', () => {181 test('should throw if devices are not declared', () => {182 globalConfig.devices = {};183 expect(compose).toThrow(errorComposer.thereAreNoDeviceConfigs(localConfig.device));184 });185 test('should throw if device config is not found', () => {186 localConfig.device = 'unknownDevice';187 expect(compose).toThrow(errorComposer.cantResolveDeviceAlias('unknownDevice'));188 });189 test('should throw on no .type in device config', () => {190 delete deviceConfig.type;191 expect(compose).toThrow(errorComposer.missingDeviceType(localConfig.device));192 });193 });194 });195 });196 });197 describe('by device type', () => {198 describe.each(KNOWN_CONFIGURATIONS)('given %s configuration', (configType) => {199 let alias = () => configType === 'aliased' ? localConfig.device : undefined;200 describe('CLI overrides', () => {201 describe('--device-name', () => {202 describe.each([203 ['ios.none'],204 ['ios.simulator'],205 ])('given iOS (%s) device', (deviceType) => {206 beforeEach(() => setConfig(deviceType, configType));207 test('should override .type', () => {208 cliConfig.deviceName = 'iPad';209 expect(compose().device).toEqual({ type: 'iPad' });210 });211 test('should override .type and .os', () => {212 cliConfig.deviceName = 'iPhone SE, iOS 9.3.5';213 expect(compose().device).toEqual({ type: 'iPhone SE', os: 'iOS 9.3.5' });214 });215 });216 describe('given android.emulator device', () => {217 beforeEach(() => setConfig('android.emulator', configType));218 test('should override .avdName', () => {219 cliConfig.deviceName = 'Galaxy_S100';220 expect(compose().device).toEqual({ avdName: 'Galaxy_S100' });221 });222 });223 describe('given android.attached device', () => {224 beforeEach(() => setConfig('android.attached', configType));225 test('should override .adbName', () => {226 cliConfig.deviceName = 'emu.*tor';227 expect(compose().device).toEqual({ adbName: 'emu.*tor' });228 });229 });230 describe('given android.genycloud device', () => {231 beforeEach(() => setConfig('android.genycloud', configType));232 test('should override .recipeName', () => {233 cliConfig.deviceName = 'anotherRecipe';234 expect(compose().device).toEqual({ recipeName: 'anotherRecipe' });235 });236 });237 describe('given a custom device', () => {238 beforeEach(() => setConfig('./customDriver', configType));239 test('should override .device', () => {240 cliConfig.deviceName = 'aCustomValue';241 expect(compose().device).toEqual('aCustomValue');242 });243 });244 });245 describe('--device-boot-args', () => {246 describe.each([247 ['ios.simulator'],248 ['android.emulator'],249 ])('given a supported device (%j)', (deviceType) => {250 beforeEach(() => setConfig(deviceType, configType));251 it('should override .bootArgs without warnings', () => {252 cliConfig.deviceBootArgs = '--example';253 expect(compose()).toEqual(expect.objectContaining({254 bootArgs: '--example'255 }));256 expect(logger.warn).not.toHaveBeenCalled();257 });258 });259 describe.each([260 ['ios.none'],261 ['android.attached'],262 ['android.genycloud'],263 ['./customDriver'],264 ])('given a non-supported device (%j)', (deviceType) => {265 beforeEach(() => setConfig(deviceType, configType));266 it('should print a warning and refuse to override .bootArgs', () => {267 cliConfig.deviceBootArgs = '--example';268 expect(compose()).not.toEqual(expect.objectContaining({269 bootArgs: '--example'270 }));271 expect(logger.warn).toHaveBeenCalledWith(expect.stringMatching(/--device-boot-args.*not supported/));272 });273 });274 });275 describe('--force-adb-install', () => {276 describe.each([277 ['android.attached'],278 ['android.emulator'],279 ['android.genycloud'],280 ])('given an Android device (%j)', (deviceType) => {281 beforeEach(() => setConfig(deviceType, configType));282 it('should override .forceAdbInstall without warnings', () => {283 cliConfig.forceAdbInstall = true;284 expect(compose()).toEqual(expect.objectContaining({285 forceAdbInstall: true,286 }));287 expect(logger.warn).not.toHaveBeenCalled();288 });289 });290 describe.each([291 ['ios.none'],292 ['ios.simulator'],293 ['./customDriver'],294 ])('given a non-supported device (%j)', (deviceType) => {295 beforeEach(() => setConfig(deviceType, configType));296 it('should print a warning and refuse to override .forceAdbInstall', () => {297 cliConfig.forceAdbInstall = true;298 expect(compose()).not.toEqual(expect.objectContaining({299 forceAdbInstall: true,300 }));301 expect(logger.warn).toHaveBeenCalledWith(expect.stringMatching(/--force-adb-install.*not supported/));302 });303 });304 });305 describe('--headless', () => {306 describe('given android.emulator device', () => {307 beforeEach(() => setConfig('android.emulator', configType));308 it('should override .headless without warnings', () => {309 cliConfig.headless = true;310 expect(compose()).toEqual(expect.objectContaining({311 headless: true,312 }));313 expect(logger.warn).not.toHaveBeenCalled();314 });315 });316 describe.each([317 ['ios.none'],318 ['ios.simulator'],319 ['android.attached'],320 ['android.genycloud'],321 ['./customDriver'],322 ])('given a non-supported device (%j)', (deviceType) => {323 beforeEach(() => setConfig(deviceType, configType));324 it('should print a warning and refuse to override .headless', () => {325 cliConfig.headless = true;326 expect(compose()).not.toEqual(expect.objectContaining({327 headless: true,328 }));329 expect(logger.warn).toHaveBeenCalledWith(expect.stringMatching(/--headless.*not supported/));330 });331 });332 });333 describe('--gpu', () => {334 describe('given android.emulator device', () => {335 beforeEach(() => setConfig('android.emulator', configType));336 it('should override .gpuMode without warnings', () => {337 cliConfig.gpu = 'auto';338 expect(compose()).toEqual(expect.objectContaining({339 gpuMode: 'auto',340 }));341 expect(logger.warn).not.toHaveBeenCalled();342 });343 });344 describe.each([345 ['ios.none'],346 ['ios.simulator'],347 ['android.attached'],348 ['./customDriver'],349 ])('given a non-supported device (%j)', (deviceType) => {350 beforeEach(() => setConfig(deviceType, configType));351 it('should print a warning and refuse to override .gpuMode', () => {352 cliConfig.gpu = 'auto';353 expect(compose()).not.toEqual(expect.objectContaining({354 gpuMode: 'auto',355 }));356 expect(logger.warn).toHaveBeenCalledWith(expect.stringMatching(/--gpu.*not supported/));357 });358 });359 });360 describe('--readonlyEmu', () => {361 describe('given android.emulator device', () => {362 beforeEach(() => setConfig('android.emulator', configType));363 it('should override .readonly without warnings', () => {364 cliConfig.readonlyEmu = true;365 expect(compose()).toEqual(expect.objectContaining({366 readonly: true367 }));368 expect(logger.warn).not.toHaveBeenCalled();369 });370 });371 describe.each([372 ['ios.none'],373 ['ios.simulator'],374 ['android.attached'],375 ['android.genycloud'],376 ['./customDriver'],377 ])('given a non-supported device (%j)', (deviceType) => {378 beforeEach(() => setConfig(deviceType, configType));379 it('should print a warning and refuse to override .readonly', () => {380 cliConfig.readonlyEmu = true;381 expect(compose()).not.toEqual(expect.objectContaining({382 readonly: true383 }));384 expect(logger.warn).toHaveBeenCalledWith(expect.stringMatching(/--readonly-emu.*not supported/));385 });386 });387 });388 });389 describe('Unhappy scenarios', () => {390 describe('missing device matcher properties', () => {391 test.each([392 [['type', 'name', 'id'], 'ios.simulator'],393 [['adbName'], 'android.attached'],394 [['avdName'], 'android.emulator'],395 [['recipeUUID', 'recipeName'], 'android.genycloud'],396 ])('should throw for missing %s for "%s" device', (expectedProps, deviceType) => {397 setConfig(deviceType, configType);398 for (const key of expectedProps) {399 delete deviceConfig.device[key];400 }401 deviceConfig.device.misspelled = 'value';402 expect(compose).toThrowError(errorComposer.missingDeviceMatcherProperties(alias(), expectedProps));403 // ...and now prove the opposite:404 deviceConfig.device[_.sample(expectedProps)] = 'someValue';405 expect(compose).not.toThrowError();406 });407 });408 test('should throw if a device type cannot be resolved', () => {409 setConfig('./customDriver', configType);410 const someError = new Error('Some error');411 givenConfigValidationError(someError);412 expect(compose).toThrow(errorComposer.invalidDeviceType(413 alias(),414 deviceConfig,415 someError416 ));417 });418 //region separate device config validation419 if (configType === 'plain') return;420 describe('.bootArgs validation', () => {421 test.each([422 'ios.none',423 'android.attached',424 'android.genycloud',425 ])('cannot be used for %j device', (deviceType) => {426 setConfig(deviceType, configType);427 deviceConfig.bootArgs = '--someArg';428 expect(compose).toThrow(errorComposer.unsupportedDeviceProperty(alias(), 'bootArgs'));429 });430 describe.each([431 'ios.simulator',432 'android.emulator',433 ])('for a supported device (%j)', (deviceType) => {434 beforeEach(() => setConfig(deviceType, configType));435 it('should throw if .bootArgs are malformed (e.g., array)', () => {436 deviceConfig.bootArgs = ['--someArg'];437 expect(compose).toThrowError(438 errorComposer.malformedDeviceProperty(alias(), 'bootArgs')439 );440 });441 });442 test('should be disabled for custom devices', () => {443 setConfig('./customDriver', configType);444 deviceConfig.bootArgs = [0xAC, 0xDC];445 expect(compose).not.toThrowError();446 });447 });448 describe('.forceAdbInstall validation', () => {449 test.each([450 'ios.none',451 'ios.simulator',452 ])('cannot be used for iOS device (%j)', (deviceType) => {453 setConfig(deviceType, configType);454 deviceConfig.forceAdbInstall = false;455 expect(compose).toThrow(errorComposer.unsupportedDeviceProperty(alias(), 'forceAdbInstall'));456 });457 describe.each([458 'android.attached',459 'android.emulator',460 'android.genycloud',461 ])('for Android device (%j)', (deviceType) => {462 beforeEach(() => setConfig(deviceType, configType));463 it('should throw if .forceAdbInstall is malformed (e.g., string)', () => {464 deviceConfig.forceAdbInstall = 'yes';465 expect(compose).toThrowError(466 errorComposer.malformedDeviceProperty(alias(), 'forceAdbInstall')467 );468 });469 });470 test('should be disabled for custom devices', () => {471 setConfig('./customDriver', configType);472 deviceConfig.forceAdbInstall = /anything/;473 expect(compose).not.toThrowError();474 });475 });476 describe('.gpuMode validation', () => {477 test.each([478 'ios.none',479 'ios.simulator',480 'android.attached',481 'android.genycloud',482 ])('cannot be used for a non-emulator device (%j)', (deviceType) => {483 setConfig(deviceType, configType);484 deviceConfig.gpuMode = 'auto';485 expect(compose).toThrow(errorComposer.unsupportedDeviceProperty(alias(), 'gpuMode'));486 });487 describe('given android.emulator device', () => {488 beforeEach(() => setConfig('android.emulator', configType));489 test(`should throw if value is not a string`, () => {490 deviceConfig.gpuMode = ['auto'];491 expect(compose).toThrowError(errorComposer.malformedDeviceProperty(alias(), 'gpuMode'));492 });493 test(`should throw if value is not in (${KNOWN_GPU_MODES})`, () => {494 for (const gpuMode of KNOWN_GPU_MODES) {495 deviceConfig.gpuMode = gpuMode;496 expect(compose).not.toThrowError();497 deviceConfig.gpuMode = gpuMode.slice(1);498 expect(compose).toThrowError(errorComposer.malformedDeviceProperty(alias(), 'gpuMode'));499 }500 });501 });502 test('should be disabled for custom devices', () => {503 setConfig('./customDriver', configType);504 deviceConfig.gpuMode = class Whatever {};505 expect(compose).not.toThrowError();506 });507 });508 describe('.headless validation', () => {509 test.each([510 'ios.none',511 'ios.simulator',512 'android.attached',513 'android.genycloud',514 ])('cannot be used for a non-emulator device (%j)', (deviceType) => {515 setConfig(deviceType, configType);516 deviceConfig.headless = true;517 expect(compose).toThrow(errorComposer.unsupportedDeviceProperty(alias(), 'headless'));518 });519 describe('given android.emulator device', () => {520 beforeEach(() => setConfig('android.emulator', configType));521 test(`should throw if value is not a boolean (e.g., string)`, () => {522 deviceConfig.headless = `${Math.random() > 0.5}`; // string523 expect(compose).toThrowError(errorComposer.malformedDeviceProperty(alias(), 'headless'));524 });525 });526 test('should be disabled for custom devices', () => {527 setConfig('./customDriver', configType);528 deviceConfig.headless = NaN;529 expect(compose).not.toThrowError();530 });531 });532 describe('.readonly validation', () => {533 test.each([534 'ios.none',535 'ios.simulator',536 'android.attached',537 'android.genycloud',538 ])('cannot be used for a non-emulator device (%j)', (deviceType) => {539 setConfig(deviceType, configType);540 deviceConfig.readonly = true;541 expect(compose).toThrow(errorComposer.unsupportedDeviceProperty(alias(), 'readonly'));542 });543 describe('given android.emulator device', () => {544 beforeEach(() => setConfig('android.emulator', configType));545 test(`should throw if value is not a boolean (e.g., string)`, () => {546 deviceConfig.readonly = `${Math.random() > 0.5}`; // string547 expect(compose).toThrowError(errorComposer.malformedDeviceProperty(alias(), 'readonly'));548 });549 });550 test('should be disabled for custom devices', () => {551 setConfig('./customDriver', configType);552 deviceConfig.readonly = () => {};553 expect(compose).not.toThrowError();554 });555 });556 describe('.utilBinaryPaths validation', () => {557 test.each([558 'ios.none',559 'ios.simulator',560 ])('cannot be used for a non-Android device (%j)', (deviceType) => {561 setConfig(deviceType, configType);562 deviceConfig.utilBinaryPaths = [];563 expect(compose).toThrow(errorComposer.unsupportedDeviceProperty(alias(), 'utilBinaryPaths'));564 });565 describe.each([566 'android.attached',567 'android.emulator',568 'android.genycloud',569 ])('for Android device (%j)', (deviceType) => {570 beforeEach(() => setConfig(deviceType, configType));571 it('should throw if .utilBinaryPaths are malformed (array of non-strings)', () => {572 deviceConfig.utilBinaryPaths = [{ path: 'valid/path/not/in/array' }];573 expect(compose).toThrowError(574 errorComposer.malformedDeviceProperty(alias(), 'utilBinaryPaths')575 );576 });577 it('should throw if device.utilBinaryPaths are malformed (string)', () => {578 deviceConfig.utilBinaryPaths = 'valid/path/not/in/array';579 expect(compose).toThrowError(580 errorComposer.malformedDeviceProperty(alias(), 'utilBinaryPaths')581 );582 });583 });584 test('should be disabled for custom devices', () => {585 setConfig('./customDriver', configType);586 deviceConfig.utilBinaryPaths = 42;587 expect(compose).not.toThrowError();588 });589 });590 });591 });592 });...

Full Screen

Full Screen

composeDeviceConfig.js

Source:composeDeviceConfig.js Github

copy

Full Screen

1// @ts-nocheck2const _ = require('lodash');3const environmentFactory = require('../environmentFactory');4const log = require('../utils/logger').child({ __filename });5/**6 * @param {DetoxConfigErrorComposer} opts.errorComposer7 * @param {Detox.DetoxConfig} opts.globalConfig8 * @param {Detox.DetoxConfiguration} opts.localConfig9 * @param {*} opts.cliConfig10 * @returns {Detox.DetoxDeviceConfig}11 */12function composeDeviceConfig(opts) {13 const { localConfig, cliConfig } = opts;14 const deviceConfig = localConfig.type15 ? composeDeviceConfigFromPlain(opts)16 : composeDeviceConfigFromAliased(opts);17 applyCLIOverrides(deviceConfig, cliConfig);18 deviceConfig.device = unpackDeviceQuery(deviceConfig);19 return deviceConfig;20}21/**22 * @param {DetoxConfigErrorComposer} opts.errorComposer23 * @param {Detox.DetoxConfig} opts.globalConfig24 * @param {Detox.DetoxPlainConfiguration} opts.localConfig25 * @returns {Detox.DetoxDeviceConfig}26 */27function composeDeviceConfigFromPlain(opts) {28 const { errorComposer, localConfig } = opts;29 const type = localConfig.type;30 const device = localConfig.device || localConfig.name;31 const utilBinaryPaths = localConfig.utilBinaryPaths;32 const deviceConfig = type in EXPECTED_DEVICE_MATCHER_PROPS33 ? _.omitBy({ type, device, utilBinaryPaths }, _.isUndefined)34 : { ...localConfig };35 validateDeviceConfig({ deviceConfig, errorComposer });36 return deviceConfig;37}38/**39 * @param {DetoxConfigErrorComposer} opts.errorComposer40 * @param {Detox.DetoxConfig} opts.globalConfig41 * @param {Detox.DetoxAliasedConfiguration} opts.localConfig42 * @returns {Detox.DetoxDeviceConfig}43 */44function composeDeviceConfigFromAliased(opts) {45 const { errorComposer, globalConfig, localConfig } = opts;46 /** @type {Detox.DetoxDeviceConfig} */47 let deviceConfig;48 const isAliased = typeof localConfig.device === 'string';49 if (isAliased) {50 if (_.isEmpty(globalConfig.devices)) {51 throw errorComposer.thereAreNoDeviceConfigs(localConfig.device);52 } else {53 deviceConfig = globalConfig.devices[localConfig.device];54 }55 if (!deviceConfig) {56 throw errorComposer.cantResolveDeviceAlias(localConfig.device);57 }58 } else {59 if (!localConfig.device) {60 throw errorComposer.deviceConfigIsUndefined();61 }62 deviceConfig = localConfig.device;63 }64 validateDeviceConfig({65 deviceConfig,66 errorComposer,67 deviceAlias: isAliased ? localConfig.device : undefined68 });69 return { ...deviceConfig };70}71/**72 * @param {DetoxConfigErrorComposer} errorComposer73 * @param {Detox.DetoxDeviceConfig} deviceConfig74 * @param {String | undefined} deviceAlias75 */76function validateDeviceConfig({ deviceConfig, errorComposer, deviceAlias }) {77 if (!deviceConfig.type) {78 throw errorComposer.missingDeviceType(deviceAlias);79 }80 const maybeError = _.attempt(() => environmentFactory.validateConfig(deviceConfig));81 if (_.isError(maybeError)) {82 throw errorComposer.invalidDeviceType(deviceAlias, deviceConfig, maybeError);83 }84 if (!KNOWN_TYPES.has(deviceConfig.type)) {85 return;86 }87 if (deviceConfig.bootArgs != null) {88 if (!_.isString(deviceConfig.bootArgs)) {89 throw errorComposer.malformedDeviceProperty(deviceAlias, 'bootArgs');90 }91 if (deviceConfig.type !== 'ios.simulator' && deviceConfig.type !== 'android.emulator') {92 throw errorComposer.unsupportedDeviceProperty(deviceAlias, 'bootArgs');93 }94 }95 if (deviceConfig.utilBinaryPaths != null) {96 if (!Array.isArray(deviceConfig.utilBinaryPaths)) {97 throw errorComposer.malformedDeviceProperty(deviceAlias, 'utilBinaryPaths');98 }99 if (deviceConfig.utilBinaryPaths.some(s => !_.isString(s))) {100 throw errorComposer.malformedDeviceProperty(deviceAlias, 'utilBinaryPaths');101 }102 if (!deviceConfig.type.match(/^android\.(attached|emulator|genycloud)$/)) {103 throw errorComposer.unsupportedDeviceProperty(deviceAlias, 'utilBinaryPaths');104 }105 }106 if (deviceConfig.forceAdbInstall !== undefined) {107 if (!_.isBoolean(deviceConfig.forceAdbInstall)) {108 throw errorComposer.malformedDeviceProperty(deviceAlias, 'forceAdbInstall');109 }110 if (!deviceConfig.type.match(/^android\.(attached|emulator|genycloud)$/)) {111 throw errorComposer.unsupportedDeviceProperty(deviceAlias, 'forceAdbInstall');112 }113 }114 if (deviceConfig.gpuMode !== undefined) {115 if (!_.isString(deviceConfig.gpuMode)) {116 throw errorComposer.malformedDeviceProperty(deviceAlias, 'gpuMode');117 }118 if (!deviceConfig.gpuMode.match(/^(auto|host|swiftshader_indirect|angle_indirect|guest)$/)) {119 throw errorComposer.malformedDeviceProperty(deviceAlias, 'gpuMode');120 }121 if (deviceConfig.type !== 'android.emulator') {122 throw errorComposer.unsupportedDeviceProperty(deviceAlias, 'gpuMode');123 }124 }125 if (deviceConfig.headless !== undefined) {126 if (!_.isBoolean(deviceConfig.headless)) {127 throw errorComposer.malformedDeviceProperty(deviceAlias, 'headless');128 }129 if (deviceConfig.type !== 'android.emulator') {130 throw errorComposer.unsupportedDeviceProperty(deviceAlias, 'headless');131 }132 }133 if (deviceConfig.readonly !== undefined) {134 if (!_.isBoolean(deviceConfig.readonly)) {135 throw errorComposer.malformedDeviceProperty(deviceAlias, 'readonly');136 }137 if (deviceConfig.type !== 'android.emulator') {138 throw errorComposer.unsupportedDeviceProperty(deviceAlias, 'readonly');139 }140 }141 if (_.isObject(deviceConfig.device)) {142 const expectedProperties = EXPECTED_DEVICE_MATCHER_PROPS[deviceConfig.type];143 if (!_.isEmpty(expectedProperties)) {144 const minimalShape = _.pick(deviceConfig.device, expectedProperties);145 if (_.isEmpty(minimalShape)) {146 throw errorComposer.missingDeviceMatcherProperties(deviceAlias, expectedProperties);147 }148 }149 }150}151function applyCLIOverrides(deviceConfig, cliConfig) {152 if (cliConfig.deviceName) {153 deviceConfig.device = cliConfig.deviceName;154 }155 const deviceType = deviceConfig.type;156 if (cliConfig.deviceBootArgs) {157 if ((deviceType === 'ios.simulator') || (deviceType === 'android.emulator')) {158 deviceConfig.bootArgs = cliConfig.deviceBootArgs;159 } else {160 log.warn(`--device-boot-args CLI override is not supported by device type = "${deviceType}" and will be ignored`);161 }162 }163 if (cliConfig.forceAdbInstall !== undefined) {164 if (deviceType.startsWith('android.')) {165 deviceConfig.forceAdbInstall = cliConfig.forceAdbInstall;166 } else {167 log.warn(`--force-adb-install CLI override is not supported by device type = "${deviceType}" and will be ignored`);168 }169 }170 const emulatorCLIConfig = _.pick(cliConfig, ['headless', 'gpu', 'readonlyEmu']);171 const emulatorOverrides = _.omitBy({172 headless: cliConfig.headless,173 gpuMode: cliConfig.gpu,174 readonly: cliConfig.readonlyEmu,175 }, _.isUndefined);176 if (!_.isEmpty(emulatorOverrides)) {177 if (deviceType === 'android.emulator') {178 Object.assign(deviceConfig, emulatorOverrides);179 } else {180 const flags = Object.keys(emulatorCLIConfig).map(key => '--' + _.kebabCase(key)).join(', ');181 log.warn(`${flags} CLI overriding is not supported by device type = "${deviceType}" and will be ignored`);182 }183 }184}185function unpackDeviceQuery(deviceConfig) {186 const query = deviceConfig.device;187 if (!_.isString(query)) {188 return query;189 }190 switch (deviceConfig.type) {191 case 'ios.none':192 case 'ios.simulator':193 if (_.includes(query, ',')) {194 const [type, os] = _.split(query, /\s*,\s*/);195 return { type, os };196 }197 return { type: query };198 case 'android.attached':199 return { adbName: query };200 case 'android.emulator':201 return { avdName: query };202 case 'android.genycloud':203 return { recipeName: query };204 default:205 return query;206 }207}208const EXPECTED_DEVICE_MATCHER_PROPS = {209 'ios.none': null,210 'ios.simulator': ['type', 'name', 'id'],211 'android.attached': ['adbName'],212 'android.emulator': ['avdName'],213 'android.genycloud': ['recipeUUID', 'recipeName'],214};215const KNOWN_TYPES = new Set(Object.keys(EXPECTED_DEVICE_MATCHER_PROPS));...

Full Screen

Full Screen

Adb.spec.js

Source:Adb.spec.js Github

copy

Full Screen

1/**2 Licensed to the Apache Software Foundation (ASF) under one3 or more contributor license agreements. See the NOTICE file4 distributed with this work for additional information5 regarding copyright ownership. The ASF licenses this file6 to you under the Apache License, Version 2.0 (the7 "License"); you may not use this file except in compliance8 with the License. You may obtain a copy of the License at9 http://www.apache.org/licenses/LICENSE-2.010 Unless required by applicable law or agreed to in writing,11 software distributed under the License is distributed on an12 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY13 KIND, either express or implied. See the License for the14 specific language governing permissions and limitations15 under the License.16*/17const CordovaError = require('cordova-common').CordovaError;18const rewire = require('rewire');19const adbOutput = `List of devices attached20emulator-5554\tdevice21emulator-5556\toffline22123a76565509e124\tdevice23123a76565509e123\tbootloader24`;25describe('Adb', () => {26 const deviceId = '123a76565509e124';27 const alreadyExistsError = 'adb: failed to install app.apk: Failure[INSTALL_FAILED_ALREADY_EXISTS]';28 const certificateError = 'adb: failed to install app.apk: Failure[INSTALL_PARSE_FAILED_NO_CERTIFICATES]';29 const downgradeError = 'adb: failed to install app.apk: Failure[INSTALL_FAILED_VERSION_DOWNGRADE]';30 let Adb;31 let execaSpy;32 beforeEach(() => {33 Adb = rewire('../../lib/Adb');34 execaSpy = jasmine.createSpy('execa');35 Adb.__set__('execa', execaSpy);36 });37 describe('devices', () => {38 it('should return the IDs of all fully booted devices & emulators', () => {39 execaSpy.and.resolveTo({ stdout: adbOutput });40 return Adb.devices().then(devices => {41 expect(devices).toEqual([42 'emulator-5554',43 '123a76565509e124'44 ]);45 });46 });47 });48 describe('install', () => {49 beforeEach(() => {50 execaSpy.and.returnValue(Promise.resolve({ stdout: '' }));51 });52 it('should target the passed device id to adb', () => {53 return Adb.install(deviceId).then(() => {54 const args = execaSpy.calls.argsFor(0);55 expect(args[0]).toBe('adb');56 const adbArgs = args[1].join(' ');57 expect(adbArgs).toMatch(`-s ${deviceId}`);58 });59 });60 it('should add the -r flag if opts.replace is set', () => {61 return Adb.install(deviceId, '', { replace: true }).then(() => {62 const adbArgs = execaSpy.calls.argsFor(0)[1];63 expect(adbArgs).toContain('-r');64 });65 });66 it('should pass the correct package path to adb', () => {67 const packagePath = 'build/test/app.apk';68 return Adb.install(deviceId, packagePath).then(() => {69 const adbArgs = execaSpy.calls.argsFor(0)[1];70 expect(adbArgs).toContain(packagePath);71 });72 });73 it('should reject with a CordovaError if the adb output suggests a failure', () => {74 execaSpy.and.returnValue(Promise.resolve({ stdout: alreadyExistsError }));75 return Adb.install(deviceId, '').then(76 () => fail('Unexpectedly resolved'),77 err => {78 expect(err).toEqual(jasmine.any(CordovaError));79 }80 );81 });82 // The following two tests are somewhat brittle as they are dependent on the83 // exact message returned. But it is better to have them tested than not at all.84 it('should give a more specific error message if there is a certificate failure', () => {85 execaSpy.and.returnValue(Promise.resolve({ stdout: certificateError }));86 return Adb.install(deviceId, '').then(87 () => fail('Unexpectedly resolved'),88 err => {89 expect(err).toEqual(jasmine.any(CordovaError));90 expect(err.message).toMatch('Sign the build');91 }92 );93 });94 it('should give a more specific error message if there is a downgrade error', () => {95 execaSpy.and.returnValue(Promise.resolve({ stdout: downgradeError }));96 return Adb.install(deviceId, '').then(97 () => fail('Unexpectedly resolved'),98 err => {99 expect(err).toEqual(jasmine.any(CordovaError));100 expect(err.message).toMatch('lower versionCode');101 }102 );103 });104 });105 describe('uninstall', () => {106 it('should call adb uninstall with the correct arguments', () => {107 const packageId = 'io.cordova.test';108 execaSpy.and.returnValue(Promise.resolve({ stdout: '' }));109 return Adb.uninstall(deviceId, packageId).then(() => {110 const args = execaSpy.calls.argsFor(0);111 expect(args[0]).toBe('adb');112 const adbArgs = args[1];113 expect(adbArgs).toContain('uninstall');114 expect(adbArgs.join(' ')).toContain(`-s ${deviceId}`);115 expect(adbArgs[adbArgs.length - 1]).toBe(packageId);116 });117 });118 });119 describe('shell', () => {120 const shellCommand = 'ls -l /sdcard';121 it('should run the passed command on the target device', () => {122 execaSpy.and.returnValue(Promise.resolve({ stdout: '' }));123 return Adb.shell(deviceId, shellCommand).then(() => {124 const args = execaSpy.calls.argsFor(0);125 expect(args[0]).toBe('adb');126 const adbArgs = args[1].join(' ');127 expect(adbArgs).toContain('shell');128 expect(adbArgs).toContain(`-s ${deviceId}`);129 expect(adbArgs).toMatch(new RegExp(`${shellCommand}$`));130 });131 });132 it('should reject with a CordovaError on failure', () => {133 const errorMessage = 'shell error';134 execaSpy.and.rejectWith(new Error(errorMessage));135 return Adb.shell(deviceId, shellCommand).then(136 () => fail('Unexpectedly resolved'),137 err => {138 expect(err).toEqual(jasmine.any(CordovaError));139 expect(err.message).toMatch(errorMessage);140 }141 );142 });143 });144 describe('start', () => {145 const activityName = 'io.cordova.test/.MainActivity';146 it('should start an activity using the shell activity manager', () => {147 const shellSpy = spyOn(Adb, 'shell').and.returnValue(Promise.resolve(''));148 return Adb.start(deviceId, activityName).then(() => {149 expect(shellSpy).toHaveBeenCalled();150 const [target, command] = shellSpy.calls.argsFor(0);151 expect(target).toBe(deviceId);152 expect(command).toContain('am start');153 expect(command).toContain(`-n${activityName}`);154 });155 });156 it('should reject with a CordovaError on a shell error', () => {157 const errorMessage = 'Test Start error';158 spyOn(Adb, 'shell').and.rejectWith(new CordovaError(errorMessage));159 return Adb.start(deviceId, activityName).then(160 () => fail('Unexpectedly resolved'),161 err => {162 expect(err).toEqual(jasmine.any(CordovaError));163 expect(err.message).toMatch(errorMessage);164 }165 );166 });167 });...

Full Screen

Full Screen

apk-utils-e2e-specs.js

Source:apk-utils-e2e-specs.js Github

copy

Full Screen

...25 (await adb.isAppInstalled('com.android.phone')).should.be.true;26 });27 it('should be able to install/remove app and detect its status', async () => {28 (await adb.isAppInstalled('foo')).should.be.false;29 await adb.install(contactManagerPath);30 (await adb.isAppInstalled('com.example.android.contactmanager')).should.be.true;31 (await adb.uninstallApk('com.example.android.contactmanager')).should.be.true;32 (await adb.isAppInstalled('com.example.android.contactmanager')).should.be.false;33 (await adb.uninstallApk('com.example.android.contactmanager')).should.be.false;34 await adb.rimraf(deviceTempPath + 'ContactManager.apk');35 await adb.push(contactManagerPath, deviceTempPath);36 await adb.installFromDevicePath(deviceTempPath + 'ContactManager.apk');37 });38 describe('startUri', async () => {39 it('should be able to start a uri', async () => {40 await adb.goToHome();41 let res = await adb.getFocusedPackageAndActivity();42 res.appPackage.should.not.equal('com.android.contacts');43 await adb.install(contactManagerPath);44 await adb.startUri('content://contacts/people', 'com.android.contacts');45 await retryInterval(10, 500, async () => {46 res = await adb.shell(['dumpsys', 'window', 'windows']);47 // depending on apilevel, app might show up as active in one of these48 // two dumpsys output formats49 let focusRe1 = '(mCurrentFocus.+\\.PeopleActivity)';50 let focusRe2 = '(mFocusedApp.+\\.PeopleActivity)';51 res.should.match(new RegExp(`${focusRe1}|${focusRe2}`));52 });53 await adb.goToHome();54 });55 });56 describe('startApp', async () => {57 it('should be able to start', async () => {58 await adb.install(contactManagerPath);59 await adb.startApp({pkg: 'com.example.android.contactmanager',60 activity: 'ContactManager'});61 await assertPackageAndActivity();62 });63 it('should throw error for wrong activity', async () => {64 await adb.install(contactManagerPath);65 await adb.startApp({pkg: 'com.example.android.contactmanager',66 activity: 'ContactManage'}).should.eventually67 .be.rejectedWith('Activity');68 });69 it('should throw error for wrong wait activity', async () => {70 await adb.install(contactManagerPath);71 await adb.startApp({pkg: 'com.example.android.contactmanager',72 activity: 'ContactManager',73 waitActivity: 'foo',74 waitDuration: 1000}).should.eventually75 .be.rejectedWith('foo');76 });77 it('should start activity with wait activity', async () => {78 await adb.install(contactManagerPath);79 await adb.startApp({pkg: 'com.example.android.contactmanager',80 activity: 'ContactManager',81 waitActivity: '.ContactManager'});82 await assertPackageAndActivity();83 });84 it('should start activity when wait activity is a wildcard', async () => {85 await adb.install(contactManagerPath);86 await adb.startApp({pkg: 'com.example.android.contactmanager',87 activity: 'ContactManager',88 waitActivity: '*'});89 await assertPackageAndActivity();90 });91 it('should start activity when wait activity contains a wildcard', async () => {92 await adb.install(contactManagerPath);93 await adb.startApp({pkg: 'com.example.android.contactmanager',94 activity: 'ContactManager',95 waitActivity: '*.ContactManager'});96 await assertPackageAndActivity();97 });98 it('should throw error for wrong activity when wait activity contains a wildcard', async () => {99 await adb.install(contactManagerPath);100 await adb.startApp({pkg: 'com.example.android.contactmanager',101 activity: 'SuperManager',102 waitActivity: '*.ContactManager'}).should.eventually103 .be.rejectedWith('Activity');104 });105 it('should throw error for wrong wait activity which contains wildcard', async () => {106 await adb.install(contactManagerPath);107 await adb.startApp({pkg: 'com.example.android.contactmanager',108 activity: 'ContactManager',109 waitActivity: '*.SuperManager'}).should.eventually110 .be.rejectedWith('SuperManager');111 });112 it('should start activity with comma separated wait packages list', async () => {113 await adb.install(contactManagerPath);114 await adb.startApp({pkg: 'com.example.android.contactmanager',115 waitPkg: 'com.android.settings, com.example.android.contactmanager',116 activity: 'ContactManager',117 waitActivity: '.ContactManager'});118 await assertPackageAndActivity();119 });120 it('should throw error for wrong activity when packages provided as comma separated list', async () => {121 await adb.install(contactManagerPath);122 await adb.startApp({pkg: 'com.example.android.contactmanager',123 waitPkg: 'com.android.settings, com.example.somethingelse',124 activity: 'SuperManager',125 waitActivity: '*.ContactManager'}).should.eventually126 .be.rejectedWith('Activity');127 });128 });129 it('should start activity when start activity is an inner class', async () => {130 await adb.install(contactManagerPath);131 await adb.startApp({pkg: 'com.android.settings',132 activity: '.Settings$NotificationAppListActivity'});133 let {appPackage, appActivity} = await adb.getFocusedPackageAndActivity();134 appPackage.should.equal('com.android.settings');135 appActivity.should.equal('.Settings$NotificationAppListActivity');136 });137 it('getFocusedPackageAndActivity should be able get package and activity', async () => {138 await adb.install(contactManagerPath);139 await adb.startApp({pkg: 'com.example.android.contactmanager',140 activity: 'ContactManager'});141 await assertPackageAndActivity();142 });143 it('extractStringsFromApk should get strings for default language', async () => {144 let {apkStrings} = await adb.extractStringsFromApk(contactManagerPath, null, '/tmp');145 apkStrings.save.should.equal('Save');146 });...

Full Screen

Full Screen

file.controller.js

Source:file.controller.js Github

copy

Full Screen

1const uploadFile = require("../middleware/upload");2const { exec } = require('child_process');3const fs = require("fs");4const baseUrl = "http://localhost:8080/files/";5const https = require('https'); 6const axios = require('axios'); 7const { stdout, stderr } = require("process");8const upload = async (req, res) => {9 try {10 await uploadFile(req, res);11 if (req.file == undefined) {12 return res.status(400).send({ message: "Please upload a file!" });13 }14 res.status(200).send({15 message: "Uploaded the file successfully: " + req.file.originalname,16 });17 } catch (err) {18 console.log(err);19 if (err.code == "LIMIT_FILE_SIZE") {20 return res.status(500).send({21 message: "File size cannot be larger than 2MB!",22 });23 }24 res.status(500).send({25 message: `Could not upload the file: ${req.file.originalname}. ${err}`,26 });27 }28};29const getListFiles = (req, res) => {30 const directoryPath = __basedir + "/resources/static/assets/uploads/";31 fs.readdir(directoryPath, function (err, files) {32 if (err) {33 res.status(500).send({34 message: "Unable to scan files!",35 });36 }37 let fileInfos = [];38 files.forEach((file) => {39 fileInfos.push({40 name: file,41 url: baseUrl + file,42 });43 });44 res.status(200).send(fileInfos);45 });46};47const download = (req, res) => {48 const fileName = req.params.name;49 const directoryPath = __basedir + "/resources/static/assets/uploads/";50 res.download(directoryPath + fileName, fileName, (err) => {51 if (err) {52 res.status(500).send({53 message: "Could not download the file. " + err,54 });55 }56 });57};58const installApk = function(finishedWrite,file,directoryPath,res){59 finishedWrite.on('finish',function(){60 exec(`unzip ${file.path} -d ${directoryPath}`,catchAdbInstallErrors) 61 const newApkPath = `${directoryPath}/app-debug.apk`62 exec(`adb install ${newApkPath}`,catchAdbInstallErrors)63 console.log("--------------------------------------------------------------------------------")64 })65 let stdeerAll = ''66 function catchAdbInstallErrors(err,stdout,stderr){67 if (err) {68 //some err occurred69 console.error(err)70 //res.send(err)71 } else {72 // the *entire* stdout and stderr (buffered)73 console.log(`stdout: ${stdout}`);74 console.log(`stderr: ${stderr}`);75 stdeerAll+=stderr76 //res.send(`stderr: ${stderr}`)77 }78 } 79 80 res.send(`stderr: ${stdeerAll}`)81}82const downloadGithubArt = async(req, res) => {83 84 const ghaBaseUrl = "api.github.com"85 const repo = "/repos/ecrseer/liner-routiner-androidkotlin/actions/artifacts"86 87 const userChroWin = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36"88 const workflwtoken = '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'89 90 const htp = "https://"91 const getArtifactArchiveUrlOptionsAx = {92 url: htp+ghaBaseUrl+repo, 93 method:'get',94 headers: {95 'User-Agent': userChroWin,96 'Authorization': 'token '+workflwtoken97 }98 }99 console.log("--------------------------------------------------------------------------------") 100 const {data} = await axios(getArtifactArchiveUrlOptionsAx).catch(er=>{101 res.send(er)102 })103 const first = data.artifacts[0]104 const archiveUrlOptions = {...getArtifactArchiveUrlOptionsAx}105 archiveUrlOptions.url = first.archive_download_url106 archiveUrlOptions.responseType = 'stream'107 const downloadArtStream = await axios(archiveUrlOptions).catch(er=>{108 res.send(er)109 })110 const directoryPath = __basedir + "/resources/"111 const file = fs.createWriteStream(directoryPath+"apepe.zip");112 113 const finishedWrite = downloadArtStream.data.pipe(file)114 115 installApk(finishedWrite,file,directoryPath,res)116};117module.exports = {118 upload,119 getListFiles,120 download,121 downloadGithubArt...

Full Screen

Full Screen

panel.js

Source:panel.js Github

copy

Full Screen

1const DEBUG = false;2const $ = document.getElementById.bind(document);3function send (type, data) {4 if (DEBUG) console.log("panel.js sending a " + type + " message; " + data);5 self.postMessage({ type: type, data: data });6};7function fetch (e) {8 let tool = e.target.dataset.tool;9 let ele = $(tool + "_progress");10 ele.style.display = "inline";11 send("download", tool);12};13function onInitialPrefs(data) {14 let adbInstall = $("adb_install");15 let fastbootInstall = $("fastboot_install");16 adbInstall.addEventListener("click", fetch);17 fastbootInstall.addEventListener("click", fetch);18 $("adb_browse").addEventListener("click", send.bind(null, "pick", "adb"));19 $("fastboot_browse").addEventListener("click", send.bind(null, "pick", "fastboot"));20 if (data.adbPath) {21 $("adb_path").textContent = data.adbPath;22 let deviceDetect = $("device_detect");23 deviceDetect.classList.remove("hidden");24 deviceDetect.addEventListener("click", send.bind(null, "detect"));25 } else {26 adbInstall.style.border = "5px solid red";27 }28 if (data.fastbootPath) {29 $("fastboot_path").textContent = data.fastbootPath;30 } else {31 fastbootInstall.style.border = "5px solid red";32 }33};34function onDownload (data) {35 if (DEBUG) console.log("panel.js received a download event: " + data);36 let ele = $(data.tool + "_progress");37 ele.value = data.value;38 ele.max = data.max;39};40function onDownloadDone (data) {41 let ele = $(data.tool + "_progress");42 ele.value = 0;43 ele.style.display = "none";44 $(data.tool + "_path").textContent = data.path;45};46function onDeviceDetected (data) {47 alert(data);48};49self.port.on("initialPrefs", onInitialPrefs);50self.port.on("download", onDownload);51self.port.on("downloadDone", onDownloadDone);52self.port.on("deviceDetected", onDeviceDetected);...

Full Screen

Full Screen

android-install-spec.js

Source:android-install-spec.js Github

copy

Full Screen

1'use strict';2var bluebird = require('bluebird');3var fs = require('fs');4var adbInstallFailureFixture = fs.readFileSync(5 './spec/fixtures/adb-install-failure.txt', 'utf8'6);7var adbInstallSuccessFixture = fs.readFileSync(8 './spec/fixtures/adb-install-success.txt',9 'utf8'10);11var Android = require('../android.js');12var mockProcess;13describe('Android', function() {14 describe('install', function() {15 beforeEach(function() {16 mockProcess = {17 stdout: adbInstallSuccessFixture,18 stderr: '',19 code: 0,20 };21 spyOn(Android, 'adb').and.callFake(function() {22 return bluebird.resolve(mockProcess);23 });24 });25 it('should run the right command', function() {26 Android.install('5554', '/foo/bar/baz.apk', false);27 expect(Android.adb).toHaveBeenCalledWith(28 '5554', 'install /foo/bar/baz.apk'29 );30 });31 it('should run the right command with reinstall', function() {32 Android.install('5554', '/foo/bar/baz.apk', true);33 expect(Android.adb).toHaveBeenCalledWith(34 '5554', 'install -r /foo/bar/baz.apk'35 );36 });37 it('should resolve on success', function(done) {38 Android.install('5554', '/foo/bar/baz.apk').then(function(data) {39 expect(data).toBeUndefined();40 done();41 });42 });43 it('should reject on failure', function(done) {44 mockProcess.stdout = adbInstallFailureFixture;45 Android.install('5554', '/foo/bar/baz.apk').then(function() {46 fail('should not have resolved');47 done();48 }).catch(function(err) {49 expect(err.message).toEqual('Already installed');50 done();51 });52 });53 });...

Full Screen

Full Screen

EmulatorDriver.js

Source:EmulatorDriver.js Github

copy

Full Screen

1// @ts-nocheck2const AndroidDriver = require('../AndroidDriver');3/**4 * @typedef { AndroidDriverDeps } EmulatorDriverDeps5 */6/**7 * @typedef { AndroidDriverProps } EmulatorDriverProps8 * @property avdName { String }9 * @property forceAdbInstall { Boolean }10 */11// TODO Unit test coverage12class EmulatorDriver extends AndroidDriver {13 /**14 * @param deps { EmulatorDriverDeps }15 * @param props { EmulatorDriverProps }16 */17 constructor(deps, { adbName, avdName, forceAdbInstall }) {18 super(deps, { adbName });19 this._deviceName = `${adbName} (${avdName})`;20 this._forceAdbInstall = forceAdbInstall;21 }22 getDeviceName() {23 return this._deviceName;24 }25 async _installAppBinaries(appBinaryPath, testBinaryPath) {26 if (this._forceAdbInstall) {27 await super._installAppBinaries(appBinaryPath, testBinaryPath);28 } else {29 await this.__installAppBinaries(appBinaryPath, testBinaryPath);30 }31 }32 async setLocation(lat, lon) {33 await this.adb.setLocation(this.adbName, lat, lon);34 }35 async __installAppBinaries(appBinaryPath, testBinaryPath) {36 await this.appInstallHelper.install(this.adbName, appBinaryPath, testBinaryPath);37 }38}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriver = require('selenium-webdriver'),2 until = webdriver.until;3var driver = new webdriver.Builder()4 .forBrowser('chrome')5 .build();6driver.findElement(By.name('q')).sendKeys('webdriver');7driver.findElement(By.name('btnG')).click();8driver.wait(until.titleIs('webdriver - Google Search'), 1000);9driver.quit();

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriver = require('selenium-webdriver'),2 until = webdriver.until;3var driver = new webdriver.Builder()4 .forBrowser('chrome')5 .build();6driver.findElement(By.name('q')).sendKeys('webdriver');7driver.findElement(By.name('btnG')).click();8driver.wait(until.titleIs('webdriver - Google Search'), 1000);9driver.quit();10[Appium] Welcome to Appium v1.4.16 (REV 4b4c1b1e1e9d9d9a9c8b6e8f7e1a2b2e2f1b1a1a)

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriver = require('selenium-webdriver');2var AndroidDriver = require('appium-android-driver');3var driver = new webdriver.Builder()4 .withCapabilities({browserName: 'chrome'})5 .build();6var androidDriver = new AndroidDriver();7androidDriver.adb.install('/path/to/apk').then(function() {8 console.log('Success!');9});10driver.quit();

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var assert = require('assert');3var path = require('path');4var desired = {5 app: path.resolve(__dirname, 'app-debug.apk'),6};7var browser = wd.remote("ondemand.saucelabs.com", 80, "SAUCE_USERNAME", "SAUCE_ACCESS_KEY");8browser.init(desired, function() {9 browser.quit();10});11var wd = require('wd');12var assert = require('assert');13var path = require('path');14var desired = {15 app: path.resolve(__dirname, 'app-debug.apk'),16};17var browser = wd.remote("hub.browserstack.com", 80, "BROWSERSTACK_USERNAME", "BROWSERSTACK_ACCESS_KEY");18browser.init(desired, function() {19 browser.quit();20});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var assert = require('assert');3var androidDriver = require('appium-android-driver');4var desiredCaps = {5};6var driver = wd.promiseChainRemote('localhost', 4723);7driver.init(desiredCaps).then(function() {8 return driver.installApp();9}).then(function () {10 console.log('App installed');11 return driver.quit();12}).done();13org.openqa.selenium.WebDriverException: An unknown server-side error occurred while processing the command. Original error: Error executing adbExec. Original error: 'Command '/Users/user/Library/Android/sdk/platform-tools/adb -P 5037 -s emulator-5554 shell pm install -r -g -t "/data/local/tmp/6d1c6d3f6a1b6a7d6e0c6e2a6a9e9c9d.apk"' exited with code 1'; Stderr: 'Failure [INSTALL_FAILED_ALREADY_EXISTS: Attempt to re-install com.example.test without first uninstalling.]; Code: -1' (WARNING: The server did not provide any stacktrace information)

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var assert = require('assert');3var serverConfig = {4};5var desiredCaps = {6};7var driver = wd.promiseChainRemote(serverConfig);8 .init(desiredCaps)9 .then(function() {10 return driver.sleep(5000);11 })12 .then(function() {13 return driver.quit();14 })15 .done();

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Appium Android Driver automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful