How to use remote method in Appium Xcuitest Driver

Best JavaScript code snippet using appium-xcuitest-driver

templates.js

Source:templates.js Github

copy

Full Screen

1/**2 * Default list of commands to execute for a PeerConnection test.3 */4const STABLE = "stable";5const HAVE_LOCAL_OFFER = "have-local-offer";6const HAVE_REMOTE_OFFER = "have-remote-offer";7const CLOSED = "closed";8const ICE_NEW = "new";9const GATH_NEW = "new";10const GATH_GATH = "gathering";11const GATH_COMPLETE = "complete"12function deltaSeconds(date1, date2) {13 return (date2.getTime() - date1.getTime())/1000;14}15function dumpSdp(test) {16 if (typeof test._local_offer !== 'undefined') {17 dump("ERROR: SDP offer: " + test._local_offer.sdp.replace(/[\r]/g, ''));18 }19 if (typeof test._remote_answer !== 'undefined') {20 dump("ERROR: SDP answer: " + test._remote_answer.sdp.replace(/[\r]/g, ''));21 }22 if ((test.pcLocal) && (typeof test.pcLocal._local_ice_candidates !== 'undefined')) {23 dump("pcLocal._local_ice_candidates: " + JSON.stringify(test.pcLocal._local_ice_candidates) + "\n");24 dump("pcLocal._remote_ice_candidates: " + JSON.stringify(test.pcLocal._remote_ice_candidates) + "\n");25 dump("pcLocal._ice_candidates_to_add: " + JSON.stringify(test.pcLocal._ice_candidates_to_add) + "\n");26 }27 if ((test.pcRemote) && (typeof test.pcRemote._local_ice_candidates !== 'undefined')) {28 dump("pcRemote._local_ice_candidates: " + JSON.stringify(test.pcRemote._local_ice_candidates) + "\n");29 dump("pcRemote._remote_ice_candidates: " + JSON.stringify(test.pcRemote._remote_ice_candidates) + "\n");30 dump("pcRemote._ice_candidates_to_add: " + JSON.stringify(test.pcRemote._ice_candidates_to_add) + "\n");31 }32 if ((test.pcLocal) && (typeof test.pcLocal.iceConnectionLog !== 'undefined')) {33 dump("pcLocal ICE connection state log: " + test.pcLocal.iceConnectionLog + "\n");34 }35 if ((test.pcRemote) && (typeof test.pcRemote.iceConnectionLog !== 'undefined')) {36 dump("pcRemote ICE connection state log: " + test.pcRemote.iceConnectionLog + "\n");37 }38 if ((test.pcLocal) && (test.pcRemote) &&39 (typeof test.pcLocal.setRemoteDescDate !== 'undefined') &&40 (typeof test.pcRemote.setLocalDescDate !== 'undefined')) {41 var delta = deltaSeconds(test.pcLocal.setRemoteDescDate, test.pcRemote.setLocalDescDate);42 dump("Delay between pcLocal.setRemote <-> pcRemote.setLocal: " + delta + "\n");43 }44 if ((test.pcLocal) && (test.pcRemote) &&45 (typeof test.pcLocal.setRemoteDescDate !== 'undefined') &&46 (typeof test.pcLocal.setRemoteDescStableEventDate !== 'undefined')) {47 var delta = deltaSeconds(test.pcLocal.setRemoteDescDate, test.pcLocal.setRemoteDescStableEventDate);48 dump("Delay between pcLocal.setRemote <-> pcLocal.signalingStateStable: " + delta + "\n");49 }50 if ((test.pcLocal) && (test.pcRemote) &&51 (typeof test.pcRemote.setLocalDescDate !== 'undefined') &&52 (typeof test.pcRemote.setLocalDescStableEventDate !== 'undefined')) {53 var delta = deltaSeconds(test.pcRemote.setLocalDescDate, test.pcRemote.setLocalDescStableEventDate);54 dump("Delay between pcRemote.setLocal <-> pcRemote.signalingStateStable: " + delta + "\n");55 }56}57// We need to verify that at least one candidate has been (or will be) gathered.58function waitForAnIceCandidate(pc) {59 return new Promise(resolve => {60 if (!pc.localRequiresTrickleIce ||61 pc._local_ice_candidates.length > 0) {62 resolve();63 } else {64 // In some circumstances, especially when both PCs are on the same65 // browser, even though we are connected, the connection can be66 // established without receiving a single candidate from one or other67 // peer. So we wait for at least one...68 pc._pc.addEventListener('icecandidate', resolve);69 }70 }).then(() => {71 ok(pc._local_ice_candidates.length > 0,72 pc + " received local trickle ICE candidates");73 isnot(pc._pc.iceGatheringState, GATH_NEW,74 pc + " ICE gathering state is not 'new'");75 });76}77function checkTrackStats(pc, rtpSenderOrReceiver, outbound) {78 var track = rtpSenderOrReceiver.track;79 var audio = (track.kind == "audio");80 var msg = pc + " stats " + (outbound ? "outbound " : "inbound ") +81 (audio ? "audio" : "video") + " rtp track id " + track.id;82 return pc.getStats(track).then(stats => {83 ok(pc.hasStat(stats, {84 type: outbound ? "outboundrtp" : "inboundrtp",85 isRemote: false,86 mediaType: audio ? "audio" : "video"87 }), msg + " - found expected stats");88 ok(!pc.hasStat(stats, {89 type: outbound ? "inboundrtp" : "outboundrtp",90 isRemote: false91 }), msg + " - did not find extra stats with wrong direction");92 ok(!pc.hasStat(stats, {93 mediaType: audio ? "video" : "audio"94 }), msg + " - did not find extra stats with wrong media type");95 });96}97var checkAllTrackStats = pc => {98 return Promise.all([].concat(99 pc._pc.getSenders().map(sender => checkTrackStats(pc, sender, true)),100 pc._pc.getReceivers().map(receiver => checkTrackStats(pc, receiver, false))));101}102// Commands run once at the beginning of each test, even when performing a103// renegotiation test.104var commandsPeerConnectionInitial = [105 function PC_SETUP_SIGNALING_CLIENT(test) {106 if (test.testOptions.steeplechase) {107 test.setupSignalingClient();108 test.registerSignalingCallback("ice_candidate", function (message) {109 var pc = test.pcRemote ? test.pcRemote : test.pcLocal;110 pc.storeOrAddIceCandidate(new RTCIceCandidate(message.ice_candidate));111 });112 test.registerSignalingCallback("end_of_trickle_ice", function (message) {113 test.signalingMessagesFinished();114 });115 }116 },117 function PC_LOCAL_SETUP_ICE_LOGGER(test) {118 test.pcLocal.logIceConnectionState();119 },120 function PC_REMOTE_SETUP_ICE_LOGGER(test) {121 test.pcRemote.logIceConnectionState();122 },123 function PC_LOCAL_SETUP_SIGNALING_LOGGER(test) {124 test.pcLocal.logSignalingState();125 },126 function PC_REMOTE_SETUP_SIGNALING_LOGGER(test) {127 test.pcRemote.logSignalingState();128 },129 function PC_LOCAL_SETUP_TRACK_HANDLER(test) {130 test.pcLocal.setupTrackEventHandler();131 },132 function PC_REMOTE_SETUP_TRACK_HANDLER(test) {133 test.pcRemote.setupTrackEventHandler();134 },135 function PC_LOCAL_CHECK_INITIAL_SIGNALINGSTATE(test) {136 is(test.pcLocal.signalingState, STABLE,137 "Initial local signalingState is 'stable'");138 },139 function PC_REMOTE_CHECK_INITIAL_SIGNALINGSTATE(test) {140 is(test.pcRemote.signalingState, STABLE,141 "Initial remote signalingState is 'stable'");142 },143 function PC_LOCAL_CHECK_INITIAL_ICE_STATE(test) {144 is(test.pcLocal.iceConnectionState, ICE_NEW,145 "Initial local ICE connection state is 'new'");146 },147 function PC_REMOTE_CHECK_INITIAL_ICE_STATE(test) {148 is(test.pcRemote.iceConnectionState, ICE_NEW,149 "Initial remote ICE connection state is 'new'");150 },151 function PC_LOCAL_CHECK_INITIAL_CAN_TRICKLE_SYNC(test) {152 is(test.pcLocal._pc.canTrickleIceCandidates, null,153 "Local trickle status should start out unknown");154 },155 function PC_REMOTE_CHECK_INITIAL_CAN_TRICKLE_SYNC(test) {156 is(test.pcRemote._pc.canTrickleIceCandidates, null,157 "Remote trickle status should start out unknown");158 },159];160var commandsGetUserMedia = [161 function PC_LOCAL_GUM(test) {162 return test.pcLocal.getAllUserMedia(test.pcLocal.constraints);163 },164 function PC_REMOTE_GUM(test) {165 return test.pcRemote.getAllUserMedia(test.pcRemote.constraints);166 },167];168var commandsPeerConnectionOfferAnswer = [169 function PC_LOCAL_SETUP_ICE_HANDLER(test) {170 test.pcLocal.setupIceCandidateHandler(test);171 },172 function PC_REMOTE_SETUP_ICE_HANDLER(test) {173 test.pcRemote.setupIceCandidateHandler(test);174 },175 function PC_LOCAL_STEEPLECHASE_SIGNAL_EXPECTED_LOCAL_TRACKS(test) {176 if (test.testOptions.steeplechase) {177 send_message({"type": "local_expected_tracks",178 "expected_tracks": test.pcLocal.expectedLocalTrackInfoById});179 }180 },181 function PC_REMOTE_STEEPLECHASE_SIGNAL_EXPECTED_LOCAL_TRACKS(test) {182 if (test.testOptions.steeplechase) {183 send_message({"type": "remote_expected_tracks",184 "expected_tracks": test.pcRemote.expectedLocalTrackInfoById});185 }186 },187 function PC_LOCAL_GET_EXPECTED_REMOTE_TRACKS(test) {188 if (test.testOptions.steeplechase) {189 return test.getSignalingMessage("remote_expected_tracks").then(190 message => {191 test.pcLocal.expectedRemoteTrackInfoById = message.expected_tracks;192 });193 }194 // Deep copy, as similar to steeplechase as possible195 test.pcLocal.expectedRemoteTrackInfoById =196 JSON.parse(JSON.stringify(test.pcRemote.expectedLocalTrackInfoById));197 },198 function PC_REMOTE_GET_EXPECTED_REMOTE_TRACKS(test) {199 if (test.testOptions.steeplechase) {200 return test.getSignalingMessage("local_expected_tracks").then(201 message => {202 test.pcRemote.expectedRemoteTrackInfoById = message.expected_tracks;203 });204 }205 // Deep copy, as similar to steeplechase as possible206 test.pcRemote.expectedRemoteTrackInfoById =207 JSON.parse(JSON.stringify(test.pcLocal.expectedLocalTrackInfoById));208 },209 function PC_LOCAL_CREATE_OFFER(test) {210 return test.createOffer(test.pcLocal).then(offer => {211 is(test.pcLocal.signalingState, STABLE,212 "Local create offer does not change signaling state");213 });214 },215 function PC_LOCAL_STEEPLECHASE_SIGNAL_OFFER(test) {216 if (test.testOptions.steeplechase) {217 send_message({"type": "offer",218 "offer": test.originalOffer,219 "offer_constraints": test.pcLocal.constraints,220 "offer_options": test.pcLocal.offerOptions});221 test._local_offer = test.originalOffer;222 test._offer_constraints = test.pcLocal.constraints;223 test._offer_options = test.pcLocal.offerOptions;224 }225 },226 function PC_LOCAL_SET_LOCAL_DESCRIPTION(test) {227 return test.setLocalDescription(test.pcLocal, test.originalOffer, HAVE_LOCAL_OFFER)228 .then(() => {229 is(test.pcLocal.signalingState, HAVE_LOCAL_OFFER,230 "signalingState after local setLocalDescription is 'have-local-offer'");231 });232 },233 function PC_REMOTE_GET_OFFER(test) {234 if (!test.testOptions.steeplechase) {235 test._local_offer = test.originalOffer;236 test._offer_constraints = test.pcLocal.constraints;237 test._offer_options = test.pcLocal.offerOptions;238 return Promise.resolve();239 }240 return test.getSignalingMessage("offer")241 .then(message => {242 ok("offer" in message, "Got an offer message");243 test._local_offer = new RTCSessionDescription(message.offer);244 test._offer_constraints = message.offer_constraints;245 test._offer_options = message.offer_options;246 });247 },248 function PC_REMOTE_SET_REMOTE_DESCRIPTION(test) {249 return test.setRemoteDescription(test.pcRemote, test._local_offer, HAVE_REMOTE_OFFER)250 .then(() => {251 is(test.pcRemote.signalingState, HAVE_REMOTE_OFFER,252 "signalingState after remote setRemoteDescription is 'have-remote-offer'");253 });254 },255 function PC_REMOTE_CHECK_CAN_TRICKLE_SYNC(test) {256 is(test.pcRemote._pc.canTrickleIceCandidates, true,257 "Remote thinks that local can trickle");258 },259 function PC_LOCAL_SANE_LOCAL_SDP(test) {260 test.pcLocal.localRequiresTrickleIce =261 sdputils.verifySdp(test._local_offer, "offer",262 test._offer_constraints, test._offer_options,263 test.testOptions);264 },265 function PC_REMOTE_SANE_REMOTE_SDP(test) {266 test.pcRemote.remoteRequiresTrickleIce =267 sdputils.verifySdp(test._local_offer, "offer",268 test._offer_constraints, test._offer_options,269 test.testOptions);270 },271 function PC_REMOTE_CREATE_ANSWER(test) {272 return test.createAnswer(test.pcRemote)273 .then(answer => {274 is(test.pcRemote.signalingState, HAVE_REMOTE_OFFER,275 "Remote createAnswer does not change signaling state");276 if (test.testOptions.steeplechase) {277 send_message({"type": "answer",278 "answer": test.originalAnswer,279 "answer_constraints": test.pcRemote.constraints});280 test._remote_answer = test.pcRemote._last_answer;281 test._answer_constraints = test.pcRemote.constraints;282 }283 });284 },285 function PC_REMOTE_SET_LOCAL_DESCRIPTION(test) {286 return test.setLocalDescription(test.pcRemote, test.originalAnswer, STABLE)287 .then(() => {288 is(test.pcRemote.signalingState, STABLE,289 "signalingState after remote setLocalDescription is 'stable'");290 })291 .then(() => test.pcRemote.markRemoteTracksAsNegotiated());292 },293 function PC_LOCAL_GET_ANSWER(test) {294 if (!test.testOptions.steeplechase) {295 test._remote_answer = test.originalAnswer;296 test._answer_constraints = test.pcRemote.constraints;297 return Promise.resolve();298 }299 return test.getSignalingMessage("answer").then(message => {300 ok("answer" in message, "Got an answer message");301 test._remote_answer = new RTCSessionDescription(message.answer);302 test._answer_constraints = message.answer_constraints;303 });304 },305 function PC_LOCAL_SET_REMOTE_DESCRIPTION(test) {306 return test.setRemoteDescription(test.pcLocal, test._remote_answer, STABLE)307 .then(() => {308 is(test.pcLocal.signalingState, STABLE,309 "signalingState after local setRemoteDescription is 'stable'");310 })311 .then(() => test.pcLocal.markRemoteTracksAsNegotiated());312 },313 function PC_REMOTE_SANE_LOCAL_SDP(test) {314 test.pcRemote.localRequiresTrickleIce =315 sdputils.verifySdp(test._remote_answer, "answer",316 test._offer_constraints, test._offer_options,317 test.testOptions);318 },319 function PC_LOCAL_SANE_REMOTE_SDP(test) {320 test.pcLocal.remoteRequiresTrickleIce =321 sdputils.verifySdp(test._remote_answer, "answer",322 test._offer_constraints, test._offer_options,323 test.testOptions);324 },325 function PC_LOCAL_CHECK_CAN_TRICKLE_SYNC(test) {326 is(test.pcLocal._pc.canTrickleIceCandidates, true,327 "Local thinks that remote can trickle");328 },329 function PC_LOCAL_WAIT_FOR_ICE_CONNECTED(test) {330 return test.pcLocal.waitForIceConnected()331 .then(() => {332 info(test.pcLocal + ": ICE connection state log: " + test.pcLocal.iceConnectionLog);333 });334 },335 function PC_REMOTE_WAIT_FOR_ICE_CONNECTED(test) {336 return test.pcRemote.waitForIceConnected()337 .then(() => {338 info(test.pcRemote + ": ICE connection state log: " + test.pcRemote.iceConnectionLog);339 });340 },341 function PC_LOCAL_VERIFY_ICE_GATHERING(test) {342 return waitForAnIceCandidate(test.pcLocal);343 },344 function PC_REMOTE_VERIFY_ICE_GATHERING(test) {345 return waitForAnIceCandidate(test.pcRemote);346 },347 function PC_LOCAL_WAIT_FOR_MEDIA_FLOW(test) {348 return test.pcLocal.waitForMediaFlow();349 },350 function PC_REMOTE_WAIT_FOR_MEDIA_FLOW(test) {351 return test.pcRemote.waitForMediaFlow();352 },353 function PC_LOCAL_CHECK_STATS(test) {354 return test.pcLocal.getStats().then(stats => {355 test.pcLocal.checkStats(stats, test.testOptions.steeplechase);356 });357 },358 function PC_REMOTE_CHECK_STATS(test) {359 return test.pcRemote.getStats().then(stats => {360 test.pcRemote.checkStats(stats, test.testOptions.steeplechase);361 });362 },363 function PC_LOCAL_CHECK_ICE_CONNECTION_TYPE(test) {364 return test.pcLocal.getStats().then(stats => {365 test.pcLocal.checkStatsIceConnectionType(stats,366 test.testOptions.expectedLocalCandidateType);367 });368 },369 function PC_REMOTE_CHECK_ICE_CONNECTION_TYPE(test) {370 return test.pcRemote.getStats().then(stats => {371 test.pcRemote.checkStatsIceConnectionType(stats,372 test.testOptions.expectedRemoteCandidateType);373 });374 },375 function PC_LOCAL_CHECK_ICE_CONNECTIONS(test) {376 return test.pcLocal.getStats().then(stats => {377 test.pcLocal.checkStatsIceConnections(stats,378 test._offer_constraints,379 test._offer_options,380 test.testOptions);381 });382 },383 function PC_REMOTE_CHECK_ICE_CONNECTIONS(test) {384 return test.pcRemote.getStats().then(stats => {385 test.pcRemote.checkStatsIceConnections(stats,386 test._offer_constraints,387 test._offer_options,388 test.testOptions);389 });390 },391 function PC_LOCAL_CHECK_MSID(test) {392 return test.pcLocal.checkMsids();393 },394 function PC_REMOTE_CHECK_MSID(test) {395 return test.pcRemote.checkMsids();396 },397 function PC_LOCAL_CHECK_TRACK_STATS(test) {398 return checkAllTrackStats(test.pcLocal);399 },400 function PC_REMOTE_CHECK_TRACK_STATS(test) {401 return checkAllTrackStats(test.pcRemote);402 },403 function PC_LOCAL_VERIFY_SDP_AFTER_END_OF_TRICKLE(test) {404 if (test.pcLocal.endOfTrickleSdp) {405 /* In case the endOfTrickleSdp promise is resolved already it will win the406 * race because it gets evaluated first. But if endOfTrickleSdp is still407 * pending the rejection will win the race. */408 return Promise.race([409 test.pcLocal.endOfTrickleSdp,410 Promise.reject("No SDP")411 ])412 .then(sdp => sdputils.checkSdpAfterEndOfTrickle(sdp, test.testOptions, test.pcLocal.label),413 () => info("pcLocal: Gathering is not complete yet, skipping post-gathering SDP check"));414 }415 },416 function PC_REMOTE_VERIFY_SDP_AFTER_END_OF_TRICKLE(test) {417 if (test.pcRemote.endOfTrickleSdp) {418 /* In case the endOfTrickleSdp promise is resolved already it will win the419 * race because it gets evaluated first. But if endOfTrickleSdp is still420 * pending the rejection will win the race. */421 return Promise.race([422 test.pcRemote.endOfTrickleSdp,423 Promise.reject("No SDP")424 ])425 .then(sdp => sdputils.checkSdpAfterEndOfTrickle(sdp, test.testOptions, test.pcRemote.label),426 () => info("pcRemote: Gathering is not complete yet, skipping post-gathering SDP check"));427 }428 }429];430function PC_LOCAL_REMOVE_ALL_BUT_H264_FROM_OFFER(test) {431 isnot(test.originalOffer.sdp.search("H264/90000"), -1, "H.264 should be present in the SDP offer");432 test.originalOffer.sdp = sdputils.removeCodec(sdputils.removeCodec(sdputils.removeCodec(433 test.originalOffer.sdp, 120), 121, 97));434 info("Updated H264 only offer: " + JSON.stringify(test.originalOffer));435};436function PC_LOCAL_REMOVE_BUNDLE_FROM_OFFER(test) {437 test.originalOffer.sdp = sdputils.removeBundle(test.originalOffer.sdp);438 info("Updated no bundle offer: " + JSON.stringify(test.originalOffer));439};440function PC_LOCAL_REMOVE_RTCPMUX_FROM_OFFER(test) {441 test.originalOffer.sdp = sdputils.removeRtcpMux(test.originalOffer.sdp);442 info("Updated no RTCP-Mux offer: " + JSON.stringify(test.originalOffer));443};444var addRenegotiation = (chain, commands, checks) => {445 chain.append(commands);446 chain.append(commandsPeerConnectionOfferAnswer);447 if (checks) {448 chain.append(checks);449 }450};451var addRenegotiationAnswerer = (chain, commands, checks) => {452 chain.append(function SWAP_PC_LOCAL_PC_REMOTE(test) {453 var temp = test.pcLocal;454 test.pcLocal = test.pcRemote;455 test.pcRemote = temp;456 });457 addRenegotiation(chain, commands, checks);...

Full Screen

Full Screen

browser_gcli_remotews.js

Source:browser_gcli_remotews.js Github

copy

Full Screen

1/*2 * Copyright 2012, Mozilla Foundation and contributors3 *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 */16"use strict";17// THIS FILE IS GENERATED FROM SOURCE IN THE GCLI PROJECT18// PLEASE TALK TO SOMEONE IN DEVELOPER TOOLS BEFORE EDITING IT19const exports = {};20function test() {21 helpers.runTestModule(exports, "browser_gcli_remotews.js");22}23// var assert = require('../testharness/assert');24// var helpers = require('./helpers');25// testRemoteWs and testRemoteXhr are virtually identical.26// Changes made here should be made there too.27// They are kept separate to save adding complexity to the test system and so28// to help us select the test that are available in different environments29exports.testRemoteWebsocket = function (options) {30 return helpers.audit(options, [31 {32 skipRemainingIf: options.isRemote || options.isNode || options.isFirefox,33 setup: "remote ",34 check: {35 input: "remote ",36 hints: "",37 markup: "EEEEEEV",38 cursor: 7,39 current: "__command",40 status: "ERROR",41 options: [ ],42 message: "Can't use 'remote'.",43 predictions: [ ],44 unassigned: [ ],45 }46 },47 {48 setup: "connect remote",49 check: {50 args: {51 prefix: { value: "remote" },52 url: { value: undefined }53 }54 },55 exec: {56 error: false57 }58 },59 {60 setup: "disconnect remote",61 check: {62 args: {63 prefix: {64 value: function (front) {65 assert.is(front.prefix, "remote", "disconnecting remote");66 }67 }68 }69 },70 exec: {71 output: /^Removed [0-9]* commands.$/,72 type: "string",73 error: false74 }75 },76 {77 setup: "connect remote --method websocket",78 check: {79 args: {80 prefix: { value: "remote" },81 url: { value: undefined }82 }83 },84 exec: {85 error: false86 }87 },88 {89 setup: "disconnect remote",90 check: {91 args: {92 prefix: {93 value: function (front) {94 assert.is(front.prefix, "remote", "disconnecting remote");95 }96 }97 }98 },99 exec: {100 output: /^Removed [0-9]* commands.$/,101 type: "string",102 error: false103 }104 },105 {106 setup: "connect remote --method websocket",107 check: {108 args: {109 prefix: { value: "remote" },110 url: { value: undefined }111 }112 },113 exec: {114 output: /^Added [0-9]* commands.$/,115 type: "string",116 error: false117 }118 },119 {120 setup: "remote ",121 check: {122 input: "remote ",123 // PhantomJS fails on this. Unsure why124 // hints: ' {',125 markup: "IIIIIIV",126 status: "ERROR",127 optionsIncludes: [128 "remote", "remote cd", "remote context", "remote echo",129 "remote exec", "remote exit", "remote firefox", "remote help",130 "remote intro", "remote make"131 ],132 message: "",133 predictionsIncludes: [ "remote" ],134 unassigned: [ ],135 }136 },137 {138 setup: "remote echo hello world",139 check: {140 input: "remote echo hello world",141 hints: "",142 markup: "VVVVVVVVVVVVVVVVVVVVVVV",143 cursor: 23,144 current: "message",145 status: "VALID",146 options: [ ],147 message: "",148 predictions: [ ],149 unassigned: [ ],150 args: {151 command: { name: "remote echo" },152 message: {153 value: "hello world",154 arg: " hello world",155 status: "VALID",156 message: ""157 }158 }159 },160 exec: {161 output: "hello world",162 type: "string",163 error: false164 }165 },166 {167 setup: "remote exec ls",168 check: {169 input: "remote exec ls",170 hints: "",171 markup: "VVVVVVVVVVVVVV",172 cursor: 14,173 current: "command",174 status: "VALID",175 options: [ ],176 message: "",177 predictions: [ ],178 unassigned: [ ],179 args: {180 command: {181 value: "ls",182 arg: " ls",183 status: "VALID",184 message: ""185 }186 }187 },188 exec: {189 // output: '', We can't rely on the contents of the FS190 type: "output",191 error: false192 }193 },194 {195 setup: "remote sleep mistake",196 check: {197 input: "remote sleep mistake",198 hints: "",199 markup: "VVVVVVVVVVVVVEEEEEEE",200 cursor: 20,201 current: "length",202 status: "ERROR",203 options: [ ],204 message: 'Can\'t convert "mistake" to a number.',205 predictions: [ ],206 unassigned: [ ],207 args: {208 command: { name: "remote sleep" },209 length: {210 value: undefined,211 arg: " mistake",212 status: "ERROR",213 message: 'Can\'t convert "mistake" to a number.'214 }215 }216 }217 },218 {219 setup: "remote sleep 1",220 check: {221 input: "remote sleep 1",222 hints: "",223 markup: "VVVVVVVVVVVVVV",224 cursor: 14,225 current: "length",226 status: "VALID",227 options: [ ],228 message: "",229 predictions: [ ],230 unassigned: [ ],231 args: {232 command: { name: "remote sleep" },233 length: { value: 1, arg: " 1", status: "VALID", message: "" }234 }235 },236 exec: {237 output: "Done",238 type: "string",239 error: false240 }241 },242 {243 setup: "remote help ",244 skipIf: true, // The help command is not remotable245 check: {246 input: "remote help ",247 hints: "[search]",248 markup: "VVVVVVVVVVVV",249 cursor: 12,250 current: "search",251 status: "VALID",252 options: [ ],253 message: "",254 predictions: [ ],255 unassigned: [ ],256 args: {257 command: { name: "remote help" },258 search: {259 value: undefined,260 arg: "",261 status: "VALID",262 message: ""263 }264 }265 },266 exec: {267 output: "",268 type: "string",269 error: false270 }271 },272 {273 setup: "remote intro",274 check: {275 input: "remote intro",276 hints: "",277 markup: "VVVVVVVVVVVV",278 cursor: 12,279 current: "__command",280 status: "VALID",281 options: [ ],282 message: "",283 predictions: [ ],284 unassigned: [ ],285 args: {286 command: { name: "remote intro" }287 }288 },289 exec: {290 output: [291 /GCLI is an experiment/,292 /F1\/Escape/293 ],294 type: "intro",295 error: false296 }297 },298 {299 setup: "context remote",300 check: {301 input: "context remote",302 // hints: ' {',303 markup: "VVVVVVVVVVVVVV",304 cursor: 14,305 current: "prefix",306 status: "VALID",307 optionsContains: [308 "remote", "remote cd", "remote echo", "remote exec", "remote exit",309 "remote firefox", "remote help", "remote intro", "remote make"310 ],311 message: "",312 // predictionsContains: [313 // 'remote', 'remote cd', 'remote echo', 'remote exec', 'remote exit',314 // 'remote firefox', 'remote help', 'remote intro', 'remote make',315 // 'remote pref'316 // ],317 unassigned: [ ],318 args: {319 command: { name: "context" },320 prefix: {321 arg: " remote",322 status: "VALID",323 message: ""324 }325 }326 },327 exec: {328 output: "Using remote as a command prefix",329 type: "string",330 error: false331 }332 },333 {334 setup: "exec ls",335 check: {336 input: "exec ls",337 hints: "",338 markup: "VVVVVVV",339 cursor: 7,340 current: "command",341 status: "VALID",342 options: [ ],343 message: "",344 predictions: [ ],345 unassigned: [ ],346 args: {347 command: { value: "ls", arg: " ls", status: "VALID", message: "" },348 }349 },350 exec: {351 // output: '', We can't rely on the contents of the filesystem352 type: "output",353 error: false354 }355 },356 {357 setup: "echo hello world",358 check: {359 input: "echo hello world",360 hints: "",361 markup: "VVVVVVVVVVVVVVVV",362 cursor: 16,363 current: "message",364 status: "VALID",365 options: [ ],366 message: "",367 predictions: [ ],368 unassigned: [ ],369 args: {370 command: { name: "remote echo" },371 message: {372 value: "hello world",373 arg: " hello world",374 status: "VALID",375 message: ""376 }377 }378 },379 exec: {380 output: /^hello world$/,381 type: "string",382 error: false383 }384 },385 {386 setup: "context",387 check: {388 input: "context",389 hints: " [prefix]",390 markup: "VVVVVVV",391 cursor: 7,392 current: "__command",393 status: "VALID",394 optionsContains: [395 "remote", "remote cd", "remote echo", "remote exec", "remote exit",396 "remote firefox", "remote help", "remote intro", "remote make"397 ],398 message: "",399 predictions: [ ],400 unassigned: [ ],401 args: {402 command: { name: "context" },403 prefix: { value: undefined, arg: "", status: "VALID", message: "" }404 }405 },406 exec: {407 output: "Command prefix is unset",408 type: "string",409 error: false410 }411 },412 {413 setup: "disconnect ",414 check: {415 input: "disconnect ",416 hints: "remote",417 markup: "VVVVVVVVVVV",418 cursor: 11,419 current: "prefix",420 status: "ERROR",421 options: [ "remote" ],422 message: "",423 predictions: [ "remote" ],424 unassigned: [ ],425 args: {426 command: { name: "disconnect" },427 prefix: {428 value: undefined,429 arg: "",430 status: "INCOMPLETE",431 message: "Value required for 'prefix'."432 }433 }434 }435 },436 {437 setup: "disconnect remote",438 check: {439 input: "disconnect remote",440 hints: "",441 markup: "VVVVVVVVVVVVVVVVV",442 status: "VALID",443 message: "",444 unassigned: [ ],445 args: {446 prefix: {447 value: function (front) {448 assert.is(front.prefix, "remote", "disconnecting remote");449 },450 arg: " remote",451 status: "VALID",452 message: ""453 }454 }455 },456 exec: {457 output: /^Removed [0-9]* commands.$/,458 type: "string",459 error: false460 }461 },462 {463 setup: "remote ",464 check: {465 input: "remote ",466 hints: "",467 markup: "EEEEEEV",468 cursor: 7,469 current: "__command",470 status: "ERROR",471 options: [ ],472 message: "Can't use 'remote'.",473 predictions: [ ],474 unassigned: [ ],475 }476 }477 ]);...

Full Screen

Full Screen

browser_gcli_remotexhr.js

Source:browser_gcli_remotexhr.js Github

copy

Full Screen

1/*2 * Copyright 2012, Mozilla Foundation and contributors3 *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 */16"use strict";17// THIS FILE IS GENERATED FROM SOURCE IN THE GCLI PROJECT18// PLEASE TALK TO SOMEONE IN DEVELOPER TOOLS BEFORE EDITING IT19const exports = {};20function test() {21 helpers.runTestModule(exports, "browser_gcli_remotexhr.js");22}23// var assert = require('../testharness/assert');24// var helpers = require('./helpers');25// testRemoteWs and testRemoteXhr are virtually identical.26// Changes made here should be made there too.27// They are kept separate to save adding complexity to the test system and so28// to help us select the test that are available in different environments29exports.testRemoteXhr = function (options) {30 return helpers.audit(options, [31 {32 skipRemainingIf: options.isRemote || options.isNode || options.isFirefox,33 setup: "remote ",34 check: {35 input: "remote ",36 hints: "",37 markup: "EEEEEEV",38 cursor: 7,39 current: "__command",40 status: "ERROR",41 options: [ ],42 message: "Can't use 'remote'.",43 predictions: [ ],44 unassigned: [ ],45 }46 },47 {48 setup: "connect remote",49 check: {50 args: {51 prefix: { value: "remote" },52 url: { value: undefined }53 }54 },55 exec: {56 error: false57 }58 },59 {60 setup: "disconnect remote",61 check: {62 args: {63 prefix: {64 value: function (front) {65 assert.is(front.prefix, "remote", "disconnecting remote");66 }67 }68 }69 },70 exec: {71 output: /^Removed [0-9]* commands.$/,72 type: "string",73 error: false74 }75 },76 {77 setup: "connect remote --method xhr",78 check: {79 args: {80 prefix: { value: "remote" },81 url: { value: undefined }82 }83 },84 exec: {85 error: false86 }87 },88 {89 setup: "disconnect remote",90 check: {91 args: {92 prefix: {93 value: function (front) {94 assert.is(front.prefix, "remote", "disconnecting remote");95 }96 }97 }98 },99 exec: {100 output: /^Removed [0-9]* commands.$/,101 type: "string",102 error: false103 }104 },105 {106 setup: "connect remote --method xhr",107 check: {108 args: {109 prefix: { value: "remote" },110 url: { value: undefined }111 }112 },113 exec: {114 output: /^Added [0-9]* commands.$/,115 type: "string",116 error: false117 }118 },119 {120 setup: "remote ",121 check: {122 input: "remote ",123 // PhantomJS fails on this. Unsure why124 // hints: ' {',125 markup: "IIIIIIV",126 status: "ERROR",127 optionsIncludes: [128 "remote", "remote cd", "remote context", "remote echo",129 "remote exec", "remote exit", "remote firefox", "remote help",130 "remote intro", "remote make"131 ],132 message: "",133 predictionsIncludes: [ "remote" ],134 unassigned: [ ],135 }136 },137 {138 setup: "remote echo hello world",139 check: {140 input: "remote echo hello world",141 hints: "",142 markup: "VVVVVVVVVVVVVVVVVVVVVVV",143 cursor: 23,144 current: "message",145 status: "VALID",146 options: [ ],147 message: "",148 predictions: [ ],149 unassigned: [ ],150 args: {151 command: { name: "remote echo" },152 message: {153 value: "hello world",154 arg: " hello world",155 status: "VALID",156 message: ""157 }158 }159 },160 exec: {161 output: "hello world",162 type: "string",163 error: false164 }165 },166 {167 setup: "remote exec ls",168 check: {169 input: "remote exec ls",170 hints: "",171 markup: "VVVVVVVVVVVVVV",172 cursor: 14,173 current: "command",174 status: "VALID",175 options: [ ],176 message: "",177 predictions: [ ],178 unassigned: [ ],179 args: {180 command: {181 value: "ls",182 arg: " ls",183 status: "VALID",184 message: ""185 }186 }187 },188 exec: {189 // output: '', We can't rely on the contents of the FS190 type: "output",191 error: false192 }193 },194 {195 setup: "remote sleep mistake",196 check: {197 input: "remote sleep mistake",198 hints: "",199 markup: "VVVVVVVVVVVVVEEEEEEE",200 cursor: 20,201 current: "length",202 status: "ERROR",203 options: [ ],204 message: 'Can\'t convert "mistake" to a number.',205 predictions: [ ],206 unassigned: [ ],207 args: {208 command: { name: "remote sleep" },209 length: {210 value: undefined,211 arg: " mistake",212 status: "ERROR",213 message: 'Can\'t convert "mistake" to a number.'214 }215 }216 }217 },218 {219 setup: "remote sleep 1",220 check: {221 input: "remote sleep 1",222 hints: "",223 markup: "VVVVVVVVVVVVVV",224 cursor: 14,225 current: "length",226 status: "VALID",227 options: [ ],228 message: "",229 predictions: [ ],230 unassigned: [ ],231 args: {232 command: { name: "remote sleep" },233 length: { value: 1, arg: " 1", status: "VALID", message: "" }234 }235 },236 exec: {237 output: "Done",238 type: "string",239 error: false240 }241 },242 {243 setup: "remote help ",244 skipIf: true, // The help command is not remotable245 check: {246 input: "remote help ",247 hints: "[search]",248 markup: "VVVVVVVVVVVV",249 cursor: 12,250 current: "search",251 status: "VALID",252 options: [ ],253 message: "",254 predictions: [ ],255 unassigned: [ ],256 args: {257 command: { name: "remote help" },258 search: {259 value: undefined,260 arg: "",261 status: "VALID",262 message: ""263 }264 }265 },266 exec: {267 output: "",268 type: "string",269 error: false270 }271 },272 {273 setup: "remote intro",274 check: {275 input: "remote intro",276 hints: "",277 markup: "VVVVVVVVVVVV",278 cursor: 12,279 current: "__command",280 status: "VALID",281 options: [ ],282 message: "",283 predictions: [ ],284 unassigned: [ ],285 args: {286 command: { name: "remote intro" }287 }288 },289 exec: {290 output: [291 /GCLI is an experiment/,292 /F1\/Escape/293 ],294 type: "intro",295 error: false296 }297 },298 {299 setup: "context remote",300 check: {301 input: "context remote",302 // hints: ' {',303 markup: "VVVVVVVVVVVVVV",304 cursor: 14,305 current: "prefix",306 status: "VALID",307 optionsContains: [308 "remote", "remote cd", "remote echo", "remote exec", "remote exit",309 "remote firefox", "remote help", "remote intro", "remote make"310 ],311 message: "",312 // predictionsContains: [313 // 'remote', 'remote cd', 'remote echo', 'remote exec', 'remote exit',314 // 'remote firefox', 'remote help', 'remote intro', 'remote make',315 // 'remote pref'316 // ],317 unassigned: [ ],318 args: {319 command: { name: "context" },320 prefix: {321 arg: " remote",322 status: "VALID",323 message: ""324 }325 }326 },327 exec: {328 output: "Using remote as a command prefix",329 type: "string",330 error: false331 }332 },333 {334 setup: "exec ls",335 check: {336 input: "exec ls",337 hints: "",338 markup: "VVVVVVV",339 cursor: 7,340 current: "command",341 status: "VALID",342 options: [ ],343 message: "",344 predictions: [ ],345 unassigned: [ ],346 args: {347 command: { value: "ls", arg: " ls", status: "VALID", message: "" },348 }349 },350 exec: {351 // output: '', We can't rely on the contents of the filesystem352 type: "output",353 error: false354 }355 },356 {357 setup: "echo hello world",358 check: {359 input: "echo hello world",360 hints: "",361 markup: "VVVVVVVVVVVVVVVV",362 cursor: 16,363 current: "message",364 status: "VALID",365 options: [ ],366 message: "",367 predictions: [ ],368 unassigned: [ ],369 args: {370 command: { name: "remote echo" },371 message: {372 value: "hello world",373 arg: " hello world",374 status: "VALID",375 message: ""376 }377 }378 },379 exec: {380 output: /^hello world$/,381 type: "string",382 error: false383 }384 },385 {386 setup: "context",387 check: {388 input: "context",389 hints: " [prefix]",390 markup: "VVVVVVV",391 cursor: 7,392 current: "__command",393 status: "VALID",394 optionsContains: [395 "remote", "remote cd", "remote echo", "remote exec", "remote exit",396 "remote firefox", "remote help", "remote intro", "remote make"397 ],398 message: "",399 predictions: [ ],400 unassigned: [ ],401 args: {402 command: { name: "context" },403 prefix: { value: undefined, arg: "", status: "VALID", message: "" }404 }405 },406 exec: {407 output: "Command prefix is unset",408 type: "string",409 error: false410 }411 },412 {413 setup: "disconnect ",414 check: {415 input: "disconnect ",416 hints: "remote",417 markup: "VVVVVVVVVVV",418 cursor: 11,419 current: "prefix",420 status: "ERROR",421 options: [ "remote" ],422 message: "",423 predictions: [ "remote" ],424 unassigned: [ ],425 args: {426 command: { name: "disconnect" },427 prefix: {428 value: undefined,429 arg: "",430 status: "INCOMPLETE",431 message: "Value required for 'prefix'."432 }433 }434 }435 },436 {437 setup: "disconnect remote",438 check: {439 input: "disconnect remote",440 hints: "",441 markup: "VVVVVVVVVVVVVVVVV",442 status: "VALID",443 message: "",444 unassigned: [ ],445 args: {446 prefix: {447 value: function (front) {448 assert.is(front.prefix, "remote", "disconnecting remote");449 },450 arg: " remote",451 status: "VALID",452 message: ""453 }454 }455 },456 exec: {457 output: /^Removed [0-9]* commands.$/,458 type: "string",459 error: false460 }461 },462 {463 setup: "remote ",464 check: {465 input: "remote ",466 hints: "",467 markup: "EEEEEEV",468 cursor: 7,469 current: "__command",470 status: "ERROR",471 options: [ ],472 message: "Can't use 'remote'.",473 predictions: [ ],474 unassigned: [ ],475 }476 }477 ]);...

