How to use device.remove method in Appium Xcuitest Driver

Best JavaScript code snippet using appium-xcuitest-driver

editorinput.js

Source:editorinput.js Github

copy

Full Screen

1/*global debug: false*/2/*global Editor: false*/3Editor.Input =4{5    // State!!!6    state :7    {8        pressedKeys : {},9        pressedButtons : {},10        mouseDeltaX : 0.0,11        mouseDeltaY : 0.0,12        mouseX : 0.0,13        mouseY : 0.0,14        mouseWheelDelta : 0.0,15        mouseEnter : false,16        mouseLeave : false,17        blur : false18    },19    previousState :20    {21        pressedKeys : {},22        pressedButtons : {},23        mouseDeltaX : 0.0,24        mouseDeltaY : 0.0,25        mouseX : 0.0,26        mouseY : 0.0,27        mouseWheelDelta : 0.0,28        mouseEnter : false,29        mouseLeave : false,30        blur : false31    },32    eventHandlersActive : false,33    getCurrentState : function editorinputstateGetCurrentStateFn()34    {35        return Editor.Input.state;36    },37    getPreviousState : function editorinputstateGetPreviousStateFn()38    {39        return Editor.Input.previousState;40    },41    clearState : function editorinputClearStateFn()42    {43        var state = Editor.Input.state;44        state.pressedKeys = {};45        state.pressedButtons = {};46    },47    updateState : function editorinputstateUpdateStateFn()48    {49        Editor.Input.previousState = Editor.Input.state;50        var previousKeyState = Editor.Input.previousState.pressedKeys;51        var previousButtonState = Editor.Input.previousState.pressedButtons;52        var newKeyState = {};53        var newMouseState = {};54        var keyName;55        var buttonName;56        for (keyName in previousKeyState)57        {58            if (previousKeyState.hasOwnProperty(keyName))59            {60                newKeyState[keyName] = previousKeyState[keyName];61            }62        }63        for (buttonName in previousButtonState)64        {65            if (previousButtonState.hasOwnProperty(buttonName))66            {67                newMouseState[buttonName] = previousButtonState[buttonName];68            }69        }70        Editor.Input.state =71        {72            pressedKeys : newKeyState,73            pressedButtons : newMouseState,74            mouseDeltaX : 0.0,75            mouseDeltaY : 0.0,76            mouseX : 0,77            mouseY : 0,78            mouseWheelDelta : 0.0,79            mouseEnter : false,80            mouseLeave : false,81            blur : false82        };83    },84    // State query methods85    isMouseDown : function editorinputstateIsMouseDownFn(inputState, mouseCode)86    {87        return (inputState.pressedButtons[mouseCode] ? true : false);88    },89    wasMousePressed : function editorinputWasMousePressedFn(inputState, previousInputState, mouseCode)90    {91        return (inputState.pressedButtons[mouseCode] && !previousInputState.pressedButtons[mouseCode]);92    },93    wasMouseReleased : function editorinputWasMouseReleasedFn(inputState, previousInputState, mouseCode)94    {95        return (!inputState.pressedButtons[mouseCode] && previousInputState.pressedButtons[mouseCode]);96    },97    isKeyDown : function editorinputIsKeyDownFn(inputState, keyCode)98    {99        return (inputState.pressedKeys[keyCode] ? true : false);100    },101    wasKeyPressed : function editorinputstateWasPressedFn(inputState, previousInputState, keyCode)102    {103        return (inputState.pressedKeys[keyCode] && !previousInputState.pressedKeys[keyCode]);104    },105    wasKeyReleased : function editorinputstateWasReleasedFn(inputState, previousInputState, keyCode)106    {107        return (!inputState.pressedKeys[keyCode] && previousInputState.pressedKeys[keyCode]);108    },109    wasMouseEntered : function editorinputWasMouseEnteredFn(inputState)110    {111        return inputState.mouseEnter;112    },113    wasMouseLeft : function editorinputWasMouseLeftFn(inputState)114    {115        return inputState.mouseLeave;116    },117    wasBlurred : function editorinputWasBlurredFn(inputState)118    {119        return inputState.wasBlurred;120    },121    getMouseDeltaX : function editorinputGetMouseDeltaXFn(inputState)122    {123        return inputState.mouseDeltaX;124    },125    getMouseX : function editorinputGetMouseXFn(inputState)126    {127        return inputState.mouseX;128    },129    getMouseY : function editorinputGetMouseYFn(inputState)130    {131        return inputState.mouseY;132    },133    getMouseDeltaY : function editorinputGetMouseDeltaYFn(inputState)134    {135        return inputState.mouseDeltaY;136    },137    getMouseWheelDelta : function editorinputGetMouseWheelDelta(inputState)138    {139        return inputState.mouseWheelDelta;140    },141    // Event handlers142    onKeyDown : function editorinputstateOnKeyDownFn(keyCode)143    {144        this.state.pressedKeys[keyCode] = true;145    },146    onKeyUp : function editorinputstateOnKeyUpFn(keyCode)147    {148        this.state.pressedKeys[keyCode] = false;149    },150    onMouseDown : function editorinputstateOnMouseDownFn(buttonCode /*, x, y*/)151    {152        this.state.pressedButtons[buttonCode] = true;153        if (buttonCode === this.inputDevice.mouseCodes.BUTTON_1)154        {155            this.inputDevice.lockMouse();156            this.inputDevice.hideMouse();157        }158    },159    onMouseUp : function editorinputstateOnMouseUpFn(buttonCode /*, x, y*/)160    {161        this.state.pressedButtons[buttonCode] = false;162        if (buttonCode === this.inputDevice.mouseCodes.BUTTON_1)163        {164            this.inputDevice.unlockMouse();165            this.inputDevice.showMouse();166        }167    },168    onMouseMove : function editorinputOnMouseMoveFn(deltaX, deltaY)169    {170        this.state.mouseDeltaX += deltaX;171        this.state.mouseDeltaY += deltaY;172    },173    onMouseOver : function editorinputOnMouseOverFn(x, y)174    {175        this.state.mouseX = x;176        this.state.mouseY = y;177    },178    onMouseWheel : function editorinputOnMouseWheelFn(delta)179    {180        this.state.mouseWheelDelta += delta;181    },182    onMouseEnter : function editorinputOnMouseEnterFn()183    {184        this.state.mouseEnter = true;185    },186    onMouseLeave : function editorinputOnMouseLeaveFn()187    {188        this.state.mouseLeave = true;189    },190    onBlur : function editorinputOnBlurFn()191    {192        this.clearState();193        this.state.blur = true;194    },195    addEventHandlers : function editorinputstateAddEventHandlersFn(inputDevice)196    {197        debug.assert(!Editor.Input.eventHandlersActive, 'Trying to re-add editor input event handlers.');198        Editor.Input.eventHandlersActive = true;199        if (!this.onKeyUpBound)200        {201            this.onKeyUpBound = this.onKeyUp.bind(this);202            this.onKeyDownBound = this.onKeyDown.bind(this);203            this.onMouseUpBound = this.onMouseUp.bind(this);204            this.onMouseDownBound = this.onMouseDown.bind(this);205            this.onMouseMoveBound = this.onMouseMove.bind(this);206            this.onMouseWheelBound = this.onMouseWheel.bind(this);207            this.onMouseOverBound = this.onMouseOver.bind(this);208            this.onMouseEnterBound = this.onMouseEnter.bind(this);209            this.onMouseLeaveBound = this.onMouseLeave.bind(this);210            this.onBlurBound = this.onBlur.bind(this);211        }212        inputDevice.addEventListener('keyup', this.onKeyUpBound);213        inputDevice.addEventListener('keydown', this.onKeyDownBound);214        inputDevice.addEventListener('mouseup', this.onMouseUpBound);215        inputDevice.addEventListener('mousedown', this.onMouseDownBound);216        inputDevice.addEventListener('mousemove', this.onMouseMoveBound);217        inputDevice.addEventListener('mousewheel', this.onMouseWheelBound);218        inputDevice.addEventListener('mouseover', this.onMouseOverBound);219        inputDevice.addEventListener('mouseenter', this.onMouseEnterBound);220        inputDevice.addEventListener('mouseleave', this.onMouseLeaveBound);221        inputDevice.addEventListener('blur', this.onBlurBound);222        this.inputDevice = inputDevice;223    },224    removeEventHandlers : function editorinputstateRemoveEventHandlersFn(inputDevice)225    {226        debug.assert(Editor.Input.eventHandlersActive, 'Trying to remove editor input event handlers which were never added.');227        Editor.Input.eventHandlersActive = false;228        inputDevice.removeEventListener('keyup', this.onKeyUpBound);229        inputDevice.removeEventListener('keydown', this.onKeyDownBound);230        inputDevice.removeEventListener('mouseup', this.onMouseUpBound);231        inputDevice.removeEventListener('mousedown', this.onMouseDownBound);232        inputDevice.removeEventListener('mousemove', this.onMouseMoveBound);233        inputDevice.removeEventListener('mousewheel', this.onMouseWheelBound);234        inputDevice.removeEventListener('mouseover', this.onMouseOverBound);235        inputDevice.removeEventListener('mouseenter', this.onMouseEnterBound);236        inputDevice.removeEventListener('mouseleave', this.onMouseLeaveBound);237        inputDevice.removeEventListener('blur', this.onBlurBound);238        delete this.inputDevice;239    }...

Full Screen

Full Screen

device_controller_specs.js

Source:device_controller_specs.js Github

copy

Full Screen

1var mongoose = require('mongoose');2var db = mongoose.createConnection();3require("../../models/device");4var Device = mongoose.model('Device');5var User = mongoose.model('User');6var device_controller = require("../../controllers/device_controller");7var should = require('should');8var passport = require("passport"),9	BasicStrategy = require('passport-http').BasicStrategy;10describe('DeviceController', function() {11	before(function() {12		mongoose.connect(config.db);13	});14	describe('register with a new device (minimum fields)', function() {15		var _posted_model = {16			guid: 'guid',17			name: 'name'18		};19		var _result;20		var _status_code;21		before(function(done) {22			User.remove({}, function() {23				Device.remove({}, function() {24					var req = {25						body: _posted_model,26						headers: []27					};28					var res = {29						status: function(status_code) {30							_status_code = status_code;31						},32						send: function(object) {33							_result = object;34							done();35						}36					};37					device_controller.create(req, res, function() {});38				});39			});40		});41		it("should create a new device", function(done) {42			Device.count({}, function(err, count) {43				count.should.equal(1);44				done();45			});46		});47		it('should create device with correct guid', function(done) {48			Device.count({49				guid: _posted_model.guid50			}, function(err, count) {51				count.should.equal(1);52				done();53			});54		});55		it('should save all the fields', function(done) {56			Device.findOne({57				guid: _posted_model.guid58			}, function(err, saved) {59				saved.guid.should.equal(_posted_model.guid);60				saved.name.should.equal(_posted_model.name);61				done();62			});63		});64		it('should return correct device', function(done) {65			Device.findOne({66				guid: _posted_model.guid67			}, function(err, saved) {68				_result.guid.should.equal(saved.guid);69				_result.id.should.equal(saved.id);70				_result.name.should.equal(saved.name);71				done();72			});73		});74		it('should return token', function() {75			_result.token.should.exist;76		});77		after(function(done) {78			User.remove({}, function() {79				Device.remove({}, function() {80					done();81				});82			});83		});84	});85	describe('register with a new device (all fields)', function() {86		var _posted_model = {87			guid: 'guid',88			name: 'name',89			user: {90				facebook_id: 'facebook_id',91				email: 'user@user.com',92				name: 'user'93			}94		};95		var _result;96		var _status_code;97		before(function(done) {98			User.remove({}, function() {99				Device.remove({}, function() {100					var req = {101						body: _posted_model,102						headers: []103					};104					var res = {105						status: function(status_code) {106							_status_code = status_code;107						},108						send: function(object) {109							_result = object;110							done();111						}112					};113					device_controller.create(req, res);114				});115			});116		});117		it("should create a new device", function(done) {118			Device.count({}, function(err, count) {119				count.should.equal(1);120				done();121			});122		});123		it('should create device with correct guid', function(done) {124			Device.count({125				guid: _posted_model.guid126			}, function(err, count) {127				count.should.equal(1);128				done();129			});130		})131		it('should save the correct name', function(done) {132			Device.findOne({133				guid: _posted_model.guid134			}, function(err, saved) {135				saved.name.should.equal(_posted_model.name);136				done();137			});138		});139		it('should save a user', function(done) {140			User.count({}, function(err, count) {141				count.should.equal(1);142				done();143			});144		});145		it('should return correct device', function(done) {146			Device.findOne({147				guid: _posted_model.guid148			}, function(err, saved) {149				_result.guid.should.equal(saved.guid);150				_result.id.should.equal(saved.id);151				_result.name.should.equal(saved.name);152				done();153			});154		});155		it('should return token', function() {156			_result.token.should.exist;157		});158		after(function(done) {159			User.remove({}, function() {160				Device.remove({}, function() {161					done();162				});163			});164		});165	});166	describe('register with an existing guid', function() {167		var _posted_model = {168			guid: 'guid',169			name: 'name'170		};171		var _result;172		var _status_code;173		before(function(done) {174			User.remove({}, function() {175				Device.remove({}, function() {176					var existing_device = new Device(_posted_model);177					existing_device.name = 'existing';178					existing_device.save(function() {179						var req = {180							body: _posted_model,181							headers: []182						};183						req.headers["authorization"] = "Basic " + new Buffer(existing_device.guid + ':' + existing_device.token).toString('base64')184						var res = {185							status: function(status_code) {186								_status_code = status_code;187							},188							send: function(object) {189								_result = object;190								done();191							}192						};193						device_controller.create(req, res, function() {});194					});195				});196			});197		});198		it("should not create a new device", function(done) {199			Device.count({}, function(err, count) {200				count.should.equal(1);201				done();202			});203		});204		it('should return correct device', function(done) {205			Device.findOne({206				guid: _posted_model.guid207			}, function(err, saved) {208				_result.guid.should.equal(saved.guid);209				_result.id.should.equal(saved.id);210				_result.name.should.equal(saved.name);211				done();212			});213		});214		it('should not return token', function() {215			should.not.exist(_result.token);216		});217		after(function(done) {218			User.remove({}, function() {219				Device.remove({}, function() {220					done();221				});222			});223		});224	});225	describe('register without specifying a guid', function() {226		var _posted_model = {227			name: 'name'228		};229		var _result;230		var _status_code;231		before(function(done) {232			User.remove({}, function() {233				Device.remove({}, function() {234					var req = {235						body: _posted_model,236						headers: []237					};238					var res = {239						status: function(status_code) {240							_status_code = status_code;241						},242						send: function(object) {243							_result = object;244							done();245						}246					};247					device_controller.create(req, res);248				});249			});250		});251		it("should not create a new device", function(done) {252			Device.count({}, function(err, count) {253				count.should.equal(0);254				done();255			});256		});257		it('should return an error', function() {258			_result.errors.guid.type.should.equal('required');259		});260		it('should return a 400 status code', function() {261			_status_code.should.equal(400);262		});263		after(function(done) {264			User.remove({}, function() {265				Device.remove({}, function() {266					done();267				});268			});269		});270	});271	describe('register without specifying a name', function() {272		var _posted_model = {273			guid: 'guid'274		};275		var _result;276		var _status_code;277		before(function(done) {278			User.remove({}, function() {279				Device.remove({}, function() {280					var req = {281						body: _posted_model,282						headers: []283					};284					var res = {285						status: function(status_code) {286							_status_code = status_code;287						},288						send: function(object) {289							_result = object;290							done();291						}292					};293					device_controller.create(req, res);294				});295			});296		});297		it("should not create a new device", function(done) {298			Device.count({}, function(err, count) {299				count.should.equal(0);300				done();301			});302		});303		it('should return an error', function() {304			_result.errors.name.type.should.equal('required');305		});306		it('should return a 400 status code', function() {307			_status_code.should.equal(400);308		});309		after(function(done) {310			Device.remove({}, function() {311				done();312			});313		});314	});315	after(function(done) {316		User.remove({}, function() {317			Device.remove({}, function() {318				mongoose.disconnect(function() {319					done();320				});321			});322		});323	});...

Full Screen

Full Screen

remove-panel.js

Source:remove-panel.js Github

copy

Full Screen

1/**2 * Copyright 2019 Arcus Project3 * 4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 * 8 *     http://www.apache.org/licenses/LICENSE-2.09 * 10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16import Analytics from 'i2web/plugins/analytics';17import Component from 'can-component';18import CanMap from 'can-map';19import 'can-map-define';20import Errors from 'i2web/plugins/errors';21import view from './remove-panel.stache';22import SidePanel from 'i2web/plugins/side-panel';23import Notifications from 'i2web/plugins/notifications';24import getAppState from 'i2web/plugins/get-app-state';25const STAGES = {26  REMOVING: 1,27  TIMED_OUT: 99,28  ERROR: 100,29};30const REMOVAL = {31  AUTOMATIC: 'HUB_AUTOMATIC',32  MANUAL: 'HUB_MANUAL',33  CLOUD: 'CLOUD',34};35export const ViewModel = CanMap.extend({36  define: {37    /**38     * @property {CanMap} device39     * @parent i2web/components/device/remove-panel40     * @description the device being removed41     */42    device: { Type: CanMap },43    /**44     * @property {number} removeTimeOutLength45     * @parent i2web/components/device/remove-panel46     * @description milliseconds to wait for the RemoveResponse to arrive47     */48    removeTimeOutLength: {49      type: 'number',50      value: 4 * 60 * 1000,51    },52    /**53     * @property {boolean} removeTimedOut54     * @parent i2web/components/device/remove-panel55     * @description if the wait for RemoveResponse ended up finishing56     */57    removeTimedOut: {58      type: 'boolean',59      value: false,60    },61    /**62     * @property {CanMap} removeResponse63     * @parent i2web/components/device/remove-panel64     * @description the payload of the RemoveResponse message that arrived in response to the initial Remove call65     */66    removeResponse: { Type: CanMap },67    /**68     * @property {CanMap} removeError69     * @parent i2web/components/device/remove-panel70     * @description the error produced during the initial Remove call71     */72    removeError: { value: null },73    /**74     * @property {CanList} removeSteps75     * @parent i2web/components/device/remove-panel76     * @description the steps of the removal process described in the RemoveResponse payload77     */78    removeSteps: {79      get() {80        return this.attr('removeResponse.steps');81      },82    },83    /**84     * @property {string} removalMode85     * @parent i2web/components/device/remove-panel86     * @description The method of removal required for this device. Attempt to guess via device protocol,87     * updating when we receive the removeResponse which tells us conclusively.88     */89    removalMode: {90      get() {91        const device = this.attr('device');92        const removeResponse = this.attr('removeResponse');93        if (removeResponse) {94          return this.attr('removeResponse.mode');95        }96        // if we don't have the remove response yet, guess until we do97        if (device.attr('isZigBee')) {98          return REMOVAL.AUTOMATIC;99        }100        if (device.attr('isZWave')) {101          return REMOVAL.MANUAL;102        }103        return REMOVAL.CLOUD;104      },105    },106    /**107     * @property {Boolean} showStepCount108     * @parent i2web/components/device/remove-panel109     * @description Only should the remove step number if the number of steps110     * is greater than 1.111     */112    showStepCount: {113      get() {114        return this.attr('removeSteps.length') > 1;115      },116    },117    /**118     * @property {boolean} isCancelling119     * @parent i2web/components/device/remove-panel120     * @description if a request to cancel the removal of this device is ongoing.121     */122    isCancelling: {123      type: 'boolean',124      value: false,125    },126    /**127     * @property {array} tip128     * @parent i2web/components/device/remove-panel129     * @description A tip string for the current removal step.130     */131    tip: {132      get() {133        const tip = this.attr('removeSteps.0.title');134        if (tip) {135          tip.replace(/^TIP:/, ''); // replace prefix if found136        }137        return tip;138      },139    },140    /**141     * @property {string} stage142     * @parent i2web/components/device/remove-panel143     * @description a keyword indicating a subview presented by this component144     */145    stage: {146      get() {147        if (this.attr('removeTimedOut')) {148          return STAGES.TIMED_OUT;149        }150        if (this.attr('removeError')) {151          return STAGES.ERROR;152        }153        return STAGES.REMOVING;154      },155    },156  },157  // create notification and close self158  success() {159    Notifications.success('Device has been removed.');160    SidePanel.close();161    this.cancelTimeout();162  },163  // cancels the ongoing removal process. if removal mode is hub manual we'll164  // make a request to cancel the ongoing unpairing.165  async cancel() {166    if (this.attr('removalMode') === REMOVAL.MANUAL) {167      const hub = getAppState().attr('hub');168      this.attr('isCancelling', true);169      try {170        await hub.UnpairingRequest('STOP_UNPAIRING');171        SidePanel.close();172      } catch (e) {173        Errors.log(e);174      } finally {175        this.attr('isCancelling', false);176      }177    } else {178      SidePanel.close();179    }180  },181  // call force remove, this will result in a base:Deleted that calls success()182  forceRemove() {183    Analytics.tag('device.more.forceremove');184    this.attr('device').ForceRemove();185  },186  // start timer that will transition the stage if the removal process takes too long187  startTimeout() {188    // halt any old timeout189    const timeout = this.attr('timeout');190    if (timeout) { clearTimeout(timeout); }191    // start timeout for removal to complete192    this.attr('timeout', setTimeout(() => {193      this.attr('removeTimedOut', true);194    }, this.removeTimeOutLength));195  },196  // cancel timeout that would've transitioned the stage if we were waiting too long197  cancelTimeout() {198    clearTimeout(this.attr('timeout'));199    this.removeAttr('timeout');200  },201  STAGES,202  REMOVAL,203});204export default Component.extend({205  tag: 'arcus-device-remove-panel',206  viewModel: ViewModel,207  view,208  events: {209    // call remove and add response/error to view model. also begin timeout waiting for removal to complete210    async inserted() {211      const vm = this.viewModel;212      vm.startTimeout();213      try {214        Analytics.tag('device.more.remove');215        const response = await vm.attr('device').Remove();216        vm.attr('removeResponse', response);217      } catch (e) {218        vm.attr('removeError', e);219        Errors.log(e);220      }221    },222    '{viewModel.device} base:Deleted': function deletionHandler() {223      // delay so we don't flash through views too quickly when unpairing a fast224      // device. Could eliminate this delay if we don't mind that, or we could implement225      // it in a smarter way (i.e only delay up to a maximum of say 3 seconds after component insertion)226      setTimeout(() => this.viewModel.success(), 2000);227    },228    '{viewModel} stage': function stageChangeHandler(vm, ev, newVal, oldVal) {229      // if we ever leave the removing stage, an exception of some sort has occurred, cancel the timeout230      if (oldVal === STAGES.REMOVING) {231        this.viewModel.cancelTimeout();232      }233    },234  },...

Full Screen

Full Screen

device_api_tests.js

Source:device_api_tests.js Github

copy

Full Screen

1var app = require("../../app");2var request = require('supertest');3var mongoose = require('mongoose');4var should = require('should');5var http = require('http');6require("../../models/device");7var Device = mongoose.model('Device');8var User = mongoose.model('User');9describe('device api', function() {10	var server;11	var result;12	before(function() {13		mongoose.connect(config.db);14	});15	describe('post new device', function() {16		before(function(done) {17			request(http.createServer(app))18				.post('/devices')19				.send({20				name: 'test device',21				guid: 'testguid'22			})23				.end(function(err, res) {24				result = res;25				done();26			});27		});28		it('should return correct status', function() {29			result.statusCode.should.equal(200);30		});31		it('should create a new device', function(done) {32			Device.count({}, function(err, count) {33				count.should.equal(1);34				done();35			});36		});37		after(function(done) {38			Device.remove({}, function() {39				done();40			});41		});42	});43	describe('post update to existing device authenticated', function() {44		var existing_device;45		before(function(done) {46			existing_device = new Device({47				name: "existing name",48				guid: "testguid"49			});50			existing_device.save(function() {51				request(http.createServer(app))52					.post('/devices')53					.auth(existing_device.guid, existing_device.token)54					.send({55					name: 'updated device',56					guid: 'testguid'57				})58					.end(function(err, res) {59					result = res;60					done();61				});62			})63		});64		it('should return correct status', function() {65			result.statusCode.should.equal(200);66		});67		it('should not create a new device', function(done) {68			Device.count({}, function(err, count) {69				count.should.equal(1);70				done();71			});72		});73		it('should update existing device', function(done) {74			Device.findById(existing_device.id, function(err, device) {75				device.name.should.equal("updated device");76				done();77			});78		});79		after(function(done) {80			Device.remove({}, function() {81				User.remove({}, function() {82					done();83				});84			});85		});86	});87	describe('post update to existing device user, with no existing matching user, authenticated', function() {88		var existing_device;89		before(function(done) {90			existing_device = new Device({91				name: "existing name",92				guid: "testguid"93			});94			existing_device.save(function() {95				request(http.createServer(app))96					.post('/devices')97					.auth(existing_device.guid, existing_device.token)98					.send({99					name: 'existing name',100					guid: 'testguid',101					user: {102						facebook_id: 'facebook_id',103						name: 'my user',104						email: 'user@email.com'105					}106				})107					.end(function(err, res) {108					result = res;109					done();110				});111			})112		});113		it('should return correct status', function() {114			result.statusCode.should.equal(200);115		});116		it('should not create a new device', function(done) {117			Device.count({}, function(err, count) {118				count.should.equal(1);119				done();120			});121		});122		it('should add user to existing device', function(done) {123			Device.findById(existing_device.id, function(err, device) {124				device.user.should.exist;125				done();126			});127		});128		it('should return a user object in the response', function() {129			result.body.user.name.should.equal('my user');130		});131		it('should save user', function(done) {132			User.count({}, function(err, count) {133				count.should.equal(1);134				done();135			})136		});137		after(function(done) {138			Device.remove({}, function() {139				User.remove({}, function() {140					done();141				});142			});143		});144	});145	describe('post update to existing device user, with existing matching user, authenticated', function() {146		var existing_device;147		before(function(done) {148			existing_device = new Device({149				name: "existing name",150				guid: "testguid"151			});152			var existing_user = new User({153				facebook_id: 'facebook_id',154				name: 'my user',155				email: 'user@email.com'156			});157			existing_user.save(function() {158				existing_device.save(function() {159					request(http.createServer(app))160						.post('/devices')161						.auth(existing_device.guid, existing_device.token)162						.send({163						name: 'existing name',164						guid: 'testguid',165						user: {166							facebook_id: 'facebook_id',167							name: 'my user',168							email: 'user@email.com'169						}170					})171						.end(function(err, res) {172						result = res;173						done();174					});175				});176			});177		});178		it('should return correct status', function() {179			result.statusCode.should.equal(200);180		});181		it('should not create a new device', function(done) {182			Device.count({}, function(err, count) {183				count.should.equal(1);184				done();185			});186		});187		it('should add user to existing device', function(done) {188			Device.findById(existing_device.id, function(err, device) {189				device.user.should.exist;190				done();191			});192		});193		it('should return a user object in the response', function() {194			result.body.user.name.should.equal('my user');195		});196		it('should not save a new user',function(done){197			User.count({}, function(err, count) {198				count.should.equal(1);199				done();200			})201		})202		after(function(done) {203			User.remove({}, function() {204				Device.remove({}, function() {205					done();206				});207			});208		});209	});210	describe('post update to existing device unauthenticated', function() {211		var existing_device;212		before(function(done) {213			existing_device = new Device({214				name: "existing name",215				guid: "testguid"216			});217			existing_device.save(function() {218				request(http.createServer(app))219					.post('/devices')220					.send({221					name: 'updated device',222					guid: 'testguid'223				})224					.end(function(err, res) {225					result = res;226					done();227				});228			})229		});230		it('should return unauthorised status', function() {231			result.statusCode.should.equal(401);232		});233		it('should not create a new device', function(done) {234			Device.count({}, function(err, count) {235				count.should.equal(1);236				done();237			});238		});239		it('should not update existing device', function(done) {240			Device.findById(existing_device.id, function(err, device) {241				device.name.should.equal("existing name");242				done();243			});244		});245		after(function(done) {246			Device.remove({}, function() {247				done();248			});249		});250	});251	describe('post update to existing device authenticated as wrong device', function() {252		var existing_device;253		var existing_device2;254		before(function(done) {255			existing_device = new Device({256				name: "existing name",257				guid: "testguid"258			});259			existing_device2 = new Device({260				guid: 'other_guid',261				name: 'other device'262			});263			existing_device2.save(function() {264				existing_device.save(function() {265					request(http.createServer(app))266						.post('/devices')267						.auth(existing_device2.guid, existing_device2.token)268						.send({269						name: 'updated device',270						guid: 'testguid'271					})272						.end(function(err, res) {273						result = res;274						done();275					});276				});277			});278		});279		it('should return unauthorised status', function() {280			result.statusCode.should.equal(401);281		});282		it('should not create a new device', function(done) {283			Device.count({}, function(err, count) {284				count.should.equal(2);285				done();286			});287		});288		it('should not update existing device', function(done) {289			Device.findById(existing_device.id, function(err, device) {290				device.name.should.equal("existing name");291				done();292			});293		});294		after(function(done) {295			Device.remove({}, function() {296				done();297			});298		});299	});300	after(function(done) {301		Device.remove({}, function() {302			mongoose.disconnect(function() {303				done();304			});305		});306	});...

Full Screen

Full Screen

dbAccess.js

Source:dbAccess.js Github

copy

Full Screen

...49function removeDevice(data){50   switch(data.key) {51      case 'User':    //Removes all the devices of a user52            if (data.username != 'undefined')53            { device.remove({ 'username': data.username }, function(err, obj) { if (err) throw err; }) }54            break;55      case 'Device':  //remove one single device, depending on the ID56            if (data.Device != 'undefined')57            { device.remove({ 'device': data.device }, function(err, obj) { if (err) throw err; }) }58            break;59      default: ;60   }61}62function removeFriendship(data){63 console.log("call arrives" + data.id + "the id" + data.key + "the key" );64 var ID = data.id;65   switch(data.key) {66      case 'ID':            //*** might not be needed67            if (ID != 'undefined')68            { friendship.remove({ 'ID': ID }, function(err, obj) { if (err) throw err; }) }69            break;70      case 'User':            //delete all friendships assigned to a user71                if (data.user != 'undefined')72                { friendship.remove({$or: [{ 'user_1': data.username}, { 'user_2': data.username}]}, function(err, obj) { if (err) throw err; }) }73                break;74      case 'Friendship':    //remove the friendship transaction between user_1 and user_275           if (user_1 != 'undefined' && user_2 != 'undefined')76           {77           friendship.remove({$or: [{ 'user_1': user_1, 'user_2': user_2 }, { 'user_2': user_1, 'user_1': user_2 }]},78           function(err, obj) { if (err) throw err; })79           }80           break;81      default: ;82   }83}84function removeUser(data){85var username = data.username;86if(typeof username != 'undefined'){87   friendship.remove({ 'user_1': username }, function(err, obj) { if (err) throw err; })88   friendship.remove({ 'user_2': username }, function(err, obj) { if (err) throw err; })89   device.remove({ 'username': username }, function(err, obj) { if (err) throw err; })90  }91}92//export function result93module.exports = {94    find: function (data) {95       if (data.type == constants.Friendship) {96           return findFriendship(data);97       }else if (data.type == constants.Device) {98           return findDevice(data);99       }else if (data.type == constants.User) {100                 return findUser(data);101             }102    },103   remove: function (data){...

Full Screen

Full Screen

devices_actions.js

Source:devices_actions.js Github

copy

Full Screen

1import { DEVICES_ACTIONS } from '../consts/action_types';2/*3export const DEVICES_ACTIONS = {4  ITEM_PREVIEW: 'DEVICES_ITEM_PREVIEW',5  ITEM_VIEW: 'DEVICES_ITEM_VIEW',6  ITEM_ADD: 'DEVICES_ITEM_ADD',7  ITEM_REMOVE: 'DEVICES_ITEM_REMOVE',8};9*/10export const SET_CURRENT_DEVICE = 'SET_CURRENT_DEVICE'11export const SET_FOCUS_DEVICE = 'SET_FOCUS_DEVICE'12export const SELECT_DEVICE = 'SELECT_DEVICE'13export const UNSELECT_DEVICE = 'UNSELECT_DEVICE'14export const FETCH_DEVICES = 'FETCH_DEVICES'15export const REQUEST_DEVICES = 'REQUEST_DEVICES'16export const RECEIVE_DEVICES = 'RECEIVE_DEVICES'17export const RECEIVE_FAIL_DEVICES = 'RECEIVE_FAIL_DEVICES'18export const DEVICE_ADD = 'DEVICE_ADD'19export const DEVICE_ADD_REQUEST = 'DEVICE_ADD_REQUEST'20export const DEVICE_ADD_DONE = 'DEVICE_ADD_DONE'21export const DEVICE_ADD_FAIL = 'DEVICE_ADD_FAIL'22export const DEVICE_EDIT = 'DEVICE_EDIT'23export const DEVICE_EDIT_REQUEST = 'DEVICE_EDIT_REQUEST'24export const DEVICE_EDIT_DONE = 'DEVICE_EDIT_DONE'25export const DEVICE_EDIT_FAIL = 'DEVICE_EDIT_FAIL'26export const DEVICE_REMOVE = 'DEVICE_REMOVE'27export const DEVICE_REMOVE_REQUEST = 'DEVICE_REMOVE_REQUEST'28export const DEVICE_REMOVE_DONE = 'DEVICE_REMOVE_DONE'29export const DEVICE_REMOVE_FAIL = 'DEVICE_REMOVE_FAIL'30export const DEVICE_EDIT_POSITION = 'DEVICE_EDIT_POSITION'31export const DEVICE_EDIT_POSITION_REQUEST = 'DEVICE_EDIT_POSITION_REQUEST'32export const DEVICE_EDIT_POSITION_DONE = 'DEVICE_EDIT_POSITION_DONE'33export const DEVICE_EDIT_POSITION_FAIL = 'DEVICE_EDIT_POSITION_FAIL'34export const SELECT_REDDIT = 'SELECT_REDDIT'35export const INVALIDATE_REDDIT = 'INVALIDATE_REDDIT'36export const setCurrentDevice = (device) => ({ type: SET_CURRENT_DEVICE, device, })37export const setFocusDevice = (device) => ({ type: SET_FOCUS_DEVICE, device, })38export const selectDevice = (device) => ({ type: SELECT_DEVICE, device, })39export const unselectDevice = (device) => ({ type: UNSELECT_DEVICE, device, })40export const fetchDevices = () => ({ type: FETCH_DEVICES })41export const requestDevices = () => ({ type: REQUEST_DEVICES })42export const receiveDevices = (list) => ({ type: RECEIVE_DEVICES, list, receivedAt: Date.now(), })43export const receiveFailDevices = (error) => ({ type: RECEIVE_FAIL_DEVICES, error, })44export const addDevice = (device) => ({ type: DEVICE_ADD, device, })45export const requestAddDevice = (device) => ({ type: DEVICE_ADD_REQUEST, device, })46export const receiveAddDevice = (device) => ({ type: DEVICE_ADD_DONE, device, })47export const receiveFailAddDevice = (error) => ({ type: DEVICE_ADD_FAIL, error, })48export const setDevice = (device) => ({ type: DEVICE_EDIT, device, })49export const requestSetDevice = (device) => ({ type: DEVICE_EDIT_REQUEST, device, })50export const receiveSetDevice = (device) => ({ type: DEVICE_EDIT_DONE, device, })51export const receiveFailSetDevice = (error) => ({ type: DEVICE_EDIT_FAIL, error, })52export const removeDevice = (device) => ({ type: DEVICE_REMOVE, device, })53export const requestRemoveDevice = (device) => ({ type: DEVICE_REMOVE_REQUEST, device, })54export const receiveRemoveDevice = (device) => ({ type: DEVICE_REMOVE_DONE, device, })55export const receiveFailRemoveDevice = (error) => ({ type: DEVICE_REMOVE_FAIL, error, })56export const setDevicePosition = (device) => ({ type: DEVICE_EDIT_POSITION, device, })57export const requestSetDevicePosition = (device) => ({ type: DEVICE_EDIT_POSITION_REQUEST, device, })58export const receiveSetDevicePosition = (device) => ({ type: DEVICE_EDIT_POSITION_DONE, device, })59export const receiveFailSetDevicePosition = (error) => ({ type: DEVICE_EDIT_POSITION_FAIL, error, })60export const previewItem = id => ({61	type: DEVICES_ACTIONS.ITEM_PREVIEW,62	id,63});64export const viewItem = id => ({65	type: DEVICES_ACTIONS.ITEM_VIEW,66	id,67});68export const addItem = item => ({69	type: DEVICES_ACTIONS.ITEM_ADD,70	item,71});72export const removeItem = id => ({73  type: DEVICES_ACTIONS.ITEM_REMOVE,74  id,...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1/*2* Copyright 2013 Research In Motion Limited.3*4* Licensed under the Apache License, Version 2.0 (the "License");5* you may not use this file except in compliance with the License.6* You may obtain a copy of the License at7*8* http://www.apache.org/licenses/LICENSE-2.09*10* Unless required by applicable law or agreed to in writing, software11* distributed under the License is distributed on an "AS IS" BASIS,12* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13* See the License for the specific language governing permissions and14* limitations under the License.15*/16describe("Battery", function () {17    var _apiDir = __dirname + "./../../../../plugins/Battery/src/blackberry10/",18        index,19        callback,20        mockPluginResult = {21            ok: jasmine.createSpy(),22            error: jasmine.createSpy(),23            noResult: jasmine.createSpy(),24            callbackOk: jasmine.createSpy()25        },26        noop = function () {},27        args,28        env = {29            webview: {30                id: 4231            }32        };33    beforeEach(function () {34        GLOBAL.window = {35            qnx: {36                webplatform: {37                    device: {38                        addEventListener: jasmine.createSpy("webplatform.device.addEventListener").andCallFake(function (evt, cb) {39                            callback = cb;40                        }),41                        removeEventListener: jasmine.createSpy("webplatform.device.removeEventListener")42                    }43                }44            }45        };46        GLOBAL.PluginResult = function () {47            return mockPluginResult;48        };49        index = require(_apiDir + "index");50    });51    afterEach(function () {52        delete GLOBAL.window;53        delete GLOBAL.PluginResult;54        delete require.cache[require.resolve(_apiDir + "index")];55    });56    describe("start", function () {57        it("calls noResult and keeps callbacks", function () {58            index.start(noop, noop, args, env);59            expect(window.qnx.webplatform.device.removeEventListener).not.toHaveBeenCalled();60            expect(window.qnx.webplatform.device.addEventListener).toHaveBeenCalled();61            expect(mockPluginResult.noResult).toHaveBeenCalledWith(true);62            expect(mockPluginResult.error).not.toHaveBeenCalled();63        });64        it("callback calls ok and keeps callbacks", function () {65            callback("OK");66            expect(mockPluginResult.callbackOk).toHaveBeenCalledWith("OK", true);67            expect(mockPluginResult.error).not.toHaveBeenCalled();68        });69        it("does not call error if already started", function () {70            index.start(noop, noop, args, env);71            window.qnx.webplatform.device.addEventListener.reset();72            mockPluginResult.noResult.reset();73            index.start(noop, noop, args, env);74            expect(window.qnx.webplatform.device.removeEventListener).toHaveBeenCalled();75            expect(window.qnx.webplatform.device.addEventListener).toHaveBeenCalled();76            expect(mockPluginResult.error).not.toHaveBeenCalled();77            expect(mockPluginResult.noResult).toHaveBeenCalledWith(true);78        });79    });80    describe("stop", function () {81        it("calls noResult and does not keep callbacks", function () {82            index.start(noop, noop, args, env);83            window.qnx.webplatform.device.removeEventListener.reset();84            index.stop(noop, noop, args, env);85            expect(window.qnx.webplatform.device.removeEventListener).toHaveBeenCalled();86            expect(mockPluginResult.noResult).toHaveBeenCalledWith(false);87        });88    });...

Full Screen

Full Screen

deviceRemove.js

Source:deviceRemove.js Github

copy

Full Screen

1/*2 * Wire3 * Copyright (C) 2018 Wire Swiss GmbH4 *5 * This program is free software: you can redistribute it and/or modify6 * it under the terms of the GNU General Public License as published by7 * the Free Software Foundation, either version 3 of the License, or8 * (at your option) any later version.9 *10 * This program is distributed in the hope that it will be useful,11 * but WITHOUT ANY WARRANTY; without even the implied warranty of12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the13 * GNU General Public License for more details.14 *15 * You should have received a copy of the GNU General Public License16 * along with this program. If not, see http://www.gnu.org/licenses/.17 *18 */19'use strict';20window.z = window.z || {};21window.z.components = z.components || {};22z.components.DeviceRemove = class DeviceRemove {23  constructor(params, component_info) {24    this.dispose = this.dispose.bind(this);25    this.device = ko.unwrap(params.device);26    this.device_remove_error = params.error || ko.observable(false);27    this.model = this.device.model;28    this.remove_form_visible = ko.observable(false);29    this.password = ko.observable('');30    this.password_subscription = this.password.subscribe(value => {31      if (value.length > 0) {32        return this.device_remove_error(false);33      }34    });35    this.click_on_submit = function() {36      if (typeof params.remove === 'function') {37        params.remove(this.password(), this.device);38      }39    };40    this.click_on_cancel = () => {41      this.remove_form_visible(false);42      if (typeof params.cancel === 'function') {43        params.cancel();44      }45    };46    this.click_on_remove_device = () => {47      this.remove_form_visible(true);48    };49  }50  dispose() {51    this.password_subscription.dispose();52  }53};54ko.components.register('device-remove', {55  template: `56    <!-- ko ifnot: remove_form_visible() -->57      <span class="device-remove-button text-red"58          data-bind="attr: {'data-uie-value': model}, click: click_on_remove_device, l10n_text: z.string.preferencesDevicesRemove"59          data-uie-name="go-remove-device"></span>60    <!-- /ko -->61    <!-- ko if: remove_form_visible() -->62      <form class="device-remove-form" data-bind="submit: click_on_submit, attr: {'data-uie-value': model}" data-ui-name="device-remove-form">63        <input  class="device-remove-input"64                type="password"65                data-bind="hasfocus: true, textInput: password, l10n_placeholder: z.string.authPlaceholderPasswordPut, css: {'device-remove-input-error': device_remove_error}"66                data-uie-name="remove-device-password" />67        <button class="device-remove-button-remove button button-medium button-fluid"68                data-bind="attr: {'data-uie-value': model}, l10n_text: z.string.preferencesDevicesRemove"69                data-uie-name="do-remove-device"70                type="submit"></button>71        <button class="device-remove-button text-graphite text-underline"72                data-bind="click: click_on_cancel, l10n_text: z.string.preferencesDevicesRemoveCancel"73                data-uie-name="remove-device-cancel"></button>74      </form>75    <!-- /ko -->76  `,77  viewModel: {78    createViewModel(params, component_info) {79      return new z.components.DeviceRemove(params, component_info);80    },81  },...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { remote } = require('webdriverio');const { remote } = require('webdriverio');2(async () => {3    const browser = await remote({4        logLe(el: 'trace',5        capabilities: {6        }7    })8    anait browscr.deleteSession();9})().catch((e) => console.error(e));

Full Screen

Using AI Code Generation

copy

Full Screen

1var we () => {2    const browser = await remote({3        capabilities: {4        }5    })6    await browser.deleteSession();7})().catch((e) => console.error(e));

Full Screen

Using AI Code Generation

copy

Full Screen

1var XCUITestDriver d require(aappium-xcuitest-driver');2var xcode = require('appium-xcode');3var driver = new XCUITestDriver();4var device = new XCUITestDriver().device;5var devices = driver.getDevices();6console.log("List of available devices: " + devices);7device.remove(devices[0]);8var devices = driver.getDevices();9console.log("List of available devices: " + devices);10device.add(devices[0]);11var devices = driver.getDevices();12console.log("List of available devices: " + devices);13var devices = driver.getDevices();14console.log("List of available devices: " + devices);15var devices = driver.getDevices();16console.log("List of available devices: " + devices);17var devices = driver.getDevices();18console.log("List of available devices: " + devices);19var devices = driver.getDevices();20console.log("List of available devices: " + devices);21var devices = driver.getDevices();22console.log("List of available devices: " + devices);

Full Screen

Using AI Code Generation

copy

Full Screen

1var XCUITestDriver = require('appium-xcuitest-driver');2var xcode = require('appium-xcode');3var driver = new XCUITestDriver();4var device = new XCUITestDriver().device;5var devices = driver.getDevices();6console.log("List of available devices: " + devices);7device.remove(devices[0]);8var devices = driver.getDevices();9console.log("List of available devices: " + devices);10device.add(devices[0]);11var devices = driver.getDevices();12console.log("List of available devices: " + devices);13var devices = driver.getDevices();14console.log("List of available devices: " + devices);15var devices = driver.getDevices();16console.log("List of available devices: " + devices);17var devices = driver.getDevices();18console.log("List of available devices: " + devices);19var devices = driver.getDevices();20console.log("List of available devices: " + devices);21var devices = driver.getDevices();22console.log("List of available devices: " + devices);

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 Xcuitest Driver automation tests on LambdaTest cloud grid

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

Sign up Free
_

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful