How to use driver.url method in Appium

Best JavaScript code snippet using appium

ncr_driverAJAX.js

Source:ncr_driverAJAX.js Github

copy

Full Screen

1// IMPORTANT: This code requires the including file to define the following variables:2//            var urlArray3//            var isPerformDriverCheckUsingAJAX4//            var isCheckDriverWithoutContactingDriver5//            var checkDriverUsingAjaxMethodCallTimeoutMs6//            var currentUrlContext7//            var workstationDriverUrl89// This code is tied to a check for Driver using a client-side AJAX approach, enabled with the v3.9.0 Preference 'CheckDriverUsingAJAX'.10var urlArray;11var CONSTANTS = {12	"driverUrlDiv" : "driverUrlDiv",13	"currentUrlIndex" : "currentUrlIndex",14	"selectedAJAXDriverUrl" : "selectedAJAXDriverUrl",15	"urlStatus_WAITING" : "WAITING",16	"urlStatus_TESTING" : "TESTING",17	"urlStatus_PASSED" : "PASSED",18	"urlStatus_FAILED" : "FAILED",19	"urlStatus_TIMEOUT" : "TIMEOUT",20	"urlStatus_SKIPPED" : "SKIPPED",21	"STATUS_INVALID_PTC_CMD" : "STATUS_INVALID_PTC_CMD",22	"STATUS_TRANSPORT_OFF" : "STATUS_TRANSPORT_OFF",23	"driverStatus_Unknown" : "STATUS_UNKNOWN"24};25var numberOfRetries = 0;26var maximumNumberOfRetries = 7;27var browserIsIE = is_ie;28var browserIsChrome = window.chrome;29var xhr;30var requestTimer;31var JSON = JSON || {};3233var timeout_instance34var interval_instance35// implement JSON.stringify serialization36JSON.stringify = JSON.stringify || function(obj) {37	var t = typeof (obj);38	if (t != "object" || obj === null) {39		// simple data type40		if (t == "string")41			obj = '"' + obj + '"';42		return String(obj);43	} else {44		// recurse array or object45		var n, v, json = [], arr = (obj && obj.constructor == Array);46		for (n in obj) {47			v = obj[n];48			t = typeof (v);49			if (t == "string")50				v = '"' + v + '"';51			else if (t == "object" && v !== null)52				v = JSON.stringify(v);53			json.push((arr ? "" : '"' + n + '":') + String(v));54		}55		return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");56	}57};5859if (typeof String.prototype.hashCode != 'function') {60	String.prototype.hashCode = function() {61		var hash = 0;62		if (this.length == 0)63			return hash;64		var i;65		var j = this.length;66		for (i = 0; i < j; i++) {67			char = this.charCodeAt(i);68			hash = ((hash << 5) - hash) + char;69			hash = hash & hash; // Convert to 32bit integer70		}71		return hash;72	}73}7475if (typeof String.prototype.startsWith != 'function') {76	String.prototype.startsWith = function(str) {77		return this.slice(0, str.length) == str;78	};79}8081if (typeof String.prototype.endsWith !== 'function') {82	String.prototype.endsWith = function(suffix) {83		return this.indexOf(suffix, this.length - suffix.length) !== -1;84	};85}8687function createXHR() {88	var functionName = "createXHR(): ";89	consoleLog(functionName + "Entering " + functionName + "...");90	var xhr;91	if (window.XDomainRequest) { // typeof XDomainRequest != "undefined"92		consoleLog(functionName93				+ "IE Browser detected, creating xhr by calling new window.XDomainRequest()...");94		xhr = new window.XDomainRequest();95	} else {96		consoleLog(functionName + "Non-IE Browser detected, creating xhr by calling new XMLHttpRequest()...");97		xhr = new XMLHttpRequest();98	}99	consoleLog(functionName + "typeof xhr is " + (typeof xhr) + "...");100	return xhr;101	consoleLog(functionName + "Exiting " + functionName + "...");102}103104function createCORSRequest(method, url) {105	var xhr = new XMLHttpRequest();106	if ("withCredentials" in xhr) {107		// Check if the XMLHttpRequest object has a "withCredentials" property.108		// "withCredentials" only exists on XMLHTTPRequest2 objects.109		xhr.open(method, url, true);110	} else if (typeof XDomainRequest != "undefined") {111		// Otherwise, check if XDomainRequest.112		// XDomainRequest only exists in IE, and is IE's way of making CORS requests.113		xhr = new XDomainRequest();114		xhr.open(method, url);115	} else {116		// Otherwise, CORS is not supported by the browser.117		xhr = null;118	}119	return xhr;120}121122function establishDriverUrl() {123	var functionName = "establishDriverUrl(): ";124	consoleLog(functionName + "Entering " + functionName + "...");125	if (urlArray && urlArray.driverUrls && (urlArray.driverUrls.length > 0)) {126		consoleLog(functionName + "urlArray contains "127				+ urlArray.driverUrls.length + " items.");128		initializeDriverUrlVerification();129	} else {130		consoleWarn("WARNING: Could not initialize urlArray from Preferences! No Driver verification can be completed!");131	}132	consoleLog(functionName + "Exiting " + functionName + "...");133}134135function initializeDriverUrlVerification() {136	var functionName = "initializeDriverUrlVerification(): ";137	consoleLog(functionName + "Entering " + functionName + "...");138	var driverUrlDiv = document.getElementById(CONSTANTS.driverUrlDiv);139	if (driverUrlDiv) {140		// Setup a currentURL DIV and one for each URL to be checked while pre-calculating each URL's hash value141		driverUrlDiv.appendChild(createDocumentFragment("<div id='" + CONSTANTS.currentUrlIndex + "'>0</div>"));142		driverUrlDiv.appendChild(createDocumentFragment("<div id='" + CONSTANTS.selectedAJAXDriverUrl + "'></div>"));143		var driverUrlVerificationIterator;144		var driverUrlVerificationLength = urlArray.driverUrls.length;145		for (driverUrlVerificationIterator = 0; driverUrlVerificationIterator < driverUrlVerificationLength; driverUrlVerificationIterator++) {146			var currentDriverUrl = urlArray.driverUrls[driverUrlVerificationIterator].driverUrl;147			var urlId = "url_" + currentDriverUrl.hashCode();148			urlArray.driverUrls[driverUrlVerificationIterator].urlId = urlId;149			urlArray.driverUrls[driverUrlVerificationIterator].status = CONSTANTS.urlStatus_WAITING;150			// Empty out the contents of an existing DIV for this URL151			var thisUrlDiv = document.getElementById(urlId);152			if (thisUrlDiv) {153				thisUrlDiv.innerHTML = "";154			}155			driverUrlDiv.appendChild(createDocumentFragment("<div id='" + urlId + "'>" + JSON.stringify(urlArray.driverUrls[driverUrlVerificationIterator]) + "'</div>"));156		}157	}158	// Setup the first URL for testing now...159	var urlDiv = document.getElementById(urlArray.driverUrls[0].urlId);160	if (urlDiv) {161		urlDiv.innerHTML = JSON.stringify(urlArray.driverUrls[0]);162		consoleLog(functionName + CONSTANTS.urlStatus_TESTING + " - "163				+ JSON.stringify(urlArray.driverUrls[0]) + "...");164		// Always use JSONP165		testDriverUrlUsingJQuerygetJSON("true");166	} else {167		consoleWarn("WARNING: Could not find DIV with id '" + urlArray.driverUrls[0].urlId + "' inside the HTML document! " +168				     " No Driver verification can be completed!");169	}170	consoleLog(functionName + "Exiting " + functionName + "...");171}172173function generateDriverCheckUrlFromDriverUrl(driverUrl) {174	return driverUrl + "?PTC_CMD=QINFO&PTC_SUCCESS_URL=" + currentUrlContext + "/Success" + "&PTC_FAILURE_URL=" + currentUrlContext + "/Failure" + "&PTC_DEPOSITID=0&format=json";175}176177function generateInfoDriverUrl(driverUrl) {178	return driverUrl + "?PTC_CMD=INFO&PTC_SUCCESS_URL=" + currentUrlContext + "/Success" + "&PTC_FAILURE_URL=" + currentUrlContext + "/Failure" + "&PTC_DEPOSITID=0&format=json";179}180181function logExceptionMessage(ex, functionName) {182	var exMessage = "";183	if (ex && ex.message) {184		exMessage = ex.message;185	}186	consoleWarn(functionName + "Exception caught while attempting to parse JSON Response ! ex.message='" + exMessage + "'");187}188189function stateChangeHandler() {190	var functionName = "stateChangeHandler(): ";191	consoleLog(functionName + "Entering CALLBACK function " + functionName192			+ "...");193	consoleLog(functionName + "xhr.readyState='" + xhr.readyState194			+ "' and xhr.status='" + xhr.status + "' and xhr.statusText='"195			+ xhr.statusText + "'.");196	if (xhr.readyState === 4) {197		if (requestTimer) {198			clearTimeout(requestTimer);199		}200		var currentUrlIndex = parseInt(document201				.getElementById(CONSTANTS.currentUrlIndex).innerHTML);202		var currentDriverUrl = urlArray.driverUrls[currentUrlIndex].driverUrl;203		var currentDriverCheckUrl = generateDriverCheckUrlFromDriverUrl(currentDriverUrl);204		var urlId = urlArray.driverUrls[currentUrlIndex].urlId;205		var currentStatus = urlArray.driverUrls[currentUrlIndex].status;206		if (xhr.status >= 200 && xhr.status < 400) {207			consoleLog(functionName + "SUCCESS: xhr.status='" + xhr.status208					+ "' and xhr.statusText='" + xhr.statusText209					+ "' and xhr.responseText='" + xhr.responseText210					+ "' for Driver URL '"211					+ JSON.stringify(urlArray.driverUrls[currentUrlIndex])212					+ "'.");213			try {214				// Deferring JQuery parsing of the Response to a future release, due to JSON parsing problems.215				// var $jq = jQuery.noConflict();216				// var driverCheckResult = $jq.parseJSON(xhr.responseText);217				// if (driverCheckResult && driverCheckResult.STATUS) {218				// 	consoleLog(functionName + "driverCheckResult.STATUS='" + driverCheckResult.STATUS + "'");219				// 	if (driverCheckResult.STATUS == CONSTANTS.STATUS_INVALID_PTC_CMD) {220				// 		// Old Driver221				// 		consoleLog(functionName + "OLD Driver Found...");222				// 	} else {223				// 		// New Driver224				// 		consoleLog(functionName + "NEW Driver Found...");225				// 	}226				// } else {227				// 	// Did not find a JSON Response as expected, assume this is an old Driver228				// }229			} catch(e) {230				logExceptionMessage(e, functionName);231			}232233			urlArray.driverUrls[currentUrlIndex].status = CONSTANTS.urlStatus_PASSED;234			setDriverStatusIndicator("DriverStatusUp");235			document.getElementById(urlId).innerHTML = JSON.stringify(urlArray.driverUrls[currentUrlIndex]);236			validDriverUrl = urlArray.driverUrls[currentUrlIndex].driverUrl;237			// Stop processing URLs now238			var loopIndex;239			var driverUrlsLength = urlArray.driverUrls.length;240			for (loopIndex = (parseInt(currentUrlIndex) + 1); loopIndex < driverUrlsLength; loopIndex++) {241				var loopCurrentUrl = urlArray.driverUrls[loopIndex].url;242				var loopUrlId = urlArray.driverUrls[loopIndex].urlId;243				urlArray.driverUrls[loopIndex].status = CONSTANTS.urlStatus_SKIPPED;244				document.getElementById(loopUrlId).innerHTML = JSON.stringify(urlArray.driverUrls[loopIndex]);245				document.getElementById(CONSTANTS.currentUrlIndex).innerHTML = loopIndex;246			}247			// Tell the Server that we found a Driver248			var selectedAJAXDriverUrlDiv = document.getElementById(CONSTANTS.selectedAJAXDriverUrl);249			if (selectedAJAXDriverUrlDiv) {250				selectedAJAXDriverUrlDiv.innerHTML = validDriverUrl;251			} else {252				var driverUrlDiv = document.getElementById(CONSTANTS.driverUrlDiv);253				if (driverUrlDiv) {254					driverUrlDiv.appendChild(createDocumentFragment("<div id='" + CONSTANTS.selectedAJAXDriverUrl + "'>" + validDriverUrl + "</div>"));255				}256			}257			sendDriverStatus(true);258		} else {259			consoleLog(functionName + "ERROR: xhr.status='" + xhr.status260					+ "' and xhr.statusText='" + xhr.statusText261					+ "' and currentUrlIndex='" + currentUrlIndex + "'.");262			urlArray.driverUrls[currentUrlIndex].status = CONSTANTS.urlStatus_FAILED;263			document.getElementById(urlId).innerHTML = JSON264					.stringify(urlArray.driverUrls[currentUrlIndex]);265			// Make the call for the next URL test, if applicable266			if ((currentUrlIndex < urlArray.driverUrls.length - 1)) {267				currentUrlIndex = parseInt(currentUrlIndex) + 1;268				// Set the currentUrlIndex value BEFORE calling testDriverUrl()269				document.getElementById(CONSTANTS.currentUrlIndex).innerHTML = currentUrlIndex;270				consoleLog(functionName271						+ "About to attempt to test the next Driver Url '"272						+ generateDriverCheckUrlFromDriverUrl(urlArray.driverUrls[currentUrlIndex].driverUrl)273						+ "' with urlIndex '" + currentUrlIndex + "'.");274				testDriverUrl();275			} else {276				consoleLog(functionName277						+ "ERROR: No more DriverUrls are available so setting the DriverStatus to DOWN.");278				// We have run out of Driver URLs to check and none have passed279				// !280				setDriverStatusIndicator("DriverStatusDown");281				// Set a Server flag to indicate that no Driver is running282				// Tell the Server that we did NOT find a Driver283				sendDriverStatus(false);284			}285		}286	}287	consoleLog(functionName + "Exiting CALLBACK function...");288}289290function testDriverUrl() {291	var functionName = "testDriverUrl(): ";292	consoleLog(functionName + "Entering " + functionName + "...");293	var currentUrlIndex = parseInt(document294			.getElementById(CONSTANTS.currentUrlIndex).innerHTML);295	var currentDriverCheckUrl = generateDriverCheckUrlFromDriverUrl(urlArray.driverUrls[currentUrlIndex].driverUrl);296	var urlId = urlArray.driverUrls[currentUrlIndex].urlId;297	var currentStatus = urlArray.driverUrls[currentUrlIndex].status;298	if (currentStatus != CONSTANTS.urlStatus_WAITING) {299		// We should only test URLs that are currently WAITING to be tested,300		// otherwise exit early301		consoleLog(functionName + "WARNING: Exiting early from " + functionName302				+ "because url had Status of '" + currentStatus303				+ "' instead of expected Status '"304				+ CONSTANTS.urlStatus_WAITING + "' ! url: "305				+ JSON.stringify(urlArray.driverUrls[currentUrlIndex]));306		return;307	}308	// Set the Status309	urlArray.driverUrls[currentUrlIndex].status = CONSTANTS.urlStatus_TESTING;310	document.getElementById(urlId).innerHTML = JSON311			.stringify(urlArray.driverUrls[currentUrlIndex]);312	consoleLog(functionName + "About to begin Testing URL: "313			+ JSON.stringify(urlArray.driverUrls[currentUrlIndex]) + ".");314	xhr = createXHR();315	// xhr = createCORSRequest("GET", currentDriverCheckUrl);316	if (!xhr) {317		throw new Error("Could not create xhr object after call to createXHR() !");318	}319	if (window.XDomainRequest) {320		// IE Browser321		try {322			consoleLog(functionName + "IE Browser detected...");323			consoleLog(functionName324					+ "IE: About to call xhr.onload = stateChangeHandler...");325			xhr.onload = stateChangeHandler;326			consoleLog(functionName + "IE: About to call xhr.open('GET', '"327					+ currentDriverCheckUrl + "', true)...");328			xhr.open("GET", currentDriverCheckUrl, true);329			consoleLog(functionName330					+ "IE: About to call xhr.send() on currentDriverCheckUrl '"331					+ currentDriverCheckUrl + "'...");332			xhr.send();333		} catch(e) {334			// Don't do anything at this point, just let it fail gracefully so the code won't abort335			logExceptionMessage(e, functionName);336		}337	} else {338		// Non-IE Browser339		try {340			consoleLog(functionName + "Non-IE Browser detected...");341			consoleLog(functionName + "Non-IE: About to call xhr.open('GET', '"342					+ currentDriverCheckUrl + "', true)...");343			xhr.open("GET", currentDriverCheckUrl, true);344			xhr.onreadystatechange = stateChangeHandler;345			consoleLog(functionName346					+ "Non-IE: About to call xhr.send() on currentDriverCheckUrl '"347					+ currentDriverCheckUrl + "'...");348			xhr.send();349		} catch(e) {350			logExceptionMessage(e, functionName);351		}352	}353354	requestTimer = setTimeout(355			function() {356				consoleLog(functionName357						+ "Entering xhr.requestTimer TIMEOUT function...");358				var currentUrlIndex = parseInt(document359						.getElementById(CONSTANTS.currentUrlIndex).innerHTML);360				if (xhr) {361					consoleLog(functionName362							+ "Inside xhr.requestTimer TIMEOUT function: currentUrlIndex="363							+ currentUrlIndex + ". About to ABORT...");364					xhr.abort();365				}366				consoleLog(functionName367						+ "Exiting xhr.requestTimer TIMEOUT function...");368			}, checkDriverUsingAjaxMethodCallTimeoutMs);369370	consoleLog(functionName + "Exiting " + functionName + "...");371}372373374function infoDriverUrlUsingJQuerygetJSON(useJSONP, driverUrl, maxTimeout, pollInterval, isRequestFromMaintenancePage) {375	var functionName = "infoDriverUrlUsingJQuerygetJSON(useJSONP='" + useJSONP376		+ "'): ";377	consoleLog(functionName + "Entering " + functionName + "...");378379	var currentDriverCheckUrl = generateInfoDriverUrl(driverUrl);380	var errorMessage = "<%= MyMessages.getGlobalValue(CONSTANTS.STATUS_TRANSPORT_OFF) %>";381	var dataType = "json";382	if (useJSONP == "true") {383		dataType = "jsonp";384	}385386	var remoteUrl = currentDriverCheckUrl;387388	if ($jq) {389		if ($jq.support && ($jq.support.cors != "undefined")) {390			$jq.support.cors = true;391		}392		$jq.ajax({393			type : "GET",394			crossDomain : "true",395			dataType : 'json',396			contentType : "application/json",397			cache : "false",398			url : remoteUrl,399			success : function(data, status) {400				consoleLog(functionName401					+ "Inside success()");402				try {403					toggleAjaxLoader(true, this);404					var driverData = sendDriverDataFromInfoCommand(data.STATUS, data.PTC_XPTINFO, data.PTC_TRANSPORT_TYPE,data.PTC_TRANSPORT_GUID, data.CLN,isRequestFromMaintenancePage);405					var status = "";406407					if (driverData && isRequestFromMaintenancePage) {408						status = driverData.split(",")[0].split("=")[1];409						if (driverData.split(",")[6].split("=")[1] != "" || status == CONSTANTS.STATUS_TRANSPORT_OFF) {410							document.getElementById("Form:MaintenanceMessage").style.display = "inline";411							document.getElementById("Form:ErrorMessageID").innerHTML = driverData.split(",")[6].split("=")[1];412						}413						if (driverData.split(",")[6].split("=")[1] != "" && status != CONSTANTS.STATUS_TRANSPORT_OFF) {414						var btn =document.getElementById("Form:CleanButton");415				        btn.disabled="true";	416						}	417						populateValuesForInfoCommand(driverData);418						pollingInit(driverData.split(",")[8].split("=")[1],driverData.split(",")[9].split("=")[1].split("}")[0],maxTimeout,pollInterval);419					}420					// rerender the TransportRecovey page form to render Cleaning recovery steps421					if(!isRequestFromMaintenancePage){422						rerenderForm();423					}424					toggleAjaxLoader(false, this);425					} catch (e) {426					logExceptionMessage(e, functionName);427					toggleAjaxLoader(false, this);428				}429			},430			error : function(data, status) {431				toggleAjaxLoader(true, this);432				var driverData = sendDriverDataFromInfoCommand(CONSTANTS.driverStatus_Unknown,"","","");433				document.getElementById("Form:ErrorMessageID").innerHTML = driverData.split(",")[6].split("=")[1];						434				document.getElementById("Form:MaintenanceMessage").style.display = "inline";435				var btn =document.getElementById("Form:CleanButton");436				btn.disabled="true";				437				populateValuesForErrors(driverData);438				pollingInit(driverData.split(",")[8].split("=")[1],driverData.split(",")[9].split("=")[1].split("}")[0],maxTimeout,pollInterval);439				toggleAjaxLoader(false, this);440				consoleLog(functionName + "Inside error(), currentUrlIndex='" + currentUrlIndex + "' and status='" + status + "'.");441			}442		});443	} else {444		consoleLog(functionName + "No jQuery defined, bypassing check of url '" + remoteUrl + "'.");445	}446447	consoleLog(functionName + "Exiting " + functionName + "...");448}449450function populateValuesForInfoCommand(driverData){451	            var status = driverData.split(",")[0].split("=")[1];452	            var imageLocation = driverData.split(",")[5].split("=")[1];	453	            document.getElementById("Form:ModelId").innerHTML = driverData.split(",")[1].split("=")[1];454				document.getElementById("Form:VendorID").innerHTML = driverData.split(",")[2].split("=")[1];455				if(document.getElementById("Form:SerialID")!=null)456				{		457				document.getElementById("Form:SerialID").innerHTML = driverData.split(",")[3].split("=")[1];458				}459			    if(document.getElementById("Form:LastCleanID")!=null)460				{461				document.getElementById("Form:LastCleanID").innerHTML = driverData.split(",")[4].split("=")[1];462				}463				document.getElementById("Form:ImageID").setAttribute("src",imageLocation);464}465466function testDriverUrlUsingJQuerygetJSON(useJSONP) {467	var functionName = "testDriverUrlUsingJQuerygetJSON(useJSONP='" + useJSONP468			+ "'): ";469	consoleLog(functionName + "Entering " + functionName + "...");470	var currentUrlIndex = parseInt(document471			.getElementById(CONSTANTS.currentUrlIndex).innerHTML);472	var currentDriverCheckUrl = generateDriverCheckUrlFromDriverUrl(urlArray.driverUrls[currentUrlIndex].driverUrl);473	var urlId = urlArray.driverUrls[currentUrlIndex].urlId;474	var currentStatus = urlArray.driverUrls[currentUrlIndex].status;475	if (currentStatus != CONSTANTS.urlStatus_WAITING) {476		// We should only test URLs that are currently WAITING to be tested,477		// otherwise exit early478		consoleLog(functionName + "WARNING: Exiting early from " + functionName479				+ "because url had Status of '" + currentStatus480				+ "' instead of expected Status '"481				+ CONSTANTS.urlStatus_WAITING + "' ! url: "482				+ JSON.stringify(urlArray.driverUrls[currentUrlIndex]));483		return;484	}485	var dataType = "json";486	if (useJSONP == "true") {487		dataType = "jsonp";488	}489	// Set the Status490	urlArray.driverUrls[currentUrlIndex].status = CONSTANTS.urlStatus_TESTING;491	document.getElementById(urlId).innerHTML = JSON492			.stringify(urlArray.driverUrls[currentUrlIndex]);493	consoleLog(functionName + "About to begin Testing URL: "494			+ JSON.stringify(urlArray.driverUrls[currentUrlIndex]) + ".");495496	var remoteUrl = currentDriverCheckUrl;497498	if ($jq) {499		if ($jq.support && ($jq.support.cors != "undefined")) {500			$jq.support.cors = true;501		}502		$jq.ajax({503			type : "GET",504			crossDomain : "true",505			dataType : dataType,506			contentType : "application/json",507			cache : "false",508			url : remoteUrl,509			timeout : checkDriverUsingAjaxMethodCallTimeoutMs,510			success : function(data, status) {511				consoleLog(functionName512						+ "Inside success(), currentUrlIndex='"513						+ currentUrlIndex + "' and status='" + status514						+ "' and data='" + JSON.stringify(data) + "'.");515				try {516					var driverCheckResult = $jq.parseJSON(data);517					if (driverCheckResult && driverCheckResult.STATUS) {518						consoleLog(functionName + "driverCheckResult.STATUS='" + driverCheckResult.STATUS + "'");519						if (driverCheckResult.STATUS == CONSTANTS.STATUS_INVALID_PTC_CMD) {520							// Old Driver521							consoleLog(functionName + "OLD Driver Found...");522						} else {523							// New Driver524							consoleLog(functionName + "NEW Driver Found...");525						}526					}527				} catch(e) {528					logExceptionMessage(e, functionName);529				}530				531				validDriverUrl = urlArray.driverUrls[currentUrlIndex].driverUrl;532				urlArray.driverUrls[currentUrlIndex].status = CONSTANTS.urlStatus_PASSED;533				setDriverStatusIndicator("DriverStatusUp");534				document.getElementById(urlArray.driverUrls[currentUrlIndex].urlId).innerHTML = JSON.stringify(urlArray.driverUrls[currentUrlIndex]);535				// Tell the Server that we found a Driver536				document.getElementById(CONSTANTS.selectedAJAXDriverUrl).innerHTML = urlArray.driverUrls[currentUrlIndex].driverUrl;537				var driverInstalledField = document.getElementById("Form\\:DriverInstalled");538				if (driverInstalledField == null || driverInstalledField == 'undefined') {539					if (document.body) {540						driverInstalledField = createDocumentFragment("<div id='Form\\:DriverInstalled'></div>");541						document.body.appendChild(driverInstalledField);542					}543				}544				if (driverInstalledField) {545					driverInstalledField.value = "true";546				}547				var selectedAJAXDriverUrlDiv = document.getElementById(CONSTANTS.selectedAJAXDriverUrl);548				if (selectedAJAXDriverUrlDiv) {549					selectedAJAXDriverUrlDiv.innerHTML = validDriverUrl;550				} else {551					var driverUrlDiv = document.getElementById(CONSTANTS.driverUrlDiv);552					if (driverUrlDiv) {553						driverUrlDiv.appendChild(createDocumentFragment("<div id='" + CONSTANTS.selectedAJAXDriverUrl + "'>" + validDriverUrl + "</div>"));554					}555				}556				if (typeof sendDriverStatus !== "undefined") {557					sendDriverStatus(true);558				}559				if (typeof skipRemainingDriverUrls !== "undefined") {560					skipRemainingDriverUrls();561				}562				563			},564			error : function(data, status) {565				consoleLog(functionName + "Inside error(), currentUrlIndex='" + currentUrlIndex + "' and status='" + status + "'.");566				if (status == "timeout") {567					urlArray.driverUrls[currentUrlIndex].status = CONSTANTS.urlStatus_TIMEOUT;568				} else {569					urlArray.driverUrls[currentUrlIndex].status = CONSTANTS.urlStatus_FAILED;570				}571				document.getElementById(urlArray.driverUrls[currentUrlIndex].urlId).innerHTML = JSON.stringify(urlArray.driverUrls[currentUrlIndex]);572				testNextDriverUrlJSON();573			}574		});575	} else {576		consoleLog(functionName + "No jQuery defined, bypassing check of url '" + remoteUrl + "'.");577	}578579	consoleLog(functionName + "Exiting " + functionName + "...");580}581582function testNextDriverUrl() {583	var functionName = "testNextDriverUrl(): ";584	consoleLog(functionName + "Entering " + functionName + "...");585	var currentUrlIndex = parseInt(document586			.getElementById(CONSTANTS.currentUrlIndex).innerHTML);587	if ((currentUrlIndex < urlArray.driverUrls.length - 1)) {588		currentUrlIndex = parseInt(currentUrlIndex) + 1;589		// Set the currentUrlIndex value BEFORE calling testDriverUrl()590		document.getElementById(CONSTANTS.currentUrlIndex).innerHTML = currentUrlIndex;591		consoleLog(functionName592				+ "About to attempt to test the next Driver Check Url '"593				+ generateDriverCheckUrlFromDriverUrl(urlArray.driverUrls[currentUrlIndex].driverUrl)594				+ "' with urlIndex '" + currentUrlIndex + "'.");595		// Always use JSONP596		testDriverUrlUsingJQuerygetJSON("true");597	} else {598		consoleLog(functionName599				+ "ERROR: No more DriverUrls are available so setting the DriverStatus to DOWN.");600		// We have run out of Driver URLs to check and none have passed !601		setDriverStatusIndicator("DriverStatusDown");602		// Set a Server flag to indicate that no Driver is running603		// Tell the Server that we did NOT find a Driver604		sendDriverStatus(false);605	}606	consoleLog(functionName + "Exiting " + functionName + "...");607}608609function testNextDriverUrlJSON() {610	var functionName = "testNextDriverUrlJSON(): ";611	consoleLog(functionName + "Entering " + functionName + "...");612	var currentUrlIndex = parseInt(document613			.getElementById(CONSTANTS.currentUrlIndex).innerHTML);614	if ((currentUrlIndex < urlArray.driverUrls.length - 1)) {615		currentUrlIndex = parseInt(currentUrlIndex) + 1;616		// Set the currentUrlIndex value BEFORE calling testDriverUrl()617		document.getElementById(CONSTANTS.currentUrlIndex).innerHTML = currentUrlIndex;618		consoleLog(functionName619				+ "About to attempt to test the next Driver Check Url '"620				+ generateDriverCheckUrlFromDriverUrl(urlArray.driverUrls[currentUrlIndex].driverUrl)621				+ "' with urlIndex '" + currentUrlIndex + "'.");622		// Always use JSONP623		testDriverUrlUsingJQuerygetJSON("true");624	} else {625		if (isCheckDriverWithoutContactingDriver) {626			// In this case, we want to assume the Driver is running and use the WorkstationDriverUrl value627			abortDriverCheck();628		} else {629			consoleLog(functionName630					+ "ERROR: No more DriverUrls are available so setting the DriverStatus to DOWN.");631			// We have run out of Driver URLs to check and none have passed !632			setDriverStatusIndicator("DriverStatusDown");633			// Set a Server flag to indicate that no Driver is running634			// Tell the Server that we did NOT find a Driver635			sendDriverStatus(false);636		}637	}638	consoleLog(functionName + "Exiting " + functionName + "...");639}640641function skipRemainingDriverUrls() {642	var functionName = "skipRemainingDriverUrls(): ";643	consoleLog(functionName + "Entering " + functionName + "...");644	var currentUrlIndex = parseInt(document645			.getElementById(CONSTANTS.currentUrlIndex).innerHTML);646	urlArray.driverUrls[currentUrlIndex].status = CONSTANTS.urlStatus_PASSED;647	setDriverStatusIndicator("DriverStatusUp");648	document.getElementById(urlArray.driverUrls[currentUrlIndex].urlId).innerHTML = JSON649			.stringify(urlArray.driverUrls[currentUrlIndex]);650	// Stop processing URLs now651	var remainingDriverUrlsIterator;652	var remainingDriverUrlsLength = urlArray.driverUrls.length;653	for (remainingDriverUrlsIterator = (parseInt(currentUrlIndex) + 1); remainingDriverUrlsIterator < remainingDriverUrlsLength; remainingDriverUrlsIterator++) {654		var loopUrlId = urlArray.driverUrls[remainingDriverUrlsIterator].urlId;655		urlArray.driverUrls[remainingDriverUrlsIterator].status = CONSTANTS.urlStatus_SKIPPED;656		document.getElementById(loopUrlId).innerHTML = JSON657				.stringify(urlArray.driverUrls[remainingDriverUrlsIterator]);658		document.getElementById(CONSTANTS.currentUrlIndex).innerHTML = remainingDriverUrlsIterator;659	}660	consoleLog(functionName + "Exiting " + functionName + "...");661}662663function setDriverStatusIndicator(statusClassName) {664	var functionName = "setDriverStatusIndicator(): ";665	consoleLog(functionName + "Entering " + functionName + "...");666	var driverStatusIndicatorElement = document.getElementById("NavForm2:DriverStatusIndicator");667	if (driverStatusIndicatorElement && driverStatusIndicatorElement.className) {668		driverStatusIndicatorElement.className = statusClassName;669	}670	consoleLog(functionName + "Exiting " + functionName + "...");671}672673function driverCheckRepeat(driverUrlArray) {674	// This code is included in all situations, but we only want to execute it if required675	if (isPerformDriverCheckUsingAJAX) {676		var functionName = "repeat(driverUrlArray): ";677		pageLog(functionName + "Entering " + functionName + "...");678		var finished = false;679		if (driverUrlArray && driverUrlArray.driverUrls680				&& (driverUrlArray.driverUrls.length > 0)) {681			var urlArraySize = parseInt(driverUrlArray.driverUrls.length);682			pageLog(functionName + "urlArraySize=" + urlArraySize);683			var checkForDriverCompletionIterator;684			var passedFound = false;685			var waitingFound = false;686			var testingFound = false;687			var statusFound = false;688			var skipAbort = false;689			for (checkForDriverCompletionIterator = 0; checkForDriverCompletionIterator < urlArraySize; checkForDriverCompletionIterator++) {690				if (driverUrlArray.driverUrls[checkForDriverCompletionIterator]) {691					// Try and obtain the updated Status from the page Div692					var currentDriverUrl = driverUrlArray.driverUrls[checkForDriverCompletionIterator].driverUrl;693					var urlId = "url_" + currentDriverUrl.hashCode();694					var thisUrlDiv = document.getElementById(urlId);695					if (thisUrlDiv && thisUrlDiv.innerHTML) {696						if (typeof jQuery !== "undefined") {697							var $myJQuery = jQuery.noConflict();698						} else {699							finished = true;700							numberOfRetries = maximumNumberOfRetries + 1;701							abortDriverCheck();702						}703						if ($myJQuery && $myJQuery.parseJSON) {704							try {705								driverUrlArray.driverUrls[checkForDriverCompletionIterator].status = $myJQuery.parseJSON(thisUrlDiv.innerHTML).status;706								pageLog(functionName + "checkForDriverCompletionIterator=" + checkForDriverCompletionIterator707										+ ", driverUrlArray.driverUrls[checkForDriverCompletionIterator].driverUrl="708										+ driverUrlArray.driverUrls[checkForDriverCompletionIterator].driverUrl709										+ ", driverUrlArray.driverUrls[checkForDriverCompletionIterator].driverCheckUrl="710										+ generateDriverCheckUrlFromDriverUrl(driverUrlArray.driverUrls[checkForDriverCompletionIterator].driverUrl)711										+ ", driverUrlArray.driverUrls[checkForDriverCompletionIterator].status="712										+ driverUrlArray.driverUrls[checkForDriverCompletionIterator].status + ".");713								if (driverUrlArray.driverUrls[checkForDriverCompletionIterator].status) {714									statusFound = true;715								} else {716									// No status means that the Initialization step did NOT run - we want to abort looping in this case !717								}718								if (driverUrlArray.driverUrls[checkForDriverCompletionIterator].status == CONSTANTS.urlStatus_PASSED) {719									passedFound = true;720									validDriverUrl = driverUrlArray.driverUrls[checkForDriverCompletionIterator].driverUrl;721									var selectedAJAXDriverUrlDiv = document.getElementById(CONSTANTS.selectedAJAXDriverUrl);722									if (selectedAJAXDriverUrlDiv && selectedAJAXDriverUrlDiv.innerHTML) {723										selectedAJAXDriverUrlDiv.innerHTML = validDriverUrl;724									}725								} else if ((!driverUrlArray.driverUrls[checkForDriverCompletionIterator].status)726										|| (driverUrlArray.driverUrls[checkForDriverCompletionIterator].status == CONSTANTS.urlStatus_WAITING)) {727									waitingFound = true;728								} else if (driverUrlArray.driverUrls[checkForDriverCompletionIterator].status == CONSTANTS.urlStatus_TESTING) {729									testingFound = true;730								}731							} catch(e) {732								// Ignore and continue since we cannot parse a status out of the DIV733								logExceptionMessage(e, functionName);734							}735						}736					} else {737						pageLog(functionName + "Could not find an updated status property in the DIV for the current URL: '" + currentDriverUrl + "'");738						skipAbort = true;739					}740				}741			}742			pageLog(functionName + "Finished processing URL Array. waitingFound="743					+ waitingFound + " and passedFound=" + passedFound744					+ " and statusFound=" + statusFound + " and testingFound=" + testingFound745					+ " and validDriverUrl=" + validDriverUrl + ".");746			if (!statusFound) {747				// No statusFound means that the Initialization step did NOT run - we want to abort looping in this case !748				var warnMsg = functionName + "Finished processing URL Array and !statusFound. None of the URLs had a status property !" +749				" statusFound=" + statusFound + " and testingFound=" + testingFound + " and sendDriverInfo=" + sendDriverInfo +750				". Setting (finished = true)...";751				pageLog(warnMsg);752				consoleWarn(warnMsg);753				finished = true;754				if (!skipAbort) {755					pageLog(functionName + "Calling abortDriverCheck()...");756					abortDriverCheck();757				}758			}759			if (waitingFound && !passedFound && !finished) {760				// We are not done checking the Driver URLs yet, check again shortly761				finished = false;762			} else if (!finished) {763				if (testingFound) {764					// We are not done waiting at least one of the AJAX calls to complete765				} else {766					if (passedFound) {767						// A valid Driver URL was found :-)768						driverInstalled = true;769					} else {770						// A valid Driver URL was NOT found :-(771						driverInstalled = false;772					}773					finished = true;774					pageLog(functionName + "Finished processing URL Array, passedFound=" + passedFound + " and driverInstalled=" + driverInstalled + " and setting finished=true.");775				}776			}777			if (finished && !skipAbort) {778				if (!driverInstalled && isCheckDriverWithoutContactingDriver) {779					// In this case, we want to assume the Driver is running and use the WorkstationDriverUrl value780					pageLog(functionName + "(!driverInstalled && isCheckDriverWithoutContactingDriver). Setting driverInstalled=true and validDriverUrl=" +workstationDriverUrl + ".");781					driverInstalled = true;782					validDriverUrl = workstationDriverUrl;783				}784				pageLog(functionName + "Finished processing URL Array, passedFound=" + passedFound + "...");785				if (typeof sendDriverStatus == "function") {786					pageLog(functionName + "About to call sendDriverStatus(driverInstalled=" + driverInstalled + ")...");787					sendDriverStatus(driverInstalled);788				}789				toggleAjaxLoaderDriver(false, this);790			}791		} else {792			pageLog("driverUrlArray was not valid so could not check it !");793		}794		if (!finished) {795			pageLog(functionName + "(!finished) ! About to call checkForDriverCompletion(repeat) again...");796			checkForDriverCompletion(driverCheckRepeat);797		} else {798			pageLog(functionName + "(finished) ! About to call redirectToFinalUrl()...");799			// Only redirect to finalUrl if we are coming in through SSO !800			var currentWindowPathname = window.location.pathname;801			pageLog(functionName + "currentWindowPathname='" + currentWindowPathname + "'.");802			if (currentWindowPathname.endsWith("RemotePageLauncher.faces")) {803				pageLog(functionName + "window.location.pathname endsWith 'RemotePageLauncher.faces'! About to call redirectToFinalUrl()...");804				redirectToFinalUrl();805			} else {806				pageLog(functionName + "window.location.pathname does NOT endsWith 'RemotePageLauncher.faces'! Will NOT redirect here...");807			}808			pageLog(functionName + "Exiting " + functionName + "...");809		}810	}811}812813function checkForDriverCompletion(callback) {814	var functionName = "checkForDriverCompletion(callback): ";815	if (isPerformDriverCheckUsingAJAX) {816		consoleLog(functionName + "(isPerformDriverCheckUsingAJAX === true), numberOfRetries=" + numberOfRetries + " and maximumNumberOfRetries=" + maximumNumberOfRetries + ".");817		if (numberOfRetries > maximumNumberOfRetries) {818			consoleLog(functionName + "No longer checking status ! numberOfRetries=" + numberOfRetries + " and maximumNumberOfRetries=" + maximumNumberOfRetries + ".");819			return;820		}821		numberOfRetries++;822		setTimeout(823				function() {824					var functionName = "checkForDriverCompletion TIMEOUT Function: ";825					pageLog(functionName + "Entering " + functionName + "...");826					if (callback && (callback instanceof Function)) {827						pageLog(functionName828								+ "About to call callback('" + JSON.stringify(urlArray) + "')...");829						callback(urlArray);830					}831				}, checkDriverUsingAjaxMethodCallTimeoutMs);832	}833}834835function abortDriverCheck() {836	var functionName = "abortDriverCheck(): ";837	pageLog(functionName + "sendDriverInfo=" + sendDriverInfo + " and workstationDriverUrl=" + workstationDriverUrl + ".");838	var appendDocFragment = true;839	driverInstalled = true;840	sendDriverInfo = true;841	var driverUrlDiv = document.getElementById(CONSTANTS.driverUrlDiv);842	if (driverUrlDiv) {843		selectedAJAXDriverUrlDiv = document.getElementById(CONSTANTS.selectedAJAXDriverUrl);844		if (selectedAJAXDriverUrlDiv) {845			pageLog(functionName + "Current DriverUrl selectedAJAXDriverUrlDiv.innerHTML=" + selectedAJAXDriverUrlDiv.innerHTML + ".");846			if (selectedAJAXDriverUrlDiv.innerHTML && selectedAJAXDriverUrlDiv.innerHTML.length > 0) {847				pageLog(functionName + "Leaving Current DriverUrl set to " + selectedAJAXDriverUrlDiv.innerHTML + ".");848				sendDriverInfo = false;849			} else {850				pageLog(functionName + "Setting Current DriverUrl to " + workstationDriverUrl + ".");851				selectedAJAXDriverUrlDiv.innerHTML = workstationDriverUrl;852			}853			appendDocFragment = false;854		}855	}856	pageLog(functionName + "Aborting URL processing, driverInstalled=" + driverInstalled + " and sendDriverInfo=" + sendDriverInfo + " and appendDocFragment=" + appendDocFragment + ".");857	if (appendDocFragment) {858		driverUrlDiv.appendChild(createDocumentFragment("<div id='" + CONSTANTS.selectedAJAXDriverUrl + "' style='display:none;'>" + workstationDriverUrl + "</div>"));859	}860	if (typeof sendDriverStatus === "function" && sendDriverInfo) {861		pageLog(functionName + "Calling sendDriverStatus(true)...");862		sendDriverStatus(true);863	}864}865/*866 * the method is called to poll the upload status every polling_interval during max_time. 867 */	868	869function pollingInit(enablePolling, uploadDate, maxTimeout, pollInterval){870	  if (enablePolling == "stealthmode"){871		  showButtonText(false);872		  var stealth_interval_instance = setTimeout(function(){showButtonText(true)}, maxTimeout);873	  } else if(enablePolling == "true"){874    	//Hide uplaod botton and show "Uploading..." text875		 showButtonText(false);876    	 doPolling(maxTimeout,pollInterval, false);877      }else{ 878    	//show botton, last upload timestamp and hide "Uploading..." text ; 879    	  showButtonText(true);880		  if(document.getElementById("Form:UploadDateID")!=null)881		 {	  882    	  document.getElementById("Form:UploadDateID").innerHTML = uploadDate;883		 }884    	  clearIntervalInstance();885    	  clearTimeoutInstance(); 886      }   	887}888	889	890function doPolling(max_time,polling_interval){891	var functionName = "doPolling(): ";892	pageLog(functionName + "Polling upload status starts.");  893	timeout_instance= setTimeout(function(){reachMaxTimeout()}, max_time);894	interval_instance = setInterval(function(){ runPolling() }, polling_interval);895}896897898899function runPolling(){900	//response acting as a flag determine if the upload log is in progress or not.901	var response = refreshStatus("runPolling");902	903	//response != null implies it's not in progress, either success or failure, so polling set off.904	if(response != false && response != "KeepPolling"){ 905	   showMessage();906	   pollingInit("false", response);907	}908	909}910911function reachMaxTimeout(){912	clearIntervalInstance();913	var response = refreshStatus("doTimeout");914	showMessage();915	pollingInit("false", response);916}917918function showButtonText(flag){919	if(flag){920		document.getElementById("Form:GetLogsButton").style.display = "";921    	document.getElementById("Form:UploadTextID").innerHTML = "";922	}else{923		document.getElementById("Form:GetLogsButton").style.display = "none";924    	document.getElementById("Form:UploadTextID").innerHTML = "Uploading...";925	}926}927928929function clearIntervalInstance(){930	clearInterval(interval_instance);931	932}933934function clearTimeoutInstance(){935	clearTimeout(timeout_instance);
...

Full Screen

Full Screen

build-uri.test.js

Source:build-uri.test.js Github

copy

Full Screen

1const Connection = require('../');2const chai = require('chai');3const fixture = require('mongodb-connection-fixture');4const fs = require('fs');5const expect = chai.expect;6const loadOptions = Connection.connect.loadOptions;7const getTasks = Connection.connect.getTasks;8const encodeURIComponentRFC3986 = Connection.encodeURIComponentRFC3986;9chai.use(require('chai-subset'));10describe('Connection model builder', () => {11  context('when building URI', () => {12    it('should include default host, port, readPreference and ssl', (done) => {13      const c = new Connection();14      expect(c.driverUrl).to.be.equal(15        'mongodb://localhost:27017/?readPreference=primary&ssl=false'16      );17      Connection.from(c.driverUrl, (error) => {18        expect(error).to.not.exist;19        done();20      });21    });22    it('should include appname', (done) => {23      const c = new Connection({ appname: 'My App' });24      expect(c.driverUrl).to.be.equal(25        'mongodb://localhost:27017/?readPreference=primary&appname=My%20App&ssl=false'26      );27      Connection.from(c.driverUrl, (error) => {28        expect(error).to.not.exist;29        done();30      });31    });32    it('should include srv prefix', () => {33      const c = new Connection({ isSrvRecord: true });34      expect(c.driverUrl).to.be.equal(35        'mongodb+srv://localhost/?readPreference=primary&ssl=false'36      );37    });38    it('should include replicaSet', (done) => {39      const c = new Connection({ appname: 'My App', replicaSet: 'testing' });40      expect(c.driverUrl).to.be.equal(41        'mongodb://localhost:27017/?replicaSet=testing&readPreference=primary&appname=My%20App&ssl=false'42      );43      Connection.from(c.driverUrl, (error) => {44        expect(error).to.not.exist;45        done();46      });47    });48    it('does not include empty replicaSet', (done) => {49      const c = new Connection({ appname: 'My App', replicaSet: '' });50      expect(c.driverUrl).to.be.equal(51        'mongodb://localhost:27017/?readPreference=primary&appname=My%20App&ssl=false'52      );53      Connection.from(c.driverUrl, (error) => {54        expect(error).to.not.exist;55        done();56      });57    });58    it('should include sslMethod equal NONE', (done) => {59      const c = new Connection({ sslMethod: 'NONE' });60      expect(c.driverUrl).to.be.equal(61        'mongodb://localhost:27017/?readPreference=primary&ssl=false'62      );63      Connection.from(c.driverUrl, (error) => {64        expect(error).to.not.exist;65        done();66      });67    });68    it('should include sslMethod equal UNVALIDATED', (done) => {69      const c = new Connection({ sslMethod: 'UNVALIDATED' });70      const options = Object.assign({}, Connection.DRIVER_OPTIONS_DEFAULT, {71        checkServerIdentity: false,72        sslValidate: false,73        readPreference: 'primary',74        connectWithNoPrimary: true75      });76      expect(c.driverUrl).to.be.equal(77        'mongodb://localhost:27017/?readPreference=primary&ssl=true'78      );79      expect(c.driverOptions).to.deep.equal(options);80      Connection.from(c.driverUrl, (error) => {81        expect(error).to.not.exist;82        done();83      });84    });85    it('should include sslMethod equal SYSTEMCA', (done) => {86      const c = new Connection({ sslMethod: 'SYSTEMCA' });87      const options = Object.assign({}, Connection.DRIVER_OPTIONS_DEFAULT, {88        checkServerIdentity: true,89        sslValidate: true,90        readPreference: 'primary',91        connectWithNoPrimary: true92      });93      expect(c.driverUrl).to.be.equal(94        'mongodb://localhost:27017/?readPreference=primary&ssl=true'95      );96      expect(c.driverOptions).to.deep.equal(options);97      Connection.from(c.driverUrl, (error) => {98        expect(error).to.not.exist;99        done();100      });101    });102    it('should include sslMethod equal IFAVAILABLE', (done) => {103      const c = new Connection({ sslMethod: 'IFAVAILABLE' });104      const options = Object.assign({}, Connection.DRIVER_OPTIONS_DEFAULT, {105        checkServerIdentity: false,106        sslValidate: true,107        readPreference: 'primary',108        connectWithNoPrimary: true109      });110      expect(c.driverUrl).to.be.equal(111        'mongodb://localhost:27017/?readPreference=primary&ssl=prefer'112      );113      expect(c.driverOptions).to.deep.equal(options);114      Connection.from(c.driverUrl, (error) => {115        expect(error).to.not.exist;116        done();117      });118    });119    it('should include sslMethod equal SERVER', (done) => {120      const c = new Connection({ sslMethod: 'SERVER', sslCA: fixture.ssl.ca });121      const options = Object.assign({}, Connection.DRIVER_OPTIONS_DEFAULT, {122        sslCA: [fixture.ssl.ca],123        sslValidate: true,124        readPreference: 'primary',125        connectWithNoPrimary: true126      });127      expect(c.driverUrl).to.be.equal(128        'mongodb://localhost:27017/?readPreference=primary&ssl=true'129      );130      expect(c.driverOptions).to.deep.equal(options);131      Connection.from(c.driverUrl, (error) => {132        expect(error).to.not.exist;133        done();134      });135    });136    it('should include sslMethod equal ALL and authMechanism equal X509', (done) => {137      const c = new Connection({138        sslMethod: 'ALL',139        sslCA: fixture.ssl.ca,140        sslCert: fixture.ssl.server,141        sslKey: fixture.ssl.server,142        authStrategy: 'X509',143        x509Username: 'testing'144      });145      const options = Object.assign({}, Connection.DRIVER_OPTIONS_DEFAULT, {146        sslCA: [fixture.ssl.ca],147        sslCert: fixture.ssl.server,148        sslKey: fixture.ssl.server,149        checkServerIdentity: false,150        sslValidate: false,151        readPreference: 'primary',152        connectWithNoPrimary: true153      });154      expect(c.driverUrl).to.be.equal(155        'mongodb://testing@localhost:27017/?authMechanism=MONGODB-X509&readPreference=primary&ssl=true&authSource=$external'156      );157      expect(c.driverOptions).to.deep.equal(options);158      Connection.from(c.driverUrl, (error) => {159        expect(error).to.not.exist;160        done();161      });162    });163    it('should include sslMethod equal ALL and passwordless private keys', (done) => {164      const c = new Connection({165        sslMethod: 'ALL',166        sslCA: fixture.ssl.ca,167        sslCert: fixture.ssl.server,168        sslKey: fixture.ssl.server169      });170      const options = Object.assign({}, Connection.DRIVER_OPTIONS_DEFAULT, {171        sslCA: [fixture.ssl.ca],172        sslCert: fixture.ssl.server,173        sslKey: fixture.ssl.server,174        sslValidate: true,175        readPreference: 'primary',176        connectWithNoPrimary: true177      });178      expect(c.driverUrl).to.be.equal(179        'mongodb://localhost:27017/?readPreference=primary&ssl=true'180      );181      expect(c.driverOptions).to.deep.equal(options);182      /* eslint-disable no-sync */183      const expectAfterLoad = {184        sslCA: [fs.readFileSync(fixture.ssl.ca)],185        sslCert: fs.readFileSync(fixture.ssl.server),186        sslKey: fs.readFileSync(fixture.ssl.server),187        sslValidate: true,188        connectWithNoPrimary: true,189        readPreference: 'primary'190      };191      /* eslint-enable no-sync */192      const tasks = getTasks(c);193      // Trigger relevant side-effect, loading the SSL files into memory.194      // eslint-disable-next-line new-cap195      tasks['Load SSL files'](function () {196        // Read files into memory as the connect function does197        expect(tasks.driverOptions).to.deep.equal(expectAfterLoad);198        done();199      });200    });201    it('should include sslMethod equal ALL and password protected private keys', (done) => {202      const c = new Connection({203        sslMethod: 'ALL',204        sslCA: fixture.ssl.ca,205        sslCert: fixture.ssl.server,206        sslKey: fixture.ssl.server,207        sslPass: 'woof'208      });209      const options = Object.assign({}, Connection.DRIVER_OPTIONS_DEFAULT, {210        sslCA: [fixture.ssl.ca],211        sslCert: fixture.ssl.server,212        sslKey: fixture.ssl.server,213        sslPass: 'woof',214        sslValidate: true,215        connectWithNoPrimary: true,216        readPreference: 'primary'217      });218      expect(c.driverUrl).to.be.equal(219        'mongodb://localhost:27017/?readPreference=primary&ssl=true'220      );221      expect(c.driverOptions).to.deep.equal(options);222      Connection.from(c.driverUrl, (error) => {223        expect(error).to.not.exist;224        done();225      });226    });227    it('should convert sslCA into an array', (done) => {228      const c = new Connection({ sslCA: fixture.ssl.ca });229      expect(Array.isArray(c.sslCA)).to.be.equal(true);230      Connection.from(c.driverUrl, (error) => {231        expect(error).to.not.exist;232        done();233      });234    });235    it('should urlencode credentials when using SCRAM-SHA-256 auth', (done) => {236      const c = new Connection({237        mongodbUsername: '@rlo',238        mongodbPassword: 'w@of',239        authStrategy: 'SCRAM-SHA-256'240      });241      expect(c.driverUrl).to.be.equal(242        'mongodb://%40rlo:w%40of@localhost:27017/?authSource=admin&authMechanism=SCRAM-SHA-256&readPreference=primary&ssl=false'243      );244      Connection.from(c.driverUrl, (error) => {245        expect(error).to.not.exist;246        done();247      });248    });249    it('should urlencode credentials when using no auth', (done) => {250      const c = new Connection({251        mongodbUsername: '@rlo',252        mongodbPassword: 'w@of'253      });254      expect(c.driverUrl).to.be.equal(255        'mongodb://%40rlo:w%40of@localhost:27017/?authSource=admin&readPreference=primary&ssl=false'256      );257      Connection.from(c.driverUrl, (error) => {258        expect(error).to.not.exist;259        done();260      });261    });262    it('should urlencode credentials when using MONGODB auth', (done) => {263      const mongodbUsername = 'user';264      const mongodbPassword = 'C;Ib86n5b8{AnExew[TU%XZy,)E6G!dk';265      const c = new Connection({ mongodbUsername, mongodbPassword });266      expect(c.driverUrl).to.be.equal(267        'mongodb://user:C%3BIb86n5b8%7BAnExew%5BTU%25XZy%2C%29E6G%21dk@localhost:27017/?authSource=admin&readPreference=primary&ssl=false'268      );269      Connection.from(c.driverUrl, (error) => {270        expect(error).to.not.exist;271        done();272      });273    });274    it('should urlencode credentials when using MONGODB auth with emoji 💕', (done) => {275      const mongodbUsername = '👌emoji😂😍😘🔥💕🎁💯🌹';276      const mongodbPassword = '👌emoji😂😍😘🔥💕🎁💯🌹';277      const c = new Connection({ mongodbUsername, mongodbPassword });278      expect(c.driverUrl).to.be.equal(279        [280          'mongodb://',281          '%F0%9F%91%8Cemoji%F0%9F%98%82%F0%9F%98%8D%F0%9F%98%98%F0%9F%94%A5%F0%9F%92%95%F0%9F%8E%81%F0%9F%92%AF%F0%9F%8C%B9',282          ':',283          '%F0%9F%91%8Cemoji%F0%9F%98%82%F0%9F%98%8D%F0%9F%98%98%F0%9F%94%A5%F0%9F%92%95%F0%9F%8E%81%F0%9F%92%AF%F0%9F%8C%B9',284          '@localhost:27017/?authSource=admin&readPreference=primary&ssl=false'285        ].join('')286      );287      Connection.from(c.driverUrl, (error) => {288        expect(error).to.not.exist;289        done();290      });291    });292    it('should urlencode credentials when using LDAP auth', (done) => {293      const ldapUsername = 'user@-azMPk]&3Wt)iP_9C:PMQ=';294      const ldapPassword = 'user@-azMPk]&3Wt)iP_9C:PMQ=';295      const c = new Connection({ ldapUsername, ldapPassword });296      expect(c.driverUrl).to.be.equal(297        [298          'mongodb://user%40-azMPk%5D%263Wt%29iP_9C%3APMQ%3D:user%40-azMPk%5D%263Wt%29iP_9C%3APMQ%3D',299          '@localhost:27017/?authMechanism=PLAIN&readPreference=primary&ssl=false&authSource=$external'300        ].join('')301      );302      Connection.from(c.driverUrl, (error) => {303        expect(error).to.not.exist;304        done();305      });306    });307    it('should urlencode credentials when using KERBEROS auth', (done) => {308      const kerberosPrincipal = 'user@-azMPk]&3Wt)iP_9C:PMQ=';309      const c = new Connection({ kerberosPrincipal });310      expect(c.driverUrl).to.be.equal(311        [312          'mongodb://user%40-azMPk%5D%263Wt%29iP_9C%3APMQ%3D',313          '@localhost:27017/?gssapiServiceName=mongodb&authMechanism=GSSAPI&readPreference=primary&ssl=false&authSource=$external'314        ].join('')315      );316      Connection.from(c.driverUrl, (error) => {317        expect(error).to.not.exist;318        done();319      });320    });321    it('should urlencode credentials when using KERBEROS auth with canonicalizing the host name', (done) => {322      const kerberosPrincipal = 'user@-azMPk]&3Wt)iP_9C:PMQ=';323      const c = new Connection({324        kerberosCanonicalizeHostname: true,325        kerberosPrincipal,326      });327      expect(c.driverUrl).to.be.equal(328        [329          'mongodb://user%40-azMPk%5D%263Wt%29iP_9C%3APMQ%3D',330          '@localhost:27017/?gssapiServiceName=mongodb&authMechanism=GSSAPI&readPreference=primary&ssl=false&authSource=$external&authMechanismProperties=CANONICALIZE_HOST_NAME:true'331        ].join('')332      );333      Connection.from(c.driverUrl, (error) => {334        expect(error).to.not.exist;335        done();336      });337    });338    it('should replace default readPreference with a custom value', (done) => {339      const c = new Connection({ readPreference: 'secondary' });340      expect(c.driverUrl).to.be.equal(341        'mongodb://localhost:27017/?readPreference=secondary&ssl=false'342      );343      Connection.from(c.driverUrl, (error) => {344        expect(error).to.not.exist;345        done();346      });347    });348    it('should build safeUrl for LDAP auth', (done) => {349      const attrs = {350        ldapUsername: 'ldap-user',351        ldapPassword: 'ldap-password',352        authStrategy: 'LDAP'353      };354      const c = new Connection(attrs);355      expect(c.driverUrl).to.be.equal(356        'mongodb://ldap-user:ldap-password@localhost:27017/?authMechanism=PLAIN&readPreference=primary&ssl=false&authSource=$external'357      );358      expect(c.safeUrl).to.be.equal(359        'mongodb://ldap-user:*****@localhost:27017/?authMechanism=PLAIN&readPreference=primary&ssl=false&authSource=$external'360      );361      Connection.from(c.driverUrl, (error) => {362        expect(error).to.not.exist;363        done();364      });365    });366    it('should include non-dependent attribute', (done) => {367      const c = new Connection({ authStrategy: 'LDAP' });368      c.ldapUsername = 'ldap-user';369      c.ldapPassword = 'ldap-password';370      expect(c.driverUrl).to.be.equal(371        'mongodb://ldap-user:ldap-password@localhost:27017/?authMechanism=PLAIN&readPreference=primary&ssl=false&authSource=$external'372      );373      Connection.from(c.driverUrl, (error) => {374        expect(error).to.not.exist;375        done();376      });377    });378    it('should urlencode ldapPassword when using LDAP auth', (done) => {379      const c = new Connection({380        authStrategy: 'LDAP',381        ldapUsername: 'arlo',382        ldapPassword: 'w@of',383        ns: 'ldap'384      });385      expect(c.driverAuthMechanism).to.be.equal('PLAIN');386      expect(c.driverUrl).to.be.equal(387        'mongodb://arlo:w%40of@localhost:27017/ldap?authMechanism=PLAIN&readPreference=primary&ssl=false&authSource=$external'388      );389      Connection.from(c.driverUrl, (error) => {390        expect(error).to.not.exist;391        done();392      });393    });394    it('should urlencode ldapUsername when using LDAP auth', (done) => {395      // COMPASS-745 - should urlencode @ once onl396      const c = new Connection({397        authStrategy: 'LDAP',398        ldapUsername: 'arlo@t.co',399        ldapPassword: 'woof',400        ns: 'ldap'401      });402      expect(c.driverAuthMechanism).to.be.equal('PLAIN');403      expect(c.driverUrl).to.be.equal(404        'mongodb://arlo%40t.co:woof@localhost:27017/ldap?authMechanism=PLAIN&readPreference=primary&ssl=false&authSource=$external'405      );406      Connection.from(c.driverUrl, (error) => {407        expect(error).to.not.exist;408        done();409      });410    });411    it('should urlencode credentials when using X509 auth', (done) => {412      const c = new Connection({413        authStrategy: 'X509',414        x509Username:415          'CN=client,OU=kerneluser:info,O=10Gen,L=New York City,ST=New York,C=US'416      });417      expect(c.driverAuthMechanism).to.be.equal('MONGODB-X509');418      expect(c.driverUrl).to.be.equal(419        'mongodb://CN%3Dclient%2COU%3Dkerneluser%3Ainfo%2CO%3D10Gen%2CL%3DNew%20York%20City' +420          '%2CST%3DNew%20York%2CC%3DUS@localhost:27017/' +421          '?authMechanism=MONGODB-X509&readPreference=primary&ssl=false&authSource=$external'422      );423      Connection.from(c.driverUrl, (error) => {424        expect(error).to.not.exist;425        done();426      });427    });428    it('should not include credentials when using X509 auth and there is no username', (done) => {429      const c = new Connection({430        authStrategy: 'X509'431      });432      expect(c.driverAuthMechanism).to.be.equal('MONGODB-X509');433      expect(c.driverUrl).to.be.equal(434        'mongodb://localhost:27017/?authMechanism=MONGODB-X509' +435          '&readPreference=primary&ssl=false&authSource=$external'436      );437      Connection.from(c.driverUrl, (error) => {438        expect(error).to.not.exist;439        done();440      });441    });442  });443  context('when building a connection object', () => {444    context('authStrategy', () => {445      it('should set authStrategy to SCRAM-SHA-256', (done) => {446        const c = new Connection({447          mongodbUsername: 'arlo',448          mongodbPassword: 'woof',449          authStrategy: 'SCRAM-SHA-256'450        });451        expect(c.authStrategy).to.be.equal('SCRAM-SHA-256');452        Connection.from(c.driverUrl, (error) => {453          expect(error).to.not.exist;454          done();455        });456      });457      it('should set default admin authSource when using SCRAM-SHA-256 auth', (done) => {458        const attrs = {459          mongodbUsername: 'arlo',460          mongodbPassword: 'woof',461          authStrategy: 'SCRAM-SHA-256'462        };463        const c = new Connection(attrs);464        expect(c.driverUrl).to.be.equal(465          'mongodb://arlo:woof@localhost:27017/?authSource=admin&authMechanism=SCRAM-SHA-256&readPreference=primary&ssl=false'466        );467        Connection.from(c.driverUrl, (error) => {468          expect(error).to.not.exist;469          done();470        });471      });472      it('should build safeUrl for SCRAM-SHA-256 auth', (done) => {473        const attrs = {474          mongodbUsername: 'arlo',475          mongodbPassword: 'woof',476          authStrategy: 'SCRAM-SHA-256'477        };478        const c = new Connection(attrs);479        expect(c.driverUrl).to.be.equal(480          'mongodb://arlo:woof@localhost:27017/?authSource=admin&authMechanism=SCRAM-SHA-256&readPreference=primary&ssl=false'481        );482        expect(c.safeUrl).to.be.equal(483          'mongodb://arlo:*****@localhost:27017/?authSource=admin&authMechanism=SCRAM-SHA-256&readPreference=primary&ssl=false'484        );485        Connection.from(c.driverUrl, (error) => {486          expect(error).to.not.exist;487          done();488        });489      });490      it('should throw the error if auth is SCRAM-SHA-256 and mongodbUsername is missing', () => {491        const attrs = {492          authStrategy: 'SCRAM-SHA-256',493          mongodbPassword: 'woof'494        };495        const c = new Connection(attrs);496        const error = c.validate(attrs);497        expect(c.isValid()).to.be.equal(false);498        expect(error.message).to.include('The \'Username\' field is required when using \'Username/Password\' or \'SCRAM-SHA-256\' for authentication.');499      });500      it('should throw the error if auth is SCRAM-SHA-256 and mongodbPassword is missing', () => {501        const attrs = {502          mongodbUsername: 'arlo',503          authStrategy: 'SCRAM-SHA-256'504        };505        const c = new Connection(attrs);506        const error = c.validate(attrs);507        expect(c.isValid()).to.be.equal(false);508        expect(error.message).to.equal('The \'Password\' field is required when using \'Username/Password\' or \'SCRAM-SHA-256\' for authentication.');509      });510      it('should throw the error if MONGODB auth receives non-applicable fields', () => {511        const attrs = {512          mongodbUsername: 'arlo',513          mongodbPassword: 'woof',514          kerberosServiceName: 'mongodb'515        };516        const c = new Connection(attrs);517        const error = c.validate(attrs);518        expect(c.isValid()).to.be.equal(false);519        expect(error.message).to.equal(520          'The Kerberos \'Service Name\' field does not apply when using MONGODB for authentication.'521        );522      });523      it('should set authStrategy to MONGODB', (done) => {524        const c = new Connection({525          mongodbUsername: 'arlo',526          mongodbPassword: 'woof'527        });528        expect(c.authStrategy).to.be.equal('MONGODB');529        Connection.from(c.driverUrl, (error) => {530          expect(error).to.not.exist;531          done();532        });533      });534      it('should set default admin authSource when using MONGODB auth', (done) => {535        const attrs = {536          authStrategy: 'MONGODB',537          mongodbUsername: 'user',538          mongodbPassword: 'somepass'539        };540        const c = new Connection(attrs);541        expect(c.driverUrl).to.be.equal(542          'mongodb://user:somepass@localhost:27017/?authSource=admin&readPreference=primary&ssl=false'543        );544        Connection.from(c.driverUrl, (error) => {545          expect(error).to.not.exist;546          done();547        });548      });549      it('should build safeUrl for MONGODB auth', (done) => {550        const attrs = {551          authStrategy: 'MONGODB',552          mongodbUsername: 'user',553          mongodbPassword: 'somepass'554        };555        const c = new Connection(attrs);556        expect(c.driverUrl).to.be.equal(557          'mongodb://user:somepass@localhost:27017/?authSource=admin&readPreference=primary&ssl=false'558        );559        expect(c.safeUrl).to.be.equal(560          'mongodb://user:*****@localhost:27017/?authSource=admin&readPreference=primary&ssl=false'561        );562        Connection.from(c.driverUrl, (error) => {563          expect(error).to.not.exist;564          done();565        });566      });567      it('should throw the error if auth is MONGODB and mongodbUsername is missing', () => {568        const attrs = { authStrategy: 'MONGODB', mongodbPassword: 'woof' };569        const c = new Connection(attrs);570        const error = c.validate(attrs);571        expect(c.isValid()).to.be.equal(false);572        expect(error.message).to.include('The \'Username\' field is required when using \'Username/Password\' or \'SCRAM-SHA-256\' for authentication.');573      });574      it('should throw the error if auth is MONGODB and mongodbPassword is missing', (done) => {575        const c = new Connection({576          mongodbUsername: 'arlo',577          mongodbPassword: 'woof'578        });579        expect(c.mongodbDatabaseName).to.be.equal(580          Connection.MONGODB_DATABASE_NAME_DEFAULT581        );582        Connection.from(c.driverUrl, (error) => {583          expect(error).to.not.exist;584          done();585        });586      });587      it('should add a real password to driver url', () => {588        const c = new Connection({589          mongodbUsername: 'arlo',590          mongodbPassword: 'woof'591        });592        expect(c.driverUrl).to.be.equal(593          'mongodb://arlo:woof@localhost:27017/?authSource=admin&readPreference=primary&ssl=false'594        );595        expect(c.driverUrl).to.be.equal(c.driverUrlWithSsh);596      });597      it('should set authStrategy to LDAP', (done) => {598        const c = new Connection({599          ldapUsername: 'arlo',600          ldapPassword: 'w@of'601        });602        expect(c.authStrategy).to.be.equal('LDAP');603        Connection.from(c.driverUrl, (error) => {604          expect(error).to.not.exist;605          done();606        });607      });608      it('should throw the error if auth is LDAP and ldapUsername is missing', () => {609        const attrs = { authStrategy: 'LDAP' };610        const c = new Connection(attrs);611        const error = c.validate(attrs);612        expect(c.isValid()).to.be.equal(false);613        expect(error.message).to.equal('The \'Username\' field is required when using \'LDAP\' for authentication.');614      });615      it('should throw the error if auth is LDAP and ldapPassword is missing', () => {616        const attrs = { authStrategy: 'LDAP', ldapUsername: 'arlo' };617        const c = new Connection(attrs);618        const error = c.validate(attrs);619        expect(c.isValid()).to.be.equal(false);620        expect(error.message).to.equal('The \'Password\' field is required when using LDAP for authentication.');621      });622      it('should set authStrategy to X509', (done) => {623        const c = new Connection({624          x509Username:625            'CN=client,OU=kerneluser,O=10Gen,L=New York City,ST=New York,C=US'626        });627        expect(c.authStrategy).to.be.equal('X509');628        Connection.from(c.driverUrl, (error) => {629          expect(error).to.not.exist;630          done();631        });632      });633      it('should not throw the error if auth is X509 and x509Username is missing', () => {634        const attrs = {635          authStrategy: 'X509',636          sslMethod: 'ALL',637          sslCA: [fixture.ssl.ca],638          sslCert: fixture.ssl.server,639          sslKey: fixture.ssl.server640        };641        const c = new Connection(attrs);642        expect(c.isValid()).to.be.equal(true);643      });644      it('should throw a validation error if auth is X509 and sslMethod is not "ALL"', () => {645        const attrs = {646          authStrategy: 'X509'647        };648        const c = new Connection(attrs);649        const error = c.validate(attrs);650        expect(c.isValid()).to.be.equal(false);651        expect(error.message).to.equal('SSL method is required to be set to \'Server and Client Validation\' when using X.509 authentication.');652      });653      it('should set default mongodb gssapiServiceName when using KERBEROS auth', (done) => {654        const c = new Connection({655          kerberosPrincipal: 'lucas@kerb.mongodb.parts'656        });657        expect(c.driverUrl).to.be.equal(658          'mongodb://lucas%40kerb.mongodb.parts@localhost:27017/?gssapiServiceName=mongodb&authMechanism=GSSAPI&readPreference=primary&ssl=false&authSource=$external'659        );660        Connection.from(c.driverUrl, (error) => {661          expect(error).to.not.exist;662          done();663        });664      });665      it('should set authStrategy to KERBEROS', (done) => {666        const c = new Connection({667          kerberosPrincipal: 'lucas@kerb.mongodb.parts'668        });669        expect(c.authStrategy).to.be.equal('KERBEROS');670        Connection.from(c.driverUrl, (error) => {671          expect(error).to.not.exist;672          done();673        });674      });675      it('should throw the error if auth is KERBEROS and kerberosPrincipal is missing', () => {676        const attrs = { authStrategy: 'KERBEROS' };677        const c = new Connection(attrs);678        const error = c.validate(attrs);679        expect(c.isValid()).to.be.equal(false);680        expect(error.message).to.equal('The Kerberos \'Principal\' field is required when using \'Kerberos\' for authentication.');681      });682      it('should *only* require a kerberosPrincipal', () => {683        const attrs = {684          authStrategy: 'KERBEROS',685          kerberosPrincipal: 'lucas@kerb.mongodb.parts'686        };687        const c = new Connection(attrs);688        expect(c.isValid()).to.be.equal(true);689      });690      it('should build safeUrl for KERBEROS auth when password is specified', (done) => {691        const attrs = {692          kerberosPrincipal: 'alena@test.test',693          ldapPassword: 'ldap-password',694        };695        const c = new Connection(attrs);696        expect(c.driverUrl).to.be.equal(697          'mongodb://alena%40test.test@localhost:27017/?gssapiServiceName=mongodb&authMechanism=GSSAPI&readPreference=primary&ssl=false&authSource=$external'698        );699        expect(c.safeUrl).to.be.equal(700          'mongodb://alena%40test.test@localhost:27017/?gssapiServiceName=mongodb&authMechanism=GSSAPI&readPreference=primary&ssl=false&authSource=$external'701        );702        Connection.from(c.driverUrl, (error) => {703          expect(error).to.not.exist;704          done();705        });706      });707      it('should set driverAuthMechanism to GSSAPI when a password is provided', (done) => {708        const c = new Connection({709          kerberosPrincipal: 'arlo/dog@krb5.mongodb.parts',710          kerberosServiceName: 'mongodb'711        });712        expect(c.driverAuthMechanism).to.be.equal('GSSAPI');713        Connection.from(c.driverUrl, (error) => {714          expect(error).to.not.exist;715          done();716        });717      });718      it('should set driverAuthMechanism to GSSAPI when a password is provided and urlencode the principal', (done) => {719        const c = new Connection({720          kerberosPrincipal: 'arlo/dog@krb5.mongodb.parts',721          kerberosServiceName: 'mongodb'722        });723        const kerberosPrincipal = encodeURIComponentRFC3986(724          c.kerberosPrincipal725        );726        const expectedPrefix = `mongodb://${kerberosPrincipal}@localhost:27017`;727        expect(c.driverAuthMechanism).to.be.equal('GSSAPI');728        expect(c.driverUrl.indexOf(expectedPrefix)).to.be.equal(0);729        Connection.from(c.driverUrl, (error) => {730          expect(error).to.not.exist;731          done();732        });733      });734      it('should set driverAuthMechanism to GSSAPI when a password is not provided', (done) => {735        const c = new Connection({736          kerberosPrincipal: 'arlo/dog@krb5.mongodb.parts'737        });738        expect(c.driverAuthMechanism).to.be.equal('GSSAPI');739        Connection.from(c.driverUrl, (error) => {740          expect(error).to.not.exist;741          done();742        });743      });744      it('should not include the `:` auth seperator', (done) => {745        const c = new Connection({746          kerberosPrincipal: 'lucas@kerb.mongodb.parts'747        });748        const kerberosPrincipal = encodeURIComponentRFC3986(749          c.kerberosPrincipal750        );751        const expectedPrefix = `mongodb://${kerberosPrincipal}@localhost:27017`;752        expect(c.driverUrl.indexOf(expectedPrefix)).to.be.equal(0);753        Connection.from(c.driverUrl, (error) => {754          expect(error).to.not.exist;755          done();756        });757      });758    });759    context('top level properties', () => {760      it('should set the default read preference to primary preferred', (done) => {761        const c = new Connection({ appname: 'My App' });762        expect(c.driverOptions).to.be.deep.equal({763          readPreference: 'primary',764          connectWithNoPrimary: true765        });766        Connection.from(c.driverUrl, (error) => {767          expect(error).to.not.exist;768          done();769        });770      });771      it('should set isSrvRecord defaults to false', (done) => {772        const c = new Connection();773        expect(c.isSrvRecord).to.be.equal(false);774        Connection.from(c.driverUrl, (error) => {775          expect(error).to.not.exist;776          done();777        });778      });779      it('should allow the mongodbDatabaseName to be optional', () => {780        const attrs = { mongodbUsername: 'arlo' };781        const c = new Connection(attrs);782        const error = c.validate(attrs);783        expect(c.isValid()).to.be.equal(false);784        expect(error.message).to.equal('The \'Password\' field is required when using \'Username/Password\' or \'SCRAM-SHA-256\' for authentication.');785      });786      it('should generate the local port when using a ssh tunnel and bind to local port does not exist', () => {787        const c = new Connection();788        c.sshTunnel = 'USER_PASSWORD';789        c.sshTunnelHostname = '123.45.67.89';790        c.sshTunnelPort = 22;791        c.sshTunnelUsername = 'user';792        c.sshTunnelPassword = 'pass';793        expect(c.driverUrl).to.not.be.equal('');794        expect(c.sshTunnelBindToLocalPort).to.not.exist;795      });796      it('should load all of the files from the filesystem if sslMethod ia ALL', (done) => {797        const c = new Connection({798          sslMethod: 'ALL',799          sslCA: [fixture.ssl.ca],800          sslCert: fixture.ssl.server,801          sslKey: fixture.ssl.server802        });803        loadOptions(c, (error, driverOptions) => {804          if (error) {805            return done(error);806          }807          const opts = driverOptions;808          expect(opts.sslValidate).to.be.equal(true);809          expect(Array.isArray(opts.sslCA)).to.be.equal(true);810          expect(Buffer.isBuffer(opts.sslCA[0])).to.be.equal(true);811          expect(opts.sslPass).to.not.exist;812          expect(Buffer.isBuffer(opts.sslCert)).to.be.equal(true);813          expect(Buffer.isBuffer(opts.sslKey)).to.be.equal(true);814          done();815        });816      });817    });818    context('extra options', () => {819      it('should use default driverOptions when there is no extra options', (done) => {820        const c = new Connection();821        expect(c.driverOptions).to.have.property('connectWithNoPrimary');822        expect(c.driverOptions).to.have.property('readPreference');823        expect(c.driverOptions).to.not.have.property('socketTimeoutMS');824        Connection.from(c.driverUrl, (error) => {825          expect(error).to.not.exist;826          done();827        });828      });829      it('should include extra options in driverOptions when specified', (done) => {830        const c = new Connection({ extraOptions: { socketTimeoutMS: 1000 } });831        const options = Object.assign({}, Connection.DRIVER_OPTIONS_DEFAULT, {832          socketTimeoutMS: 1000,833          readPreference: 'primary'834        });835        expect(c.driverOptions).to.deep.equal(options);836        Connection.from(c.driverUrl, (error) => {837          expect(error).to.not.exist;838          done();839        });840      });841    });842    context('promote values', () => {843      it('should not include promoteValues when not specified', (done) => {844        const c = new Connection();845        expect(c.driverOptions).to.not.have.property('promoteValues');846        Connection.from(c.driverUrl, (error) => {847          expect(error).to.not.exist;848          done();849        });850      });851      it('should set promoteValues to true', (done) => {852        const c = new Connection({ promoteValues: true });853        expect(c.driverOptions).to.have.property('promoteValues');854        expect(c.driverOptions.promoteValues).to.be.equal(true);855        Connection.from(c.driverUrl, (error) => {856          expect(error).to.not.exist;857          done();858        });859      });860      it('should set promoteValues to false', (done) => {861        const c = new Connection({ promoteValues: false });862        expect(c.driverOptions).to.have.property('promoteValues');863        expect(c.driverOptions.promoteValues).to.be.equal(false);864        Connection.from(c.driverUrl, (error) => {865          expect(error).to.not.exist;866          done();867        });868      });869    });870    context('connection type', () => {871      it('should set default connectionType to NODE_DRIVER', (done) => {872        const c = new Connection({});873        expect(c.connectionType).to.be.equal('NODE_DRIVER');874        Connection.from(c.driverUrl, (error) => {875          expect(error).to.not.exist;876          done();877        });878      });879      it('should set default host and port when connectionType is NODE_DRIVER', (done) => {880        const c = new Connection({ connectionType: 'NODE_DRIVER' });881        expect(c.hostname).to.be.equal('localhost');882        expect(c.port).to.be.equal(27017);883        Connection.from(c.driverUrl, (error) => {884          expect(error).to.not.exist;885          done();886        });887      });888      it('should not allow stitchClientAppId', () => {889        const c = new Connection({890          connectionType: 'NODE_DRIVER',891          stitchClientAppId: 'xkcd42'892        });893        expect(c.isValid()).to.be.equal(false);894      });895      it('should not allow stitchClientAppId', () => {896        const c = new Connection({897          connectionType: 'NODE_DRIVER',898          stitchBaseUrl: 'http://localhost:9001/'899        });900        expect(c.isValid()).to.be.equal(false);901      });902      it('should not allow stitchGroupId', () => {903        const c = new Connection({904          connectionType: 'NODE_DRIVER',905          stitchGroupId: '23xkcd'906        });907        expect(c.isValid()).to.be.equal(false);908      });909      it('should not allow stitchServiceName', () => {910        const c = new Connection({911          connectionType: 'NODE_DRIVER',912          stitchServiceName: 'woof'913        });914        expect(c.isValid()).to.be.equal(false);915      });916      it('should require stitchClientAppId when connectionType is STITCH_ATLAS', () => {917        const c = new Connection({ connectionType: 'STITCH_ATLAS' });918        expect(c.isValid()).to.be.equal(false);919      });920      it('should be valid when stitchClientAppId is included and connectionType is STITCH_ATLAS', () => {921        const c = new Connection({922          connectionType: 'STITCH_ATLAS',923          stitchClientAppId: 'xkcd42'924        });925        expect(c.isValid()).to.be.equal(true);926      });927      it('should require stitchClientAppId when connectionType is STITCH_ON_PREM', () => {928        const c = new Connection({929          connectionType: 'STITCH_ON_PREM',930          stitchBaseUrl: 'http://localhost:9001/',931          stitchGroupId: '23xkcd',932          stitchServiceName: 'woof'933        });934        expect(c.isValid()).to.be.equal(false);935      });936      it('should require stitchBaseUrl when connectionType is STITCH_ON_PREM', () => {937        const c = new Connection({938          connectionType: 'STITCH_ON_PREM',939          stitchClientAppId: 'xkcd42',940          stitchGroupId: '23xkcd',941          stitchServiceName: 'woof'942        });943        expect(c.isValid()).to.be.equal(false);944      });945      it('should require stitchGroupId when connectionType is STITCH_ON_PREM', () => {946        const c = new Connection({947          connectionType: 'STITCH_ON_PREM',948          stitchClientAppId: 'xkcd42',949          stitchBaseUrl: 'http://localhost:9001/',950          stitchServiceName: 'woof'951        });952        expect(c.isValid()).to.be.equal(false);953      });954      it('should require stitchServiceName when connectionType is STITCH_ON_PREM', () => {955        const c = new Connection({956          connectionType: 'STITCH_ON_PREM',957          stitchClientAppId: 'xkcd42',958          stitchBaseUrl: 'http://localhost:9001/',959          stitchGroupId: '23xkcd'960        });961        expect(c.isValid()).to.be.equal(false);962      });963      it('should be valid when all required fields are included and connectionType is STITCH_ON_PREM ', () => {964        const c = new Connection({965          connectionType: 'STITCH_ON_PREM',966          stitchClientAppId: 'xkcd42',967          stitchBaseUrl: 'http://localhost:9001/',968          stitchGroupId: '23xkcd',969          stitchServiceName: 'woof'970        });971        expect(c.isValid()).to.be.equal(true);972      });973    });974  });975  context('when using the isURI() method', () => {976    it('should return true when using a mongodb protocol', () => {977      const isURI = Connection.isURI('mongodb://localhost&ssl=false');978      expect(isURI).to.be.equal(true);979    });980    it('should return true when using a mongodb+srv protocol', () => {981      const isURI = Connection.isURI('mongodb+srv://localhost&ssl=false');982      expect(isURI).to.be.equal(true);983    });984    it('should return false when using another protocol', () => {985      const isURI = Connection.isURI('mongodb+somethign://localhost&ssl=false');986      expect(isURI).to.be.equal(false);987    });988    it('should return false when using a shell connection string', () => {989      const isURI = Connection.isURI('mongo "mongodb://localhost&ssl=false"');990      expect(isURI).to.be.equal(false);991    });992  });993  context('when building a connection object from URI', () => {994    it('should throw the type error', () => {995      expect(996        () =>997          new Connection(998            'mongodb://mongodb1.example.com:27317,mongodb2.example.com:27017/?replicaSet=mySet&authSource=authDB'999          )1000      ).to.throw(1001        TypeError,1002        'To create a connection object from URI please use `Connection.from` function.'1003      );1004    });1005  });...

Full Screen

Full Screen

DriverPack.js

Source:DriverPack.js Github

copy

Full Screen

1var DriverPack = {2    path: AppData + '\\DRPSu\\DRIVERS',3    not_installed: [],4    installed: [],5    not_versions: [],6	_json: [],7	getDevType: function(DevID) {8		if (DevID.indexOf("VEN")  != -1) { return "PCI"; }9		if (DevID.indexOf("VID")  != -1) { return "USB"; }10		if (DevID.indexOf("ACPI") != -1) { return "ACPI"; }11		if (DevID.indexOf("PNP")  != -1) { return "PNP"; }12		if (DevID.indexOf("IDE")  != -1) { return "IDE"; }13		if (DevID.indexOf("USB")  != -1) { return "USB"; }14		if (DevID.indexOf("ROOT") != -1) { return "ROOT"; }15		if (DevID.indexOf("SCSI") != -1) { return "SCSI"; }16		if (DevID.indexOf("STORAGE") != -1) { return "STORAGE"; }17		if (DevID.indexOf("MONITOR") != -1) { return "MONITOR"; }18		return "UNK";19    },20    /*21		driverDetect()22		Сканирует устройства компьютера и получает их DeviceID.23		ToDo:24		- Эта функция довольно требовательна к ресурсам и нужнается в оптимизации25		- IE10+ может использовать Web Workers26		- Вместо setTimeout() использовать setImmediate(), это может улучшить скорость на ~500мс.27    */28	driverDetect: function(callback){29		/*30		ClassGuid, CompatID, Description, DeviceClass, DeviceID, DeviceName, DriverDate, DriverProviderName, DriverVersion, HardWareID, InfName, IsSigned, Location, Manufacturer, Signer,31		*/32		/*33		var start = new Date();34		//var DrivercolItems = objWMIService.ExecQuery("SELECT HardWareID FROM Win32_PnPSignedDriver WHERE HardWareID != null AND (HardWareID LIKE 'PCI%' OR HardWareID LIKE 'HDAUDIO%' OR HardWareID LIKE 'USB%' OR HardWareID LIKE 'ACPI%' OR HardWareID LIKE '*%')", "WQL");35		var DrivercolItems = objWMIService.ExecQuery("SELECT * FROM  Win32_PnPSignedDriver WHERE HardWareID != null", "WQL");36		var DriverenumItems = new Enumerator(DrivercolItems);37		var i = 0;38        for (; !DriverenumItems.atEnd(); DriverenumItems.moveNext()) {39			//var devid = DriverenumItems.item().DeviceID.toString().toUpperCase();40			var driverItem = DriverenumItems.item();41			var driverDeviceID = driverItem.HardWareID.toString().toUpperCase()42			if ((driverDeviceID.indexOf('PCI\\')==0) || (driverDeviceID.indexOf('USB\\')==0) || (driverDeviceID.indexOf('HDAUDIO\\')==0) || (driverDeviceID.indexOf('ACPI\\')==0) || (driverDeviceID.indexOf('*')==0)) {43				//Добавляем устройства только таких типов: PCI, USB, HDAUDIO, ACPI44				if (this.installed.indexOf(driverDeviceID) == -1){ //Только уникальные DeviceID45					//this.installed[i++] = driverDeviceID;46				}47			}48        }49		var end = new Date();50		alert('Speed driverDetect(): ' + (end.getTime()-start.getTime()) + ' ms');51		*/52		log('DriverPack.driverDetect() - start');53		var start = new Date();54		var DrivercolItems = objWMIService.ExecQuery("SELECT * FROM  Win32_PnPSignedDriver WHERE HardWareID != null", "WQL");55		var DriverenumItems = new Enumerator(DrivercolItems);56		DriverenumItems.moveFirst();57		var counter = 0,58			limit = 1000000000,59			handle,60			action = function(){61				if ((DriverenumItems.atEnd() == true) || (counter >= limit)){62					log('DriverPack.driverDetect() - end');63					log('DriverPack.installed JSON',DriverPack.installed);64					callback();65					clearTimeout(handle);66					return;67				}68				for (var i = 0; i < 5 && DriverenumItems.atEnd() == false; i++) {69					var driverItem = DriverenumItems.item();70					var driverDeviceID = driverItem.HardWareID.toString().toUpperCase();71					if ((driverDeviceID.indexOf('PCI\\')==0) || (driverDeviceID.indexOf('USB\\')==0) || (driverDeviceID.indexOf('HDAUDIO\\')==0) || (driverDeviceID.indexOf('ACPI\\')==0) || (driverDeviceID.indexOf('*')==0)) {72						//Добавляем устройства только таких типов: PCI, USB, HDAUDIO, ACPI73						if (DriverPack.installed.indexOf(driverDeviceID) == -1){ //Только уникальные DeviceID74							DriverPack.installed[DriverPack.installed.length] = driverDeviceID;75						}76					}77					DriverenumItems.moveNext();78				}79				counter++;80				handle = setTimeout(action, 0);81			};82		action();83	},84	stringifyWithLimit: function (array, limit)  {85		var safe;86		var take = limit * 0.02;87		var decoded_limit = limit * 0.75;88		var serialized;89		while (true) {90			serialized = JSON.stringify(array.slice(0, take));91			if (take > array.length - 1) {92				log('[stringifyWithLimit] picked ' + array.length + ' out of ' + array.length + ' (all)');93				return serialized;94			} else if (serialized.length > decoded_limit) {95				if (safe) {96					log('[stringifyWithLimit] picked ' + take + ' out of ' + array.length);97					return safe;98				} else {99					if (take > 0) {100						log('[stringifyWithLimit] could not pick, restarting loop...');101						take = 0;102						continue;103					} else {104						log('failed to serialize drivers');105						return JSON.stringify([]);106					}107				}108			} else {109				safe = serialized;110			}111			take++;112		}113	},114	/*115		init()116		Запускать процесс сканирования компьютера, отправляет информацию об устройствах на сервер. Принимает JSON ответ.117	*/118    init: function (callback) {119		log('DriverPack.init()');120		DriverPack.driverDetect(function(){121			//document.getElementById('loader').style.display = 'none';122			log("JSON drivers:",DriverPack.installed);123			// TODO: send installed and not_installed without cutting it to 2000 characters124			var data = {125				not_installed: DriverPack.stringifyWithLimit(DriverPack.not_installed, 2000).replace(/\\\\/ig,"-"),126				installed: DriverPack.stringifyWithLimit(DriverPack.installed, 2000).replace(/\\\\/ig,"-"),127				version: (is64 ? '64': '32'),128				os: (OSVersion=='6.1'?'7':OSVersion)129			};130			var get = Object.keys(data).map(function (k) {131				return encodeURIComponent(k) + '=' + encodeURIComponent(data[k])132			}).join('&');133			log('JSONp URL:', [ 'http://test-st.drp.su/drivers/response.php?' + get + '&callback' ] );134			JSONP(135				'http://test-st.drp.su/drivers/response.php?' + get + '&callback',136				function(json){137					log('DriverPack.init() - JSONP response:',json);138					DriverPack.loadDB(json);139					DriverPack.detectDownloaded();140					callback();141				}142			);143		});144        /*echo('  DriverPack.init();');145         echo('  test(JSON.stringify(DriverPack._db), \'' + JSON.stringify(DriverPack._db) + '\');');*/146    },147	/*148		detectDownloaded()149		Проходится по всей базе и расставляет свойство isDownloaded тем, которые уже были скачанны.150	*/151	detectDownloaded: function () {152		var check = DriverPack.get({153			'SELECT': '*'154		});155		log('DriverPack.detectDownloaded() - start:',DriverPack._json);156		check.forEach(function(item, i, check) {157			//isDownloaded158			DriverPack._json[i].isDownloaded = false;159			if (driver_exists(item.URL,DriverPack.path)) {160				DriverPack._json[i].isDownloaded = true;161			}162		});163		log('DriverPack.detectDownloaded() - end:',DriverPack._json);164	},165	/*166		download()167		Скачивает драйверы из массива IDs.168		ToDo:169		- Убрать лишний setTimeout()170		- Убрать вызов statistics.event отсюда171		- Убрать вызов progressCounter отсюда172	*/173	download: function (IDs, events) {174		var defaultEvents = {175			beforeAllDownloaded: function(){},176			beforeDownloading: function(){},177			afterDownloading: function(){},178			afterAllDownloaded: function(){}179		};180		events = extendJSON(defaultEvents,events);181		var url = DriverPack.get({182			'SELECT': '*',183			'WHERE': IDs184		});185		setTimeout(186			function(){187				log('Started downloading IDs: ' + IDs);188				events.beforeAllDownloaded();189				wget.downloadFiles(events, DriverPack.path, url).caught(function(err) {190					log('DriverPack: error on downloading:', err);191				}).lastly(function () {192					log('Downloaded drivers!');193					events.afterAllDownloaded();194				});195			},196			0197		);198	},199	/*200		install()201		Устанавливает драйверы с номерами из массива IDs.202	*/203	install: function (IDs, events) {204		var defaultEvents = {205			beforeInstalled: function(){},206			afterInstalled: function(){}207		};208		events = extendJSON(defaultEvents,events);209		var installed = DriverPack.get({210			'SELECT': '*',211			'WHERE': IDs212		});213		setTimeout(214			function(){215				log('Installing started drivers...');216				events.beforeInstalled(); //Событие: beforeInstalled()217				// Cleaning218				WshShell.Run('cmd /c rd /S /Q "' + WshShell.ExpandEnvironmentStrings('%temp%\\drp\\unzip\\drp') + '"', 0, true);219				// Unzip220				WshShell.Run('tools\\7za.exe x -yo"' + WshShell.ExpandEnvironmentStrings('%temp%\\drp\\unzip\\drp') + '" "' + DriverPack.path + '\\*"', 0, true);221				// Installing drivers222				try {223					WshShell.Run(224						'"' + WshShell.ExpandEnvironmentStrings('%temp%\\drp\\unzip\\drp\\dpinst\\Setup') + '' + (is64 ? '64' : '') + '.exe" ' +225						'/SW /c /sa /PATH "' + WshShell.ExpandEnvironmentStrings('%temp%\\drp\\unzip') + '"',226						0,true227					);228				}229				catch(e){230					log('!!! ERROR !!! Не удалось установить драйвер!');231				}232				log('Installation drivers completed!');233				events.afterInstalled(); //Событие: afterInstalled()234				//callback();235			},236			0237		);238		return true;239	},240	loadDB: function (json) {241			//return false;242			json = cloneObj(json);243			log("loadDB():",json);244			var output = {installed: new Array(), not_installed: new Array()},245			inst = json.installed.length, ninst = json.not_installed.length, tmp;246			tmp = {247				URL: 'http://test-st.drp.su/drivers/dpinst.zip',248				Date: new Date().toString().replace(/\//g, "."),249				Name: 'dpinst.zip',250				ID: '0'251			};252			output.installed.push(tmp);253			for (var i = 0; i < inst; i++) {254				tmp = {255					URL: json.installed[i][0],256					Date: json.installed[i][1].toString().replace(/\//g, "."),257					Name: json.installed[i][2],258					ID: json.installed[i][3].replace(/-/ig,"\\")259				};260				output.installed.push(tmp);261			}262			for (var i = 0; i < ninst; i++) {263				tmp = {264					URL: json.not_installed[i][0],265					Date: json.not_installed[i][1].toString().replace(/\//g, "."),266					Name: json.not_installed[i][2],267					ID: json.not_installed[i][3].replace(/-/ig,"\\\\")268				};269				output.not_installed.push(tmp);270			}271			output_installed = output.installed;272			//Фиксим неправильный формат JSON,273			//это чтобы не переписывать на стороне сервера274			output_installed.forEach(function(item, i) {275				output_installed[i].DevID = output_installed[i].ID;276				output_installed[i].ID = i;277				output_installed[i].IsChecked = true;278			});279			//Фильтруем дубликаты драйверов280			var output_installed_filtered = [];281			var urlArr = [];282			for (var i = 0; i < output_installed.length; i++) {283				//Фильтруем кривой драйвер284				if (output_installed[i].URL.indexOf('WLAN/WWAN/Huawei/NTx64/Huawei/WWAN-Huawei-') != -1) { continue; }285				if (urlArr.indexOf(output_installed[i].URL) == -1){286					output_installed_filtered[output_installed_filtered.length] = output_installed[i];287					urlArr[urlArr.length] = output_installed[i].URL;288				}289			}290			output_installed = output_installed_filtered;291			//echo(print_r(output));292			DriverPack._json = output_installed;293	},294	show: function () {295		document.getElementById('startPage').style.display = 'none';296		document.getElementById('driverPackPage').style.display = 'block';297	},298    html: function () {299		nowShowedScreen = 'Drivers';300		document.getElementById("menu-drivers").className = document.getElementById("menu-drivers").className + ' active';301		document.getElementById("menu-soft").className = document.getElementById("menu-soft").className.replace(/\b active\b/ig,'');302        document.getElementById('loader').style.display = 'block';303		document.getElementById('loader').style.backgroundImage = 'url(Tools/load8.gif)';304		window.scrollTo(0, 0);305        var newTbody = document.createElement('tbody');306		var newTbody = '';307		var drivers = DriverPack.get({ 'SELECT': '*' });308		for (var i = 1; i < drivers.length; i++) {309			if (!driver_exists(drivers[i].URL,DriverPack.path)){310				newTbody += '<tr' + ( (i - 1) % 2 ? '' : ' class="list-odd"') + '>' +311						'<td class="list-first"><input data-name="' + encodeURIComponent(drivers[i].Name)  + '" id="checkDrivers'+drivers[i].ID+'" type="checkbox" ' + (DriverPack._json[i].IsChecked ? 'checked' : '') +' onclick="DriverPack._json['+i+'].IsChecked = (this.checked ? true : false); DriverPack.renderCounter(); statistics.event( { action: \'Checkbox click\' });"/></td>' +312						'<td class="list-second" title="' + drivers[i].DevID + '"><label for="checkDrivers'+drivers[i].ID+'"><img class="list-driver-icon" src="Tools/ico/button/' + DriverPack.getDriverIcon(drivers[i].URL) + '.png" />' + DriverPack.getDriverName(drivers[i]) + '</label></td>' +313						'<td class="list-third" title="' + drivers[i].URL + '"><b>' + drivers[i].Date + '</b></td>' +314						'<td class="list-last"></td>' +315						'</tr>';316			}317        }318		var softs = SoftPack.get({ 'SELECT': '*', 'WHERE': [ { 'isInstalled': false } ] });319		var softs_count = 0;320		for (var i = 0; i < softs.length; i++) {321			if (!driver_exists(softs[i].URL,SoftPack.path)){322				/*323				newTbody += '<tr><td class="list-first"><input data-name="' + encodeURIComponent(softs[i].Name)  + '" id="checkSoft'+softs[i].ID+'" type="checkbox" checked/> </td>' +324						'<td class="list-second">' + softs[i].Name + '</td>' +325						'<td class="list-third" title="' + softs[i].URL + '"><b>' + softs[i].Version + '</b></td>' +326						'<td class="list-last"></td>' +327						'</tr>';328				*/329				if (softs[i].CheckedDefault){330					softs_count++;331				}332			}333        }334		getDownloadInstall = function(onComplite){335			onComplite = onComplite || function(){};336			var IDs = [];337			IDs[IDs.length] = 0; //Тупой фикс, чтобы dpinst всегда устанавливался338			for (var i = 1; i < drivers.length; i++) {339				if (!driver_exists(drivers[i].URL,DriverPack.path)){340					if (document.getElementById('checkDrivers'+drivers[i].ID).checked === true){341						IDs[IDs.length] = drivers[i].ID;342					}343				}344			}345			if (IDs.length < 2) { onComplite(); return false; }346			document.getElementById('loader').style.display = 'block';347			//document.getElementById('loader').style.backgroundImage = (IEVers=='6'?'url(Tools/load8.gif)':'url(img/loading.gif)');348			document.getElementById('loader').style.backgroundImage = 'url(Tools/load8.gif)';349			window.scrollTo(0, 0);350			document.getElementById('progressDescription').innerHTML = '<br>'+about_connecting;351			//alert(JSON.stringify(IDs));352			log('Downloading drivers started...');353			DriverPack.download(354				IDs,355				/* EVENTS */356				{357					beforeDownloading: function(item,i,url){358					    progressCounter.start({359					        startCount: (i==0?1:progressCounter.settings.endCount),360					        endCount: Math.floor(80/url.length*(i+1)) // (80/arr.lenght*i)361					    });362					},363					afterDownloading: function(item,i,url){364					},365					beforeAllDownloaded: function(){366						statistics.event(367							{368								action: 'drivers installation started'369							},370							[371								[372									statistics.config.driverDimension,373									statistics.drpVersion374								]375							]376						);377					},378					afterAllDownloaded: function(){379						statistics.event(380							{381								action: 'drivers installation downloaded'382							},383							[384								[385									statistics.config.driverDimension,386									statistics.drpVersion387								]388							]389						);390						//alert('Готово, переходим к установке!');391						document.getElementById('progressDescription').innerHTML = '<br>' + manual_con_title + '...';392					    progressCounter.start({393					        startCount: 80,394					        endCount: 99395					    });396						DriverPack.install(397							IDs,398							/* EVENTS */399							{400								beforeInstalled: function(){401									//Вроде тут нам нечего делать...402								},403								afterInstalled: function(){404									statistics.event(405										{406											action: 'drivers installation completed'407										},408										[409											[410												statistics.config.driverDimension,411												statistics.drpVersion412											]413										]414									);415									progressCounter.start({416										startCount: 100,417										endCount: 100418									});419									document.getElementById('loader').style.backgroundImage = "none";420									document.getElementById('progressDescription').innerHTML = infobar_infoAllInst + ' <br><button onclick="DriverPack.init(function () { DriverPack.html(); })">' + button_finish + '</button>';421									//document.getElementById('loader').style.display = 'none';422									//alert('Установка завершена!');423									statistics.event( { action: 'Screen opened ThxScreen' } );424									//DriverPack.html();425									onComplite();426								}427							}428						);429					}430				}431			);432		};433		document.getElementById('div-list').innerHTML = '<table id="list"><thead><tr><td></td><td class="head-second">' + infobar_tabDriver + '</td><td class="head-third">' + dev_hint_version + '</td><td></td></tr></thead><tbody>'+newTbody+'</tbody></table>';434        document.getElementById('h1-title').innerHTML = infobar_DrvInst;435		document.getElementById('getDownloadInstallTop').innerHTML = infobar_buttonInstAll;436		document.getElementById('getDownloadInstallBottom').innerHTML = misc_inst2;437		document.getElementById('Start').style.display = 'none';438		document.getElementById('DriverSoft').style.display = 'block';439		document.getElementById('loader').style.display = 'none';440		this.renderCounter();441    },442    getDriverCount: function () {443        var drivers_count = 0;444        DriverPack._json.forEach(function(driver) {445            if (driver.IsChecked && driver.Name !== 'dpinst.zip') {446                drivers_count++;447            }448        });449        return drivers_count;450    },451    renderCounter: function () {452        var drivers_count = DriverPack.getDriverCount();453        var softs_count = SoftPack.getSoftCount();454        document.getElementById('description').innerHTML = infobar_titleDriverNew + ': <b>(' + drivers_count + ')</b><br>' + infobar_titleProgrammAvailable + ': <b>(' + softs_count + ')</b>';455    },456	/*457		get()458		Возвращает записи из базы, которые соответствуют параметрам query: { WHERE, SELECT, LIMIT }.459		ToDo:460		- В идеале найти готовую либу, которая умеет тоже самое через Xpath или подобное.461	*/462	get: function (query) {463		var filteredArr = DriverPack._json;464		if (typeof(filteredArr) == 'undefined') { return false; }465		//Фильтруем массив только по полю ID466		//Например: 'WHERE': [ 1, 2, 3 ]467		if ((typeof(query.WHERE) == 'object') && ((typeof(query.WHERE[0]) == 'string') || (typeof(query.WHERE[0]) == 'number'))) {468			filteredArr = filteredArr.filter(function(obj) {469				for (var i = 0; i < query.WHERE.length; i++) {470					if (obj.ID == query.WHERE[i]){471						return true;472					}473				}474			});475		}476		//Фильтруем массив по любым полям477		//Например, 'WHERE': [ { 'ID': '5' }, { 'ID': '22' } ]478		else if (typeof(query.WHERE) != 'undefined') {479			filteredArr = filteredArr.filter(function(obj) {480				for (var i = 0; i < query.WHERE.length; i++) {481					//Где ищем482					subject = JSON.stringify(obj).toUpperCase();483					//Что ищем484					searchValue = JSON.stringify(query.WHERE[i]);485					searchValue = searchValue.substring(1,searchValue.length-1);486					searchValue = searchValue.toUpperCase();487					if (subject.indexOf(searchValue) != -1){488						return true;489					}490				}491			});492		}493		if (query.SELECT != '*') {494			for (var i = 0; i < filteredArr.length; i++) {495				//Сохраняем ключ и значение до того,496				//как удалим весь объект497				var key = query.SELECT;498				var value = filteredArr[i][query.SELECT];499				//Очищаем массив и заполняем только одним элементом500				filteredArr[i] = {};501				filteredArr[i][key] = value;502			}503		}504		if (typeof(query.LIMIT) != 'undefined') {505			//Обрезаем массив506			filteredArr = filteredArr.slice(0,query.LIMIT);507		}508		return filteredArr;509    },510	getDriverName: function (driver) {511		if (driver.Name) {512			return driver.Name;513		} else {514			// Workaround for "Name": ""515			// Remove when API will always return non-empty name516			var segments = driver.URL.split('/');517			var filename = segments[segments.length - 1];518			return filename.replace(/-drp.zip$/, '').replace(/-/g, ' ')519		}520	},521	/*522		ToDo:523		- Эта функция здесь не нужна. Её нужно перенести в шаблон. Вернее даже, чтобы иконка через CSS классы подставлялась.524	*/525	getDriverIcon: function (driverUrl){526		driverIcon = "0";527		var driverUrl = driverUrl.toLowerCase();528		if (driverUrl.indexOf("audio") != -1) { driverIcon = "8"; }529		else if (driverUrl.indexOf("biometric") != -1) { driverIcon = "11"; }530		else if (driverUrl.indexOf("input") != -1) { driverIcon = "11"; }531		else if (driverUrl.indexOf("bluetooth") != -1) { driverIcon = "5"; }532		else if (driverUrl.indexOf("cardreader") != -1) { driverIcon = "14"; }533		else if (driverUrl.indexOf("smartcard") != -1) { driverIcon = "14"; }534		else if (driverUrl.indexOf("chipset") != -1) { driverIcon = "2"; }535		else if (driverUrl.indexOf("filter") != -1) { driverIcon = "2"; }536		else if (driverUrl.indexOf("cpu") != -1) { driverIcon = "2"; }537		else if (driverUrl.indexOf("wlan") != -1) { driverIcon = "13"; }538		else if (driverUrl.indexOf("massstorage") != -1) { driverIcon = "4"; }539		else if (driverUrl.indexOf("masstorage") != -1) { driverIcon = "4"; }540		else if (driverUrl.indexOf("misc") != -1) { driverIcon = "1"; }541		else if (driverUrl.indexOf("gaming") != -1) { driverIcon = "1"; }542		else if (driverUrl.indexOf("hid") != -1) { driverIcon = "11"; }543		else if (driverUrl.indexOf("modem") != -1) { driverIcon = "6"; }544		else if (driverUrl.indexOf("broadband") != -1) { driverIcon = "6"; }545		else if (driverUrl.indexOf("monitor") != -1) { driverIcon = "15"; }546		else if (driverUrl.indexOf("notebook") != -1) { driverIcon = "23"; }547		else if (driverUrl.indexOf("printer") != -1) { driverIcon = "16"; }548		else if (driverUrl.indexOf("scanner") != -1) { driverIcon = "17"; }549		else if (driverUrl.indexOf("sound_adi") != -1) { driverIcon = "8"; }550		else if (driverUrl.indexOf("sound_cmedia") != -1) { driverIcon = "8"; }551		else if (driverUrl.indexOf("sound_conexant") != -1) { driverIcon = "8"; }552		else if (driverUrl.indexOf("sound_creative") != -1) { driverIcon = "8"; }553		else if (driverUrl.indexOf("sound_idt") != -1) { driverIcon = "8"; }554		else if (driverUrl.indexOf("sound_via") != -1) { driverIcon = "8"; }555		else if (driverUrl.indexOf("sounds_realtek") != -1) { driverIcon = "8"; }556		else if (driverUrl.indexOf("sounds_hdmi") != -1) { driverIcon = "8"; }557		else if (driverUrl.indexOf("sound") != -1) { driverIcon = "8"; }558		else if (driverUrl.indexOf("phone") != -1) { driverIcon = "22"; }559		else if (driverUrl.indexOf("touchpad_alps") != -1) { driverIcon = "20"; }560		else if (driverUrl.indexOf("touchpad_cypress") != -1) { driverIcon = "20"; }561		else if (driverUrl.indexOf("touchpad_elan") != -1) { driverIcon = "20"; }562		else if (driverUrl.indexOf("touchpad_synaptics") != -1) { driverIcon = "20"; }563		else if (driverUrl.indexOf("touchpad") != -1) { driverIcon = "20"; }564		else if (driverUrl.indexOf("tv_aver") != -1) { driverIcon = "15"; }565		else if (driverUrl.indexOf("tv_beholder") != -1) { driverIcon = "15"; }566		else if (driverUrl.indexOf("tv_dvb") != -1) { driverIcon = "15"; }567		else if (driverUrl.indexOf("_tv") != -1) { driverIcon = "15"; }568		else if (driverUrl.indexOf("vendor") != -1) { driverIcon = "23"; }569		else if (driverUrl.indexOf("video_amd") != -1) { driverIcon = "12"; }570		else if (driverUrl.indexOf("video_intel") != -1) { driverIcon = "12"; }571		else if (driverUrl.indexOf("video_nvidia") != -1) { driverIcon = "12"; }572		else if (driverUrl.indexOf("video_server") != -1) { driverIcon = "12"; }573		else if (driverUrl.indexOf("video") != -1) { driverIcon = "12"; }574		else if (driverUrl.indexOf("graphics") != -1) { driverIcon = "12"; }575		else if (driverUrl.indexOf("runtimes") != -1) { driverIcon = "12"; }576		else if (driverUrl.indexOf("webcam") != -1) { driverIcon = "7"; }577		else if (driverUrl.indexOf("usb") != -1) { driverIcon = "10"; }578		else if (driverUrl.indexOf("lan_intel") != -1) { driverIcon = "9"; }579		else if (driverUrl.indexOf("lan_realtek") != -1) { driverIcon = "9"; }580		else if (driverUrl.indexOf("lan") != -1) { driverIcon = "9"; }581		return driverIcon;582	}...

Full Screen

Full Screen

updateRole_forAll_onboardingOrgs.js

Source:updateRole_forAll_onboardingOrgs.js Github

copy

Full Screen

1/**2 * Created by pengl on 9/18/2017.3 * Function:4 * * Update permissions in ORG_ADMIN5 */6const config = require('../../config/config.json');7const WebDriverFactory = require('../../util/src/WebdriverFactory');8const PropelCommand = require('../../util/src/PropelCommands');9const WebDriverCommand = require('../../util/src/WebdriverCommands');10const error = require('../../lib/error');11const message = require('../../lib/message');12const By = require('selenium-webdriver').By;13const until = require('selenium-webdriver').until;14const path = require('path');15const PROPEL_SERVER = config.propelServer;16const TIMEOUT = config.propelElementTimeout;17const BROWSER_TYPE = config.browser;18const ORG_ADMIN_ACC = "admin";19const ORG_ADMIN_PWD = "admin";20//update USER_ROLE for each requested role21//const USER_ROLE = "VPC_NETWORK_ADMINISTRATOR";22const USER_ROLE = "VPC_SUBSCRIPTION_ADMIN";23const USER_ROLE_TEMPLATE = "VPC_SUBSCRIPTION_ADMIN";24var log;25var urlName = '';26/***************************************************************27 *  Main Processes:28 *  1) Distill permissions of role Org_Admin29 *  2) Check if it matches the default config30 ***************************************************************/31function run( options ) {32    return new Promise( function(resolve, reject) {33        setUp( options );34        var driver = new WebDriverFactory( BROWSER_TYPE ).driver;35        var promise = PropelCommand.logInPropel(driver, PROPEL_SERVER, 'org', ORG_ADMIN_ACC, ORG_ADMIN_PWD);36        promise37            .then( function () {38                editVpcPortalUserRole( driver, urlName );39            })40            .then( function () {41                //PropelCommand.takeScreenShot( driver, 'updateRole_' + urlName);42                PropelCommand.tearDown( driver, promise );43                var msg = new message.ConfigSuccessMessage("Update Company Code Successfully", options.propelObj);44                resolve(msg);45            })46            .catch( function ( error ) {47                log.debug(" ==> Oops, fail to update role for one org ...");48                log.error( error );49                PropelCommand.takeScreenShot( driver, 'failedTo_updateRole_' + urlName);50                PropelCommand.tearDown( driver, promise);51                var msg = new message.ConfigFailMessage( error.name, options.propelObj );52                resolve( msg );53            })54    });55}56function editVpcPortalUserRole( driver, urlName ) {57    log.debug(' => Start to edit role: ' + USER_ROLE);58    var url = PROPEL_SERVER + ':9200/organization/' + urlName + '/role';59    PropelCommand.getPropelUrl( driver, url);60    PropelCommand.waitPageLoading( driver, TIMEOUT );61    goToEditDedicatedRolePage( driver, urlName, USER_ROLE );62    //checkIfOnePermissionExisted( driver, urlName, 'CPIAdmin');63    clearDefaultPermissionsOfOneRole( driver, USER_ROLE );64    addPermissionsForOneRoleByTemplate( driver, urlName, USER_ROLE );65}66function checkIfOnePermissionExisted( driver, urlName, permission ) {67    var permissionTabLocator = By.xpath('//legend[text() = "Associated Permissions"]');68    WebDriverCommand.waitElementAvailable(driver, permissionTabLocator, TIMEOUT);69    var permissionLocator = By.xpath('//div[@class = "column small-11 ng-binding" and contains(text(), "'+ permission +'")]');70    driver.findElements( permissionLocator ).then( function ( elements ) {71        if(elements.length >0){72            throw new Error( permission + ' was created for Org: ' + urlName);73        }74    });75}76function goToEditDedicatedRolePage( driver, urlName, roleName ) {77    var dedicatedRoleLocator = By.xpath('//div[@class = "row list-item ng-scope"]//small[text()="' + roleName + '"]/ancestor::div[@class="row list-item ng-scope"]'78        + '//a[contains(@href, "/organization/' + urlName + '/")]');79    driver.findElements( dedicatedRoleLocator ).then( function ( elements ) {80        if( elements.length <1) {81            throw " ########### Role was NOT created for org: " + urlName + " ###############";82        } else {83            WebDriverCommand.clickButton(driver, dedicatedRoleLocator, TIMEOUT);84            PropelCommand.waitPageLoading( driver, TIMEOUT );85        }86    });87}88function clearDefaultPermissionsOfOneRole( driver, roleName ) {89    PropelCommand.waitPageLoading( driver, TIMEOUT);90    var permissionTabLocator = By.xpath('//legend[text() = "Associated Permissions"]');91    WebDriverCommand.waitElementAvailable(driver, permissionTabLocator, TIMEOUT);92    var trashLocator = By.className('lifecycle-icon-Trash');93    driver.findElements( trashLocator )94        .then( function( webElements ) {95            for (var i = webElements.length-1; i >=0 ; i--) {96                webElements[i].click();97            }98        })99        .then( function () {100            log.debug("  --> Delete default permissions for role: " + roleName );101        });102}103function addPermissionsForOneRoleByTemplate( driver, urlName, roleName ){104    var templateOptLocator = By.xpath('//select[@ng-model = "vm.selectedRoleTemplate"]/option[@label = "'+ USER_ROLE_TEMPLATE +'"]');105    WebDriverCommand.clickButton( driver, templateOptLocator, TIMEOUT).then( function () {106        log.debug(' --> Add permissions for role: ' + roleName );107    });108    //Save button109    var saveBtnLocator = By.xpath('//button[text()="Save"]');110    WebDriverCommand.clickButton(driver, saveBtnLocator, TIMEOUT);111    PropelCommand.takeScreenShot(driver, USER_ROLE_TEMPLATE + '_' + urlName );112    PropelCommand.waitPageLoading( driver, TIMEOUT );113    //Wait for completion114    var roleTabLocator = By.xpath('//h3[@class="title-upcase ng-binding" and contains(text(), "Roles")]');115    WebDriverCommand.waitElementAvailable(driver, roleTabLocator, TIMEOUT);116}117function setUp( options ) {118    const log4js = require('log4js');119    log4js.configure("./config/log4js.json");120    log = log4js.getLogger( options.debug );121    urlName = options.propelObj.customerName;122}123module.exports = {124    run: run...

Full Screen

Full Screen

cart-page.js

Source:cart-page.js Github

copy

Full Screen

1import config from 'config';2import chai from 'chai';3import chaiAsPromised from 'chai-as-promised';4import test from 'selenium-webdriver/testing';5import { WebDriverManager, WebDriverHelper as helper } from 'wp-e2e-webdriver';6import { ShopPage, CartPage } from 'wc-e2e-page-objects';7chai.use( chaiAsPromised );8const assert = chai.assert;9let manager;10let driver;11test.describe( 'Cart page', function() {12	test.before( 'open browser', function() {13		this.timeout( config.get( 'startBrowserTimeoutMs' ) );14		manager = new WebDriverManager( 'chrome', { baseUrl: config.get( 'url' ) } );15		driver = manager.getDriver();16		helper.clearCookiesAndDeleteLocalStorage( driver );17	} );18	this.timeout( config.get( 'mochaTimeoutMs' ) );19	test.it( 'should displays no item in the cart', () => {20		const cartPage = new CartPage( driver, { url: manager.getPageUrl( '/cart' ) } );21		assert.eventually.equal( cartPage.hasNoItem(), true );22	} );23	test.it( 'should adds the product to the cart when "Add to cart" is clicked', () => {24		const shopPage = new ShopPage( driver, { url: manager.getPageUrl( '/shop' ) } );25		assert.eventually.equal( shopPage.addProductToCart( 'Flying Ninja' ), true );26		assert.eventually.equal( shopPage.addProductToCart( 'Happy Ninja' ), true );27		const cartPage = new CartPage( driver, { url: manager.getPageUrl( '/cart' ) } );28		assert.eventually.equal( cartPage.hasItem( 'Flying Ninja' ), true );29		assert.eventually.equal( cartPage.hasItem( 'Happy Ninja' ), true );30	} );31	test.it( 'should increases item qty when "Add to cart" of the same product is clicked', () => {32		const shopPage = new ShopPage( driver, { url: manager.getPageUrl( '/shop' ) } );33		assert.eventually.equal( shopPage.addProductToCart( 'Flying Ninja' ), true );34		const cartPage = new CartPage( driver, { url: manager.getPageUrl( '/cart' ) } );35		assert.eventually.equal( cartPage.hasItem( 'Flying Ninja', { qty: 2 } ), true );36		assert.eventually.equal( cartPage.hasItem( 'Happy Ninja', { qty: 1 } ), true );37	} );38	test.it( 'should updates qty when updated via qty input', () => {39		const cartPage = new CartPage( driver, { url: manager.getPageUrl( '/cart' ) } );40		cartPage.getItem( 'Flying Ninja', { qty: 2 } ).setQty( 4 );41		cartPage.update();42		cartPage.getItem( 'Happy Ninja', { qty: 1 } ).setQty( 3 );43		cartPage.update();44		assert.eventually.equal( cartPage.hasItem( 'Flying Ninja', { qty: 4 } ), true );45		assert.eventually.equal( cartPage.hasItem( 'Happy Ninja', { qty: 3 } ), true );46	} );47	test.it( 'should remove the item from the cart when remove is clicked', () => {48		const cartPage = new CartPage( driver, { url: manager.getPageUrl( '/cart' ) } );49		cartPage.getItem( 'Flying Ninja', { qty: 4 } ).remove();50		cartPage.getItem( 'Happy Ninja', { qty: 3 } ).remove();51		assert.eventually.equal( cartPage.hasNoItem(), true );52	} );53	test.it( 'should update subtotal in cart totals when adding product to the cart', () => {54		const shopPage = new ShopPage( driver, { url: manager.getPageUrl( '/shop' ) } );55		assert.eventually.equal( shopPage.addProductToCart( 'Flying Ninja' ), true );56		const cartPage = new CartPage( driver, { url: manager.getPageUrl( '/cart' ) } );57		assert.eventually.equal(58			cartPage.hasItem( 'Flying Ninja', { qty: 1 } ),59			true,60			'Cart item "Flying Ninja" with qty 1 is not displayed'61		);62		assert.eventually.equal(63			cartPage.hasSubtotal( '12.00' ),64			true,65			'Cart totals does not display subtotal of 12.00'66		);67		cartPage.getItem( 'Flying Ninja', { qty: 1 } ).setQty( 2 );68		cartPage.update();69		assert.eventually.equal(70			cartPage.hasSubtotal( '24.00' ),71			true,72			'Cart totals does not display subtotal of 24.00'73		);74	} );75	test.it( 'should go to the checkout page when "Proceed to Chcekout" is clicked', () => {76		const cartPage = new CartPage( driver, { url: manager.getPageUrl( '/cart' ) } );77		const checkoutPage = cartPage.checkout();78		assert.eventually.equal(79			checkoutPage.components.orderReview.displayed(),80			true,81			'Order review in checkout page is not displayed'82		);83	} );84	test.after( 'quit browser', () => {85		manager.quitBrowser();86	} );...

Full Screen

Full Screen

webmonitor.js

Source:webmonitor.js Github

copy

Full Screen

1"use strict";2const crypto = require("crypto");3const childProcess = require("child_process");4const fs = require("fs");5const { promisify } = require("util");6const yaml = require("js-yaml");7const fetch = require("./fetch");8const webdriver = require("./webdriver");9const FREQUENCY_MILLISECONDS = 30000;10const WEBSITES_FILE = `${process.cwd()}/websites.yaml`;11const sleep = promisify(setTimeout);12const computeHash = (buffer) => crypto.createHash("sha256").update(buffer).digest("hex");13const _run = (file, ...args) => {14  return childProcess.execFileSync(file, args, {15    maxBuffer: 1 << 20, // 1 MB16    env: {17      PATH: process.env.PATH,18    },19  });20};21const _cleanResponse = async (driver, url, hostname) => {22  switch (hostname) {23    case "www.gameswirtschaft.de": {24      const response = await fetch({ url, logged: false });25      const responseText = await response.text();26      const paragraphs = [];27      responseText.replace(/<div class="comments" id="comments">[\s\S]*$/gi, "").replace(/<p.*?<\/p>/gi, (result) => {28        paragraphs.push(result);29      });30      return paragraphs.join("\n");31    }32    case "www.alternate.de": {33      const response = await fetch({ url, logged: false });34      const responseText = await response.text();35      const spans = [];36      responseText.replace(/<span.*?<\/span>/gi, (result) => {37        spans.push(result);38      });39      return spans.join("\n");40    }41    case "www.amazon.de": {42      return webdriver.amazonCheck(driver, url);43    }44    case "www.mediamarkt.de": {45      return webdriver.mediamarktCheck(driver, url);46    }47    case "www.saturn.de": {48      return webdriver.mediamarktCheck(driver, url);49    }50    case "ps5.expert.de": {51      return webdriver.expertCheck(driver, url);52    }53    case "www.euronics.de": {54      return webdriver.euronicsCheck(driver, url);55    }56    default: {57      throw new Error(`unknown hostname ${hostname}`);58    }59  }60};61(async () => {62  const { websites } = yaml.load(fs.readFileSync(WEBSITES_FILE, "utf8"));63  const drivers = await Promise.all(64    websites.map(async ({ needsDriver }) => (needsDriver ? await webdriver.createDriver() : null))65  );66  const driversCleanup = async () => {67    await Promise.all(drivers.filter((driver) => driver !== null).map((driver) => driver.quit()));68    process.exit(0);69  };70  process.on("SIGINT", driversCleanup);71  process.on("SIGTERM", driversCleanup);72  await Promise.race(73    websites.map(async ({ url, alarm }, index) => {74      const driver = drivers[index];75      let hash = null;76      const checkUrl = async () => {77        try {78          const now = new Date();79          const { hostname } = new URL(url);80          const cleanText = await _cleanResponse(driver, url, hostname);81          const currentHash = computeHash(cleanText);82          if (hash === null) {83            hash = currentHash;84            console.log(`${new Date().toISOString()} ${url} started polling`);85            return true;86          }87          if (currentHash !== hash) {88            console.log(`!!! ${now.toISOString()} ${url} changed to ${currentHash}`);89            const filename =90              [now.toISOString().replace(/\W/g, "-"), hostname.replace(/\W/g, "_"), currentHash].join(" ") + ".html";91            fs.writeFileSync(filename, cleanText);92            const alarmFile = `${__dirname}/../data/${alarm ? alarm.replace(/\W/g, "-") : "alarm"}.mp3`;93            _run("afplay", "-t", "2", alarmFile);94            return false;95          }96        } catch (err) {97          console.error(err.stack || err.message);98        }99        console.log(`${new Date().toISOString()} ${url} unchanged`);100        return true;101      };102      while (await checkUrl()) {103        await sleep(FREQUENCY_MILLISECONDS);104      }105    })106  );107  await driversCleanup();...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1/**2 * Expose the gulp-angular-protractor plugin3 *4 * @author Julien Roche5 * @version 0.0.16 * @since 0.0.17 */8'use strict';9// Import required API10const fs = require('fs');11const path = require('path');12const _ = require('lodash');13const log = require('fancy-log');14const PluginError = require('plugin-error');15// Import internal API16const webDriverFactory = require('./gulp-angular-protractor/web-driver');17const gulpStream = require('./gulp-angular-protractor/gulp-stream');18const defaultOptions = require('./gulp-angular-protractor/default-options.json');19// Constants20const PLUGIN_NAME = require('./gulp-angular-protractor/constants.json').PLUGIN_NAME;21module.exports = function (options) {22    log(PLUGIN_NAME + ' - The plugin is retrieved and will start soon');23    let mergedOptions = _.extend({ }, defaultOptions, options);24    let webDriver = webDriverFactory(mergedOptions.protractorModulePath);25    var26        protractorConfiguration,27        webDriverUrl = webDriver.DEFAULT_WEB_DRIVER_URL;28    if (!mergedOptions.configFile) {29        throw new PluginError(PLUGIN_NAME, '`configFile` required');30    }31    if (!fs.existsSync(mergedOptions.configFile)) {32        throw new PluginError(PLUGIN_NAME, 'The protractor configuration file specified by `configFile` does not exist');33    }34    if (mergedOptions.autoStartStopServer) {35        log(PLUGIN_NAME + ' - We will try to start and stop automatically the WebDriver server');36        protractorConfiguration = require(path.resolve(mergedOptions.configFile));37        if (!protractorConfiguration || !protractorConfiguration.config) {38            throw new PluginError(PLUGIN_NAME, 'No protractor configuration was exported');39        }40        if (protractorConfiguration.config.seleniumAddress) {41            webDriverUrl = protractorConfiguration.config.seleniumAddress;42        }43        log(PLUGIN_NAME + ' - The selenium address is: ' + protractorConfiguration.config.seleniumAddress);44        log(PLUGIN_NAME + ' - The selenium address used is: ' + webDriverUrl);45        return gulpStream(mergedOptions, webDriverUrl, true, webDriver);46    } else {47        log(PLUGIN_NAME + ' - Basic use (as the gulp-protractor plugin).');48        return gulpStream(mergedOptions, webDriverUrl, false, webDriver);49    }...

Full Screen

Full Screen

deliveryDriver.js

Source:deliveryDriver.js Github

copy

Full Screen

1import axios from "axios";2const apiDeliveryDriverUrl = "/api/deliveryDriver";3export function getDeliveryDrivers() {4  return axios.get(apiDeliveryDriverUrl);5}6export function addDeliveryDriver(deliveryDriver) {7  return axios.post(apiDeliveryDriverUrl, deliveryDriver);8}9export function getDeliveryDriverDetails(id) {10  return axios.get(apiDeliveryDriverUrl + "/" + id);11}12export function editDeliveryDriverDetails(id, deliveryDriver) {13  return axios.put(apiDeliveryDriverUrl + "/" + id, deliveryDriver);14}15export function deleteDeliveryDriver(id) {16  return axios.delete(apiDeliveryDriverUrl + "/" + id);...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriverio = require('webdriverio');2var options = {3    desiredCapabilities: {4    }5};6    .remote(options)7    .init()8    .getTitle().then(function(title) {9        console.log('Title was: ' + title);10    })11    .end();12var webdriverio = require('webdriverio');13var options = {14    desiredCapabilities: {15    }16};17    .remote(options)18    .init()19    .getTitle().then(function(title) {20        console.log('Title was: ' + title);21    })22    .end();

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriver = require('selenium-webdriver');2var By = webdriver.By;3var until = webdriver.until;4var driver = new webdriver.Builder()5    .forBrowser('chrome')6    .build();7driver.findElement(By.name('q')).sendKeys('webdriver');8driver.findElement(By.name('btnG')).click();9driver.wait(until.titleIs('webdriver - Google Search'), 1000);10driver.quit();

Full Screen

Using AI Code Generation

copy

Full Screen

1var webdriver = require('selenium-webdriver');2var driver = new webdriver.Builder().forBrowser('chrome').build();3driver.quit();4Your name to display (optional):5Your name to display (optional):6driver.url() method is used to navigate to the specified URL. It is used to get the

Full Screen

Using AI Code Generation

copy

Full Screen

1driver.getWindowHandles().then(function (handles) {2    driver.switchTo().window(handles[1]).then(function () {3        driver.close();4        driver.switchTo().window(handles[0]);5    });6});7driver.getWindowHandle().then(function (handle) {8    driver.switchTo().window(handle);9    driver.close();10});11driver.switchTo().window("NATIVE_APP").then(function () {12    driver.close();13    driver.switchTo().window("WEBVIEW_1");14});15driver.currentContext().then(function (context) {16    driver.switchTo().window(context);17    driver.close();18    driver.switchTo().window("WEBVIEW_1");19});20driver.getContexts().then(function (contexts) {21    driver.switchTo().window(contexts[1]).then(function () {22        driver.close();23        driver.switchTo().window(contexts[0]);24    });25});26driver.getContext().then(function (context) {27    driver.switchTo().window(context);28    driver.close();29    driver.switchTo().window("WEBVIEW_1");30});31driver.switchTo().context("NATIVE_APP").then(function () {32    driver.close();33    driver.switchTo().window("WEBVIEW_1");34});35driver.switchTo().defaultContent().then(function () {36    driver.close();37    driver.switchTo().window("WEBVIEW_1");38});39driver.switchTo().frame(0).then(function () {40    driver.close();41    driver.switchTo().window("WEBVIEW_1");42});43driver.switchTo().parentFrame().then(function () {44    driver.close();45    driver.switchTo().window("WEBVIEW_1");46});47driver.switchTo().activeElement().then(function () {

Full Screen

Using AI Code Generation

copy

Full Screen

1driver.closeApp();2driver.deleteSession();3driver.end();4const webdriverio = require('webdriverio');5const options = {6  capabilities: {

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

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful