How to use processCapabilities method in Appium Base Driver

Best JavaScript code snippet using appium-base-driver

capabilities-specs.js

Source:capabilities-specs.js Github

copy

Full Screen

...189    });190  });191  describe('#processCaps', function () {192    it('should return "alwaysMatch" if "firstMatch" and "constraints" were not provided', function () {193      processCapabilities({}).should.deep.equal({});194    });195    it('should return merged caps', function () {196      processCapabilities({197        alwaysMatch: {hello: 'world'},198        firstMatch: [{foo: 'bar'}]199      }).should.deep.equal({hello: 'world', foo: 'bar'});200    });201    it('should strip out the "appium:" prefix for non-standard capabilities', function () {202      processCapabilities({203        alwaysMatch: {'appium:hello': 'world'},204        firstMatch: [{'appium:foo': 'bar'}]205      }).should.deep.equal({hello: 'world', foo: 'bar'});206    });207    it('should still accept prefixed caps even if they are standard capabilities (https://www.w3.org/TR/webdriver/#dfn-table-of-standard-capabilities)', function () {208      processCapabilities({209        alwaysMatch: {'appium:platformName': 'Whatevz'},210        firstMatch: [{'appium:browserName': 'Anything'}],211      }).should.deep.equal({platformName: 'Whatevz', browserName: 'Anything'});212    });213    it('should prefer standard caps that are non-prefixed to prefixed', function () {214      processCapabilities({215        alwaysMatch: {'appium:platformName': 'Foo', 'platformName': 'Bar'},216        firstMatch: [{'appium:browserName': 'FOO', 'browserName': 'BAR'}],217      }).should.deep.equal({platformName: 'Bar', browserName: 'BAR'});218    });219    it('should throw exception if duplicates in alwaysMatch and firstMatch', function () {220      (() => processCapabilities({221        alwaysMatch: {'platformName': 'Fake', 'appium:fakeCap': 'foobar'},222        firstMatch: [{'appium:platformName': 'bar'}],223      })).should.throw(/should not exist on both primary/);224    });225    it('should not throw an exception if presence constraint is not met on a firstMatch capability', function () {226      const caps = processCapabilities({227        alwaysMatch: {'platformName': 'Fake', 'appium:fakeCap': 'foobar'},228        firstMatch: [{'foo': 'bar'}],229      }, {230        platformName: {231          presence: true,232        },233        fakeCap: {234          presence: true235        },236      });237      caps.platformName.should.equal('Fake');238      caps.fakeCap.should.equal('foobar');239      caps.foo.should.equal('bar');240    });241    it('should throw an exception if no matching caps were found', function () {242      (() => processCapabilities({243        alwaysMatch: {'platformName': 'Fake', 'appium:fakeCap': 'foobar'},244        firstMatch: [{'foo': 'bar'}],245      }, {246        platformName: {247          presence: true,248        },249        fakeCap: {250          presence: true251        },252        missingCap: {253          presence: true,254        },255      })).should.throw(/'missingCap' can't be blank/);256    });257    describe('validate Appium constraints', function () {258      let constraints = {...desiredCapabilityConstraints};259      let matchingCaps = {'platformName': 'Fake', 'automationName': 'Fake', 'deviceName': 'Fake'};260      let caps;261      it('should validate when alwaysMatch has the proper caps', function () {262        caps = {263          alwaysMatch: matchingCaps,264          firstMatch: [{}],265        };266        processCapabilities(caps, constraints).should.deep.equal(matchingCaps);267      });268      it('should validate when firstMatch[0] has the proper caps', function () {269        caps = {270          alwaysMatch: {},271          firstMatch: [matchingCaps],272        };273        processCapabilities(caps, constraints).should.deep.equal(matchingCaps);274      });275      it('should validate when alwaysMatch and firstMatch[0] have the proper caps when merged together', function () {276        caps = {277          alwaysMatch: _.omit(matchingCaps, ['deviceName']),278          firstMatch: [{'appium:deviceName': 'Fake'}],279        };280        processCapabilities(caps, constraints).should.deep.equal(matchingCaps);281      });282      it('should validate when automationName is omitted', function () {283        caps = {284          alwaysMatch: _.omit(matchingCaps, ['automationName']),285        };286        processCapabilities(caps, constraints).should.deep.equal(_.omit(matchingCaps, 'automationName'));287      });288      it('should pass if first element in "firstMatch" does validate and second element does not', function () {289        caps = {290          alwaysMatch: {},291          firstMatch: [292            matchingCaps,293            {badCaps: 'badCaps'},294          ],295        };296        processCapabilities(caps, constraints).should.deep.equal(matchingCaps);297      });298      it('should pass if first element in "firstMatch" does not validate and second element does', function () {299        caps = {300          alwaysMatch: {},301          firstMatch: [302            {badCaps: 'badCaps'},303            matchingCaps,304          ],305        };306        processCapabilities(caps, constraints).should.deep.equal(matchingCaps);307      });308      it('should fail when bad parameters are passed in more than one firstMatch capability', function () {309        caps = {310          alwaysMatch: {},311          firstMatch: [{312            bad: 'params',313          }, {314            more: 'bad-params',315          }],316        };317        (() => processCapabilities(caps, constraints)).should.throw(/Could not find matching capabilities/);318      });319    });320  });321  describe('.findNonPrefixedCaps', function () {322    it('should find alwaysMatch caps with no prefix', function () {323      findNonPrefixedCaps({alwaysMatch: {324        'non-standard': 'dummy',325      }}).should.eql(['non-standard']);326    });327    it('should not find a standard cap in alwaysMatch', function () {328      findNonPrefixedCaps({alwaysMatch: {329        'platformName': 'Any',330      }}).should.eql([]);331    });...

Full Screen

Full Screen

builder.js

Source:builder.js Github

copy

Full Screen

...100      // Get the new capabilities101      if ($scope.request.host) {102        requestCapabilities($scope.request).success(function(xml) {103          // Apply capabilities to the scope104          var cap = processCapabilities($scope.request.service, xml);105          angular.extend($scope, cap);106          angular.extend($scope.request, cap.defaults);107          $scope.capabilitiesError = null;108        }).error(function(error) {109          $scope.capabilitiesError = error? error : "Unable to retrieve the server's capabilities.";110        });111      }112    };113    // Update capabilities if the host or service type changes114    $scope.$watch('request.host', updateCapabilities);115    $scope.$watch('request.service', updateCapabilities);116    // Update the list of properties for the features of this service117    function updateFeatureProperties() {118      getFeatureInfo($scope.request).success(function(xml) {...

Full Screen

Full Screen

utils.js

Source:utils.js Github

copy

Full Screen

...82    // Call the process capabilities algorithm to find matching caps on the W3C83    // (see: https://github.com/jlipps/simple-wd-spec#processing-capabilities)84    let isFixingNeededForW3cCaps = false;85    try {86      desiredCaps = processCapabilities(w3cCapabilities, constraints, true);87    } catch (error) {88      if (!hasJSONWPCaps) {89        return {90          desiredCaps,91          processedJsonwpCapabilities,92          processedW3CCapabilities,93          protocol,94          error,95        };96      }97      logger.info(`Could not parse W3C capabilities: ${error.message}`);98      isFixingNeededForW3cCaps = true;99    }100    if (hasJSONWPCaps && !isFixingNeededForW3cCaps) {101      const differingKeys = _.difference(_.keys(processedJsonwpCapabilities), _.keys(removeW3CPrefixes(desiredCaps)));102      if (!_.isEmpty(differingKeys)) {103        logger.info(`The following capabilities were provided in the JSONWP desired capabilities that are missing ` +104          `in W3C capabilities: ${JSON.stringify(differingKeys)}`);105        isFixingNeededForW3cCaps = true;106      }107    }108    if (isFixingNeededForW3cCaps && hasJSONWPCaps) {109      logger.info('Trying to fix W3C capabilities by merging them with JSONWP caps');110      w3cCapabilities = fixW3cCapabilities(w3cCapabilities, jsonwpCapabilities);111      try {112        desiredCaps = processCapabilities(w3cCapabilities, constraints, true);113      } catch (error) {114        logger.warn(`Could not parse fixed W3C capabilities: ${error.message}. Falling back to JSONWP protocol`);115        return {116          desiredCaps: processedJsonwpCapabilities,117          processedJsonwpCapabilities,118          processedW3CCapabilities: null,119          protocol: MJSONWP,120        };121      }122    }123    // Create a new w3c capabilities payload that contains only the matching caps in `alwaysMatch`124    processedW3CCapabilities = {125      alwaysMatch: {...insertAppiumPrefixes(desiredCaps)},126      firstMatch: [{}],...

Full Screen

Full Screen

app.js

Source:app.js Github

copy

Full Screen

1var webdriver = require('browserstack-webdriver'),2    //  queue = require ('./queue'),3    fs = require('fs'),4    path = require('path'),5    spawn = require('child_process').spawn,6    async = require ('async'),7    config = {}, //configuration information for the browserstack tests8    capabilitiesBlock = [], //listing of devices and browsers to run the test on9    bs = undefined, //browserstack web driver10    platform = '', //os platform, used to point to correct binary11    configPath = '', //file path to the browserstack.config file12    loadedFunctions = null;13//load the configuration file14if (process.argv[2] && fs.existsSync(process.argv[2])){15    configPath = process.argv[2];16} else {17    configPath = 'browserstack.config';18}19//run the process20async.waterfall([21    readConfig,22    loadUserScripts,23    processCapabilities24], function (err, results){25    if (err){26        console.error (err);27    } else {28        console.log ('Screenshot tasks complete')29    }30    process.exit();31});32//======================Functions==========================33function readConfig (cb){34    if (!fs.existsSync (configPath)){35        cb('Missing a browserstack.config file');36        return false;37    }38    data = fs.readFileSync (configPath, {encoding: 'utf8'});39    if (!data) {40        cb('Missing a browserstack.config file');41        return false;42    }43    data = JSON.parse(data);44    config = data.configuration;45    capabilitiesBlock = data.capabilities;46    if (config.isLocal) {47        //spawn the browserstack web driver, and attach listeners48        bs = spawn('./binaries/BrowserStackLocal', ['-localIdentifier', config.localIdentifier, '-force', config.key, config.localServerSettings]);49        bs.stdout.on('data', function(data) {50            console.log('stdout: ' + data);51        });52        bs.stderr.on('data', function(data) {53            console.log('stderr: ' + data);54        });55        //Give the browserstack web driver time to load before starting tests56        setTimeout(function() {57            cb(null, config, capabilitiesBlock);58        }, 5000);59    } else {60        cb(null, config, capabilitiesBlock);61    }62}63function loadUserScripts (config, capabilitiesBlock, cb){64    var result = '',65        loadedFunctions;66    if (config.userFunctions.file){67        if (fs.existsSync('./' + config.userFunctions.file + '.js')){68            loadedFunctions = require('../' + config.userFunctions.file);69            70            if (!loadedFunctions) {71                cb('Failed to load user script');72            }73            cb(null, loadedFunctions, config, capabilitiesBlock);74        } else {75            cb('Failed to load user script');76        }77    }78}79function processCapabilities (loadedFunctions, config, capabilitiesBlock, asyncCallback) {80    async.eachLimit (capabilitiesBlock, 2, function (i, cb){81        try {82            var capabilities = i,83                driver = {};84            driver = new webdriver.Builder().85            usingServer('http://hub.browserstack.com/wd/hub').86            withCapabilities(capabilities).87            build();88            driver.get(config.url);89            if (loadedFunctions){90                loadedFunctions[config.userFunctions.functionName].call(driver);91            }92            driver93            .takeScreenshot()94            .then(function(data) {95                fs.writeFile(path.join(__dirname.substr(0, __dirname.lastIndexOf('/')), 'screenshots', (capabilities.browser || capabilities.browserName) +96                    '_' + (capabilities.os || capabilities.device) +97                    '_' + (capabilities.os_version || '') +98                    '_' + (capabilities.resolution || '') + '.png'), data.replace(/^data:image\/png;base64,/, ''), 'base64', function(err) {99                    if (err) {100                        cb(err)101                    } else {102                        cb();103                    }104                });105            });106        } catch (e) {107            console.log(e);108            if (driver.quit) driver.quit();109            cb(e);110        }}, function (err){111            if (err) {112                if (bs) bs.kill();113                asyncCallback(err);114            }else{115                asyncCallback(null, 'Screenshots complete');116            }117        }118    );...

Full Screen

Full Screen

session_commands.js

Source:session_commands.js Github

copy

Full Screen

...8    reachedMaximumActiveSessions,9    MAXIMUM_ACTIVE_SESSIONS10  } = require('./session');11let Debugger = null;12function processCapabilities(caps) {13  let desiredCaps = caps.desiredCapabilities || {},14    requiredCaps = caps.requiredCapabilities || {},15    unprocessedCaps = Object.assign({}, desiredCaps, requiredCaps),16    serverCaps = {17      browserName: 'chrome',18      browserVersion: '',19      platformName: '',20      platformVersion: '',21      acceptSslCerts: false22    },23    unmetCaps = [];24  for (let cap in unprocessedCaps) {25    let value = unprocessedCaps[cap];26    if (requiredCaps[cap] !== undefined &&27      serverCaps[cap] !== undefined &&28      value !== serverCaps[cap]) {29      unmetCaps.push(30        `Required capability ${cap} ${value} does not match server capability ${serverCaps[cap]}`31      );32      continue;33    }34    if (['proxy', 'pageLoadStrategy', 'chromeOptions'].indexOf(cap) > -1) {35      serverCaps[cap] = unprocessedCaps[cap];36    } else if (requiredCaps[cap] !== undefined) {37      unmetCaps.push(38        `Unknown required capability ${cap} ${value}`39      );40    }41  }42  if (unmetCaps.length) {43    throw(new error.SessionNotCreatedError(unmetCaps.join(';')));44  }45  return serverCaps;46}47/**48 * [New Session command](https://www.w3.org/TR/webdriver/#new-session)49 *50 * @param {!Object<*>} parameters The command parameters.51 */52function newSession(parameters) {53  if (reachedMaximumActiveSessions()) {54    return Promise.reject(55      new error.SessionNotCreatedError(56        `Maximum(${MAXIMUM_ACTIVE_SESSIONS}) active sessions reached.`57      )58    );59  }60  if (typeof parameters !== 'object') {61    return Promise.reject(62      new error.SessionNotCreatedError('Cannot find desiredCapabilities.')63    );64  }65  let capsResult;66  try {67    if (parameters.capabilities && parameters.capabilities.desiredCapabilities) {68      capsResult = processCapabilities(parameters.capabilities);69    } else if (parameters.desiredCapabilities) {70      capsResult = processCapabilities({ desiredCapabilities: parameters.desiredCapabilities });71    } else {72      throw(new error.SessionNotCreatedError('Cannot find desiredCapabilities.'));73    }74  } catch(e) {75    return Promise.reject(e);76  }77  let session = new Session();78  addSession(session);79  if (capsResult.pageLoadStrategy) {80    session.setPageLoadStrategy(capsResult.pageLoadStrategy);81  }82  return session.trackTabs(Debugger.list, Debugger.new)83    .then(() => {84      let tab = session.getFirstTab(),...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1const browserslist = require('browserslist');2const os = require('os');3const { spawnSync } = require('child_process');4function processCapabilities(capabilities) {5  // keep only one capability for each unique browser6  return capabilities.filter((c) => (7    c === capabilities.find((c2) => (8      c2.browser === c.browser && c2.browser_version === c.browser_version9    ))10  ));11}12const BrowserstackBrowserslistLaunchers = (config, logger, injector) => {13  const log = logger.create('framework.browserstack-browserslist-launchers');14  function loadCapabilitiesSync(username, accessKey) {15    const result = spawnSync('node', ['load-capabilities-cli.js', username, accessKey], {16      cwd: __dirname,17    });18    const stdout = result.stdout.toString();19    const stderr = result.stderr.toString();20    if (stderr) {21      log.error(stderr);22    }23    if (result.status !== 0) {24      process.exit(result.status);25    }26    const capabilitiesString = `[${stdout.split(os.EOL).filter(Boolean).join(',')}]`;27    return JSON.parse(capabilitiesString);28  }29  config = config || {};30  config.browserStack = config.browserStack || {};31  config.browserStackBrowserslistLaunchers = config.browserStackBrowserslistLaunchers || {};32  if (!config.browserStack.username || !config.browserStack.accessKey) {33    log.error(`Either browserStack.username or browserStack.accessKey (or both) is not defined in your config.`);34    process.exit();35  }36  if (browserslist().length === 0) {37    log.error(`Your browserslist config does not contain any queries.`);38    process.exit();39  }40  if (!config.browserStackBrowserslistLaunchers.processCapabilities) {41    config.browserStackBrowserslistLaunchers.processCapabilities = processCapabilities;42  }43  const allCapabilities = loadCapabilitiesSync(44    config.browserStack.username,45    config.browserStack.accessKey,46  );47  const noChangesMessage = 'No changes will be made to config.browsers.';48  if (allCapabilities.length === 0) {49    log.error(`BrowserStack doesn't look to have capabilities available for your browserslist config. ${noChangesMessage}`);50    return;51  }52  const capabilities = config53    .browserStackBrowserslistLaunchers54    .processCapabilities(allCapabilities);55  if (capabilities.length === 0) {56    log.error(`After processing capabilities there are 0 left. ${noChangesMessage}`);57    return;58  }59  const browsers = [];60  const customLaunchers = {};61  capabilities.forEach((c) => {62    const uniqueName = `${c.browser} ${c.browser_version} (${c.os} ${c.os_version})`;63    browsers.push(uniqueName);64    customLaunchers[uniqueName] = c;65  });66  config.browsers = browsers;67  // instead of setting config.customLaunchers which has no effect at this point68  // we need to create a factory for each custom launcher...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var AppiumBaseDriver = require('appium-base-driver');2var appiumBaseDriver = new AppiumBaseDriver();3var caps = {4};5appiumBaseDriver.processCapabilities(caps);6var AppiumAndroidDriver = require('appium-android-driver');7var appiumAndroidDriver = new AppiumAndroidDriver();8var caps = {9};10appiumAndroidDriver.processCapabilities(caps);11var AppiumIOSDriver = require('appium-ios-driver');12var appiumIOSDriver = new AppiumIOSDriver();13var caps = {14};15appiumIOSDriver.processCapabilities(caps);16var AppiumWindowsDriver = require('appium-windows-driver');17var appiumWindowsDriver = new AppiumWindowsDriver();18var caps = {19};20appiumWindowsDriver.processCapabilities(caps);21var AppiumMacDriver = require('appium-mac-driver');22var appiumMacDriver = new AppiumMacDriver();23var caps = {24};25appiumMacDriver.processCapabilities(caps);26var AppiumYouiEngineDriver = require('appium-youiengine-driver');27var appiumYouiEngineDriver = new AppiumYouiEngineDriver();28var caps = {29};30appiumYouiEngineDriver.processCapabilities(caps);

Full Screen

Using AI Code Generation

copy

Full Screen

1var AppiumBaseDriver = require('appium-base-driver');2var driver = new AppiumBaseDriver();3var caps = {4};5driver.processCapabilities(caps).then(function (caps) {6  console.log(caps);7});8var AppiumBaseDriver = require('appium-base-driver');9var driver = new AppiumBaseDriver();10var caps = {11};12driver.processCapabilities(caps).then(function (caps) {13  console.log(caps);14});15Copyright (c) 2019-present, Appium Committers

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriverio = require('webdriverio');2var Appium = require('appium');3var caps = {4};5var appium = new Appium();6appium.start(caps);7appium.on('ready', function() {8  var driver = webdriverio.remote({9  });10  driver.init(function() {11      driver.title(function(err, title) {12        console.log('Title was: ' + title);13        driver.end(function() {14          appium.stop();15        });16      });17    });18  });19});20appium.on('error', function(err) {21  console.log('Error: ' + err);22});23appium.on('exit', function() {24  console.log('Appium exited');25});26    throw err;27    at Function.Module._resolveFilename (module.js:336:15)28    at Function.Module._load (module.js:278:25)29    at Function.Module.runMain (module.js:501:10)30    at startup (node.js:129:16)

Full Screen

Using AI Code Generation

copy

Full Screen

1const processCaps = require('appium-base-driver').processCapabilities;2const caps = {3};4processCaps(caps).then((processedCaps) => {5  console.log(processedCaps);6});7{ platformName: 'iOS',8  showXcodeLog: true }

Full Screen

Using AI Code Generation

copy

Full Screen

1var BaseDriver = require('appium-base-driver').BaseDriver;2var desiredCaps = {3};4var baseDriver = new BaseDriver();5baseDriver.processCapabilities(desiredCaps).then(function (caps) {6    console.log(caps);7});8{9}10var BaseDriver = require('appium-base-driver').BaseDriver;11var desiredCaps = {12};13var baseDriver = new BaseDriver();14baseDriver.createSession(desiredCaps).then(function (session) {15    console.log(session);16});

Full Screen

Using AI Code Generation

copy

Full Screen

1const AppiumBaseDriver = require('appium-base-driver');2let caps = {3};4let driver = new AppiumBaseDriver();5driver.processCapabilities(caps).then((caps) => {6    console.log(caps);7});8{9}

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 Base 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