How to use routeToCommandName method in Appium Base Driver

Best JavaScript code snippet using appium-base-driver

routes.js

Source:routes.js Github

copy

Full Screen

1import _ from 'lodash';2import { util } from 'appium-support';3import { PROTOCOLS, DEFAULT_BASE_PATH } from '../constants';4const SET_ALERT_TEXT_PAYLOAD_PARAMS = {5  validate: (jsonObj) => (!util.hasValue(jsonObj.value) && !util.hasValue(jsonObj.text)) &&6      'either "text" or "value" must be set',7  optional: ['value', 'text'],8  // Prefer 'value' since it's more backward-compatible.9  makeArgs: (jsonObj) => [jsonObj.value || jsonObj.text],10};11// define the routes, mapping of HTTP methods to particular driver commands,12// and any parameters that are expected in a request13// parameters can be `required` or `optional`14const METHOD_MAP = {15  '/status': {16    GET: {command: 'getStatus'}17  },18  '/session': {19    POST: {command: 'createSession', payloadParams: {20      validate: (jsonObj) => (!jsonObj.capabilities && !jsonObj.desiredCapabilities) && 'we require one of "desiredCapabilities" or "capabilities" object',21      optional: ['desiredCapabilities', 'requiredCapabilities', 'capabilities']}}22  },23  '/sessions': {24    GET: {command: 'getSessions'}25  },26  '/session/:sessionId': {27    GET: {command: 'getSession'},28    DELETE: {command: 'deleteSession'}29  },30  '/session/:sessionId/timeouts': {31    GET: {command: 'getTimeouts'}, // W3C route32    POST: {command: 'timeouts', payloadParams: {33      validate: (jsonObj, protocolName) => {34        if (protocolName === PROTOCOLS.W3C) {35          if (!util.hasValue(jsonObj.script) && !util.hasValue(jsonObj.pageLoad) && !util.hasValue(jsonObj.implicit)) {36            return 'W3C protocol expects any of script, pageLoad or implicit to be set';37          }38        } else {39          if (!util.hasValue(jsonObj.type) || !util.hasValue(jsonObj.ms)) {40            return 'MJSONWP protocol requires type and ms';41          }42        }43      },44      optional: ['type', 'ms', 'script', 'pageLoad', 'implicit'],45    }}46  },47  '/session/:sessionId/timeouts/async_script': {48    POST: {command: 'asyncScriptTimeout', payloadParams: {required: ['ms']}}49  },50  '/session/:sessionId/timeouts/implicit_wait': {51    POST: {command: 'implicitWait', payloadParams: {required: ['ms']}}52  },53  // JSONWP54  '/session/:sessionId/window_handle': {55    GET: {command: 'getWindowHandle'}56  },57  // W3C58  '/session/:sessionId/window/handle': {59    GET: {command: 'getWindowHandle'}60  },61  // JSONWP62  '/session/:sessionId/window_handles': {63    GET: {command: 'getWindowHandles'}64  },65  // W3C66  '/session/:sessionId/window/handles': {67    GET: {command: 'getWindowHandles'}68  },69  '/session/:sessionId/url': {70    GET: {command: 'getUrl'},71    POST: {command: 'setUrl', payloadParams: {required: ['url']}}72  },73  '/session/:sessionId/forward': {74    POST: {command: 'forward'}75  },76  '/session/:sessionId/back': {77    POST: {command: 'back'}78  },79  '/session/:sessionId/refresh': {80    POST: {command: 'refresh'}81  },82  '/session/:sessionId/execute': {83    POST: {command: 'execute', payloadParams: {required: ['script', 'args']}}84  },85  '/session/:sessionId/execute_async': {86    POST: {command: 'executeAsync', payloadParams: {required: ['script', 'args']}}87  },88  '/session/:sessionId/screenshot': {89    GET: {command: 'getScreenshot'}90  },91  '/session/:sessionId/ime/available_engines': {92    GET: {command: 'availableIMEEngines'}93  },94  '/session/:sessionId/ime/active_engine': {95    GET: {command: 'getActiveIMEEngine'}96  },97  '/session/:sessionId/ime/activated': {98    GET: {command: 'isIMEActivated'}99  },100  '/session/:sessionId/ime/deactivate': {101    POST: {command: 'deactivateIMEEngine'}102  },103  '/session/:sessionId/ime/activate': {104    POST: {command: 'activateIMEEngine', payloadParams: {required: ['engine']}}105  },106  '/session/:sessionId/frame': {107    POST: {command: 'setFrame', payloadParams: {required: ['id']}}108  },109  '/session/:sessionId/frame/parent': {110    POST: {}111  },112  '/session/:sessionId/window': {113    GET: {command: 'getWindowHandle'},114    POST: {command: 'setWindow', payloadParams: {115      optional: ['name', 'handle'],116      // Return both values to match W3C and JSONWP protocols117      makeArgs: (jsonObj) => {118        if (util.hasValue(jsonObj.handle) && !util.hasValue(jsonObj.name)) {119          return [jsonObj.handle, jsonObj.handle];120        }121        if (util.hasValue(jsonObj.name) && !util.hasValue(jsonObj.handle)) {122          return [jsonObj.name, jsonObj.name];123        }124        return [jsonObj.name, jsonObj.handle];125      },126      validate: (jsonObj) => (!util.hasValue(jsonObj.name) && !util.hasValue(jsonObj.handle))127        && 'we require one of "name" or "handle" to be set',128    }},129    DELETE: {command: 'closeWindow'}130  },131  '/session/:sessionId/window/:windowhandle/size': {132    GET: {command: 'getWindowSize'},133    POST: {}134  },135  '/session/:sessionId/window/:windowhandle/position': {136    POST: {},137    GET: {}138  },139  '/session/:sessionId/window/:windowhandle/maximize': {140    POST: {command: 'maximizeWindow'}141  },142  '/session/:sessionId/cookie': {143    GET: {command: 'getCookies'},144    POST: {command: 'setCookie', payloadParams: {required: ['cookie']}},145    DELETE: {command: 'deleteCookies'}146  },147  '/session/:sessionId/cookie/:name': {148    GET: {command: 'getCookie'},149    DELETE: {command: 'deleteCookie'}150  },151  '/session/:sessionId/source': {152    GET: {command: 'getPageSource'}153  },154  '/session/:sessionId/title': {155    GET: {command: 'title'}156  },157  '/session/:sessionId/element': {158    POST: {command: 'findElement', payloadParams: {required: ['using', 'value']}}159  },160  '/session/:sessionId/elements': {161    POST: {command: 'findElements', payloadParams: {required: ['using', 'value']}}162  },163  '/session/:sessionId/element/active': {164    GET: {command: 'active'}, // W3C: https://w3c.github.io/webdriver/webdriver-spec.html#dfn-get-active-element165    POST: {command: 'active'}166  },167  '/session/:sessionId/element/:elementId': {168    GET: {}169  },170  '/session/:sessionId/element/:elementId/element': {171    POST: {command: 'findElementFromElement', payloadParams: {required: ['using', 'value']}}172  },173  '/session/:sessionId/element/:elementId/elements': {174    POST: {command: 'findElementsFromElement', payloadParams: {required: ['using', 'value']}}175  },176  '/session/:sessionId/element/:elementId/click': {177    POST: {command: 'click'}178  },179  '/session/:sessionId/element/:elementId/submit': {180    POST: {command: 'submit'}181  },182  '/session/:sessionId/element/:elementId/text': {183    GET: {command: 'getText'}184  },185  '/session/:sessionId/element/:elementId/value': {186    POST: {187      command: 'setValue',188      payloadParams: {189        validate: (jsonObj) => (!util.hasValue(jsonObj.value) && !util.hasValue(jsonObj.text)) &&190            'we require one of "text" or "value" params',191        optional: ['value', 'text'],192        // override the default argument constructor because of the special193        // logic here. Basically we want to accept either a value (old JSONWP)194        // or a text (new W3C) parameter, but only send one of them to the195        // command (not both). Prefer 'value' since it's more196        // backward-compatible.197        makeArgs: (jsonObj) => [jsonObj.value || jsonObj.text],198      }199    }200  },201  '/session/:sessionId/keys': {202    POST: {command: 'keys', payloadParams: {required: ['value']}}203  },204  '/session/:sessionId/element/:elementId/name': {205    GET: {command: 'getName'}206  },207  '/session/:sessionId/element/:elementId/clear': {208    POST: {command: 'clear'}209  },210  '/session/:sessionId/element/:elementId/selected': {211    GET: {command: 'elementSelected'}212  },213  '/session/:sessionId/element/:elementId/enabled': {214    GET: {command: 'elementEnabled'}215  },216  '/session/:sessionId/element/:elementId/attribute/:name': {217    GET: {command: 'getAttribute'}218  },219  '/session/:sessionId/element/:elementId/equals/:otherId': {220    GET: {command: 'equalsElement'}221  },222  '/session/:sessionId/element/:elementId/displayed': {223    GET: {command: 'elementDisplayed'}224  },225  '/session/:sessionId/element/:elementId/location': {226    GET: {command: 'getLocation'}227  },228  '/session/:sessionId/element/:elementId/location_in_view': {229    GET: {command: 'getLocationInView'}230  },231  '/session/:sessionId/element/:elementId/size': {232    GET: {command: 'getSize'}233  },234  '/session/:sessionId/element/:elementId/css/:propertyName': {235    GET: {command: 'getCssProperty'}236  },237  '/session/:sessionId/orientation': {238    GET: {command: 'getOrientation'},239    POST: {command: 'setOrientation', payloadParams: {required: ['orientation']}}240  },241  '/session/:sessionId/rotation': {242    GET: {command: 'getRotation'},243    POST: {command: 'setRotation', payloadParams: {required: ['x', 'y', 'z']}}244  },245  '/session/:sessionId/moveto': {246    POST: {command: 'moveTo', payloadParams: {optional: ['element', 'xoffset', 'yoffset']}}247  },248  '/session/:sessionId/click': {249    POST: {command: 'clickCurrent', payloadParams: {optional: ['button']}}250  },251  '/session/:sessionId/buttondown': {252    POST: {command: 'buttonDown', payloadParams: {optional: ['button']}}253  },254  '/session/:sessionId/buttonup': {255    POST: {command: 'buttonUp', payloadParams: {optional: ['button']}}256  },257  '/session/:sessionId/doubleclick': {258    POST: {command: 'doubleClick'}259  },260  '/session/:sessionId/touch/click': {261    POST: {command: 'click', payloadParams: {required: ['element']}}262  },263  '/session/:sessionId/touch/down': {264    POST: {command: 'touchDown', payloadParams: {required: ['x', 'y']}}265  },266  '/session/:sessionId/touch/up': {267    POST: {command: 'touchUp', payloadParams: {required: ['x', 'y']}}268  },269  '/session/:sessionId/touch/move': {270    POST: {command: 'touchMove', payloadParams: {required: ['x', 'y']}}271  },272  '/session/:sessionId/touch/scroll': {273    POST: {}274  },275  '/session/:sessionId/touch/doubleclick': {276    POST: {}277  },278  '/session/:sessionId/actions': {279    POST: {command: 'performActions', payloadParams: {required: ['actions']}},280    DELETE: {command: 'releaseActions'},281  },282  '/session/:sessionId/touch/longclick': {283    POST: {command: 'touchLongClick', payloadParams: {required: ['elements']}}284  },285  '/session/:sessionId/touch/flick': {286    POST: {command: 'flick', payloadParams: {optional: ['element', 'xspeed', 'yspeed', 'xoffset', 'yoffset', 'speed']}}287  },288  '/session/:sessionId/location': {289    GET: {command: 'getGeoLocation'},290    POST: {command: 'setGeoLocation', payloadParams: {required: ['location']}}291  },292  '/session/:sessionId/local_storage': {293    GET: {},294    POST: {},295    DELETE: {}296  },297  '/session/:sessionId/local_storage/key/:key': {298    GET: {},299    DELETE: {}300  },301  '/session/:sessionId/local_storage/size': {302    GET: {}303  },304  '/session/:sessionId/session_storage': {305    GET: {},306    POST: {},307    DELETE: {}308  },309  '/session/:sessionId/session_storage/key/:key': {310    GET: {},311    DELETE: {}312  },313  '/session/:sessionId/session_storage/size': {314    GET: {}315  },316  // Selenium 4 clients317  '/session/:sessionId/se/log': {318    POST: {command: 'getLog', payloadParams: {required: ['type']}}319  },320  // Selenium 4 clients321  '/session/:sessionId/se/log/types': {322    GET: {command: 'getLogTypes'}323  },324  // mjsonwire, appium clients325  '/session/:sessionId/log': {326    POST: {command: 'getLog', payloadParams: {required: ['type']}}327  },328  // mjsonwire, appium clients329  '/session/:sessionId/log/types': {330    GET: {command: 'getLogTypes'}331  },332  '/session/:sessionId/application_cache/status': {333    GET: {}334  },335  //336  // mjsonwire337  //338  '/session/:sessionId/context': {339    GET: {command: 'getCurrentContext'},340    POST: {command: 'setContext', payloadParams: {required: ['name']}}341  },342  '/session/:sessionId/contexts': {343    GET: {command: 'getContexts'}344  },345  '/session/:sessionId/element/:elementId/pageIndex': {346    GET: {command: 'getPageIndex'}347  },348  '/session/:sessionId/network_connection': {349    GET: {command: 'getNetworkConnection'},350    POST: {command: 'setNetworkConnection', payloadParams: {unwrap: 'parameters', required: ['type']}}351  },352  '/session/:sessionId/touch/perform': {353    POST: {command: 'performTouch', payloadParams: {wrap: 'actions', required: ['actions']}}354  },355  '/session/:sessionId/touch/multi/perform': {356    POST: {command: 'performMultiAction', payloadParams: {required: ['actions'], optional: ['elementId']}}357  },358  '/session/:sessionId/receive_async_response': {359    POST: {command: 'receiveAsyncResponse', payloadParams: {required: ['status', 'value']}}360  },361  '/session/:sessionId/appium/device/shake': {362    POST: {command: 'mobileShake'}363  },364  '/session/:sessionId/appium/device/system_time': {365    GET: {command: 'getDeviceTime', payloadParams: {optional: ['format']}},366    POST: {command: 'getDeviceTime', payloadParams: {optional: ['format']}}367  },368  '/session/:sessionId/appium/device/lock': {369    POST: {command: 'lock', payloadParams: {optional: ['seconds']}}370  },371  '/session/:sessionId/appium/device/unlock': {372    POST: {command: 'unlock'}373  },374  '/session/:sessionId/appium/device/is_locked': {375    POST: {command: 'isLocked'}376  },377  '/session/:sessionId/appium/start_recording_screen': {378    POST: {command: 'startRecordingScreen', payloadParams: {optional: ['options']}}379  },380  '/session/:sessionId/appium/stop_recording_screen': {381    POST: {command: 'stopRecordingScreen', payloadParams: {optional: ['options']}}382  },383  '/session/:sessionId/appium/performanceData/types': {384    POST: {command: 'getPerformanceDataTypes'}385  },386  '/session/:sessionId/appium/getPerformanceData': {387    POST: {command: 'getPerformanceData', payloadParams: {required: ['packageName', 'dataType'], optional: ['dataReadTimeout']}}388  },389  '/session/:sessionId/appium/device/press_keycode': {390    POST: {command: 'pressKeyCode', payloadParams: {required: ['keycode'], optional: ['metastate', 'flags']}}391  },392  '/session/:sessionId/appium/device/long_press_keycode': {393    POST: {command: 'longPressKeyCode', payloadParams: {required: ['keycode'], optional: ['metastate', 'flags']}}394  },395  '/session/:sessionId/appium/device/finger_print': {396    POST: {command: 'fingerprint', payloadParams: {required: ['fingerprintId']}}397  },398  '/session/:sessionId/appium/device/send_sms': {399    POST: {command: 'sendSMS', payloadParams: {required: ['phoneNumber', 'message']}}400  },401  '/session/:sessionId/appium/device/gsm_call': {402    POST: {command: 'gsmCall', payloadParams: {required: ['phoneNumber', 'action']}}403  },404  '/session/:sessionId/appium/device/gsm_signal': {405    POST: {406      command: 'gsmSignal',407      payloadParams: {408        validate: (jsonObj) => (!util.hasValue(jsonObj.signalStrength) && !util.hasValue(jsonObj.signalStrengh)) &&409            'we require one of "signalStrength" or "signalStrengh" params',410        optional: ['signalStrength', 'signalStrengh'],411        // backward-compatible. sonObj.signalStrength can be 0412        makeArgs: (jsonObj) => [util.hasValue(jsonObj.signalStrength) ? jsonObj.signalStrength : jsonObj.signalStrengh]413      }414    }415  },416  '/session/:sessionId/appium/device/gsm_voice': {417    POST: {command: 'gsmVoice', payloadParams: {required: ['state']}}418  },419  '/session/:sessionId/appium/device/power_capacity': {420    POST: {command: 'powerCapacity', payloadParams: {required: ['percent']}}421  },422  '/session/:sessionId/appium/device/power_ac': {423    POST: {command: 'powerAC', payloadParams: {required: ['state']}}424  },425  '/session/:sessionId/appium/device/network_speed': {426    POST: {command: 'networkSpeed', payloadParams: {required: ['netspeed']}}427  },428  '/session/:sessionId/appium/device/keyevent': {429    POST: {command: 'keyevent', payloadParams: {required: ['keycode'], optional: ['metastate']}}430  },431  '/session/:sessionId/appium/device/rotate': {432    POST: {command: 'mobileRotation', payloadParams: {433      required: ['x', 'y', 'radius', 'rotation', 'touchCount', 'duration'],434      optional: ['element'] }}435  },436  '/session/:sessionId/appium/device/current_activity': {437    GET: {command: 'getCurrentActivity'}438  },439  '/session/:sessionId/appium/device/current_package': {440    GET: {command: 'getCurrentPackage'}441  },442  //region Applications Management443  '/session/:sessionId/appium/device/install_app': {444    POST: {445      command: 'installApp',446      payloadParams: {447        required: ['appPath'],448        optional: ['options']449      }450    }451  },452  '/session/:sessionId/appium/device/activate_app': {453    POST: {454      command: 'activateApp',455      payloadParams: {456        required: [['appId'], ['bundleId']],457        optional: ['options']458      }459    }460  },461  '/session/:sessionId/appium/device/remove_app': {462    POST: {463      command: 'removeApp',464      payloadParams: {465        required: [['appId'], ['bundleId']],466        optional: ['options']467      }468    }469  },470  '/session/:sessionId/appium/device/terminate_app': {471    POST: {472      command: 'terminateApp',473      payloadParams: {474        required: [['appId'], ['bundleId']],475        optional: ['options']476      }477    }478  },479  '/session/:sessionId/appium/device/app_installed': {480    POST: {481      command: 'isAppInstalled',482      payloadParams: {483        required: [['appId'], ['bundleId']]484      }485    }486  },487  '/session/:sessionId/appium/device/app_state': {488    GET: {489      command: 'queryAppState',490      payloadParams: {491        required: [['appId'], ['bundleId']]492      }493    },494    POST: {495      command: 'queryAppState',496      payloadParams: {497        required: [['appId'], ['bundleId']]498      }499    }500  },501  //endregion502  '/session/:sessionId/appium/device/hide_keyboard': {503    POST: {command: 'hideKeyboard', payloadParams: {optional: ['strategy', 'key', 'keyCode', 'keyName']}}504  },505  '/session/:sessionId/appium/device/is_keyboard_shown': {506    GET: {command: 'isKeyboardShown'}507  },508  '/session/:sessionId/appium/device/push_file': {509    POST: {command: 'pushFile', payloadParams: {required: ['path', 'data']}}510  },511  '/session/:sessionId/appium/device/pull_file': {512    POST: {command: 'pullFile', payloadParams: {required: ['path']}}513  },514  '/session/:sessionId/appium/device/pull_folder': {515    POST: {command: 'pullFolder', payloadParams: {required: ['path']}}516  },517  '/session/:sessionId/appium/device/toggle_airplane_mode': {518    POST: {command: 'toggleFlightMode'}519  },520  '/session/:sessionId/appium/device/toggle_data': {521    POST: {command: 'toggleData'}522  },523  '/session/:sessionId/appium/device/toggle_wifi': {524    POST: {command: 'toggleWiFi'}525  },526  '/session/:sessionId/appium/device/toggle_location_services': {527    POST: {command: 'toggleLocationServices'}528  },529  '/session/:sessionId/appium/device/open_notifications': {530    POST: {command: 'openNotifications'}531  },532  '/session/:sessionId/appium/device/start_activity': {533    POST: {534      command: 'startActivity',535      payloadParams: {536        required: ['appPackage', 'appActivity'],537        optional: ['appWaitPackage', 'appWaitActivity', 'intentAction',538          'intentCategory', 'intentFlags', 'optionalIntentArguments', 'dontStopAppOnReset']539      }540    }541  },542  '/session/:sessionId/appium/device/system_bars': {543    GET: {command: 'getSystemBars'}544  },545  '/session/:sessionId/appium/device/display_density': {546    GET: {command: 'getDisplayDensity'}547  },548  '/session/:sessionId/appium/simulator/touch_id': {549    POST: {command: 'touchId', payloadParams: {required: ['match']}}550  },551  '/session/:sessionId/appium/simulator/toggle_touch_id_enrollment': {552    POST: {command: 'toggleEnrollTouchId', payloadParams: {optional: ['enabled']}}553  },554  '/session/:sessionId/appium/app/launch': {555    POST: {command: 'launchApp'}556  },557  '/session/:sessionId/appium/app/close': {558    POST: {command: 'closeApp'}559  },560  '/session/:sessionId/appium/app/reset': {561    POST: {command: 'reset'}562  },563  '/session/:sessionId/appium/app/background': {564    POST: {command: 'background', payloadParams: {required: ['seconds']}}565  },566  '/session/:sessionId/appium/app/end_test_coverage': {567    POST: {command: 'endCoverage', payloadParams: {required: ['intent', 'path']}}568  },569  '/session/:sessionId/appium/app/strings': {570    POST: {command: 'getStrings', payloadParams: {optional: ['language', 'stringFile']}}571  },572  '/session/:sessionId/appium/element/:elementId/value': {573    POST: {command: 'setValueImmediate', payloadParams: {574      validate: (jsonObj) => (!util.hasValue(jsonObj.value) && !util.hasValue(jsonObj.text)) &&575          'we require one of "text" or "value" params',576      optional: ['value', 'text'],577      // We want to either a value (old JSONWP) or a text (new W3C) parameter,578      // but only send one of them to the command (not both).579      // Prefer 'value' since it's more backward-compatible.580      makeArgs: (jsonObj) => [jsonObj.value || jsonObj.text],581    }}582  },583  '/session/:sessionId/appium/element/:elementId/replace_value': {584    POST: {command: 'replaceValue', payloadParams: {585      validate: (jsonObj) => (!util.hasValue(jsonObj.value) && !util.hasValue(jsonObj.text)) &&586          'we require one of "text" or "value" params',587      optional: ['value', 'text'],588      // We want to either a value (old JSONWP) or a text (new W3C) parameter,589      // but only send one of them to the command (not both).590      // Prefer 'value' since it's more backward-compatible.591      makeArgs: (jsonObj) => [jsonObj.value ?? jsonObj.text ?? ''],592    }}593  },594  '/session/:sessionId/appium/settings': {595    POST: {command: 'updateSettings', payloadParams: {required: ['settings']}},596    GET: {command: 'getSettings'}597  },598  '/session/:sessionId/appium/receive_async_response': {599    POST: {command: 'receiveAsyncResponse', payloadParams: {required: ['response']}}600  },601  '/session/:sessionId/appium/execute_driver': {602    POST: {command: 'executeDriverScript', payloadParams: {required: ['script'], optional: ['type', 'timeout']}}603  },604  '/session/:sessionId/appium/events': {605    POST: {command: 'getLogEvents', payloadParams: {optional: ['type']}}606  },607  '/session/:sessionId/appium/log_event': {608    POST: {command: 'logCustomEvent', payloadParams: {required: ['vendor', 'event']}}609  },610  /*611   * The W3C spec has some changes to the wire protocol.612   * https://w3c.github.io/webdriver/webdriver-spec.html613   * Begin to add those changes here, keeping the old version614   * since clients still implement them.615   */616  // old alerts617  '/session/:sessionId/alert_text': {618    GET: {command: 'getAlertText'},619    POST: {620      command: 'setAlertText',621      payloadParams: SET_ALERT_TEXT_PAYLOAD_PARAMS,622    }623  },624  '/session/:sessionId/accept_alert': {625    POST: {command: 'postAcceptAlert'}626  },627  '/session/:sessionId/dismiss_alert': {628    POST: {command: 'postDismissAlert'}629  },630  // https://w3c.github.io/webdriver/webdriver-spec.html#user-prompts631  '/session/:sessionId/alert/text': {632    GET: {command: 'getAlertText'},633    POST: {634      command: 'setAlertText',635      payloadParams: SET_ALERT_TEXT_PAYLOAD_PARAMS,636    }637  },638  '/session/:sessionId/alert/accept': {639    POST: {command: 'postAcceptAlert'}640  },641  '/session/:sessionId/alert/dismiss': {642    POST: {command: 'postDismissAlert'}643  },644  // https://w3c.github.io/webdriver/webdriver-spec.html#get-element-rect645  '/session/:sessionId/element/:elementId/rect': {646    GET: {command: 'getElementRect'}647  },648  '/session/:sessionId/execute/sync': {649    POST: {command: 'execute', payloadParams: {required: ['script', 'args']}}650  },651  '/session/:sessionId/execute/async': {652    POST: {command: 'executeAsync', payloadParams: {required: ['script', 'args']}}653  },654  // Pre-W3C endpoint for element screenshot655  '/session/:sessionId/screenshot/:elementId': {656    GET: {command: 'getElementScreenshot'}657  },658  '/session/:sessionId/element/:elementId/screenshot': {659    GET: {command: 'getElementScreenshot'}660  },661  '/session/:sessionId/window/rect': {662    GET: {command: 'getWindowRect'},663    POST: {command: 'setWindowRect', payloadParams: {required: ['x', 'y', 'width', 'height']}},664  },665  '/session/:sessionId/window/maximize': {666    POST: {command: 'maximizeWindow'}667  },668  '/session/:sessionId/window/minimize': {669    POST: {command: 'minimizeWindow'}670  },671  '/session/:sessionId/window/fullscreen': {672    POST: {command: 'fullScreenWindow'}673  },674  '/session/:sessionId/element/:elementId/property/:name': {675    GET: {command: 'getProperty'}676  },677  '/session/:sessionId/appium/device/set_clipboard': {678    POST: {679      command: 'setClipboard',680      payloadParams: {681        required: ['content'],682        optional: [683          'contentType',684          'label',685        ]686      },687    }688  },689  '/session/:sessionId/appium/device/get_clipboard': {690    POST: {691      command: 'getClipboard',692      payloadParams: {693        optional: [694          'contentType',695        ]696      },697    }698  },699  '/session/:sessionId/appium/compare_images': {700    POST: {701      command: 'compareImages',702      payloadParams: {703        required: ['mode', 'firstImage', 'secondImage'],704        optional: ['options']705      },706    }707  },708  // chromium devtools709  // https://chromium.googlesource.com/chromium/src/+/master/chrome/test/chromedriver/server/http_handler.cc710  '/session/:sessionId/:vendor/cdp/execute': {711    POST: {command: 'executeCdp', payloadParams: {required: ['cmd', 'params']}}712  },713  //region Webauthn714  // https://www.w3.org/TR/webauthn-2/#sctn-automation-add-virtual-authenticator715  '/session/:sessionId/webauthn/authenticator': {716    POST: {717      command: 'addVirtualAuthenticator',718      payloadParams: {719        required: ['protocol', 'transport'],720        optional: ['hasResidentKey', 'hasUserVerification', 'isUserConsenting', 'isUserVerified'],721      }722    }723  },724  '/session/:sessionId/webauthn/authenticator/:authenticatorId': {725    DELETE: {726      command: 'removeVirtualAuthenticator'727    }728  },729  '/session/:sessionId/webauthn/authenticator/:authenticatorId/credential': {730    POST: {731      command: 'addAuthCredential',732      payloadParams: {733        required: ['credentialId', 'isResidentCredential', 'rpId', 'privateKey'],734        optional: ['userHandle', 'signCount'],735      }736    }737  },738  '/session/:sessionId/webauthn/authenticator/:authenticatorId/credentials': {739    GET: {command: 'getAuthCredential'},740    DELETE: {command: 'removeAllAuthCredentials'},741  },742  '/session/:sessionId/webauthn/authenticator/:authenticatorId/credentials/:credentialId': {743    DELETE: {command: 'removeAuthCredential'}744  },745  '/session/:sessionId/webauthn/authenticator/:authenticatorId/uv': {746    POST: {747      command: 'setUserAuthVerified',748      payloadParams: {749        required: ['isUserVerified']750      }751    }752  },753  //endregion754};755// driver command names756let ALL_COMMANDS = [];757for (let v of _.values(METHOD_MAP)) {758  for (let m of _.values(v)) {759    if (m.command) {760      ALL_COMMANDS.push(m.command);761    }762  }763}764const RE_ESCAPE = /[-[\]{}()+?.,\\^$|#\s]/g;765const RE_PARAM = /([:*])(\w+)/g;766class Route {767  constructor (route) {768    this.paramNames = [];769    let reStr = route.replace(RE_ESCAPE, '\\$&');770    reStr = reStr.replace(RE_PARAM, (_, mode, name) => {771      this.paramNames.push(name);772      return mode === ':' ? '([^/]*)' : '(.*)';773    });774    this.routeRegexp = new RegExp(`^${reStr}$`);775  }776  parse (url) {777    //if (url.indexOf('timeouts') !== -1 && this.routeRegexp.toString().indexOf('timeouts') !== -1) {778    //debugger;779    //}780    let matches = url.match(this.routeRegexp);781    if (!matches) return; // eslint-disable-line curly782    let i = 0;783    let params = {};784    while (i < this.paramNames.length) {785      const paramName = this.paramNames[i++];786      params[paramName] = matches[i];787    }788    return params;789  }790}791function routeToCommandName (endpoint, method, basePath = DEFAULT_BASE_PATH) {792  let dstRoute = null;793  // remove any query string794  if (endpoint.includes('?')) {795    endpoint = endpoint.slice(0, endpoint.indexOf('?'));796  }797  const actualEndpoint = endpoint === '/' ? '' :798    (_.startsWith(endpoint, '/') ? endpoint : `/${endpoint}`);799  for (let currentRoute of _.keys(METHOD_MAP)) {800    const route = new Route(`${basePath}${currentRoute}`);801    // we don't care about the actual session id for matching802    if (route.parse(`${basePath}/session/ignored-session-id${actualEndpoint}`) ||803        route.parse(`${basePath}${actualEndpoint}`) || route.parse(actualEndpoint)) {804      dstRoute = currentRoute;805      break;806    }807  }808  if (!dstRoute) return; // eslint-disable-line curly809  const methods = _.get(METHOD_MAP, dstRoute);810  method = _.toUpper(method);811  if (_.has(methods, method)) {812    const dstMethod = _.get(methods, method);813    if (dstMethod.command) {814      return dstMethod.command;815    }816  }817}818// driver commands that do not require a session to already exist819const NO_SESSION_ID_COMMANDS = ['createSession', 'getStatus', 'getSessions'];...

Full Screen

Full Screen

test_routes.js

Source:test_routes.js Github

copy

Full Screen

1import _ from 'lodash';2// define the routes, mapping of HTTP methods to particular driver commands,3// and any parameters that are expected in a request4// parameters can be `required` or `optional`5const METHOD_MAP = {6        '/wd/hub/status': {7            GET: {command: 'getStatus'}8        },9        '/wd/hub/session': {10            POST: {command: 'createSession', payloadParams: {11                validate: (jsonObj) => (!jsonObj.capabilities && !jsonObj.desiredCapabilities) && 'we require one of "desiredCapabilities" or "capabilities" object',12                optional: ['desiredCapabilities', 'requiredCapabilities', 'capabilities']}}13    },14    '/wd/hub/sessions': {15    GET: {command: 'getSessions'}16},17'/wd/hub/session/:sessionId': {18    GET: {command: 'getSession'},19    DELETE: {command: 'deleteSession'}20},21'/wd/hub/session/:sessionId/timeouts': {22    POST: {command: 'timeouts', payloadParams: {required: ['type', 'ms']}}23},24'/wd/hub/session/:sessionId/timeouts/async_script': {25    POST: {command: 'asyncScriptTimeout', payloadParams: {required: ['ms']}}26},27'/wd/hub/session/:sessionId/timeouts/implicit_wait': {28    POST: {command: 'implicitWait', payloadParams: {required: ['ms']}}29},30'/wd/hub/session/:sessionId/window_handle': {31    GET: {command: 'getWindowHandle'}32},33'/wd/hub/session/:sessionId/window_handles': {34    GET: {command: 'getWindowHandles'}35},36'/wd/hub/session/:sessionId/url': {37    GET: {command: 'getUrl'},38    POST: {command: 'setUrl', payloadParams: {required: ['url']}}39},40'/wd/hub/session/:sessionId/forward': {41    POST: {command: 'forward'}42},43'/wd/hub/session/:sessionId/back': {44    POST: {command: 'back'}45},46'/wd/hub/session/:sessionId/refresh': {47    POST: {command: 'refresh'}48},49'/wd/hub/session/:sessionId/execute': {50    POST: {command: 'execute', payloadParams: {required: ['script', 'args']}}51},52'/wd/hub/session/:sessionId/execute_async': {53    POST: {command: 'executeAsync', payloadParams: {required: ['script', 'args']}}54},55'/wd/hub/session/:sessionId/screenshot': {56    GET: {command: 'getScreenshot'}57},58'/wd/hub/session/:sessionId/ime/available_engines': {59    GET: {command: 'availableIMEEngines'}60},61'/wd/hub/session/:sessionId/ime/active_engine': {62    GET: {command: 'getActiveIMEEngine'}63},64'/wd/hub/session/:sessionId/ime/activated': {65    GET: {command: 'isIMEActivated'}66},67'/wd/hub/session/:sessionId/ime/deactivate': {68    POST: {command: 'deactivateIMEEngine'}69},70'/wd/hub/session/:sessionId/ime/activate': {71    POST: {command: 'activateIMEEngine', payloadParams: {required: ['engine']}}72},73'/wd/hub/session/:sessionId/frame': {74    POST: {command: 'setFrame', payloadParams: {required: ['id']}}75},76'/wd/hub/session/:sessionId/frame/parent': {77    POST: {}78},79'/wd/hub/session/:sessionId/window': {80    POST: {command: 'setWindow', payloadParams: {required: ['name']}},81    DELETE: {command: 'closeWindow'}82},83'/wd/hub/session/:sessionId/window/:windowhandle/size': {84    GET: {command: 'getWindowSize'},85    POST: {}86},87'/wd/hub/session/:sessionId/window/:windowhandle/position': {88    POST: {},89    GET: {}90},91'/wd/hub/session/:sessionId/window/:windowhandle/maximize': {92    POST: {command: 'maximizeWindow'}93},94'/wd/hub/session/:sessionId/cookie': {95    GET: {command: 'getCookies'},96    POST: {command: 'setCookie', payloadParams: {required: ['cookie']}},97    DELETE: {command: 'deleteCookies'}98},99'/wd/hub/session/:sessionId/cookie/:name': {100    DELETE: {command: 'deleteCookie'}101},102'/wd/hub/session/:sessionId/source': {103    GET: {command: 'getPageSource'}104},105'/wd/hub/session/:sessionId/title': {106    GET: {command: 'title'}107},108'/wd/hub/session/:sessionId/element': {109    POST: {command: 'findElement', payloadParams: {required: ['using', 'value']}}110},111'/wd/hub/session/:sessionId/elements': {112    POST: {command: 'findElements', payloadParams: {required: ['using', 'value']}}113},114'/wd/hub/session/:sessionId/element/active': {115    POST: {command: 'active'}116},117'/wd/hub/session/:sessionId/element/:elementId': {118    GET: {}119},120'/wd/hub/session/:sessionId/element/:elementId/element': {121    POST: {command: 'findElementFromElement', payloadParams: {required: ['using', 'value']}}122},123'/wd/hub/session/:sessionId/element/:elementId/elements': {124    POST: {command: 'findElementsFromElement', payloadParams: {required: ['using', 'value']}}125},126'/wd/hub/session/:sessionId/element/:elementId/click': {127    POST: {command: 'click'}128},129'/wd/hub/session/:sessionId/element/:elementId/submit': {130    POST: {command: 'submit'}131},132'/wd/hub/session/:sessionId/element/:elementId/text': {133    GET: {command: 'getText'}134},135'/wd/hub/session/:sessionId/element/:elementId/value': {136    POST: {command: 'setValue', payloadParams: {137        validate: (jsonObj) => {138            return (!jsonObj.value && !jsonObj.text) &&139                'we require one of "text" or "value" params';140        },141        optional: ['value', 'text'],142            makeArgs: (jsonObj) => {143            // override the default argument constructor because of the special144            // logic here. Basically we want to accept either a value (old JSONWP)145            // or a text (new W3C) parameter, but only send one of them to the146            // command (not both). Prefer 'value' since it's more147            // backward-compatible.148            return [jsonObj.value || jsonObj.text];149        }150    }}151},152'/wd/hub/session/:sessionId/keys': {153    POST: {command: 'keys', payloadParams: {required: ['value']}}154},155'/wd/hub/session/:sessionId/element/:elementId/name': {156    GET: {command: 'getName'}157},158'/wd/hub/session/:sessionId/element/:elementId/clear': {159    POST: {command: 'clear'}160},161'/wd/hub/session/:sessionId/element/:elementId/selected': {162    GET: {command: 'elementSelected'}163},164'/wd/hub/session/:sessionId/element/:elementId/enabled': {165    GET: {command: 'elementEnabled'}166},167'/wd/hub/session/:sessionId/element/:elementId/attribute/:name': {168    GET: {command: 'getAttribute'}169},170'/wd/hub/session/:sessionId/element/:elementId/equals/:otherId': {171    GET: {command: 'equalsElement'}172},173'/wd/hub/session/:sessionId/element/:elementId/displayed': {174    GET: {command: 'elementDisplayed'}175},176'/wd/hub/session/:sessionId/element/:elementId/location': {177    GET: {command: 'getLocation'}178},179'/wd/hub/session/:sessionId/element/:elementId/location_in_view': {180    GET: {command: 'getLocationInView'}181},182'/wd/hub/session/:sessionId/element/:elementId/size': {183    GET: {command: 'getSize'}184},185'/wd/hub/session/:sessionId/element/:elementId/css/:propertyName': {186    GET: {command: 'getCssProperty'}187},188'/wd/hub/session/:sessionId/orientation': {189    GET: {command: 'getOrientation'},190    POST: {command: 'setOrientation', payloadParams: {required: ['orientation']}}191},192'/wd/hub/session/:sessionId/rotation': {193    GET: {command: 'getRotation'},194    POST: {command: 'setRotation', payloadParams: {required: ['x', 'y', 'z']}}195},196'/wd/hub/session/:sessionId/moveto': {197    POST: {command: 'moveTo', payloadParams: {optional: ['element', 'xoffset', 'yoffset']}}198},199'/wd/hub/session/:sessionId/click': {200    POST: {command: 'clickCurrent', payloadParams: {optional: ['button']}}201},202'/wd/hub/session/:sessionId/buttondown': {203    POST: {}204},205'/wd/hub/session/:sessionId/buttonup': {206    POST: {}207},208'/wd/hub/session/:sessionId/doubleclick': {209    POST: {}210},211'/wd/hub/session/:sessionId/touch/click': {212    POST: {command: 'click', payloadParams: {required: ['element']}}213},214'/wd/hub/session/:sessionId/touch/down': {215    POST: {command: 'touchDown', payloadParams: {required: ['x', 'y']}}216},217'/wd/hub/session/:sessionId/touch/up': {218    POST: {command: 'touchUp', payloadParams: {required: ['x', 'y']}}219},220'/wd/hub/session/:sessionId/touch/move': {221    POST: {command: 'touchMove', payloadParams: {required: ['x', 'y']}}222},223'/wd/hub/session/:sessionId/touch/scroll': {224    POST: {}225},226'/wd/hub/session/:sessionId/touch/doubleclick': {227    POST: {}228},229'/wd/hub/session/:sessionId/touch/longclick': {230    POST: {command: 'touchLongClick', payloadParams: {required: ['elements']}}231},232'/wd/hub/session/:sessionId/touch/flick': {233    POST: {command: 'flick', payloadParams: {optional: ['element', 'xspeed', 'yspeed', 'xoffset', 'yoffset', 'speed']}}234},235'/wd/hub/session/:sessionId/location': {236    GET: {command: 'getGeoLocation'},237    POST: {command: 'setGeoLocation', payloadParams: {required: ['location']}}238},239'/wd/hub/session/:sessionId/local_storage': {240    GET: {},241    POST: {},242    DELETE: {}243},244'/wd/hub/session/:sessionId/local_storage/key/:key': {245    GET: {},246    DELETE: {}247},248'/wd/hub/session/:sessionId/local_storage/size': {249    GET: {}250},251'/wd/hub/session/:sessionId/session_storage': {252    GET: {},253    POST: {},254    DELETE: {}255},256'/wd/hub/session/:sessionId/session_storage/key/:key': {257    GET: {},258    DELETE: {}259},260'/wd/hub/session/:sessionId/session_storage/size': {261    GET: {}262},263'/wd/hub/session/:sessionId/log': {264    POST: {command: 'getLog', payloadParams: {required: ['type']}}265},266'/wd/hub/session/:sessionId/log/types': {267    GET: {command: 'getLogTypes'}268},269'/wd/hub/session/:sessionId/application_cache/status': {270    GET: {}271},272//273// mjsonwire274//275'/wd/hub/session/:sessionId/context': {276    GET: {command: 'getCurrentContext'},277    POST: {command: 'setContext', payloadParams: {required: ['name']}}278},279'/wd/hub/session/:sessionId/contexts': {280    GET: {command: 'getContexts'}281},282'/wd/hub/session/:sessionId/element/:elementId/pageIndex': {283    GET: {command: 'getPageIndex'}284},285'/wd/hub/session/:sessionId/network_connection': {286    GET: {command: 'getNetworkConnection'},287    POST: {command: 'setNetworkConnection', payloadParams: {unwrap: 'parameters', required: ['type']}}288},289'/wd/hub/session/:sessionId/touch/perform': {290    POST: {command: 'performTouch', payloadParams: {wrap: 'actions', required: ['actions']}}291},292'/wd/hub/session/:sessionId/touch/multi/perform': {293    POST: {command: 'performMultiAction', payloadParams: {required: ['actions'], optional: ['elementId']}}294},295'/wd/hub/session/:sessionId/receive_async_response': {296    POST: {command: 'receiveAsyncResponse', payloadParams: {required: ['status', 'value']}}297},298'/wd/hub/session/:sessionId/appium/device/shake': {299    POST: {command: 'mobileShake'}300},301'/wd/hub/session/:sessionId/appium/device/system_time': {302    GET: {command: 'getDeviceTime'}303},304'/wd/hub/session/:sessionId/appium/device/lock': {305    POST: {command: 'lock', payloadParams: {optional: ['seconds']}}306},307'/wd/hub/session/:sessionId/appium/device/unlock': {308    POST: {command: 'unlock'}309},310'/wd/hub/session/:sessionId/appium/device/is_locked': {311    POST: {command: 'isLocked'}312},313'/wd/hub/session/:sessionId/appium/start_recording_screen': {314    POST: {command: 'startRecordingScreen', payloadParams: {required: ['filePath', 'videoSize', 'timeLimit', 'bitRate']}}315},316'/wd/hub/session/:sessionId/appium/stop_recording_screen': {317    POST: {command: 'stopRecordingScreen'}318},319'/wd/hub/session/:sessionId/appium/performanceData/types': {320    POST: {command: 'getPerformanceDataTypes'}321},322'/wd/hub/session/:sessionId/appium/getPerformanceData': {323    POST: {command: 'getPerformanceData', payloadParams: {required: ['packageName', 'dataType'], optional: ['dataReadTimeout']}}324},325'/wd/hub/session/:sessionId/appium/device/press_keycode': {326    POST: {command: 'pressKeyCode', payloadParams: {required: ['keycode'], optional: ['metastate']}}327},328'/wd/hub/session/:sessionId/appium/device/long_press_keycode': {329    POST: {command: 'longPressKeyCode', payloadParams: {required: ['keycode'], optional: ['metastate']}}330},331'/wd/hub/session/:sessionId/appium/device/finger_print': {332    POST: {command: 'fingerprint', payloadParams: {required: ['fingerprintId']}}333},334'/wd/hub/session/:sessionId/appium/device/send_sms': {335    POST: {command: 'sendSMS', payloadParams: {required: ['phoneNumber', 'message']}}336},337'/wd/hub/session/:sessionId/appium/device/gsm_call': {338    POST: {command: 'gsmCall', payloadParams: {required: ['phoneNumber', 'action']}}339},340'/wd/hub/session/:sessionId/appium/device/gsm_signal': {341    POST: {command: 'gsmSignal', payloadParams: {required: ['signalStrength']}}342},343'/wd/hub/session/:sessionId/appium/device/gsm_voice': {344    POST: {command: 'gsmVoice', payloadParams: {required: ['state']}}345},346'/wd/hub/session/:sessionId/appium/device/power_capacity': {347    POST: {command: 'powerCapacity', payloadParams: {required: ['percent']}}348},349'/wd/hub/session/:sessionId/appium/device/power_ac': {350    POST: {command: 'powerAC', payloadParams: {required: ['state']}}351},352'/wd/hub/session/:sessionId/appium/device/network_speed': {353    POST: {command: 'networkSpeed', payloadParams: {required: ['netspeed']}}354},355'/wd/hub/session/:sessionId/appium/device/keyevent': {356    POST: {command: 'keyevent', payloadParams: {required: ['keycode'], optional: ['metastate']}}357},358'/wd/hub/session/:sessionId/appium/device/rotate': {359    POST: {command: 'mobileRotation', payloadParams: {360        required: ['x', 'y', 'radius', 'rotation', 'touchCount', 'duration'],361            optional: ['element'] }}362},363'/wd/hub/session/:sessionId/appium/device/current_activity': {364    GET: {command: 'getCurrentActivity'}365},366'/wd/hub/session/:sessionId/appium/device/current_package': {367    GET: {command: 'getCurrentPackage'}368},369'/wd/hub/session/:sessionId/appium/device/install_app': {370    POST: {command: 'installApp', payloadParams: {required: ['appPath']}}371},372'/wd/hub/session/:sessionId/appium/device/remove_app': {373    POST: {command: 'removeApp', payloadParams: {required: [['appId'], ['bundleId']]}}374},375'/wd/hub/session/:sessionId/appium/device/app_installed': {376    POST: {command: 'isAppInstalled', payloadParams: {required: ['bundleId']}}377},378'/wd/hub/session/:sessionId/appium/device/hide_keyboard': {379    POST: {command: 'hideKeyboard', payloadParams: {optional: ['strategy', 'key', 'keyCode', 'keyName']}}380},381'/wd/hub/session/:sessionId/appium/device/is_keyboard_shown': {382    GET: {command: 'isKeyboardShown'}383},384'/wd/hub/session/:sessionId/appium/device/push_file': {385    POST: {command: 'pushFile', payloadParams: {required: ['path', 'data']}}386},387'/wd/hub/session/:sessionId/appium/device/pull_file': {388    POST: {command: 'pullFile', payloadParams: {required: ['path']}}389},390'/wd/hub/session/:sessionId/appium/device/pull_folder': {391    POST: {command: 'pullFolder', payloadParams: {required: ['path']}}392},393'/wd/hub/session/:sessionId/appium/device/toggle_airplane_mode': {394    POST: {command: 'toggleFlightMode'}395},396'/wd/hub/session/:sessionId/appium/device/toggle_data': {397    POST: {command: 'toggleData'}398},399'/wd/hub/session/:sessionId/appium/device/toggle_wifi': {400    POST: {command: 'toggleWiFi'}401},402'/wd/hub/session/:sessionId/appium/device/toggle_location_services': {403    POST: {command: 'toggleLocationServices'}404},405'/wd/hub/session/:sessionId/appium/device/open_notifications': {406    POST: {command: 'openNotifications'}407},408'/wd/hub/session/:sessionId/appium/device/start_activity': {409    POST: {command: 'startActivity', payloadParams: {required: ['appPackage', 'appActivity'],410        optional: ['appWaitPackage', 'appWaitActivity',411        'intentAction', 'intentCategory',412        'intentFlags', 'optionalIntentArguments',413        'dontStopAppOnReset']}}414},415'/wd/hub/session/:sessionId/appium/device/system_bars': {416    GET: {command: 'getSystemBars'}417},418'/wd/hub/session/:sessionId/appium/device/display_density': {419    GET: {command: 'getDisplayDensity'}420},421'/wd/hub/session/:sessionId/appium/simulator/touch_id': {422    POST: {command: 'touchId', payloadParams: {required: ['match']}}423},424'/wd/hub/session/:sessionId/appium/simulator/toggle_touch_id_enrollment': {425    POST: {command: 'toggleEnrollTouchId', payloadParams: {optional: ['enabled']}}426},427'/wd/hub/session/:sessionId/appium/app/launch': {428    POST: {command: 'launchApp'}429},430'/wd/hub/session/:sessionId/appium/app/close': {431    POST: {command: 'closeApp'}432},433'/wd/hub/session/:sessionId/appium/app/reset': {434    POST: {command: 'reset'}435},436'/wd/hub/session/:sessionId/appium/app/background': {437    POST: {command: 'background', payloadParams: {required: ['seconds']}}438},439'/wd/hub/session/:sessionId/appium/app/end_test_coverage': {440    POST: {command: 'endCoverage', payloadParams: {required: ['intent', 'path']}}441},442'/wd/hub/session/:sessionId/appium/app/strings': {443    POST: {command: 'getStrings', payloadParams: {optional: ['language', 'stringFile']}}444},445'/wd/hub/session/:sessionId/appium/element/:elementId/value': {446    POST: {command: 'setValueImmediate', payloadParams: {required: ['value']}}447},448'/wd/hub/session/:sessionId/appium/element/:elementId/replace_value': {449    POST: {command: 'replaceValue', payloadParams: {required: ['value']}}450},451'/wd/hub/session/:sessionId/appium/settings': {452    POST: {command: 'updateSettings', payloadParams: {required: ['settings']}},453    GET: {command: 'getSettings'}454},455'/wd/hub/session/:sessionId/appium/receive_async_response': {456    POST: {command: 'receiveAsyncResponse', payloadParams: {required: ['response']}}457},458/*459 * The W3C spec has some changes to the wire protocol.460 * https://w3c.github.io/webdriver/webdriver-spec.html461 * Begin to add those changes here, keeping the old version462 * since clients still implement them.463 */464// old alerts465'/wd/hub/session/:sessionId/alert_text': {466    GET: {command: 'getAlertText'},467    POST: {command: 'setAlertText', payloadParams: {required: ['text']}}468},469'/wd/hub/session/:sessionId/accept_alert': {470    POST: {command: 'postAcceptAlert'}471},472'/wd/hub/session/:sessionId/dismiss_alert': {473    POST: {command: 'postDismissAlert'}474},475// https://w3c.github.io/webdriver/webdriver-spec.html#user-prompts476'/wd/hub/session/:sessionId/alert/text': {477    GET: {command: 'getAlertText'},478    POST: {command: 'setAlertText', payloadParams: {required: ['text']}}479},480'/wd/hub/session/:sessionId/alert/accept': {481    POST: {command: 'postAcceptAlert'}482},483'/wd/hub/session/:sessionId/alert/dismiss': {484    POST: {command: 'postDismissAlert'}485},486// https://w3c.github.io/webdriver/webdriver-spec.html#get-element-rect487'/wd/hub/session/:sessionId/element/:elementId/rect': {488    GET: {command: 'getElementRect'}489},490};491// driver command names492let ALL_COMMANDS = [];493for (let v of _.values(METHOD_MAP)) {494    for (let m of _.values(v)) {495        if (m.command) {496            ALL_COMMANDS.push(m.command);497        }498    }499}500const RE_ESCAPE = /[\-\[\]{}()+?.,\\\^$|#\s]/g;501const RE_PARAM = /([:*])(\w+)/g;502class Route {503    constructor (route) {504        this.paramNames = [];505        let reStr = route.replace(RE_ESCAPE, "\\$&");506        reStr = reStr.replace(RE_PARAM, (_, mode, name) => {507            this.paramNames.push(name);508        return mode === ":" ? "([^/]*)" : "(.*)";509    });510        this.routeRegexp = new RegExp(`^${reStr}$`);511    }512    parse (url) {513        let matches = url.match(this.routeRegexp);514        if (!matches) return; // eslint-disable-line curly515        let i = 0;516        let params = {};517        while (i < this.paramNames.length) {518            const paramName = this.paramNames[i++];519            params[paramName] = matches[i];520        }521        return params;522    }523}524function routeToCommandName (endpoint, method) {525    let dstRoute = null;526    const actualEndpoint = _.startsWith(endpoint, '/') ? endpoint : `/${endpoint}`;527    for (let currentRoute of _.keys(METHOD_MAP)) {528        const route = new Route(currentRoute);529        // we don't care about the actual session id for matching530        if (route.parse(`/wd/hub/session/ignored-session-id${actualEndpoint}`) ||531            route.parse(`/wd/hub${actualEndpoint}`) || route.parse(actualEndpoint)) {532            dstRoute = currentRoute;533            break;534        }535    }536    if (!dstRoute) return; // eslint-disable-line curly537    const methods = _.get(METHOD_MAP, dstRoute);538    if (_.has(methods, method)) {539        const dstMethod = _.get(methods, method);540        if (dstMethod.command) {541            return dstMethod.command;542        }543    }544}545// driver commands that do not require a session to already exist546const NO_SESSION_ID_COMMANDS = ['createSession', 'getStatus', 'getSessions'];...

Full Screen

Full Screen

proxy.js

Source:proxy.js Github

copy

Full Screen

...178  }179  requestToCommandName (url, method) {180    const extractCommandName = (pattern) => {181      const pathMatch = pattern.exec(url);182      return pathMatch ? routeToCommandName(pathMatch[1], method) : null;183    };184    let commandName = routeToCommandName(url, method);185    if (!commandName && _.includes(url, '/wd/hub/session/')) {186      commandName = extractCommandName(/\/wd\/hub\/session\/[^/]+(.+)/);187    }188    if (!commandName && _.includes(url, '/wd/hub/')) {189      commandName = extractCommandName(/\/wd\/hub(\/.+)/);190    }191    return commandName;192  }193  async proxyCommand (url, method, body = null) {194    const commandName = this.requestToCommandName(url, method);195    if (!commandName) {196      return await this.proxy(url, method, body);197    }198    log.debug(`Matched '${url}' to command name '${commandName}'`);...

Full Screen

Full Screen

routes-specs.js

Source:routes-specs.js Github

copy

Full Screen

...38    });39  });40  describe('check route to command name conversion', function () {41    it('should properly lookup correct command name for endpoint with session', function () {42      const cmdName = routeToCommandName('/timeouts', 'POST');43      cmdName.should.equal('timeouts');44    });45    it('should properly lookup correct command name for endpoint with session', function () {46      const cmdName = routeToCommandName('/timeouts/implicit_wait', 'POST');47      cmdName.should.equal('implicitWait');48    });49    it('should properly lookup correct command name for endpoint without session', function () {50      const cmdName = routeToCommandName('/status', 'GET');51      cmdName.should.equal('getStatus');52    });53    it('should properly lookup correct command name for endpoint without leading slash', function () {54      const cmdName = routeToCommandName('status', 'GET');55      cmdName.should.equal('getStatus');56    });57    it('should properly lookup correct command name for fully specified endpoint', function () {58      const cmdName = routeToCommandName('/wd/hub/status', 'GET');59      cmdName.should.equal('getStatus');60    });61    it('should not find command name if incorrect input data has been specified', function () {62      for (let [route, method] of [['/wd/hub/status', 'POST'], ['/xstatus', 'GET'], ['status', 'POST']]) {63        const cmdName = routeToCommandName(route, method);64        chai.should().equal(cmdName, undefined);65      }66    });67  });...

Full Screen

Full Screen

proxy-helper.js

Source:proxy-helper.js Github

copy

Full Screen

...18  const proxy = isSessionCommand ? this.wda.jwproxy : this.wda.noSessionProxy;19  if (!proxy) {20    throw new Error("Can't call proxyCommand without WDA proxy active");21  }22  const cmdName = routeToCommandName(endpoint, method);23  const timeout = this._getCommandTimeout(cmdName);24  let res = null;25  if (timeout) {26    log.debug(`Setting custom timeout to ${timeout} ms for "${cmdName}" command`);27    let isCommandExpired = false;28    res = await B.Promise.resolve(proxy.command(endpoint, method, body))29                  .timeout(timeout)30                  .catch(B.Promise.TimeoutError, () => {31                    isCommandExpired = true;32                  });33    if (isCommandExpired) {34      proxy.cancelActiveRequests();35      const errMsg = `Appium did not get any response from "${cmdName}" command in ${timeout} ms`;36      await this.startUnexpectedShutdown(new errors.TimeoutError(errMsg));...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1// transpile:main2import { Protocol, isSessionCommand,3         routeConfiguringFunction } from './protocol';4import { NO_SESSION_ID_COMMANDS, ALL_COMMANDS, METHOD_MAP,5         routeToCommandName } from './routes';6import { errors, isErrorType, errorFromMJSONWPStatusCode, errorFromW3CJsonCode } from './errors';7export {8  Protocol, routeConfiguringFunction, errors, isErrorType,9  errorFromMJSONWPStatusCode, errorFromW3CJsonCode, ALL_COMMANDS, METHOD_MAP,10  routeToCommandName, NO_SESSION_ID_COMMANDS, isSessionCommand,...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const BaseDriver = require('appium-base-driver');2const routeToCommandName = BaseDriver.prototype.routeToCommandName;3const commandName = routeToCommandName('POST', '/wd/hub/session/1234567890/appium/device/press_keycode');4const AndroidDriver = require('appium-android-driver');5const routeToCommandName = AndroidDriver.prototype.routeToCommandName;6const commandName = routeToCommandName('POST', '/wd/hub/session/1234567890/appium/device/press_keycode');7const IosDriver = require('appium-ios-driver');8const routeToCommandName = IosDriver.prototype.routeToCommandName;9const commandName = routeToCommandName('POST', '/wd/hub/session/1234567890/appium/device/press_keycode');10const WindowsDriver = require('appium-windows-driver');11const routeToCommandName = WindowsDriver.prototype.routeToCommandName;12const commandName = routeToCommandName('POST', '/wd/hub/session/1234567890/appium/device/press_keycode');13const MacDriver = require('appium-mac-driver');14const routeToCommandName = MacDriver.prototype.routeToCommandName;15const commandName = routeToCommandName('POST', '/wd/hub/session/1234567890/appium/device/press_keycode');16const YouiEngineDriver = require('appium-youiengine-driver');17const routeToCommandName = YouiEngineDriver.prototype.routeToCommandName;18const commandName = routeToCommandName('POST', '/wd/hub/session/1234567890/appium/device/press_keycode');19const EspressoDriver = require('app

Full Screen

Using AI Code Generation

copy

Full Screen

1var BaseDriver = require('appium-base-driver').BaseDriver;2var driver = new BaseDriver();3var route = driver.routeToCommandName('POST', '/wd/hub/session/1234567890/element/1/click');4console.log(route);5{ route: 'elementIdClick', method: 'POST' }6    route = route.replace(/\/$/, '');7    route = route.split('/');8    route.shift();9    route.shift();10    route = route.pop();11    route = `${method.toLowerCase()}${route.charAt(0).toUpperCase() + route.slice(1)}`;12    return route;13}14let command = this.routeToCommandName(method, url);15    if (!this[command]) {16      throw new errors.UnknownCommandError();17    }18    return await this[command](...args);19let command = this.routeToCommandName(method, url);20    if (!this[command]) {21      throw new errors.UnknownCommandError();22    }23    return await this[command](...args);24let command = this.routeToCommandName(method, url);25    if (!this[command]) {26      throw new errors.UnknownCommandError();27    }28    return await this[command](...args);29let command = this.routeToCommandName(method, url);30    if (!this[command]) {31      throw new errors.UnknownCommandError();32    }33    return await this[command](...args);34let command = this.routeToCommandName(method, url);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { routeToCommandName } = require('appium-base-driver');2const commandName = routeToCommandName('POST', '/session/:sessionId/appium/element/:elementId/value');3console.log(commandName);4const { routeToCommandName } = require('appium');5const commandName = routeToCommandName('POST', '/session/:sessionId/appium/element/:elementId/value');6console.log(commandName);7const { commands } = require('appium-base-driver');8const commandName = commands.getCommandName('POST', '/session/:sessionId/appium/element/:elementId/value');9console.log(commandName);10const { commands } = require('appium');11const commandName = commands.getCommandName('POST', '/session/:sessionId/appium/element/:elementId/value');12console.log(commandName);

Full Screen

Using AI Code Generation

copy

Full Screen

1let BaseDriver = require('appium-base-driver');2let routeToCommandName = BaseDriver.prototype.routeToCommandName;3let routeToCommandNameResult = routeToCommandName('get', '/some/path');4console.log(routeToCommandNameResult);5let BaseDriver = require('appium-base-driver');6let routeToCommandName = BaseDriver.prototype.routeToCommandName;7let routeToCommandNameResult = routeToCommandName('get', '/some/path/:id');8console.log(routeToCommandNameResult);9let BaseDriver = require('appium-base-driver');10let routeToCommandName = BaseDriver.prototype.routeToCommandName;11let routeToCommandNameResult = routeToCommandName('get', '/some/path/:id/:name');12console.log(routeToCommandNameResult);13let BaseDriver = require('appium-base-driver');14let routeToCommandName = BaseDriver.prototype.routeToCommandName;15let routeToCommandNameResult = routeToCommandName('get', '/some/path/:id/:name/:age');16console.log(routeToCommandNameResult);17let BaseDriver = require('appium-base-driver');18let routeToCommandName = BaseDriver.prototype.routeToCommandName;19let routeToCommandNameResult = routeToCommandName('get', '/some/path/:id/:name/:age/:location');20console.log(routeToCommandNameResult);21let BaseDriver = require('appium-base-driver');22let routeToCommandName = BaseDriver.prototype.routeToCommandName;23let routeToCommandNameResult = routeToCommandName('get', '/some/path/:id/:name/:age/:location/:country');24console.log(routeToCommandNameResult);

Full Screen

Using AI Code Generation

copy

Full Screen

1const BaseDriver = require('appium-base-driver');2const driver = new BaseDriver();3console.log(driver.routeToCommandName('POST', '/session/1234567890/appium/device/lock'));4const AndroidDriver = require('appium-android-driver');5const driver = new AndroidDriver();6console.log(driver.routeToCommandName('POST', '/session/1234567890/appium/device/lock'));7const IosDriver = require('appium-ios-driver');8const driver = new IosDriver();9console.log(driver.routeToCommandName('POST', '/session/1234567890/appium/device/lock'));10const WindowsDriver = require('appium-windows-driver');11const driver = new WindowsDriver();12console.log(driver.routeToCommandName('POST', '/session/1234567890/appium/device/lock'));13const MacDriver = require('appium-mac-driver');14const driver = new MacDriver();15console.log(driver.routeToCommandName('POST', '/session/1234567890/appium/device/lock'));16const YouiEngineDriver = require('appium-youiengine-driver');17const driver = new YouiEngineDriver();18console.log(driver.routeToCommandName('POST', '/session/1234567890/appium/device/lock'));19const EspressoDriver = require('appium-espresso-driver');20const driver = new EspressoDriver();21console.log(driver.routeToCommandName('POST', '/session/1234567890/appium/device/lock'));22const XCUITestDriver = require('appium-xcuitest-driver');23const driver = new XCUITestDriver();24console.log(driver.routeToCommandName('POST', '/session/1234567890/appium/device/lock'));

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