Best JavaScript code snippet using appium-android-driver
driver-specs.js
Source:driver-specs.js
1import chai from 'chai';2import chaiAsPromised from 'chai-as-promised';3import log from '../../lib/logger';4import sinon from 'sinon';5import { helpers, SETTINGS_HELPER_PKG_ID } from '../../lib/android-helpers';6import { withMocks } from 'appium-test-support';7import AndroidDriver from '../..';8import ADB from 'appium-adb';9import { errors } from 'appium-base-driver';10import { fs } from 'appium-support';11import { SharedPrefsBuilder } from 'shared-preferences-builder';12import _ from 'lodash';13let driver;14let sandbox = sinon.createSandbox();15let expect = chai.expect;16chai.should();17chai.use(chaiAsPromised);18describe('driver', function () {19 describe('constructor', function () {20 it('should call BaseDriver constructor with opts', function () {21 let driver = new AndroidDriver({foo: 'bar'});22 driver.should.exist;23 driver.opts.foo.should.equal('bar');24 });25 it('should have this.findElOrEls', function () {26 let driver = new AndroidDriver({foo: 'bar'});27 driver.findElOrEls.should.exist;28 driver.findElOrEls.should.be.a('function');29 });30 });31 describe('emulator methods', function () {32 describe('fingerprint', function () {33 it('should be rejected if isEmulator is false', function () {34 let driver = new AndroidDriver();35 sandbox.stub(driver, 'isEmulator').returns(false);36 driver.fingerprint(1111).should.eventually.be.rejectedWith('fingerprint method is only available for emulators');37 driver.isEmulator.calledOnce.should.be.true;38 });39 });40 describe('sendSMS', function () {41 it('sendSMS should be rejected if isEmulator is false', function () {42 let driver = new AndroidDriver();43 sandbox.stub(driver, 'isEmulator').returns(false);44 driver.sendSMS(4509, 'Hello Appium').should.eventually.be.rejectedWith('sendSMS method is only available for emulators');45 driver.isEmulator.calledOnce.should.be.true;46 });47 });48 describe('sensorSet', function () {49 it('sensorSet should be rejected if isEmulator is false', function () {50 let driver = new AndroidDriver();51 sandbox.stub(driver, 'isEmulator').returns(false);52 driver.sensorSet({sensorType: 'light', value: 0}).should.eventually.be.rejectedWith('sensorSet method is only available for emulators');53 driver.isEmulator.calledOnce.should.be.true;54 });55 });56 });57 describe('sharedPreferences', function () {58 driver = new AndroidDriver();59 let adb = new ADB();60 driver.adb = adb;61 let builder = new SharedPrefsBuilder();62 describe('should skip setting sharedPreferences', withMocks({driver}, (mocks) => {63 it('on undefined name', async function () {64 driver.opts.sharedPreferences = {};65 (await driver.setSharedPreferences()).should.be.false;66 mocks.driver.verify();67 });68 }));69 describe('should set sharedPreferences', withMocks({driver, adb, builder, fs}, (mocks) => {70 it('on defined sharedPreferences object', async function () {71 driver.opts.appPackage = 'io.appium.test';72 driver.opts.sharedPreferences = {73 name: 'com.appium.prefs',74 prefs: [{type: 'string', name: 'mystr', value: 'appium rocks!'}]75 };76 mocks.driver.expects('getPrefsBuilder').once().returns(builder);77 mocks.builder.expects('build').once();78 mocks.builder.expects('toFile').once();79 mocks.adb.expects('shell').once()80 .withExactArgs(['mkdir', '-p', '/data/data/io.appium.test/shared_prefs']);81 mocks.adb.expects('push').once()82 .withExactArgs('/tmp/com.appium.prefs.xml', '/data/data/io.appium.test/shared_prefs/com.appium.prefs.xml');83 mocks.fs.expects('exists').once()84 .withExactArgs('/tmp/com.appium.prefs.xml')85 .returns(true);86 mocks.fs.expects('unlink').once()87 .withExactArgs('/tmp/com.appium.prefs.xml');88 await driver.setSharedPreferences();89 mocks.driver.verify();90 mocks.adb.verify();91 mocks.builder.verify();92 mocks.fs.verify();93 });94 }));95 });96 describe('createSession', function () {97 beforeEach(function () {98 driver = new AndroidDriver();99 sandbox.stub(driver, 'checkAppPresent');100 sandbox.stub(driver, 'checkPackagePresent');101 sandbox.stub(driver, 'startAndroidSession');102 sandbox.stub(ADB, 'createADB').callsFake(function (opts) {103 return {104 getDevicesWithRetry () {105 return [106 {udid: 'emulator-1234'},107 {udid: 'rotalume-1337'}108 ];109 },110 getPortFromEmulatorString () {111 return 1234;112 },113 setDeviceId: () => {},114 setEmulatorPort: () => {},115 adbPort: opts.adbPort,116 networkSpeed: () => {},117 getApiLevel: () => 22,118 };119 });120 sandbox.stub(driver.helpers, 'configureApp')121 .withArgs('/path/to/some', '.apk')122 .returns('/path/to/some.apk');123 });124 afterEach(function () {125 sandbox.restore();126 });127 it('should verify device is an emulator', function () {128 driver.opts.avd = 'Nexus_5X_Api_23';129 driver.isEmulator().should.equal(true);130 driver.opts.avd = undefined;131 driver.opts.udid = 'emulator-5554';132 driver.isEmulator().should.equal(true);133 driver.opts.udid = '01234567889';134 driver.isEmulator().should.equal(false);135 });136 it('should get browser package details if browserName is provided', async function () {137 sandbox.spy(helpers, 'getChromePkg');138 await driver.createSession({platformName: 'Android', deviceName: 'device', browserName: 'Chrome'});139 helpers.getChromePkg.calledOnce.should.be.true;140 });141 it('should check an app is present', async function () {142 await driver.createSession({platformName: 'Android', deviceName: 'device', app: '/path/to/some.apk'});143 driver.checkAppPresent.calledOnce.should.be.true;144 });145 it('should check a package is present', async function () {146 await driver.createSession({platformName: 'Android', deviceName: 'device', appPackage: 'some.app.package'});147 driver.checkPackagePresent.calledOnce.should.be.true;148 });149 it('should accept a package via the app capability', async function () {150 await driver.createSession({platformName: 'Android', deviceName: 'device', app: 'some.app.package'});151 driver.checkPackagePresent.calledOnce.should.be.true;152 });153 it('should add server details to caps', async function () {154 await driver.createSession({platformName: 'Android', deviceName: 'device', appPackage: 'some.app.package'});155 driver.caps.webStorageEnabled.should.exist;156 });157 it('should pass along adbPort capability to ADB', async function () {158 await driver.createSession({platformName: 'Android', deviceName: 'device', appPackage: 'some.app.package', adbPort: 1111});159 driver.adb.adbPort.should.equal(1111);160 });161 it('should proxy screenshot if nativeWebScreenshot is off', async function () {162 await driver.createSession({platformName: 'Android', deviceName: 'device', browserName: 'chrome', nativeWebScreenshot: false});163 driver.getProxyAvoidList()164 .some((x) => x[1].toString().includes('/screenshot'))165 .should.be.false;166 });167 it('should not proxy screenshot if nativeWebScreenshot is on', async function () {168 await driver.createSession({platformName: 'Android', deviceName: 'device', browserName: 'chrome', nativeWebScreenshot: true});169 driver.getProxyAvoidList()170 .some((x) => x[1].toString().includes('/screenshot'))171 .should.be.true;172 });173 });174 describe('deleteSession', function () {175 beforeEach(function () {176 driver = new AndroidDriver();177 driver.caps = {};178 driver.adb = new ADB();179 driver.bootstrap = new helpers.bootstrap(driver.adb);180 sandbox.stub(driver, 'stopChromedriverProxies');181 sandbox.stub(driver.adb, 'setIME');182 sandbox.stub(driver.adb, 'forceStop');183 sandbox.stub(driver.adb, 'goToHome');184 sandbox.stub(driver.adb, 'uninstallApk');185 sandbox.stub(driver.adb, 'stopLogcat');186 sandbox.stub(driver.adb, 'setAnimationState');187 sandbox.stub(driver.adb, 'setDefaultHiddenApiPolicy');188 sandbox.stub(driver.adb, 'getApiLevel').returns(27);189 sandbox.stub(driver.bootstrap, 'shutdown');190 sandbox.spy(log, 'debug');191 });192 afterEach(function () {193 sandbox.restore();194 });195 it('should not do anything if Android Driver has already shut down', async function () {196 driver.bootstrap = null;197 await driver.deleteSession();198 driver.stopChromedriverProxies.called.should.be.false;199 driver.adb.stopLogcat.called.should.be.true;200 });201 it('should call stopLogcat even if skipLogcatCapture is true', async function () {202 driver.opts.skipLogcatCapture = true;203 await driver.deleteSession();204 driver.adb.stopLogcat.called.should.be.true;205 });206 it('should reset keyboard to default IME', async function () {207 driver.opts.unicodeKeyboard = true;208 driver.opts.resetKeyboard = true;209 driver.defaultIME = 'someDefaultIME';210 await driver.deleteSession();211 driver.adb.setIME.calledOnce.should.be.true;212 });213 it('should force stop non-Chrome sessions', async function () {214 await driver.deleteSession();215 driver.adb.forceStop.calledOnce.should.be.true;216 });217 it('should uninstall APK if required', async function () {218 driver.opts.fullReset = true;219 await driver.deleteSession();220 driver.adb.uninstallApk.calledOnce.should.be.true;221 });222 it('should call setAnimationState to enable it with API Level 27', async function () {223 driver._wasWindowAnimationDisabled = true;224 await driver.deleteSession();225 driver.adb.setAnimationState.calledOnce.should.be.true;226 driver.adb.setDefaultHiddenApiPolicy.calledOnce.should.be.false;227 });228 it('should call setAnimationState to enable it with API Level 28', async function () {229 driver._wasWindowAnimationDisabled = true;230 driver.adb.getApiLevel.restore();231 sandbox.stub(driver.adb, 'getApiLevel').returns(28);232 await driver.deleteSession();233 driver.adb.setAnimationState.calledOnce.should.be.true;234 driver.adb.setDefaultHiddenApiPolicy.calledOnce.should.be.true;235 });236 it('should not call setAnimationState', async function () {237 driver._wasWindowAnimationDisabled = false;238 await driver.deleteSession();239 driver.adb.setAnimationState.calledOnce.should.be.false;240 driver.adb.setDefaultHiddenApiPolicy.calledOnce.should.be.false;241 });242 });243 describe('dismissChromeWelcome', function () {244 before(function () {245 driver = new AndroidDriver();246 });247 it('should verify chromeOptions args', function () {248 driver.opts = {};249 driver.shouldDismissChromeWelcome().should.be.false;250 driver.opts = {chromeOptions: {}};251 driver.shouldDismissChromeWelcome().should.be.false;252 driver.opts = {chromeOptions: {args: []}};253 driver.shouldDismissChromeWelcome().should.be.false;254 driver.opts = {chromeOptions: {args: '--no-first-run'}};255 driver.shouldDismissChromeWelcome().should.be.false;256 driver.opts = {chromeOptions: {args: ['--disable-dinosaur-easter-egg']}};257 driver.shouldDismissChromeWelcome().should.be.false;258 driver.opts = {chromeOptions: {args: ['--no-first-run']}};259 driver.shouldDismissChromeWelcome().should.be.true;260 });261 });262 describe('initAUT', withMocks({helpers}, (mocks) => {263 beforeEach(function () {264 driver = new AndroidDriver();265 driver.caps = {};266 });267 it('should throw error if run with full reset', async function () {268 driver.opts = {appPackage: 'app.package', appActivity: 'act', fullReset: true};269 await driver.initAUT().should.be.rejectedWith(/Full reset requires an app capability/);270 });271 it('should reset if run with fast reset', async function () {272 driver.opts = {appPackage: 'app.package', appActivity: 'act', fullReset: false, fastReset: true};273 driver.adb = 'mock_adb';274 mocks.helpers.expects('resetApp').withArgs('mock_adb');275 await driver.initAUT();276 mocks.helpers.verify();277 });278 it('should keep data if run without reset', async function () {279 driver.opts = {appPackage: 'app.package', appActivity: 'act', fullReset: false, fastReset: false};280 mocks.helpers.expects('resetApp').never();281 await driver.initAUT();282 mocks.helpers.verify();283 });284 it('should install "otherApps" if set in capabilities', async function () {285 const otherApps = ['http://URL_FOR/fake/app.apk'];286 const tempApps = ['/path/to/fake/app.apk'];287 driver.opts = {288 appPackage: 'app.package',289 appActivity: 'act',290 fullReset: false,291 fastReset: false,292 otherApps: `["${otherApps[0]}"]`,293 };294 sandbox.stub(driver.helpers, 'configureApp')295 .withArgs(otherApps[0], '.apk')296 .returns(tempApps[0]);297 mocks.helpers.expects('installOtherApks').once().withArgs(tempApps, driver.adb, driver.opts);298 await driver.initAUT();299 mocks.helpers.verify();300 });301 it('should uninstall a package "uninstallOtherPackages" if set in capabilities', async function () {302 const uninstallOtherPackages = 'app.bundle.id1';303 driver.opts = {304 appPackage: 'app.package',305 appActivity: 'act',306 fullReset: false,307 fastReset: false,308 uninstallOtherPackages,309 };310 driver.adb = new ADB();311 sandbox.stub(driver.adb, 'uninstallApk')312 .withArgs('app.bundle.id1')313 .returns(true);314 mocks.helpers.expects('uninstallOtherPackages').once().withArgs(driver.adb, [uninstallOtherPackages], [SETTINGS_HELPER_PKG_ID]);315 await driver.initAUT();316 mocks.helpers.verify();317 });318 it('should uninstall multiple packages "uninstallOtherPackages" if set in capabilities', async function () {319 const uninstallOtherPackages = ['app.bundle.id1', 'app.bundle.id2'];320 driver.opts = {321 appPackage: 'app.package',322 appActivity: 'act',323 fullReset: false,324 fastReset: false,325 uninstallOtherPackages: `["${uninstallOtherPackages[0]}", "${uninstallOtherPackages[1]}"]`,326 };327 driver.adb = new ADB();328 sandbox.stub(driver.adb, 'uninstallApk')329 .returns(true);330 mocks.helpers.expects('uninstallOtherPackages').once().withArgs(driver.adb, uninstallOtherPackages, [SETTINGS_HELPER_PKG_ID]);331 await driver.initAUT();332 mocks.helpers.verify();333 });334 it('get all 3rd party packages', async function () {335 driver.adb = new ADB();336 sandbox.stub(driver.adb, 'shell')337 .returns('package:app.bundle.id1\npackage:io.appium.settings\npackage:io.appium.uiautomator2.server\npackage:io.appium.uiautomator2.server.test\n');338 (await helpers.getThirdPartyPackages(driver.adb, [SETTINGS_HELPER_PKG_ID]))339 .should.eql(['app.bundle.id1', 'io.appium.uiautomator2.server', 'io.appium.uiautomator2.server.test']);340 });341 it('get all 3rd party packages with multiple package filter', async function () {342 driver.adb = new ADB();343 sandbox.stub(driver.adb, 'shell')344 .returns('package:app.bundle.id1\npackage:io.appium.settings\npackage:io.appium.uiautomator2.server\npackage:io.appium.uiautomator2.server.test\n');345 (await helpers.getThirdPartyPackages(driver.adb, [SETTINGS_HELPER_PKG_ID, 'io.appium.uiautomator2.server']))346 .should.eql(['app.bundle.id1', 'io.appium.uiautomator2.server.test']);347 });348 it('get no 3rd party packages', async function () {349 driver.adb = new ADB();350 sandbox.stub(driver.adb, 'shell').throws('');351 (await helpers.getThirdPartyPackages(driver.adb, [SETTINGS_HELPER_PKG_ID]))352 .should.eql([]);353 });354 }));355 describe('startAndroidSession', function () {356 beforeEach(function () {357 driver = new AndroidDriver();358 driver.adb = new ADB();359 driver.bootstrap = new helpers.bootstrap(driver.adb);360 driver.settings = { update () {} };361 driver.caps = {};362 // create a fake bootstrap because we can't mock363 // driver.bootstrap.<whatever> in advance364 let fakeBootstrap = {365 start () {},366 onUnexpectedShutdown: {catch () {}}367 };368 sandbox.stub(helpers, 'initDevice');369 sandbox.stub(helpers, 'unlock');370 sandbox.stub(helpers, 'bootstrap').returns(fakeBootstrap);371 sandbox.stub(driver, 'initAUT');372 sandbox.stub(driver, 'startAUT');373 sandbox.stub(driver, 'defaultWebviewName');374 sandbox.stub(driver, 'setContext');375 sandbox.stub(driver, 'startChromeSession');376 sandbox.stub(driver, 'dismissChromeWelcome');377 sandbox.stub(driver.settings, 'update');378 sandbox.stub(driver.adb, 'getPlatformVersion');379 sandbox.stub(driver.adb, 'getScreenSize');380 sandbox.stub(driver.adb, 'getModel');381 sandbox.stub(driver.adb, 'getManufacturer');382 sandbox.stub(driver.adb, 'getApiLevel').returns(27);383 sandbox.stub(driver.adb, 'setHiddenApiPolicy');384 sandbox.stub(driver.adb, 'setAnimationState');385 });386 afterEach(function () {387 sandbox.restore();388 });389 it('should set actual platform version', async function () {390 await driver.startAndroidSession();391 driver.adb.getPlatformVersion.calledOnce.should.be.true;392 });393 it('should auto launch app if it is on the device', async function () {394 driver.opts.autoLaunch = true;395 await driver.startAndroidSession();396 driver.initAUT.calledOnce.should.be.true;397 });398 it('should handle chrome sessions', async function () {399 driver.opts.browserName = 'Chrome';400 await driver.startAndroidSession();401 driver.startChromeSession.calledOnce.should.be.true;402 });403 it('should unlock the device', async function () {404 await driver.startAndroidSession();405 helpers.unlock.calledOnce.should.be.true;406 });407 it('should start AUT if auto lauching', async function () {408 driver.opts.autoLaunch = true;409 await driver.startAndroidSession();410 driver.initAUT.calledOnce.should.be.true;411 });412 it('should not start AUT if not auto lauching', async function () {413 driver.opts.autoLaunch = false;414 await driver.startAndroidSession();415 driver.initAUT.calledOnce.should.be.false;416 });417 it('should set the context if autoWebview is requested', async function () {418 driver.opts.autoWebview = true;419 await driver.startAndroidSession();420 driver.defaultWebviewName.calledOnce.should.be.true;421 driver.setContext.calledOnce.should.be.true;422 });423 it('should set the context if autoWebview is requested using timeout', async function () {424 driver.setContext.onCall(0).throws(errors.NoSuchContextError);425 driver.setContext.onCall(1).returns();426 driver.opts.autoWebview = true;427 driver.opts.autoWebviewTimeout = 5000;428 await driver.startAndroidSession();429 driver.defaultWebviewName.calledOnce.should.be.true;430 driver.setContext.calledTwice.should.be.true;431 });432 it('should respect timeout if autoWebview is requested', async function () {433 this.timeout(10000);434 driver.setContext.throws(new errors.NoSuchContextError());435 let begin = Date.now();436 driver.opts.autoWebview = true;437 driver.opts.autoWebviewTimeout = 5000;438 await driver.startAndroidSession().should.eventually.be.rejected;439 driver.defaultWebviewName.calledOnce.should.be.true;440 // we have a timeout of 5000ms, retrying on 500ms, so expect 10 times441 driver.setContext.callCount.should.equal(10);442 let end = Date.now();443 (end - begin).should.be.above(4500);444 });445 it('should not set the context if autoWebview is not requested', async function () {446 await driver.startAndroidSession();447 driver.defaultWebviewName.calledOnce.should.be.false;448 driver.setContext.calledOnce.should.be.false;449 });450 it('should set ignoreUnimportantViews cap', async function () {451 driver.opts.ignoreUnimportantViews = true;452 await driver.startAndroidSession();453 driver.settings.update.calledOnce.should.be.true;454 driver.settings.update.firstCall.args[0].ignoreUnimportantViews.should.be.true;455 });456 it('should not call dismissChromeWelcome on missing chromeOptions', async function () {457 driver.opts.browserName = 'Chrome';458 await driver.startAndroidSession();459 driver.dismissChromeWelcome.calledOnce.should.be.false;460 });461 it('should call setAnimationState with API level 27', async function () {462 driver.opts.disableWindowAnimation = true;463 sandbox.stub(driver.adb, 'isAnimationOn').returns(true);464 await driver.startAndroidSession();465 driver.adb.isAnimationOn.calledOnce.should.be.true;466 driver.adb.setHiddenApiPolicy.calledOnce.should.be.false;467 driver.adb.setAnimationState.calledOnce.should.be.true;468 });469 it('should call setAnimationState with API level 28', async function () {470 driver.opts.disableWindowAnimation = true;471 sandbox.stub(driver.adb, 'isAnimationOn').returns(true);472 driver.adb.getApiLevel.restore();473 sandbox.stub(driver.adb, 'getApiLevel').returns(28);474 await driver.startAndroidSession();475 driver.adb.isAnimationOn.calledOnce.should.be.true;476 driver.adb.setHiddenApiPolicy.calledOnce.should.be.true;477 driver.adb.setAnimationState.calledOnce.should.be.true;478 });479 it('should not call setAnimationState', async function () {480 driver.opts.disableWindowAnimation = true;481 sandbox.stub(driver.adb, 'isAnimationOn').returns(false);482 await driver.startAndroidSession();483 driver.adb.isAnimationOn.calledOnce.should.be.true;484 driver.adb.setHiddenApiPolicy.calledOnce.should.be.false;485 driver.adb.setAnimationState.calledOnce.should.be.false;486 });487 });488 describe('startChromeSession', function () {489 beforeEach(function () {490 driver = new AndroidDriver();491 driver.adb = new ADB();492 driver.bootstrap = new helpers.bootstrap(driver.adb);493 driver.settings = { update () { } };494 driver.caps = {};495 sandbox.stub(driver, 'setupNewChromedriver').returns({496 on: _.noop,497 proxyReq: _.noop,498 });499 sandbox.stub(driver, 'dismissChromeWelcome');500 });501 afterEach(function () {502 sandbox.restore();503 });504 it('should call dismissChromeWelcome', async function () {505 driver.opts.browserName = 'Chrome';506 driver.opts.chromeOptions = {507 'args': ['--no-first-run']508 };509 await driver.startChromeSession();510 driver.dismissChromeWelcome.calledOnce.should.be.true;511 });512 });513 describe('validateDesiredCaps', function () {514 before(function () {515 driver = new AndroidDriver();516 });517 it('should throw an error if caps do not contain an app, package or valid browser', function () {518 expect(() => {519 driver.validateDesiredCaps({platformName: 'Android', deviceName: 'device'});520 }).to.throw(/must include/);521 expect(() => {522 driver.validateDesiredCaps({platformName: 'Android', deviceName: 'device', browserName: 'Netscape Navigator'});523 }).to.throw(/must include/);524 });525 it('should not throw an error if caps contain an app, package or valid browser', function () {526 expect(() => {527 driver.validateDesiredCaps({platformName: 'Android', deviceName: 'device', app: '/path/to/some.apk'});528 }).to.not.throw(Error);529 expect(() => {530 driver.validateDesiredCaps({platformName: 'Android', deviceName: 'device', browserName: 'Chrome'});531 }).to.not.throw(Error);532 expect(() => {533 driver.validateDesiredCaps({platformName: 'Android', deviceName: 'device', appPackage: 'some.app.package'});534 }).to.not.throw(/must include/);535 });536 it('should not be sensitive to platform name casing', function () {537 expect(() => {538 driver.validateDesiredCaps({platformName: 'AnDrOiD', deviceName: 'device', app: '/path/to/some.apk'});539 }).to.not.throw(Error);540 });541 it('should not throw an error if caps contain both an app and browser, for grid compatibility', function () {542 expect(() => {543 driver.validateDesiredCaps({platformName: 'Android', deviceName: 'device', app: '/path/to/some.apk', browserName: 'iPhone'});544 }).to.not.throw(Error);545 });546 it('should not throw an error if caps contain androidScreenshotPath capability', function () {547 expect(() => {548 driver.validateDesiredCaps({platformName: 'Android', deviceName: 'device', app: '/path/to/some.apk', androidScreenshotPath: '/path/to/screenshotdir'});549 }).to.not.throw(Error);550 });551 });552 describe('proxying', function () {553 before(function () {554 driver = new AndroidDriver();555 driver.sessionId = 'abc';556 });557 describe('#proxyActive', function () {558 it('should exist', function () {559 driver.proxyActive.should.be.an.instanceof(Function);560 });561 it('should return false', function () {562 driver.proxyActive('abc').should.be.false;563 });564 it('should throw an error if session id is wrong', function () {565 (() => { driver.proxyActive('aaa'); }).should.throw;566 });567 });568 describe('#getProxyAvoidList', function () {569 it('should exist', function () {570 driver.getProxyAvoidList.should.be.an.instanceof(Function);571 });572 it('should return jwpProxyAvoid array', function () {573 let avoidList = driver.getProxyAvoidList('abc');574 avoidList.should.be.an.instanceof(Array);575 avoidList.should.eql(driver.jwpProxyAvoid);576 });577 it('should throw an error if session id is wrong', function () {578 (() => { driver.getProxyAvoidList('aaa'); }).should.throw;579 });580 });581 describe('#canProxy', function () {582 it('should exist', function () {583 driver.canProxy.should.be.an.instanceof(Function);584 });585 it('should return false', function () {586 driver.canProxy('abc').should.be.false;587 });588 it('should throw an error if session id is wrong', function () {589 (() => { driver.canProxy('aaa'); }).should.throw;590 });591 });592 });...
espresso-runner.js
Source:espresso-runner.js
...49 ].includes(appState);50 if (shouldUninstallApp) {51 logger.info(`Uninstalling Espresso Test Server apk from the target device (pkg: '${TEST_APK_PKG}')`);52 try {53 await this.adb.uninstallApk(TEST_APK_PKG);54 } catch (err) {55 logger.warn(`Error uninstalling '${TEST_APK_PKG}': ${err.message}`);56 }57 }58 if (shouldInstallApp) {59 logger.info(`Installing Espresso Test Server apk from the target device (path: '${this.modServerPath}')`);60 try {61 await this.adb.install(this.modServerPath, { replace: false, timeout: this.androidInstallTimeout });62 logger.info(`Installed Espresso Test Server apk '${this.modServerPath}' (pkg: '${TEST_APK_PKG}')`);63 } catch (err) {64 logger.errorAndThrow(`Cannot install '${this.modServerPath}' because of '${err.message}'`);65 }66 }67 }68 async installTestApk () {69 let rebuild = this.forceEspressoRebuild;70 if (rebuild) {71 logger.debug(`'forceEspressoRebuild' capability is enabled`);72 } else if (await this.isAppPackageChanged()) {73 logger.info(`Forcing Espresso server rebuild because of changed application package`);74 rebuild = true;75 }76 if (rebuild && await fs.exists(this.modServerPath)) {77 logger.debug(`Deleting the obsolete Espresso server package '${this.modServerPath}'`);78 await fs.unlink(this.modServerPath);79 }80 if (!(await fs.exists(this.modServerPath))) {81 await this.buildNewModServer();82 }83 const isSigned = await this.adb.checkApkCert(this.modServerPath, TEST_APK_PKG);84 if (!isSigned) {85 await this.adb.sign(this.modServerPath);86 }87 if ((rebuild || !isSigned) && await this.adb.uninstallApk(TEST_APK_PKG)) {88 logger.info('Uninstalled the obsolete Espresso server package from the device under test');89 }90 await this.installServer();91 }92 async buildNewModServer () {93 logger.info(`Repackaging espresso server for: '${this.appPackage}'`);94 const packageTmpDir = path.resolve(this.tmpDir, this.appPackage);95 const newManifestPath = path.resolve(this.tmpDir, 'AndroidManifest.xml');96 await fs.rimraf(newManifestPath);97 logger.info(`Creating new manifest: '${newManifestPath}'`);98 await mkdirp(packageTmpDir);99 await fs.copyFile(TEST_MANIFEST_PATH, newManifestPath);100 await this.adb.compileManifest(newManifestPath, TEST_APK_PKG, this.appPackage); // creates a file `${newManifestPath}.apk`101 await this.adb.insertManifest(newManifestPath, TEST_APK_PATH, this.modServerPath); // copies from second to third and add manifest...
apk-utils-e2e-specs.js
Source:apk-utils-e2e-specs.js
...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 these...
espresso-runner-specs.js
Source:espresso-runner-specs.js
...68 systemPort: 4724, devicePort: 6790, appPackage: 'io.appium.example',69 forceEspressoRebuild: false70 });71 await espresso.installServer();72 espresso.adb.uninstallApk().should.eql(1);73 espresso.adb.install().should.eql(1);74 });75 it('should install older server', async function () {76 sandbox.stub(ADB, 'createADB').callsFake(function () {77 uninstallCount = -1;78 installCount = -1;79 return Object.assign(80 commonStub,81 {82 getApplicationInstallState: () => adbCmd.APP_INSTALL_STATE.OLDER_VERSION_INSTALLED,83 }84 );85 });86 const adb = ADB.createADB();87 const espresso = new EspressoRunner({88 adb, tmpDir: 'tmp', host: 'localhost',89 systemPort: 4724, devicePort: 6790, appPackage: 'io.appium.example',90 forceEspressoRebuild: false91 });92 await espresso.installServer();93 espresso.adb.uninstallApk().should.eql(1);94 espresso.adb.install().should.eql(1);95 });96 it('should install from no server', async function () {97 sandbox.stub(ADB, 'createADB').callsFake(function () {98 uninstallCount = -1;99 installCount = -1;100 return Object.assign(101 commonStub,102 {103 getApplicationInstallState: () => adbCmd.APP_INSTALL_STATE.NOT_INSTALLED104 }105 );106 });107 const adb = ADB.createADB();108 const espresso = new EspressoRunner({109 adb, tmpDir: 'tmp', host: 'localhost',110 systemPort: 4724, devicePort: 6790, appPackage: 'io.appium.example',111 forceEspressoRebuild: false112 });113 await espresso.installServer();114 espresso.adb.uninstallApk().should.eql(0);115 espresso.adb.install().should.eql(1);116 });117 it('should raise an error when it fails to install an apk', async function () {118 sandbox.stub(ADB, 'createADB').callsFake(function () {119 uninstallCount = -1;120 installCount = -1;121 return Object.assign(122 commonStub,123 {124 getApplicationInstallState: () => adbCmd.APP_INSTALL_STATE.NOT_INSTALLED,125 install: () => {126 throw new Error('error happened');127 }128 }129 );130 });131 const adb = ADB.createADB();132 const espresso = new EspressoRunner({133 adb, tmpDir: 'tmp', host: 'localhost',134 systemPort: 4724, devicePort: 6790, appPackage: 'io.appium.example',135 forceEspressoRebuild: false136 });137 await espresso.installServer().should.eventually.to.be.rejectedWith(/error happened/i);138 espresso.adb.uninstallApk().should.eql(0);139 });140 });...
selendroid.js
Source:selendroid.js
...34 }35 needsUninstall = await this.checkAndSignCert(this.modServerPath) || needsUninstall;36 if (needsUninstall) {37 logger.info('New server was built, uninstalling any instances of it');38 await this.adb.uninstallApk(this.modServerPkg);39 }40 }41 async installModifiedServer () {42 let installed = await this.adb.isAppInstalled(this.modServerPkg);43 if (!installed) {44 await this.adb.install(this.modServerPath);45 }46 }47 async buildNewModServer () {48 logger.info(`Repackaging selendroid for: '${this.appPackage}'`);49 let packageTmpDir = path.resolve(this.tmpDir, this.appPackage);50 let newManifestPath = path.resolve(this.tmpDir, 'AndroidManifest.xml');51 logger.info(`Creating new manifest: '${newManifestPath}'`);52 await fs.mkdir(packageTmpDir);...
android-helper-e2e-specs.js
Source:android-helper-e2e-specs.js
...25 this.timeout(MOCHA_TIMEOUT);26 await retryInterval(10, 500, async function () {27 if (await adb.isAppInstalled(opts.appPackage)) {28 // this sometimes times out on Travis, so retry29 await adb.uninstallApk(opts.appPackage);30 }31 });32 await adb.isAppInstalled(opts.appPackage).should.eventually.be.false;33 await helpers.installApkRemotely(adb, opts);34 await adb.isAppInstalled(opts.appPackage).should.eventually.be.true;35 });36 });37 describe('ensureDeviceLocale @skip-ci', function () {38 after(async function () {39 await helpers.ensureDeviceLocale(adb, 'en', 'US');40 });41 it('should set device language and country', async function () {42 await helpers.ensureDeviceLocale(adb, 'fr', 'FR');43 if (await adb.getApiLevel() < 23) {44 await adb.getDeviceLanguage().should.eventually.equal('fr');45 await adb.getDeviceCountry().should.eventually.equal('FR');46 } else {47 await adb.getDeviceLocale().should.eventually.equal('fr-FR');48 }49 });50 });51 describe('pushSettingsApp', function () {52 const settingsPkg = 'io.appium.settings';53 it('should be able to upgrade from settings v1 to latest', async function () {54 await adb.uninstallApk(settingsPkg);55 // get and install old version of settings app56 await exec('npm', ['install', `${settingsPkg}@2.0.0`]);57 // old version has a different apk path, so manually enter58 // otherwise pushing the app will fail because import will have the old59 // path cached60 const settingsApkPath = path.resolve(__dirname, '..', '..', '..',61 'node_modules', 'io.appium.settings', 'bin', 'settings_apk-debug.apk');62 await adb.install(settingsApkPath);63 // get latest version of settings app64 await exec('npm', ['uninstall', settingsPkg]);65 await exec('npm', ['install', settingsPkg]);66 await helpers.pushSettingsApp(adb, true);67 });68 });69 describe('pushUnlock', function () {70 const unlockPkg = 'appium-unlock';71 const unlockBundle = 'io.appium.unlock';72 it('should be able to upgrade from unlock v0.0.1 to latest', async function () {73 await adb.uninstallApk(unlockBundle);74 // get and install old version of settings app75 await exec('npm', ['install', `${unlockPkg}@0.0.1`]);76 await adb.install(unlockApkPath);77 // get latest version of settings app78 await exec('npm', ['uninstall', unlockPkg]);79 await exec('npm', ['install', unlockPkg]);80 await helpers.pushUnlock(adb);81 });82 });...
bootstrap-e2e-specs.js
Source:bootstrap-e2e-specs.js
...18 before(async function () {19 adb = await ADB.createADB();20 const packageName = 'io.appium.android.apis',21 activityName = '.ApiDemos';22 await adb.uninstallApk('io.appium.android.apis');23 await adb.install(apiDemos);24 await adb.startApp({pkg: packageName,25 activity: activityName});26 androidBootstrap = new AndroidBootstrap(adb, systemPort);27 await androidBootstrap.start('io.appium.android.apis', false);28 });29 after(async function () {30 await androidBootstrap.shutdown();31 });32 it('sendAction should work', async function () {33 (await androidBootstrap.sendAction('wake')).should.equal(true);34 });35 it('sendCommand should work', async function () {36 (await androidBootstrap.sendCommand(COMMAND_TYPES.ACTION, {action: 'getDataDir'})).should...
adb-emu-commands-e2e-specs.js
Source:adb-emu-commands-e2e-specs.js
...22 });23 it('fingerprint should open the secret activity on emitted valid finger touch event', async () => {24 if (await adb.isAppInstalled(pkg)) {25 await adb.forceStop(pkg);26 await adb.uninstallApk(pkg);27 }28 await adb.install(fingerprintPath);29 await adb.startApp({pkg, activity});30 await sleep(500);31 let app = await adb.getFocusedPackageAndActivity();32 app.appActivity.should.equal(activity);33 await adb.fingerprint(1111);34 await sleep(2500);35 app = await adb.getFocusedPackageAndActivity();36 app.appActivity.should.equal(secretActivity);37 });...
Using AI Code Generation
1var wd = require('wd');2var assert = require('assert');3var AndroidDriver = require('appium-android-driver');4var ADB = require('appium-adb');5var driver = new AndroidDriver();6var adb = new ADB();7var desiredCaps = {8};9var driver = wd.promiseChainRemote('localhost', 4723);10driver.init(desiredCaps).then(function() {11 adb.uninstallApk('com.example.android.contactmanager', function(err) {12 if (err) {13 console.log(err);14 }15 });16});17driver.quit();
Using AI Code Generation
1var driver = new webdriver.Builder()2 .withCapabilities({3 })4 .build();5 .init()6 .then(function() {7 return driver.adb.uninstallApk('io.appium.android.apis');8 })9 .then(function() {10 console.log("uninstall successful");11 })12 .fin(function() {13 return driver.quit();14 })15 .done();16var driver = new webdriver.Builder()17 .withCapabilities({18 })19 .build();20 .init()21 .then(function() {22 return driver.adb.uninstallApk('io.appium.android.apis');23 })24 .then(function() {25 console.log("uninstall successful");26 })27 .fin(function() {28 return driver.quit();29 })30 .done();31var driver = new webdriver.Builder()32 .withCapabilities({33 })34 .build();35 .init()36 .then(function() {37 return driver.adb.uninstallApk('io.appium.android.apis');38 })39 .then(function() {40 console.log("uninstall successful");41 })42 .fin(function() {43 return driver.quit();44 })45 .done();
Using AI Code Generation
1var androidDriver = new AndroidDriver();2androidDriver.uninstallApk("com.example.testapp");3androidDriver.quit();4AndroidDriver.prototype.uninstallApk = function(apk) {5 this.adb.uninstallApk(apk);6};7ADB.prototype.uninstallApk = function(pkg) {8 this.exec("uninstall " + pkg);9};10ADB.prototype.exec = function(cmd, cb) {11 var args = cmd.split(" ");12 var bin = this.binaries.adb;13 var child = spawn(bin, args);14 var out = "";15 child.stdout.on('data', function (data) {16 out += data;17 });18 child.on('exit', function (code) {19 if (code !== 0) {20 logger.error("ADB exited with code " + code);21 logger.error("ADB stderr: " + out);22 return cb(new Error("ADB exited with code " + code));23 }24 cb(null, out);25 });26};27var spawn = function (cmd, args, opts) {28 var sp = child_process.spawn(cmd, args, opts);29 sp.on('error', function (err) {30 logger.error("Error occured while spawning " + cmd + " with args: " + args);31 logger.error(err);32 });33 return sp;34};35var spawn = function (cmd, args, opts) {36 var sp = child_process.spawn(cmd, args, opts);37 sp.on('error', function (err) {38 logger.error("Error occured while spawning " + cmd + " with args: " + args);39 logger.error(err);40 });41 return sp;42};43var spawn = function (cmd, args, opts) {44 var sp = child_process.spawn(cmd, args, opts);45 sp.on('error', function (err) {46 logger.error("Error occured while spawning " + cmd + " with args: " + args
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!