Full Screen

Full Screen

RemoteDirectory-spec.js

Source:RemoteDirectory-spec.js Github

copy

Full Screen

1'use babel';2/* @flow */3/*4 * Copyright (c) 2015-present, Facebook, Inc.5 * All rights reserved.6 *7 * This source code is licensed under the license found in the LICENSE file in8 * the root directory of this source tree.9 */10var fs = require('fs');11var path = require('path');12var {Directory} = require('atom');13var RemoteDirectory = require('../lib/RemoteDirectory');14var RemoteFile = require('../lib/RemoteFile');15var temp = require('temp').track();16var connectionMock = require('./connection_mock');17var FILE_MODE = 33188;18describe('RemoteDirectory', () => {19 it('does not have an existsSync() method', () => {20 // existsSync() is not implemented to prevent GitRepositoryProvider from21 // trying to create a GitRepository for this Directory. We need to create a22 // RemoteGitRepositoryProvider to handle this case correctly.23 expect(RemoteDirectory.prototype.existsSync).toBe(undefined);24 });25 it('does not list the property used to mark the directory as remote as one of its enumerable properties.', () => {26 var remoteDirectory = new RemoteDirectory(connectionMock, 'nuclide://example.com:9090/');27 for (var property in remoteDirectory) {28 expect(property).not.toBe('__nuclide_remote_directory__');29 }30 });31 describe('::isRemoteDirectory', () => {32 it('distinguishes a RemoteDirectory from a Directory.', () => {33 var remoteDirectory = new RemoteDirectory(connectionMock, 'nuclide://example.com:9090/');34 expect(RemoteDirectory.isRemoteDirectory(remoteDirectory)).toBe(true);35 var localDirectory = new Directory('/Test/Path');36 expect(RemoteDirectory.isRemoteDirectory(localDirectory)).toBe(false);37 });38 });39});40describe('RemoteDirectory::isRoot()', () => {41 it('nuclide://example.com:9090/ is a root', () => {42 var path = 'nuclide://example.com:9090/';43 var remoteDirectory = new RemoteDirectory(connectionMock, path);44 expect(remoteDirectory.isRoot()).toBe(true);45 });46 it('nuclide://example.com:9090/path/to/directory is not a root', () => {47 var path = 'nuclide://example.com:9090/path/to/directory';48 var remoteDirectory = new RemoteDirectory(connectionMock, path);49 expect(remoteDirectory.isRoot()).toBe(false);50 });51});52describe('RemoteDirectory::getBaseName()', () => {53 it('to handle a root path', () => {54 var path = 'nuclide://example.com:9090/';55 var remoteDirectory = new RemoteDirectory(connectionMock, path);56 expect(remoteDirectory.getBaseName()).toBe('');57 });58 it('to handle a non-root path', () => {59 var path = 'nuclide://example.com:9090/path/to/directory';60 var remoteDirectory = new RemoteDirectory(connectionMock, path);61 expect(remoteDirectory.getBaseName()).toBe('directory');62 });63});64describe('RemoteDirectory::relativize()', () => {65 it('to relativize a file against a root path', () => {66 var path = 'nuclide://example.com:9090/';67 var remoteDirectory = new RemoteDirectory(connectionMock, path);68 expect(remoteDirectory.relativize('nuclide://example.com:9090/foo/bar'))69 .toBe('foo/bar');70 });71});72describe('RemoteDirectory::getEntries()', () => {73 it('sorts directories then files alphabetically case insensitive', () => {74 var remote = jasmine.createSpyObj('RemoteConnection', ['getClient', 'createDirectory', 'createFile']);75 var client = jasmine.createSpyObj('NuclideClient', ['readdir']);76 remote.getClient.andReturn(client);77 remote.createDirectory.andCallFake((uri) => {78 return new RemoteDirectory(remote, uri);79 });80 remote.createFile.andCallFake((uri) => {81 return new RemoteFile(remote, uri);82 });83 var fileStats = {isFile() {return true;}};84 var directoryStats = {isFile() {return false;}};85 // Directories should sort first, then files, and case should be ignored86 client.readdir.andReturn([87 {file: 'Aa', stats: fileStats},88 {file: 'a', stats: fileStats},89 {file: 'Bb', stats: directoryStats},90 {file: 'b', stats: directoryStats},91 ]);92 var path = 'nuclide://example.com:9090/';93 var remoteDirectory = new RemoteDirectory(remote, path);94 remoteDirectory.getEntries((err, entries) => {95 expect(err).toBe(null);96 var sortedEntries = entries.map((entry) => entry.getBaseName());97 expect(sortedEntries).toEqual(['b', 'Bb', 'a', 'Aa']);98 });99 });100});101describe('RemoteDirectory::getParent()', () => {102 it('a root is its own parent', () => {103 var path = 'nuclide://example.com:9090/';104 var remoteDirectory = new RemoteDirectory(connectionMock, path);105 expect(remoteDirectory.getParent()).toBe(remoteDirectory);106 });107 it('a non-root has the expected parent', () => {108 var remote = {createDirectory(){}};109 var parentDirectory = jasmine.createSpy('RemoteDirectory');110 spyOn(remote, 'createDirectory').andReturn(parentDirectory);111 var path = 'nuclide://example.com:9090/path/to/directory';112 var remoteDirectory = new RemoteDirectory(remote, path);113 expect(remoteDirectory.getParent()).toBe(parentDirectory);114 expect(remote.createDirectory).toHaveBeenCalledWith(115 'nuclide://example.com:9090/path/to');116 });117});118describe('RemoteDirectory::contains()', () => {119 it('returns false when passed undefined path', () => {120 var path = 'nuclide://example.com:9090/';121 var remoteDirectory = new RemoteDirectory(connectionMock, path);122 expect(remoteDirectory.contains(undefined)).toBe(false);123 });124 it('returns false when passed null path', () => {125 var remote = jasmine.createSpy('RemoteConnection');126 var path = 'nuclide://example.com:9090/';127 var remoteDirectory = new RemoteDirectory(remote, path);128 expect(remoteDirectory.contains(null)).toBe(false);129 });130 it('returns false when passed empty path', () => {131 var path = 'nuclide://example.com:9090/';132 var remoteDirectory = new RemoteDirectory(connectionMock, path);133 expect(remoteDirectory.contains('')).toBe(false);134 });135 it('returns true when passed sub directory', () => {136 var path = 'nuclide://example.com:9090/';137 var remoteDirectory = new RemoteDirectory(connectionMock, path);138 expect(remoteDirectory.contains('nuclide://example.com:9090/asdf')).toBe(true);139 });140});141describe('RemoteDirectory::getFile()', () => {142 it('returns a RemoteFile under the directory', () => {143 var remote = {createFile(){}};144 var remoteFile = jasmine.createSpy('RemoteFile');145 spyOn(remote, 'createFile').andReturn(remoteFile);146 var path = 'nuclide://example.com:9090/path/to/directory';147 var remoteDirectory = new RemoteDirectory(remote, path);148 expect(remoteDirectory.getFile('foo.txt')).toBe(remoteFile);149 expect(remote.createFile).toHaveBeenCalledWith(150 'nuclide://example.com:9090/path/to/directory/foo.txt');151 });152});153describe('RemoteDirectory::delete()', () => {154 var tempDir;155 beforeEach(() => {156 tempDir = temp.mkdirSync('delete_test');157 });158 it('deletes the existing directory', () => {159 waitsForPromise(async () => {160 var directoryPath = path.join(tempDir, 'directory_to_delete');161 fs.mkdirSync(directoryPath);162 fs.mkdirSync(path.join(directoryPath, 'subdir'));163 var directory = new RemoteDirectory(connectionMock, directoryPath);164 expect(fs.existsSync(directoryPath)).toBe(true);165 await directory.delete();166 expect(fs.existsSync(directoryPath)).toBe(false);167 });168 });169 it('deletes the non-existent directory', () => {170 waitsForPromise(async () => {171 var directoryPath = path.join(tempDir, 'directory_to_delete');172 var directory = new RemoteDirectory(connectionMock, directoryPath);173 await directory.delete();174 expect(fs.existsSync(directoryPath)).toBe(false);175 });176 });177});178describe('RemoteDirectory::rename()', () => {179 var tempDir;180 beforeEach(() => {181 tempDir = temp.mkdirSync('rename_test');182 });183 // We only do this simple test to make sure it's delegating to the connection.184 // Adding the other cases is misleading and incorrect since it's actually185 // delegating to `fsPromise` here.186 it('renames existing directories', () => {187 waitsForPromise(async () => {188 var directoryPath = path.join(tempDir, 'directory_to_rename');189 fs.mkdirSync(directoryPath);190 var newDirectoryPath = path.join(tempDir, 'new_directory_name');191 expect(fs.existsSync(directoryPath)).toBe(true);192 var directory = new RemoteDirectory(connectionMock, directoryPath);193 await directory.rename(newDirectoryPath);194 expect(fs.existsSync(directoryPath)).toBe(false);195 expect(fs.existsSync(newDirectoryPath)).toBe(true);196 expect(directory.getLocalPath()).toEqual(newDirectoryPath);197 });198 });199});200describe('RemoteDirectory::onDidChange()', () => {201 var WATCHMAN_SETTLE_TIME_MS = 1 * 1000;202 var directoryPath;203 var filePath;204 beforeEach(() => {205 jasmine.getEnv().defaultTimeoutInterval = 10000;206 directoryPath = temp.mkdirSync('on_did_change_test');207 filePath = path.join(directoryPath, 'sample_file.txt');208 fs.writeFileSync(filePath, 'sample contents!');209 waitsForPromise(() => connectionMock.getClient().watchDirectoryRecursive(directoryPath));210 waits(WATCHMAN_SETTLE_TIME_MS + /* buffer */ 10); // wait for the watchman to settle on the created directory and file.211 });212 afterEach(() => {213 waitsForPromise(() => connectionMock.getClient().unwatchDirectoryRecursive(directoryPath));214 });215 it('notifies onDidChange observers when a new file is added to the directory', () => {216 var directory = new RemoteDirectory(connectionMock, directoryPath);217 var changeHandler = jasmine.createSpy();218 directory.onDidChange(changeHandler);219 waitsFor(() => !directory._pendingSubscription);220 runs(() => fs.writeFileSync(path.join(directoryPath, 'new_file.txt'), 'new contents!'));221 waitsFor(() => changeHandler.callCount > 0);222 runs(() => {223 expect(changeHandler.callCount).toBe(1);224 expect(changeHandler.argsForCall[0][0]).toEqual([{name: 'new_file.txt', mode: FILE_MODE, exists: true, new: true}]);225 });226 });227 it('notifies onDidChange observers when a file is removed from the directory', () => {228 var directory = new RemoteDirectory(connectionMock, directoryPath);229 var changeHandler = jasmine.createSpy();230 directory.onDidChange(changeHandler);231 waitsFor(() => !directory._pendingSubscription);232 runs(() => fs.unlinkSync(filePath));233 waitsFor(() => changeHandler.callCount > 0);234 runs(() => {235 expect(changeHandler.callCount).toBe(1);236 expect(changeHandler.argsForCall[0][0]).toEqual([{name: path.basename(filePath), mode: FILE_MODE, exists: false, new: false}]);237 });238 });239 it('Doesn\'t notify observers when a file is changed contents inside the the directory', () => {240 var directory = new RemoteDirectory(connectionMock, directoryPath);241 var changeHandler = jasmine.createSpy();242 directory.onDidChange(changeHandler);243 waitsFor(() => !directory._pendingSubscription);244 fs.writeFileSync(filePath, 'new contents!');245 waits(1000);246 runs(() => expect(changeHandler.callCount).toBe(0));247 });248 it('batches change events into a single call', () => {249 var directory = new RemoteDirectory(connectionMock, directoryPath);250 var changeHandler = jasmine.createSpy();251 directory.onDidChange(changeHandler);252 waitsFor(() => !directory._pendingSubscription);253 runs(() => {254 fs.writeFileSync(path.join(directoryPath, 'new_file_1.txt'), 'new contents 1!');255 fs.writeFileSync(path.join(directoryPath, 'new_file_2.txt'), 'new contents 2!');256 });257 waitsFor(() => changeHandler.callCount > 0);258 runs(() => {259 expect(changeHandler.callCount).toBe(1);260 var sortedChange = changeHandler.argsForCall[0][0].sort((a, b) => a.name > b.name);261 expect(sortedChange).toEqual([262 {name: 'new_file_1.txt', exists: true, mode: FILE_MODE, new: true},263 {name: 'new_file_2.txt', exists: true, mode: FILE_MODE, new: true},264 ]);265 });266 });...

Full Screen

Full Screen

main.js

Source:main.js Github

copy

Full Screen

1'use babel';2/* @flow */3/*4 * Copyright (c) 2015-present, Facebook, Inc.5 * All rights reserved.6 *7 * This source code is licensed under the license found in the LICENSE file in8 * the root directory of this source tree.9 */10var {CompositeDisposable, TextEditor} = require('atom');11var subscriptions: ?CompositeDisposable = null;12var pendingFiles = {};13var logger = null;14function getLogger() {15 return logger || (logger = require('nuclide-logging').getLogger());16}17var RemoteConnection = null;18function getRemoteConnection(): RemoteConnection {19 return RemoteConnection || (RemoteConnection = require('nuclide-remote-connection').RemoteConnection);20}21async function createRemoteConnection(remoteProjectConfig: RemoteConnectionConfiguration): Promise<?RemoteConnection> {22 var RemoteConnection = getRemoteConnection();23 try {24 var connection = new RemoteConnection(restoreClientKey(remoteProjectConfig));25 await connection.initialize();26 return connection;27 } catch (e) {28 // If connection fails using saved config, open connect dialog.29 var {openConnectionDialog} = require('nuclide-ssh-dialog');30 return openConnectionDialog({31 initialServer: remoteProjectConfig.host,32 initialCwd: remoteProjectConfig.cwd,33 });34 }35}36function addRemoteFolderToProject(connection: RemoteConnection) {37 var workingDirectoryUri = connection.getUriForInitialWorkingDirectory();38 // If restoring state, then the project already exists with local directory and wrong repo instances.39 // Hence, we remove it here, if existing, and add the new path for which we added a workspace opener handler.40 atom.project.removePath(workingDirectoryUri);41 atom.project.addPath(workingDirectoryUri);42 var subscription = atom.project.onDidChangePaths(paths => {43 if (paths.indexOf(workingDirectoryUri) !== -1) {44 return;45 }46 // The project was removed from the tree.47 subscription.dispose();48 closeOpenFilesForRemoteProject(connection.getConfig());49 var hostname = connection.getRemoteHostname();50 if (getRemoteConnection().getByHostname(hostname).length > 1) {51 getLogger().info('Remaining remote projects using Nuclide Server - no prompt to shutdown');52 return connection.close();53 }54 var choice = atom.confirm({55 message: 'No more remote projects on the host: `' + hostname + '`, Would you like to shutdown Nuclide server there?',56 buttons: ['Shutdown', 'Keep It'],57 });58 if (choice === 1) {59 return connection.close();60 }61 if (choice === 0) {62 connection.getClient().shutdownServer();63 return connection.close();64 }65 });66}67function closeOpenFilesForRemoteProject(remoteProjectConfig: RemoteConnectionConfiguration): Array<string> {68 var {closeTabForBuffer} = require('nuclide-atom-helpers');69 var {sanitizeNuclideUri} = require('./utils');70 var {host: projectHostname, cwd: projectDirectory} = remoteProjectConfig;71 var closedUris = [];72 atom.workspace.getTextEditors().forEach(editor => {73 var rawUrl = editor.getURI();74 if (!rawUrl) {75 return;76 }77 var uri = sanitizeNuclideUri(rawUrl);78 var {hostname: fileHostname, path: filePath} = require('nuclide-remote-uri').parse(uri);79 if (fileHostname === projectHostname && filePath.startsWith(projectDirectory)) {80 closeTabForBuffer(editor.getBuffer());81 if (filePath !== projectDirectory) {82 closedUris.push(uri);83 }84 }85 });86 return closedUris;87}88/**89 * Restore a nuclide project state from a serialized state of the remote connection config.90 */91async function restoreNuclideProjectState(remoteProjectConfig: RemoteConnectionConfiguration) {92 // TODO use the rest of the config for the connection dialog.93 var {host: projectHostname, cwd: projectDirectory} = remoteProjectConfig;94 // try to re-connect, then, add the project to atom.project and the tree.95 var connection = await createRemoteConnection(remoteProjectConfig);96 if (!connection) {97 getLogger().info('No RemoteConnection returned on restore state trial:', projectHostname, projectDirectory);98 }99 // Reload the project files that have empty text editors/buffers open.100 var closedUris = closeOpenFilesForRemoteProject(remoteProjectConfig);101 // On Atom restart, it tries to open the uri path as a file tab because it's not a local directory.102 // Hence, we close it in the cleanup, because we have the needed connection config saved103 // with the last opened files in the package state.104 if (connection) {105 closedUris.forEach(uri => atom.workspace.open(uri));106 }107}108function cleanupRemoteNuclideProjects() {109 getRemoteRootDirectories().forEach(directory => atom.project.removePath(directory.getPath()));110}111function getRemoteRootDirectories() {112 return atom.project.getDirectories().filter(directory => directory.getPath().startsWith('nuclide:'));113}114/**115 * The same TextEditor must be returned to prevent Atom from creating multiple tabs116 * for the same file, because Atom doesn't cache pending opener promises.117 */118async function createEditorForNuclide(connection: RemoteConnection, uri: string): TextEditor {119 var NuclideTextBuffer = require('./NuclideTextBuffer');120 var buffer = new NuclideTextBuffer(connection, {filePath: uri});121 buffer.setEncoding(atom.config.get('core.fileEncoding'));122 try {123 await buffer.load();124 } catch(err) {125 getLogger().warn('buffer load issue:', err);126 throw err;127 }128 return new TextEditor(/*editorOptions*/ {buffer, registerEditor: true});129}130/**131 * Encrypts the clientKey of a RemoteConnectionConfiguration.132 * @param remoteProjectConfig - The config with the clientKey we want encrypted.133 * @return returns the passed in config with the clientKey encrypted.134 */135function protectClientKey(remoteProjectConfig: RemoteConnectionConfiguration): RemoteConnectionConfiguration {136 var {replacePassword} = require('nuclide-keytar-wrapper');137 var crypto = require('crypto');138 var sha1 = crypto.createHash('sha1');139 sha1.update(`${remoteProjectConfig.host}:${remoteProjectConfig.port}`);140 var sha1sum = sha1.digest('hex');141 var {salt, password, encryptedString} = encryptString(remoteProjectConfig.clientKey);142 replacePassword('nuclide.remoteProjectConfig', sha1sum, `${password}`);143 remoteProjectConfig.clientKey = encryptedString + '.' + salt;144 return remoteProjectConfig;145}146/**147 * Decrypts the clientKey of a RemoteConnectionConfiguration.148 * @param remoteProjectConfig - The config with the clientKey we want encrypted.149 * @return returns the passed in config with the clientKey encrypted.150 */151function restoreClientKey(remoteProjectConfig: RemoteConnectionConfiguration): RemoteConnectionConfiguration {152 var {getPassword} = require('nuclide-keytar-wrapper');153 var crypto = require('crypto');154 var sha1 = crypto.createHash('sha1');155 sha1.update(`${remoteProjectConfig.host}:${remoteProjectConfig.port}`);156 var sha1sum = sha1.digest('hex');157 var password = getPassword('nuclide.remoteProjectConfig', sha1sum);158 if (!password) {159 throw new Error('Cannot find password for encrypted client key');160 }161 var salt;162 var clientKey;163 [clientKey, salt] = remoteProjectConfig.clientKey.split('.');164 if (!clientKey || !salt) {165 throw new Error('Cannot decrypt client key');166 }167 remoteProjectConfig.clientKey = decryptString(clientKey, password, salt);168 return remoteProjectConfig;169}170function decryptString(text: string, password: string, salt: string): string {171 var crypto = require('crypto');172 var decipher = crypto.createDecipheriv(173 'aes-128-cbc',174 new Buffer(password, 'base64'),175 new Buffer(salt, 'base64'));176 var decryptedString = decipher.update(text, 'base64', 'utf8');177 decryptedString += decipher.final('utf8');178 return decryptedString;179}180function encryptString(text: string): any {181 var crypto = require('crypto');182 var password = crypto.randomBytes(16).toString('base64');183 var salt = crypto.randomBytes(16).toString('base64');184 var cipher = crypto.createCipheriv(185 'aes-128-cbc',186 new Buffer(password, 'base64'),187 new Buffer(salt, 'base64'));188 var encryptedString = cipher.update(text, 'utf8', 'base64');189 encryptedString += cipher.final('base64');190 return {191 password,192 salt,193 encryptedString,194 };195}196module.exports = {197 __test__: {198 decryptString,199 encryptString,200 },201 activate(state: ?any): void {202 subscriptions = new CompositeDisposable();203 subscriptions.add(getRemoteConnection().onDidAddRemoteConnection(connection => {204 addRemoteFolderToProject(connection);205 }));206 // Don't do require or any other expensive operations in activate().207 subscriptions.add(atom.packages.onDidActivateInitialPackages(() => {208 // Subscribe opener before restoring the remote projects.209 subscriptions.add(atom.workspace.addOpener((uri = '') => {210 if (uri.startsWith('nuclide:')) {211 var connection = getRemoteConnection().getForUri(uri);212 // On Atom restart, it tries to open the uri path as a file tab because it's not a local directory.213 // We can't let that create a file with the initial working directory path.214 if (connection && uri !== connection.getUriForInitialWorkingDirectory()) {215 if (pendingFiles[uri]) {216 return pendingFiles[uri];217 }218 var textEditorPromise = pendingFiles[uri] = createEditorForNuclide(connection, uri);219 var removeFromCache = () => delete pendingFiles[uri];220 textEditorPromise.then(removeFromCache, removeFromCache);221 return textEditorPromise;222 }223 }224 }));225 subscriptions.add(atom.commands.add(226 'atom-workspace',227 'nuclide-remote-projects:connect',228 () => require('nuclide-ssh-dialog').openConnectionDialog()229 ));230 // Remove remote projects added in case of reloads.231 // We already have their connection config stored.232 var remoteProjectsConfig = (state && state.remoteProjectsConfig) || [];233 remoteProjectsConfig.forEach(restoreNuclideProjectState);234 // Clear obsolete config.235 atom.config.set('nuclide.remoteProjectsConfig', []);236 }));237 },238 serialize(): any {239 var remoteProjectsConfig = getRemoteRootDirectories()240 .map(directory => {241 var connection = getRemoteConnection().getForUri(directory.getPath());242 return connection && protectClientKey(connection.getConfig());243 }).filter(config => !!config);244 return {245 remoteProjectsConfig,246 };247 },248 deactivate(): void {249 // This should always be true here, but we do this to appease Flow.250 if (subscriptions) {251 subscriptions.dispose();252 subscriptions = null;253 }254 },255 createRemoteDirectoryProvider(): RemoteDirectoryProvider {256 var RemoteDirectoryProvider = require('./RemoteDirectoryProvider');257 return new RemoteDirectoryProvider();258 },...

Full Screen

Full Screen

aboutNewTabService.js

Source:aboutNewTabService.js Github

copy

Full Screen

1/*2 * This Source Code Form is subject to the terms of the Mozilla Public3 * License, v. 2.0. If a copy of the MPL was not distributed with this4 * file, You can obtain one at http://mozilla.org/MPL/2.0/.5*/6/* globals XPCOMUtils, NewTabPrefsProvider, Services,7 Locale, UpdateUtils, NewTabRemoteResources8*/9"use strict";10const {utils: Cu, interfaces: Ci} = Components;11Cu.import("resource://gre/modules/XPCOMUtils.jsm");12Cu.import("resource://gre/modules/Services.jsm");13XPCOMUtils.defineLazyModuleGetter(this, "UpdateUtils",14 "resource://gre/modules/UpdateUtils.jsm");15XPCOMUtils.defineLazyModuleGetter(this, "NewTabPrefsProvider",16 "resource:///modules/NewTabPrefsProvider.jsm");17XPCOMUtils.defineLazyModuleGetter(this, "Locale",18 "resource://gre/modules/Locale.jsm");19XPCOMUtils.defineLazyModuleGetter(this, "NewTabRemoteResources",20 "resource:///modules/NewTabRemoteResources.jsm");21const LOCAL_NEWTAB_URL = "chrome://browser/content/newtab/newTab.xhtml";22const REMOTE_NEWTAB_PATH = "/newtab/v%VERSION%/%CHANNEL%/%LOCALE%/index.html";23const ABOUT_URL = "about:newtab";24// Pref that tells if remote newtab is enabled25const PREF_REMOTE_ENABLED = "browser.newtabpage.remote";26// Pref branch necesssary for testing27const PREF_REMOTE_CS_TEST = "browser.newtabpage.remote.content-signing-test";28// The preference that tells whether to match the OS locale29const PREF_MATCH_OS_LOCALE = "intl.locale.matchOS";30// The preference that tells what locale the user selected31const PREF_SELECTED_LOCALE = "general.useragent.locale";32// The preference that tells what remote mode is enabled.33const PREF_REMOTE_MODE = "browser.newtabpage.remote.mode";34// The preference that tells which remote version is expected.35const PREF_REMOTE_VERSION = "browser.newtabpage.remote.version";36const VALID_CHANNELS = new Set(["esr", "release", "hardened", "beta", "alpha", "aurora", "nightly"]);37function AboutNewTabService() {38 NewTabPrefsProvider.prefs.on(PREF_REMOTE_ENABLED, this._handleToggleEvent.bind(this));39 this._updateRemoteMaybe = this._updateRemoteMaybe.bind(this);40 // trigger remote change if needed, according to pref41 this.toggleRemote(Services.prefs.getBoolPref(PREF_REMOTE_ENABLED));42}43/*44 * A service that allows for the overriding, at runtime, of the newtab page's url.45 * Additionally, the service manages pref state between a remote and local newtab page.46 *47 * There is tight coupling with browser/about/AboutRedirector.cpp.48 *49 * 1. Browser chrome access:50 *51 * When the user issues a command to open a new tab page, usually clicking a button52 * in the browser chrome or using shortcut keys, the browser chrome code invokes the53 * service to obtain the newtab URL. It then loads that URL in a new tab.54 *55 * When not overridden, the default URL emitted by the service is "about:newtab".56 * When overridden, it returns the overriden URL.57 *58 * 2. Redirector Access:59 *60 * When the URL loaded is about:newtab, the default behavior, or when entered in the61 * URL bar, the redirector is hit. The service is then called to return either of62 * two URLs, a chrome or remote one, based on the browser.newtabpage.remote pref.63 *64 * NOTE: "about:newtab" will always result in a default newtab page, and never an overridden URL.65 *66 * Access patterns:67 *68 * The behavior is different when accessing the service via browser chrome or via redirector69 * largely to maintain compatibility with expectations of add-on developers.70 *71 * Loading a chrome resource, or an about: URL in the redirector with either the72 * LOAD_NORMAL or LOAD_REPLACE flags yield unexpected behaviors, so a roundtrip73 * to the redirector from browser chrome is avoided.74 */75AboutNewTabService.prototype = {76 _newTabURL: ABOUT_URL,77 _remoteEnabled: false,78 _remoteURL: null,79 _overridden: false,80 classID: Components.ID("{dfcd2adc-7867-4d3a-ba70-17501f208142}"),81 QueryInterface: XPCOMUtils.generateQI([Ci.nsIAboutNewTabService]),82 _xpcom_categories: [{83 service: true84 }],85 _handleToggleEvent(prefName, stateEnabled, forceState) { // jshint unused:false86 if (this.toggleRemote(stateEnabled, forceState)) {87 Services.obs.notifyObservers(null, "newtab-url-changed", ABOUT_URL);88 }89 },90 /**91 * React to changes to the remote newtab pref.92 *93 * If browser.newtabpage.remote is true, this will change the default URL to the94 * remote newtab page URL. If browser.newtabpage.remote is false, the default URL95 * will be a local chrome URL.96 *97 * This will only act if there is a change of state and if not overridden.98 *99 * @returns {Boolean} Returns if there has been a state change100 *101 * @param {Boolean} stateEnabled remote state to set to102 * @param {Boolean} forceState force state change103 */104 toggleRemote(stateEnabled, forceState) {105 if (!forceState && (this._overriden || stateEnabled === this._remoteEnabled)) {106 // exit there is no change of state107 return false;108 }109 let csTest = Services.prefs.getBoolPref(PREF_REMOTE_CS_TEST);110 if (stateEnabled) {111 if (!csTest) {112 this._remoteURL = this.generateRemoteURL();113 } else {114 this._remoteURL = this._newTabURL;115 }116 NewTabPrefsProvider.prefs.on(117 PREF_SELECTED_LOCALE,118 this._updateRemoteMaybe);119 NewTabPrefsProvider.prefs.on(120 PREF_MATCH_OS_LOCALE,121 this._updateRemoteMaybe);122 NewTabPrefsProvider.prefs.on(123 PREF_REMOTE_MODE,124 this._updateRemoteMaybe);125 NewTabPrefsProvider.prefs.on(126 PREF_REMOTE_VERSION,127 this._updateRemoteMaybe);128 this._remoteEnabled = true;129 } else {130 NewTabPrefsProvider.prefs.off(PREF_SELECTED_LOCALE, this._updateRemoteMaybe);131 NewTabPrefsProvider.prefs.off(PREF_MATCH_OS_LOCALE, this._updateRemoteMaybe);132 NewTabPrefsProvider.prefs.off(PREF_REMOTE_MODE, this._updateRemoteMaybe);133 NewTabPrefsProvider.prefs.off(PREF_REMOTE_VERSION, this._updateRemoteMaybe);134 this._remoteEnabled = false;135 }136 if (!csTest) {137 this._newTabURL = ABOUT_URL;138 }139 return true;140 },141 /*142 * Generate a default url based on remote mode, version, locale and update channel143 */144 generateRemoteURL() {145 let releaseName = this.releaseFromUpdateChannel(UpdateUtils.UpdateChannel);146 let path = REMOTE_NEWTAB_PATH147 .replace("%VERSION%", this.remoteVersion)148 .replace("%LOCALE%", Locale.getLocale())149 .replace("%CHANNEL%", releaseName);150 let mode = Services.prefs.getCharPref(PREF_REMOTE_MODE, "production");151 if (!(mode in NewTabRemoteResources.MODE_CHANNEL_MAP)) {152 mode = "production";153 }154 return NewTabRemoteResources.MODE_CHANNEL_MAP[mode].origin + path;155 },156 /*157 * Returns the default URL.158 *159 * This URL only depends on the browser.newtabpage.remote pref. Overriding160 * the newtab page has no effect on the result of this function.161 *162 * The result is also the remote URL if this is in a test (PREF_REMOTE_CS_TEST)163 *164 * @returns {String} the default newtab URL, remote or local depending on browser.newtabpage.remote165 */166 get defaultURL() {167 let csTest = Services.prefs.getBoolPref(PREF_REMOTE_CS_TEST);168 if (this._remoteEnabled || csTest) {169 return this._remoteURL;170 }171 return LOCAL_NEWTAB_URL;172 },173 /*174 * Updates the remote location when the page is not overriden.175 *176 * Useful when there is a dependent pref change177 */178 _updateRemoteMaybe() {179 if (!this._remoteEnabled || this._overridden) {180 return;181 }182 let url = this.generateRemoteURL();183 if (url !== this._remoteURL) {184 this._remoteURL = url;185 Services.obs.notifyObservers(null, "newtab-url-changed",186 this._remoteURL);187 }188 },189 /**190 * Returns the release name from an Update Channel name191 *192 * @returns {String} a release name based on the update channel. Defaults to nightly193 */194 releaseFromUpdateChannel(channelName) {195 return VALID_CHANNELS.has(channelName) ? channelName : "nightly";196 },197 get newTabURL() {198 return this._newTabURL;199 },200 get remoteVersion() {201 return Services.prefs.getCharPref(PREF_REMOTE_VERSION, "1");202 },203 get remoteReleaseName() {204 return this.releaseFromUpdateChannel(UpdateUtils.UpdateChannel);205 },206 set newTabURL(aNewTabURL) {207 let csTest = Services.prefs.getBoolPref(PREF_REMOTE_CS_TEST);208 aNewTabURL = aNewTabURL.trim();209 if (aNewTabURL === ABOUT_URL) {210 // avoid infinite redirects in case one sets the URL to about:newtab211 this.resetNewTabURL();212 return;213 } else if (aNewTabURL === "") {214 aNewTabURL = "about:blank";215 }216 let remoteURL = this.generateRemoteURL();217 let prefRemoteEnabled = Services.prefs.getBoolPref(PREF_REMOTE_ENABLED);218 let isResetLocal = !prefRemoteEnabled && aNewTabURL === LOCAL_NEWTAB_URL;219 let isResetRemote = prefRemoteEnabled && aNewTabURL === remoteURL;220 if (isResetLocal || isResetRemote) {221 if (this._overriden && !csTest) {222 // only trigger a reset if previously overridden and this is no test223 this.resetNewTabURL();224 }225 return;226 }227 // turn off remote state if needed228 if (!csTest) {229 this.toggleRemote(false);230 } else {231 // if this is a test, we want the remoteURL to be set232 this._remoteURL = aNewTabURL;233 }234 this._newTabURL = aNewTabURL;235 this._overridden = true;236 Services.obs.notifyObservers(null, "newtab-url-changed", this._newTabURL);237 },238 get overridden() {239 return this._overridden;240 },241 get remoteEnabled() {242 return this._remoteEnabled;243 },244 resetNewTabURL() {245 this._overridden = false;246 this._newTabURL = ABOUT_URL;247 this.toggleRemote(Services.prefs.getBoolPref(PREF_REMOTE_ENABLED), true);248 Services.obs.notifyObservers(null, "newtab-url-changed", this._newTabURL);249 }250};...

Full Screen

Full Screen

test_remote_client_manager.js

Source:test_remote_client_manager.js Github

copy

Full Screen

1/* Any copyright is dedicated to the Public Domain.2 http://creativecommons.org/publicdomain/zero/1.0/ */3"use strict";4const {5 remoteClientManager,6} = require("devtools/client/shared/remote-debugging/remote-client-manager");7const {8 CONNECTION_TYPES,9} = require("devtools/client/shared/remote-debugging/constants");10add_task(async function testRemoteClientManager() {11 for (const type of Object.values(CONNECTION_TYPES)) {12 const fakeClient = createFakeClient();13 const runtimeInfo = {};14 const clientId = "clientId";15 const remoteId = remoteClientManager.getRemoteId(clientId, type);16 const connectionType = remoteClientManager.getConnectionTypeByRemoteId(17 remoteId18 );19 equal(20 connectionType,21 type,22 `[${type}]: Correct connection type was returned by getConnectionTypeByRemoteId`23 );24 equal(25 remoteClientManager.hasClient(clientId, type),26 false,27 `[${type}]: hasClient returns false if no client was set`28 );29 equal(30 remoteClientManager.getClient(clientId, type),31 null,32 `[${type}]: getClient returns null if no client was set`33 );34 equal(35 remoteClientManager.getClientByRemoteId(remoteId),36 null,37 `[${type}]: getClientByRemoteId returns null if no client was set`38 );39 equal(40 remoteClientManager.getRuntimeInfoByRemoteId(remoteId),41 null,42 `[${type}]: getRuntimeInfoByRemoteId returns null if no client was set`43 );44 remoteClientManager.setClient(clientId, type, fakeClient, runtimeInfo);45 equal(46 remoteClientManager.hasClient(clientId, type),47 true,48 `[${type}]: hasClient returns true`49 );50 equal(51 remoteClientManager.getClient(clientId, type),52 fakeClient,53 `[${type}]: getClient returns the correct client`54 );55 equal(56 remoteClientManager.getClientByRemoteId(remoteId),57 fakeClient,58 `[${type}]: getClientByRemoteId returns the correct client`59 );60 equal(61 remoteClientManager.getRuntimeInfoByRemoteId(remoteId),62 runtimeInfo,63 `[${type}]: getRuntimeInfoByRemoteId returns the correct object`64 );65 remoteClientManager.removeClient(clientId, type);66 equal(67 remoteClientManager.hasClient(clientId, type),68 false,69 `[${type}]: hasClient returns false after removing the client`70 );71 equal(72 remoteClientManager.getClient(clientId, type),73 null,74 `[${type}]: getClient returns null after removing the client`75 );76 equal(77 remoteClientManager.getClientByRemoteId(remoteId),78 null,79 `[${type}]: getClientByRemoteId returns null after removing the client`80 );81 equal(82 remoteClientManager.getRuntimeInfoByRemoteId(),83 null,84 `[${type}]: getRuntimeInfoByRemoteId returns null after removing the client`85 );86 }87 // Test various fallback scenarios for APIs relying on remoteId, when called without a88 // remoteId, we expect to get the information for the local this-firefox runtime.89 const { THIS_FIREFOX } = CONNECTION_TYPES;90 const thisFirefoxClient = createFakeClient();91 const thisFirefoxInfo = {};92 remoteClientManager.setClient(93 THIS_FIREFOX,94 THIS_FIREFOX,95 thisFirefoxClient,96 thisFirefoxInfo97 );98 equal(99 remoteClientManager.getClientByRemoteId(),100 thisFirefoxClient,101 `[fallback]: getClientByRemoteId returns this-firefox if remoteId is null`102 );103 equal(104 remoteClientManager.getRuntimeInfoByRemoteId(),105 thisFirefoxInfo,106 `[fallback]: getRuntimeInfoByRemoteId returns this-firefox if remoteId is null`107 );108 const otherRemoteId = remoteClientManager.getRemoteId(109 "clientId",110 CONNECTION_TYPES.USB111 );112 equal(113 remoteClientManager.getClientByRemoteId(otherRemoteId),114 null,115 `[fallback]: getClientByRemoteId does not fallback if remoteId is non-null`116 );117 equal(118 remoteClientManager.getRuntimeInfoByRemoteId(otherRemoteId),119 null,120 `[fallback]: getRuntimeInfoByRemoteId does not fallback if remoteId is non-null`121 );122});123add_task(async function testRemoteClientManagerWithUnknownType() {124 const remoteId = remoteClientManager.getRemoteId(125 "someClientId",126 "NotARealType"127 );128 const connectionType = remoteClientManager.getConnectionTypeByRemoteId(129 remoteId130 );131 equal(132 connectionType,133 CONNECTION_TYPES.UNKNOWN,134 `Connection type UNKNOWN was returned by getConnectionTypeByRemoteId`135 );136});137function createFakeClient() {138 const EventEmitter = require("devtools/shared/event-emitter");139 const client = {};140 EventEmitter.decorate(client);141 return client;...

Full Screen

Full Screen

cors-redirect-credentials.js

Source:cors-redirect-credentials.js Github

copy

Full Screen

1if (this.document === undefined) {2 importScripts("/resources/testharness.js");3 importScripts("../resources/utils.js");4 importScripts("/common/get-host-info.sub.js")5}6function corsRedirectCredentials(desc, redirectUrl, redirectLocation, redirectStatus, locationCredentials) {7 var url = redirectUrl8 var urlParameters = "?redirect_status=" + redirectStatus;9 urlParameters += "&location=" + encodeURIComponent(redirectLocation.replace("://", "://" + locationCredentials + "@"));10 var requestInit = {"mode": "cors", "redirect": "follow", "credentials":"include"};11 promise_test(function(test) {12 return promise_rejects(test, new TypeError(), fetch(url + urlParameters, requestInit));13 }, desc);14}15var redirPath = dirname(location.pathname) + RESOURCES_DIR + "redirect.py";16var preflightPath = dirname(location.pathname) + RESOURCES_DIR + "preflight.py";17var host_info = get_host_info();18var localRedirect = host_info.HTTP_ORIGIN + redirPath;19var remoteRedirect = host_info.HTTP_ORIGIN_WITH_DIFFERENT_PORT + redirPath;20var localLocation = host_info.HTTP_ORIGIN + preflightPath;21var remoteLocation = host_info.HTTP_ORIGIN_WITH_DIFFERENT_PORT + preflightPath;22var remoteLocation2 = host_info.HTTP_REMOTE_ORIGIN + preflightPath;23for (var code of [301, 302, 303, 307, 308]) {24 corsRedirectCredentials("Redirect " + code + " from same origin to remote with user and password", localRedirect, remoteLocation, code, "user:password");25 corsRedirectCredentials("Redirect " + code + " from same origin to remote with user", localRedirect, remoteLocation, code, "user:");26 corsRedirectCredentials("Redirect " + code + " from same origin to remote with password", localRedirect, remoteLocation, code, ":password");27 corsRedirectCredentials("Redirect " + code + " from remote to same origin with user and password", remoteRedirect, localLocation, code, "user:password");28 corsRedirectCredentials("Redirect " + code + " from remote to same origin with user", remoteRedirect, localLocation, code, "user:");29 corsRedirectCredentials("Redirect " + code + " from remote to same origin with password", remoteRedirect, localLocation, code, ":password");30 corsRedirectCredentials("Redirect " + code + " from remote to same remote with user and password", remoteRedirect, remoteLocation, code, "user:password");31 corsRedirectCredentials("Redirect " + code + " from remote to same remote with user", remoteRedirect, remoteLocation, code, "user:");32 corsRedirectCredentials("Redirect " + code + " from remote to same remote with password", remoteRedirect, remoteLocation, code, ":password");33 corsRedirectCredentials("Redirect " + code + " from remote to another remote with user and password", remoteRedirect, remoteLocation2, code, "user:password");34 corsRedirectCredentials("Redirect " + code + " from remote to another remote with user", remoteRedirect, remoteLocation2, code, "user:");35 corsRedirectCredentials("Redirect " + code + " from remote to another remote with password", remoteRedirect, remoteLocation2, code, ":password");36}...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const wdio = require('webdriverio');2const opts = {3 capabilities: {4 }5};6let client = wdio.remote(opts);7 .init()8 .then(() => {9 return client.execute('mobile: launchApp', {bundleId: 'com.apple.mobilesafari'});10 })11 .then(() => {12 return client.pause(10000);13 })14 .then(() => {15 return client.execute('mobile: terminateApp', {bundleId: 'com.apple.mobilesafari'});16 })17 .then(() => {18 return client.end();19 })20 .catch((err) => {21 console.log(err);22 });23const wdio = require('webdriverio');24const opts = {25 capabilities: {26 }27};28let client = wdio.remote(opts);29 .init()30 .then(() => {31 return client.execute('mobile: launchApp', {bundleId: 'com.apple.mobilesafari'});32 })33 .then(() => {34 return client.pause(10000);35 })36 .then(() => {37 return client.execute('mobile: terminateApp', {bundleId: 'com.apple.mobilesafari'});38 })39 .then(() => {40 return client.end();41 })42 .catch((err) => {43 console.log(err);44 });45const wdio = require('webdriverio');46const opts = {47 capabilities: {

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriver = require('selenium-webdriver');2var remote = require('selenium-webdriver/remote');3var assert = require('assert');4var driver = new webdriver.Builder()5 .withCapabilities({6 })7 .build();8driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');9driver.findElement(webdriver.By.name('btnK')).click();10driver.wait(function() {11 return driver.getTitle().then(function(title) {12 return title === 'webdriver - Google Search';13 });14}, 1000);15driver.quit();16[debug] [JSONWP Proxy] Got response with status 200: "{\"value\":\"Invalid element coordinates: {0, 0}\",\"sessionId\":\"0A8C0D1C-7F2A-4A2B-8A8A-7F07A1F6F7A8\",\"status\":13}"

Full Screen

Using AI Code Generation

copy

Full Screen

1(async () => {2 const driver = await wdio.remote({3 capabilities: {4 }5 });6 await driver.pause(3000);7 await driver.execute('mobile: launchApp', {bundleId: 'com.apple.MobileAddressBook'});8 await driver.pause(3000);9 await driver.execute('mobile: terminateApp', {bundleId: 'com.apple.MobileAddressBook'});10 await driver.pause(3000);11 await driver.deleteSession();12})();13exports.config = {14 capabilities: [{15 }],16 appium: {17 args: {

Full Screen

Using AI Code Generation

copy

Full Screen

1async function test() {2 const driver = await wdio.remote({3 capabilities: {4 }5 });6 const source = await driver.getPageSource();7 console.log(source);8}9test();10 (Driver info: chromedriver=86.0.4240.22 (b0e4c7c4e1d3b7ec8f9b3f9c0a2c0e7e8d3e2b7d-refs/branch-heads/4240@{#362}),platform=Mac OS X 10.15.7 x86_64)11goog:chromeOptions: {12 }13goog:chromeOptions: {14 }15goog:chromeOptions: {16 }17goog:chromeOptions: {18 }

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var assert = require('assert');3var username = "mamta";4var accessKey = "d0e6a4e6-8f1b-4e7c-9b2f-8b5e5b1d7a21";5var serverConfig = {6};7var desiredCaps = {8};9var driver = wd.promiseChainRemote(serverConfig);10 .init(desiredCaps)11 .setImplicitWaitTimeout(10000)12 .elementByAccessibilityId('IntegerA')13 .sendKeys('10')14 .elementByAccessibilityId('IntegerB')15 .sendKeys('50')16 .elementByAccessibilityId('ComputeSumButton')17 .click()18 .elementByAccessibilityId('Answer')19 .text().then(function(text) {20 assert.equal(text, "60");21 })22 .fin(function() { return driver.quit(); })23 .done();24var wd = require('wd');25var assert = require('assert');26var username = "mamta";27var accessKey = "d0e6a4e6-8f1b-4e7c-9b2f-8b5e5b1d7a21";28var serverConfig = {29};30var desiredCaps = {

Full Screen

Using AI Code Generation

copy

Full Screen

1var XCUITestDriver = require('/Users/xyz/Desktop/Appium-XCUITest-Driver/lib/driver.js');2var driver = new XCUITestDriver();3driver.createSession({desiredCapabilities: {app: '/Users/xyz/Desktop/MyApp.app', platformName: 'iOS', platformVersion: '9.2', deviceName: 'iPhone 6'}});4var IOSDriver = require('/Users/xyz/Desktop/Appium/lib/devices/ios/ios.js');5var driver = new IOSDriver();6driver.createSession({desiredCapabilities: {app: '/Users/xyz/Desktop/MyApp.app', platformName: 'iOS', platformVersion: '9.2', deviceName: 'iPhone 6'}});7var AndroidDriver = require('/Users/xyz/Desktop/Appium/lib/devices/android/android.js');8var driver = new AndroidDriver();9driver.createSession({desiredCapabilities: {app: '/Users/xyz/Desktop/MyApp.apk', platformName: 'Android', platformVersion: '5.1', deviceName: 'Android Emulator'}});10var WindowsDriver = require('/Users/xyz/Desktop/Appium/lib/devices/windows/windows.js');11var driver = new WindowsDriver();12driver.createSession({desiredCapabilities: {app: '/Users/xyz/Desktop/MyApp.appx', platformName: 'Windows', platformVersion: '10', deviceName: 'WindowsPC'}});13var MacDriver = require('/Users/xyz/Desktop/Appium/lib/devices/mac/mac.js');14var driver = new MacDriver();15driver.createSession({desiredCapabilities: {app: '/Users/xyz/Desktop/MyApp.app', platformName: 'Mac', platformVersion: '10.11', deviceName: 'Mac'}});

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