code
stringlengths
1
2.08M
language
stringclasses
1 value
// Copyright 2012 Google Inc. All Rights Reserved. /* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Utility for handling authorization and updating the UI * accordingy. * @author api.nickm@gmail.com (Nick Mihailovski) */ /** * Authorization information. This should be obtained through the Google APIs * developers console. https://code.google.com/apis/console/ * Also there is more information about how to get these in the authorization * section in the Google JavaScript Client Library. * https://code.google.com/p/google-api-javascript-client/wiki/Authentication */ var clientId = '821751250764.apps.googleusercontent.com'; var apiKey = 'AIzaSyAPusS7gzp0bTla1ogGW_hJOwamaBwVT5Q'; var scopes = 'https://www.googleapis.com/auth/analytics.readonly'; /** * Callback executed once the Google APIs Javascript client library has loaded. * The function name is specified in the onload query parameter of URL to load * this library. After 1 millisecond, checkAuth is called. */ function handleClientLoad() { gapi.client.setApiKey(apiKey); window.setTimeout(checkAuth, 1); } /** * Uses the OAuth2.0 clientId to query the Google Accounts service * to see if the user has authorized. Once complete, handleAuthResults is * called. */ function checkAuth() { gapi.auth.authorize({ client_id: clientId, scope: scopes, immediate: true}, handleAuthResult); } /** * Handler that is called once the script has checked to see if the user has * authorized access to their Google Analytics data. If the user has authorized * access, the analytics api library is loaded and the handleAuthorized * function is executed. If the user has not authorized access to their data, * the handleUnauthorized function is executed. * @param {Object} authResult The result object returned form the authorization * service that determine whether the user has currently authorized access * to their data. If it exists, the user has authorized access. */ function handleAuthResult(authResult) { if (authResult) { gapi.client.load('analytics', 'v3', handleAuthorized); } else { handleUnauthorized(); } } /** * Updates the UI once the user has authorized this script to access their * data. This changes the visibiilty on some buttons and adds the * makeApiCall click handler to the run-demo-button. */ function handleAuthorized() { var authorizeButton = document.getElementById('authorize-button'); var runDemoButton = document.getElementById('run-demo-button'); authorizeButton.style.visibility = 'hidden'; runDemoButton.style.visibility = ''; runDemoButton.onclick = makeApiCall; outputToPage('Click the Run Demo button to begin.'); } /** * Updates the UI if a user has not yet authorized this script to access * their Google Analytics data. This function changes the visibility of * some elements on the screen. It also adds the handleAuthClick * click handler to the authorize-button. */ function handleUnauthorized() { var authorizeButton = document.getElementById('authorize-button'); var runDemoButton = document.getElementById('run-demo-button'); runDemoButton.style.visibility = 'hidden'; authorizeButton.style.visibility = ''; authorizeButton.onclick = handleAuthClick; outputToPage('Please authorize this script to access Google Analytics.'); } /** * Handler for clicks on the authorization button. This uses the OAuth2.0 * clientId to query the Google Accounts service to see if the user has * authorized. Once complete, handleAuthResults is called. * @param {Object} event The onclick event. */ function handleAuthClick(event) { gapi.auth.authorize({ client_id: clientId, scope: scopes, immediate: false}, handleAuthResult); return false; }
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. /* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Sample program traverses the Managemt API hierarchy to * retrieve the first profile id. This profile id is then used to query the * Core Reporting API to retrieve the top 25 organic * Note: auth_util.js is required for this to run. * @author api.nickm@gmail.com (Nick Mihailovski) */ /** * Executes a query to the Management API to retrieve all the users accounts. * Once complete, handleAccounts is executed. Note: A user must have gone * through the Google APIs authorization routine and the Google Anaytics * client library must be loaded before this function is called. */ function makeApiCall() { outputToPage('Querying Accounts.'); gapi.client.analytics.management.accounts.list().execute(handleAccounts); } /** * Handles the API response for querying the accounts collection. This checks * to see if any error occurs as well as checks to make sure the user has * accounts. It then retrieve the ID of the first account and then executes * queryWebProeprties. * @param {Object} response The response object with data from the * accounts collection. */ function handleAccounts(response) { if (!response.code) { if (response && response.items && response.items.length) { var firstAccountId = response.items[0].id; queryWebproperties(firstAccountId); } else { updatePage('No accounts found for this user.') } } else { updatePage('There was an error querying accounts: ' + response.message); } } /** * Executes a query to the Management API to retrieve all the users * webproperties for the provided accountId. Once complete, * handleWebproperties is executed. * @param {String} accountId The ID of the account from which to retrieve * webproperties. */ function queryWebproperties(accountId) { updatePage('Querying Webproperties.'); gapi.client.analytics.management.webproperties.list({ 'accountId': accountId }).execute(handleWebproperties); } /** * Handles the API response for querying the webproperties collection. This * checks to see if any error occurs as well as checks to make sure the user * has webproperties. It then retrieve the ID of both the account and the * first webproperty, then executes queryProfiles. * @param {Object} response The response object with data from the * webproperties collection. */ function handleWebproperties(response) { if (!response.code) { if (response && response.items && response.items.length) { var firstAccountId = response.items[0].accountId; var firstWebpropertyId = response.items[0].id; queryProfiles(firstAccountId, firstWebpropertyId); } else { updatePage('No webproperties found for this user.') } } else { updatePage('There was an error querying webproperties: ' + response.message); } } /** * Executes a query to the Management API to retrieve all the users * profiles for the provided accountId and webPropertyId. Once complete, * handleProfiles is executed. * @param {String} accountId The ID of the account from which to retrieve * profiles. * @param {String} webpropertyId The ID of the webproperty from which to * retrieve profiles. */ function queryProfiles(accountId, webpropertyId) { updatePage('Querying Profiles.'); gapi.client.analytics.management.profiles.list({ 'accountId': accountId, 'webPropertyId': webpropertyId }).execute(handleProfiles); } /** * Handles the API response for querying the profiles collection. This * checks to see if any error occurs as well as checks to make sure the user * has profiles. It then retrieve the ID of the first profile and * finally executes queryCoreReportingApi. * @param {Object} response The response object with data from the * profiles collection. */ function handleProfiles(response) { if (!response.code) { if (response && response.items && response.items.length) { var firstProfileId = response.items[0].id; queryCoreReportingApi(firstProfileId); } else { updatePage('No profiles found for this user.') } } else { updatePage('There was an error querying profiles: ' + response.message); } } /** * Execute a query to the Core Reporting API to retrieve the top 25 * organic search terms by visits for the profile specified by profileId. * Once complete, handleCoreReportingResults is executed. * @param {String} profileId The profileId specifying which profile to query. */ function queryCoreReportingApi(profileId) { updatePage('Querying Core Reporting API.'); gapi.client.analytics.data.ga.get({ 'ids': 'ga:' + profileId, 'start-date': lastNDays(14), 'end-date': lastNDays(0), 'metrics': 'ga:visits', 'dimensions': 'ga:source,ga:keyword', 'sort': '-ga:visits,ga:source', 'filters': 'ga:medium==organic', 'max-results': 25 }).execute(handleCoreReportingResults); } /** * Handles the API reponse for querying the Core Reporting API. This first * checks if any errors occured and prints the error messages to the screen. * If sucessful, the profile name, headers, result table are printed for the * user. * @param {Object} response The reponse returned from the Core Reporting API. */ function handleCoreReportingResults(response) { if (!response.code) { if (response.rows && response.rows.length) { var output = []; // Profile Name. output.push('Profile Name: ', response.profileInfo.profileName, '<br>'); var table = ['<table>']; // Put headers in table. table.push('<tr>'); for (var i = 0, header; header = response.columnHeaders[i]; ++i) { table.push('<th>', header.name, '</th>'); } table.push('</tr>'); // Put cells in table. for (var i = 0, row; row = response.rows[i]; ++i) { table.push('<tr><td>', row.join('</td><td>'), '</td></tr>'); } table.push('</table>'); output.push(table.join('')); outputToPage(output.join('')); } else { outputToPage('No results found.'); } } else { updatePage('There was an error querying core reporting API: ' + response.message); } } /** * Utility method to update the output section of the HTML page. Used * to output messages to the user. This overwrites any existing content * in the output area. * @param {String} output The HTML string to output. */ function outputToPage(output) { document.getElementById('output').innerHTML = output; } /** * Utility method to update the output section of the HTML page. Used * to output messages to the user. This appends content to any existing * content in the output area. * @param {String} output The HTML string to output. */ function updatePage(output) { document.getElementById('output').innerHTML += '<br>' + output; } /** * Utility method to return the lastNdays from today in the format yyyy-MM-dd. * @param {Number} n The number of days in the past from tpday that we should * return a date. Value of 0 returns today. */ function lastNDays(n) { var today = new Date(); var before = new Date(); before.setDate(today.getDate() - n); var year = before.getFullYear(); var month = before.getMonth() + 1; if (month < 10) { month = '0' + month; } var day = before.getDate(); if (day < 10) { day = '0' + day; } return [year, month, day].join('-'); }
JavaScript
// Copyright 2012 Google Inc. All Rights Reserved. /* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Sample program demonstrates methods of the * Enterprise License Manager API * @author smarquardt@google.com (Stafford Marquardt) */ /** * Loads the Licensing API. */ function init() { gapi.client.load('licensing', 'v1', auth); } /** * Authenticates into the Licensing API, using the Client ID specified * in the UI. */ function auth() { var clientId = document.getElementById("clientId").value; // Scope for License Manager API var scope = 'https://www.googleapis.com/auth/apps.licensing'; var config = { 'client_id': clientId, 'scope': scope } gapi.auth.authorize(config, function() { console.log('login complete'); console.log(gapi.auth.getToken()); }); // Update UI after auth $('#authreq').hide(); $('#lmui').show(); } /** * Calls the appropriate method of the API based on the method selected * by the user in the UI. */ function manageLicenses(){ var custID = document.getElementById("custid").value; var userID = document.getElementById("userid").value; var action = document.getElementById("mgmtaction").value; var prodID = document.getElementById("prodid").value; var skuID = document.getElementById("skuid").value; var oldSkuID = document.getElementById("oldskuid").value; if (action=="view"){ viewLicenses(custID, prodID); } else if (action=="viewsku") { viewLicensesBySku(custID, prodID, skuID); } else if (action=="assign") { assignLicense(prodID, skuID, userID); } else if (action=="bulkassign") { bulkAssign(prodID, skuID, userID); } else if (action=="reassign") { reassign(prodID, oldSkuID, skuID, userID); } else if (action=="delete") { deleteLicense(prodID, skuID, userID) } else if (action=="bulkdelete") { bulkDelete(prodID, skuID, userID); } } /** * Updates the SKU picklist in the UI each time the product is changed. */ function updateSkus(){ var prodID = document.getElementById("prodid").value; if (prodID=='Google-Coordinate'){ var skuList = ['Google-Coordinate']; } else if (prodID == "Google-Drive-storage"){ var skuList = [ 'Google-Drive-storage-20GB', 'Google-Drive-storage-50GB', 'Google-Drive-storage-200GB', 'Google-Drive-storage-400GB', 'Google-Drive-storage-1TB', 'Google-Drive-storage-2TB', 'Google-Drive-storage-4TB', 'Google-Drive-storage-8TB', 'Google-Drive-storage-16TB' ] } var skuPicker = ""; for (sku in skuList){ skuPicker += '<option value="' + skuList[sku] + '">' + skuList[sku] + '</option>'; } $(".skupicker").html(skuPicker); } /** * Updates the fields that display in the UI each time a different API * method is selected by the user. */ function updateUI(){ var action = document.getElementById("mgmtaction").value; if (action=="view"){ $('.userinfo').hide(); $('.prodinfo').show(); $('.skuinfo').hide(); $('.oldskuinfo').hide(); } else if (action=="viewsku"){ $('.userinfo').hide(); $('.prodinfo').show(); $('.skuinfo').show(); $('.oldskuinfo').hide(); } else if (action=="reassign"){ $('.userinfo').show(); $('.prodinfo').show(); $('.skuinfo').show(); $('.oldskuinfo').show(); } else { $('.userinfo').show(); $('.prodinfo').show(); $('.skuinfo').show(); $('.oldskuinfo').hide(); } if (action=="bulkassign" || action=="bulkdelete"){ $('#userlabel').html('Target Users (comma separated)'); $('#skulabel').html('SKU'); } else if (action=="assign" || action=="delete"){ $('#userlabel').html('Target User'); $('#skulabel').html('SKU'); } else if (action=="reassign"){ $('#skulabel').html('New SKU'); } } /** * Calls the listForProduct method of the API to retrieve all licenses * assigned for a given product. * @param {String} prodID The product for which to retrieve licenses. * @param {String} custID The domain name for which to retrieve licenses. */ function viewLicenses(custID, prodID) { var request = gapi.client.licensing.licenseAssignments.listForProduct({ 'productId': prodID, 'customerId': custID }); request.execute(function(resp) { console.log(resp); document.getElementById("response").innerHTML = "<h3>API Response</h3>"; if (resp.error){ document.getElementById("response").innerHTML += JSON.stringify(resp.error); } else if (resp.items){ document.getElementById("response").innerHTML += "<p><strong>Assigned Licenses:</strong></p><ul>"; for(var i=0;i < resp.items.length;i++) { txt = document.createTextNode(resp.items[i].userId); document.getElementById("response").innerHTML += "<li>" + resp.items[i].userId + "</li>"; } document.getElementById("response").innerHTML += "</ul>"; } else { document.getElementById("response").innerHTML += "<em>No licenses found</em>"; } document.getElementById("response").innerHTML += "</ul>"; }); } /** * Calls the listForProductAndSku method of the API to retrieve all licenses * assigned for a given product and SKU combination. * @param {String} prodID The product for which to retrieve licenses. * @param {String} custID The domain name for which to retrieve licenses. * @param {String} skuID The SKU for which to retrieve licenses. */ function viewLicensesBySku(custID, prodID, skuID) { var request = gapi.client.licensing.licenseAssignments.listForProductAndSku({ 'productId': prodID, 'customerId': custID, 'skuId':skuID }); request.execute(function(resp) { console.log(resp); document.getElementById("response").innerHTML = "<h3>API Response</h3>"; if (resp.error){ document.getElementById("response").innerHTML += JSON.stringify(resp.error); } else if (resp.items){ document.getElementById("response").innerHTML += "<p><strong>Assigned Licenses:</strong></p><ul>"; for(var i=0;i < resp.items.length;i++) { txt = document.createTextNode(resp.items[i].userId); document.getElementById("response").innerHTML += "<li>" + resp.items[i].userId + "</li>"; } document.getElementById("response").innerHTML += "</ul>"; } else { document.getElementById("response").innerHTML += "<em>No licenses found</em>" } document.getElementById("response").innerHTML += "</ul>"; }); } /** * Calls the insert method of the API to assign a license to a user for * the specified product and SKU. * @param {String} prodID The product for which to assign a license. * @param {String} skuID The SKU for which to assign a license. * @param {String} userID The user to receive a license. */ function assignLicense(prodID, skuID, userID) { var request = gapi.client.licensing.licenseAssignments.insert({ 'productId': prodID, 'skuId': skuID, 'resource': {"userId": userID} }); request.execute(function(resp) { document.getElementById("response").innerHTML = "<h3>API Response</h3>" + JSON.stringify(resp); }); } /** * Calls the update method of the API to change a user's SKU given an * existing license for the same product. * @param {String} prodID The product for which to swap a license. * @param {String} oldSkuID The current SKU to swap out. * @param {String} newSkuID The new SKU to assign. * @param {String} userID The user to be updated. */ function reassign(prodID, oldSkuID, newSkuID, userID) { var request = gapi.client.licensing.licenseAssignments.update({ 'productId': prodID, 'skuId': oldSkuID, 'userId' : userID, 'resource': {"skuId": newSkuID} }); request.execute(function(resp) { document.getElementById("response").innerHTML = "<h3>API Response</h3>" + JSON.stringify(resp); }); } /** * Calls the delete method of the API to unassign a license from a user for * the specified product and SKU. * @param {String} prodID The product for which to unassign a license. * @param {String} skuID The SKU for which to unassign a license. * @param {String} userID The user to lose a license. */ function deleteLicense(prodID, skuID, userID) { var request = gapi.client.licensing.licenseAssignments.delete({ "userId": userID, 'productId': prodID, 'skuId': skuID }); request.execute(function(resp) { document.getElementById("response").innerHTML = "<h3>API Response</h3>" + JSON.stringify(resp); }); } /** * Calls the insert method of the API to assign licenses to multiple users for * the specified product and SKU in batch. * @param {String} prodID The product for which to assign a license. * @param {String} skuID The SKU for which to assign a license. * @param {Array.<string>} userIDs The users to receive licenses. */ function bulkAssign(prodID, skuID, userIDs) { var rpcBatch = gapi.client.newRpcBatch(); // Set up batch gapi.client.register('licensing.licenseAssignments.insert', 'v1'); var users = userIDs.split(','); // Split CSV field into individual users for (id in users) { // Go through each user var user = $.trim(users[id]); // Trim whitespace around username var batchRequest = gapi.client.licensing.licenseAssignments.insert({ 'resource': {"userId": user}, 'productId': prodID, 'skuId': skuID }); rpcBatch.add(batchRequest); } rpcBatch.execute(batchCallback); } /** * Calls the delete method of the API to unassign licenses from multiple users * for the specified product and SKU in batch. * @param {String} prodID The product for which to unassign a license. * @param {String} skuID The SKU for which to unassign a license. * @param {Array.<string>} userIDs The users to lose licenses. */ function bulkDelete(prodID, skuID, userIDs) { var rpcBatch = gapi.client.newRpcBatch(); // Set up batch gapi.client.register('licensing.licenseAssignments.delete', 'v1'); var users = userIDs.split(','); // Split CSV field into individual users for (id in users) { // Go through each user var user = $.trim(users[id]); // Trim whitespace around username var batchRequest = gapi.client.licensing.licenseAssignments.delete({ 'userId': user, 'productId': prodID, 'skuId': skuID }); rpcBatch.add(batchRequest); } rpcBatch.execute(batchCallback); } /** * Displays the results of a batch operation. * @param {Object} jsonResponse The response returned by License Manager API * in JSON format. * @param {Object} rawResponse Raw response returned by the License Manager API. */ function batchCallback(jsonResponse, rawResponse) { // Clear and prep the response panel document.getElementById("response").innerHTML = "<h3>API Response</h3>"; for (var id in jsonResponse) { console.log(jsonResponse[id]); // Logs each individual response in Console } // Log the raw string response, a JSON-string representing the id-response map document.getElementById("response").innerHTML += JSON.stringify(rawResponse); }
JavaScript
/// <reference path="jquery-ui-1.10.4.js" /> /// <reference path="modernizr-2.7.2.js" /> /// <reference path="jquery-2.1.1.js" /> /// <reference path="jquery.validate.js" /> /// <reference path="jquery.validate.unobtrusive.js" /> /// <reference path="knockout-2.2.0.debug.js" />
JavaScript
try { var pageTracker = _gat._getTracker("UA-18761191-1"); pageTracker._trackPageview(); } catch(err) {}
JavaScript
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
JavaScript
<script type="text/javascript"> if ($.cookie("username") != null && $.cookie("username") != "") { $("#j_username").val($.cookie("username")); $("#j_password").focus(); } else { $("#j_username").focus(); } function saveUsername(theForm) { $.cookie("username",theForm.j_username.value, { expires: 30, path: "<c:url value="/"/>"}); } function validateForm(form) { var valid = validateRequired(form); if (valid == false) { $(".form-group").addClass('error'); } return valid; } function passwordHint() { if ($("#j_username").val().length == 0) { alert("<fmt:message key="errors.required"><fmt:param><fmt:message key="label.username"/></fmt:param></fmt:message>"); $("#j_username").focus(); } else { location.href="<c:url value="/passwordHint"/>?username=" + $("#j_username").val(); } } function requestRecoveryToken() { if ($("#j_username").val().length == 0) { alert("<fmt:message key="errors.required"><fmt:param><fmt:message key="label.username"/></fmt:param></fmt:message>"); $("#j_username").focus(); } else { location.href="<c:url value="/requestRecoveryToken"/>?username=" + $("#j_username").val(); } } function required () { this.aa = new Array("j_username", "<fmt:message key="errors.required"><fmt:param><fmt:message key="label.username"/></fmt:param></fmt:message>", new Function ("varName", " return this[varName];")); this.ab = new Array("j_password", "<fmt:message key="errors.required"><fmt:param><fmt:message key="label.password"/></fmt:param></fmt:message>", new Function ("varName", " return this[varName];")); } </script>
JavaScript
// This function is used by the login screen to validate user/pass // are entered. function validateRequired(form) { var bValid = true; var focusField = null; var i = 0; var fields = new Array(); oRequired = new required(); for (x in oRequired) { if ((form[oRequired[x][0]].type == 'text' || form[oRequired[x][0]].type == 'textarea' || form[oRequired[x][0]].type == 'select-one' || form[oRequired[x][0]].type == 'radio' || form[oRequired[x][0]].type == 'password') && form[oRequired[x][0]].value == '') { if (i == 0) focusField = form[oRequired[x][0]]; fields[i++] = oRequired[x][1]; bValid = false; } } if (fields.length > 0) { focusField.focus(); alert(fields.join('\n')); } return bValid; } // This function is a generic function to create form elements function createFormElement(element, type, name, id, value, parent) { var e = document.createElement(element); e.setAttribute("name", name); e.setAttribute("type", type); e.setAttribute("id", id); e.setAttribute("value", value); parent.appendChild(e); } function confirmDelete(obj) { var msg = "Are you sure you want to delete this " + obj + "?"; ans = confirm(msg); return ans; } // 18n version of confirmDelete. Message must be already built. function confirmMessage(obj) { var msg = "" + obj; ans = confirm(msg); return ans; }
JavaScript
var MiniProfiler = (function ($) { var options, container; var hasLocalStorage = function () { try { return 'localStorage' in window && window['localStorage'] !== null; } catch (e) { return false; } }; var getVersionedKey = function (keyPrefix) { return keyPrefix + '-' + options.version; } var save = function (keyPrefix, value) { if (!hasLocalStorage()) { return; } // clear old keys with this prefix, if any for (var i = 0; i < localStorage.length; i++) { if ((localStorage.key(i) || '').indexOf(keyPrefix) > -1) { localStorage.removeItem(localStorage.key(i)); } } // save under this version localStorage[getVersionedKey(keyPrefix)] = value; }; var load = function (keyPrefix) { if (!hasLocalStorage()) { return null; } return localStorage[getVersionedKey(keyPrefix)]; }; var fetchTemplates = function (success) { var key = 'mini-profiler-templates', cached = load(key); if (cached) { $('body').append(cached); success(); } else { $.get(options.path + 'mini-profiler-includes.tmpl?v=' + options.version, function (data) { if (data) { save(key, data); $('body').append(data); success(); } }); } }; var fetchResults = function (id) { $.getJSON(options.path + 'mini-profiler-results?id=' + id + '&popup=1', function (json) { buttonShow(json); }); }; var renderTemplate = function (json) { return $('#profilerTemplate').tmpl(json); }; var buttonShow = function (json) { var result = renderTemplate(json).appendTo(container), button = result.find('.profiler-button'), popup = result.find('.profiler-popup'); // button will appear in corner with the total profiling duration - click to show details button.click(function () { buttonClick(button, popup); }); // small duration steps and the column with aggregate durations are hidden by default; allow toggling toggleHidden(popup); // lightbox in the queries popup.find('.queries-show').click(function () { queriesShow($(this), result); }); // limit count if (container.find('.profiler-result').length > options.maxTracesToShow) container.find('.profiler-result').first().remove(); button.show(); }; var toggleHidden = function (popup) { var trivial = popup.find('.toggle-trivial'); var childrenTime = popup.find('.toggle-duration-with-children'); childrenTime.add(trivial).click(function () { var link = $(this), klass = link.attr('class').substr('toggle-'.length), isHidden = link.text().indexOf('show') > -1; popup.find('.' + klass).toggle(isHidden); link.text(link.text().replace(isHidden ? 'show' : 'hide', isHidden ? 'hide' : 'show')); popupPreventHorizontalScroll(popup); }); // if option is set or all our timings are trivial, go ahead and show them if (options.showTrivial || trivial.data('show-on-load')) { trivial.click(); } // if option is set, go ahead and show time with children if (options.showChildrenTime) { childrenTime.click(); } }; var buttonClick = function (button, popup) { // we're toggling this button/popup if (popup.is(':visible')) { popupHide(button, popup); } else { var visiblePopups = container.find('.profiler-popup:visible'), theirButtons = visiblePopups.siblings('.profiler-button'); // hide any other popups popupHide(theirButtons, visiblePopups); // before showing the one we clicked popupShow(button, popup); } }; var popupShow = function (button, popup) { button.addClass('profiler-button-active'); popupSetDimensions(button, popup); popup.show(); popupPreventHorizontalScroll(popup); }; var popupSetDimensions = function (button, popup) { var top = button.position().top - 1, // position next to the button we clicked windowHeight = $(window).height(), maxHeight = windowHeight - top - 40; // make sure the popup doesn't extend below the fold popup .css({ 'top': top, 'max-height': maxHeight }) .css(options.renderPosition, button.outerWidth() - 3); // move left or right, based on config }; var popupPreventHorizontalScroll = function (popup) { var childrenHeight = 0; popup.children().each(function () { childrenHeight += $(this).height(); }); popup.css({ 'padding-right': childrenHeight > popup.height() ? 40 : 10 }); } var popupHide = function (button, popup) { button.removeClass('profiler-button-active'); popup.hide(); }; var queriesShow = function (link, result) { var px = 30, win = $(window), width = win.width() - 2 * px, height = win.height() - 2 * px, queries = result.find('.profiler-queries'); // opaque background $('<div class="profiler-queries-bg"/>').appendTo('body').css({ 'height': $(document).height() }).show(); // center the queries and ensure long content is scrolled queries.css({ 'top': px, 'max-height': height, 'width': width }).css(options.renderPosition, px) .find('table').css({ 'width': width }); // have to show everything before we can get a position for the first query queries.show(); queriesScrollIntoView(link, queries, queries); // syntax highlighting prettyPrint(); }; var queriesScrollIntoView = function (link, queries, whatToScroll) { var id = link.closest('tr').attr('data-timing-id'), cells = queries.find('tr[data-timing-id="' + id + '"] td'); // ensure they're in view whatToScroll.scrollTop(whatToScroll.scrollTop() + cells.first().position().top - 100); // highlight and then fade back to original bg color cells.each(function () { var td = $(this), originalColor = td.css('background-color'); td.css('background-color', '#FFFFBB').animate({ backgroundColor: originalColor }, 2000); }); }; var bindDocumentEvents = function () { $(document).bind('click keyup', function (e) { var popup = $('.profiler-popup:visible'); if (!popup.length) { return; } var button = popup.siblings('.profiler-button'), queries = popup.closest('.profiler-result').find('.profiler-queries'), bg = $('.profiler-queries-bg'), isEscPress = e.type == 'keyup' && e.which == 27, hidePopup = false, hideQueries = false; if (bg.is(':visible')) { // ctrl-c will be hit on html target - let's not hide. hideQueries = isEscPress || (e.type == 'click' && !$.contains(queries[0], e.target) && !$.contains(popup[0], e.target)); } else if (popup.is(':visible')) { hidePopup = isEscPress || (e.type == 'click' && !$.contains(popup[0], e.target) && !$.contains(button[0], e.target) && button[0] != e.target); } if (hideQueries) { bg.remove(); queries.hide(); } if (hidePopup) { popupHide(button, popup); } }); }; var initFullView = function () { // first, get jquery tmpl, then render and bind handlers fetchTemplates(function () { // profiler will be defined in the full page's head renderTemplate(profiler).appendTo(container); var popup = $('.profiler-popup'); toggleHidden(popup); prettyPrint(); // since queries are already shown, just highlight and scroll when clicking a "1 sql" link popup.find('.queries-show').click(function () { queriesScrollIntoView($(this), $('.profiler-queries'), $(document)); }); }); }; var initPopupView = function () { // all fetched profilings will go in here container = $('<div class="profiler-results"/>').appendTo('body'); // MiniProfiler.RenderIncludes() sets which corner to render in - default is upper left container.addClass(options.renderPosition); // we'll render results json via a jquery.tmpl - after we get the templates, we'll fetch the initial json to populate it fetchTemplates(function () { // get master page profiler results fetchResults(options.id); }); // fetch profile results for any ajax calls $(document).ajaxComplete(function (e, xhr, settings) { if (xhr) { var id = xhr.getResponseHeader('X-MiniProfiler-Id'); if (id) { fetchResults(id); } } }); // currently, saving to long-term storage is done when a full results page is displayed; this causes issues in web-farms when a // dev right-clicks a share link and copies... the results aren't pushed to a place that all other servers can reach $('.share-profiler-results').live('mousedown', function(e) { // so do a fetch when "share" is right-clicked if (e.which == 3) { $.get($(this).attr('href')); } }); // some elements want to be hidden on certain doc events bindDocumentEvents(); }; return { init: function (opt) { options = opt || {}; // when rendering a shared, full page, this div will exist container = $('.profiler-result-full'); if (container.length) { initFullView(); } else { initPopupView(); } }, renderDate: function (jsonDate) { // JavaScriptSerializer sends dates as /Date(1308024322065)/ if (jsonDate) { return new Date(parseInt(jsonDate.replace("/Date(", "").replace(")/", ""), 10)).toUTCString(); } }, renderIndent: function (depth) { var result = ''; for (var i = 0; i < depth; i++) { result += '&nbsp;'; } return result; }, renderExecuteType: function (typeId) { // see MvcMiniProfiler.ExecuteType enum switch (typeId) { case 0: return 'None'; case 1: return 'NonQuery'; case 2: return 'Scalar'; case 3: return 'Reader'; } }, shareUrl: function (id) { return options.path + 'mini-profiler-results?id=' + id; }, getSqlTimings: function (root) { var result = [], addToResults = function (timing) { if (timing.SqlTimings) { for (var i = 0, sqlTiming; i < timing.SqlTimings.length; i++) { sqlTiming = timing.SqlTimings[i]; // HACK: add info about the parent Timing to each SqlTiming so UI can render sqlTiming.ParentTimingName = timing.Name; result.push(sqlTiming); } } if (timing.Children) { for (var i = 0; i < timing.Children.length; i++) { addToResults(timing.Children[i]); } } }; // start adding at the root and recurse down addToResults(root); // sort results by time result.sort(function (a, b) { return a.StartMilliseconds - b.StartMilliseconds; }); return result; }, formatDuration: function (duration) { return (duration || 0).toFixed(1); } }; })(jQuery); // prettify.js // http://code.google.com/p/google-code-prettify/ window.PR_SHOULD_USE_CONTINUATION=true;window.PR_TAB_WIDTH=8;window.PR_normalizedHtml=window.PR=window.prettyPrintOne=window.prettyPrint=void 0;window._pr_isIE6=function(){var y=navigator&&navigator.userAgent&&navigator.userAgent.match(/\bMSIE ([678])\./);y=y?+y[1]:false;window._pr_isIE6=function(){return y};return y}; (function(){function y(b){return b.replace(L,"&amp;").replace(M,"&lt;").replace(N,"&gt;")}function H(b,f,i){switch(b.nodeType){case 1:var o=b.tagName.toLowerCase();f.push("<",o);var l=b.attributes,n=l.length;if(n){if(i){for(var r=[],j=n;--j>=0;)r[j]=l[j];r.sort(function(q,m){return q.name<m.name?-1:q.name===m.name?0:1});l=r}for(j=0;j<n;++j){r=l[j];r.specified&&f.push(" ",r.name.toLowerCase(),'="',r.value.replace(L,"&amp;").replace(M,"&lt;").replace(N,"&gt;").replace(X,"&quot;"),'"')}}f.push(">"); for(l=b.firstChild;l;l=l.nextSibling)H(l,f,i);if(b.firstChild||!/^(?:br|link|img)$/.test(o))f.push("</",o,">");break;case 3:case 4:f.push(y(b.nodeValue));break}}function O(b){function f(c){if(c.charAt(0)!=="\\")return c.charCodeAt(0);switch(c.charAt(1)){case "b":return 8;case "t":return 9;case "n":return 10;case "v":return 11;case "f":return 12;case "r":return 13;case "u":case "x":return parseInt(c.substring(2),16)||c.charCodeAt(1);case "0":case "1":case "2":case "3":case "4":case "5":case "6":case "7":return parseInt(c.substring(1), 8);default:return c.charCodeAt(1)}}function i(c){if(c<32)return(c<16?"\\x0":"\\x")+c.toString(16);c=String.fromCharCode(c);if(c==="\\"||c==="-"||c==="["||c==="]")c="\\"+c;return c}function o(c){var d=c.substring(1,c.length-1).match(RegExp("\\\\u[0-9A-Fa-f]{4}|\\\\x[0-9A-Fa-f]{2}|\\\\[0-3][0-7]{0,2}|\\\\[0-7]{1,2}|\\\\[\\s\\S]|-|[^-\\\\]","g"));c=[];for(var a=[],k=d[0]==="^",e=k?1:0,h=d.length;e<h;++e){var g=d[e];switch(g){case "\\B":case "\\b":case "\\D":case "\\d":case "\\S":case "\\s":case "\\W":case "\\w":c.push(g); continue}g=f(g);var s;if(e+2<h&&"-"===d[e+1]){s=f(d[e+2]);e+=2}else s=g;a.push([g,s]);if(!(s<65||g>122)){s<65||g>90||a.push([Math.max(65,g)|32,Math.min(s,90)|32]);s<97||g>122||a.push([Math.max(97,g)&-33,Math.min(s,122)&-33])}}a.sort(function(v,w){return v[0]-w[0]||w[1]-v[1]});d=[];g=[NaN,NaN];for(e=0;e<a.length;++e){h=a[e];if(h[0]<=g[1]+1)g[1]=Math.max(g[1],h[1]);else d.push(g=h)}a=["["];k&&a.push("^");a.push.apply(a,c);for(e=0;e<d.length;++e){h=d[e];a.push(i(h[0]));if(h[1]>h[0]){h[1]+1>h[0]&&a.push("-"); a.push(i(h[1]))}}a.push("]");return a.join("")}function l(c){for(var d=c.source.match(RegExp("(?:\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]|\\\\u[A-Fa-f0-9]{4}|\\\\x[A-Fa-f0-9]{2}|\\\\[0-9]+|\\\\[^ux0-9]|\\(\\?[:!=]|[\\(\\)\\^]|[^\\x5B\\x5C\\(\\)\\^]+)","g")),a=d.length,k=[],e=0,h=0;e<a;++e){var g=d[e];if(g==="(")++h;else if("\\"===g.charAt(0))if((g=+g.substring(1))&&g<=h)k[g]=-1}for(e=1;e<k.length;++e)if(-1===k[e])k[e]=++n;for(h=e=0;e<a;++e){g=d[e];if(g==="("){++h;if(k[h]===undefined)d[e]="(?:"}else if("\\"=== g.charAt(0))if((g=+g.substring(1))&&g<=h)d[e]="\\"+k[h]}for(h=e=0;e<a;++e)if("^"===d[e]&&"^"!==d[e+1])d[e]="";if(c.ignoreCase&&r)for(e=0;e<a;++e){g=d[e];c=g.charAt(0);if(g.length>=2&&c==="[")d[e]=o(g);else if(c!=="\\")d[e]=g.replace(/[a-zA-Z]/g,function(s){s=s.charCodeAt(0);return"["+String.fromCharCode(s&-33,s|32)+"]"})}return d.join("")}for(var n=0,r=false,j=false,q=0,m=b.length;q<m;++q){var t=b[q];if(t.ignoreCase)j=true;else if(/[a-z]/i.test(t.source.replace(/\\u[0-9a-f]{4}|\\x[0-9a-f]{2}|\\[^ux]/gi, ""))){r=true;j=false;break}}var p=[];q=0;for(m=b.length;q<m;++q){t=b[q];if(t.global||t.multiline)throw Error(""+t);p.push("(?:"+l(t)+")")}return RegExp(p.join("|"),j?"gi":"g")}function Y(b){var f=0;return function(i){for(var o=null,l=0,n=0,r=i.length;n<r;++n)switch(i.charAt(n)){case "\t":o||(o=[]);o.push(i.substring(l,n));l=b-f%b;for(f+=l;l>=0;l-=16)o.push(" ".substring(0,l));l=n+1;break;case "\n":f=0;break;default:++f}if(!o)return i;o.push(i.substring(l));return o.join("")}}function I(b, f,i,o){if(f){b={source:f,c:b};i(b);o.push.apply(o,b.d)}}function B(b,f){var i={},o;(function(){for(var r=b.concat(f),j=[],q={},m=0,t=r.length;m<t;++m){var p=r[m],c=p[3];if(c)for(var d=c.length;--d>=0;)i[c.charAt(d)]=p;p=p[1];c=""+p;if(!q.hasOwnProperty(c)){j.push(p);q[c]=null}}j.push(/[\0-\uffff]/);o=O(j)})();var l=f.length;function n(r){for(var j=r.c,q=[j,z],m=0,t=r.source.match(o)||[],p={},c=0,d=t.length;c<d;++c){var a=t[c],k=p[a],e=void 0,h;if(typeof k==="string")h=false;else{var g=i[a.charAt(0)]; if(g){e=a.match(g[1]);k=g[0]}else{for(h=0;h<l;++h){g=f[h];if(e=a.match(g[1])){k=g[0];break}}e||(k=z)}if((h=k.length>=5&&"lang-"===k.substring(0,5))&&!(e&&typeof e[1]==="string")){h=false;k=P}h||(p[a]=k)}g=m;m+=a.length;if(h){h=e[1];var s=a.indexOf(h),v=s+h.length;if(e[2]){v=a.length-e[2].length;s=v-h.length}k=k.substring(5);I(j+g,a.substring(0,s),n,q);I(j+g+s,h,Q(k,h),q);I(j+g+v,a.substring(v),n,q)}else q.push(j+g,k)}r.d=q}return n}function x(b){var f=[],i=[];if(b.tripleQuotedStrings)f.push([A,/^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/, null,"'\""]);else b.multiLineStrings?f.push([A,/^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,null,"'\"`"]):f.push([A,/^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,null,"\"'"]);b.verbatimStrings&&i.push([A,/^@\"(?:[^\"]|\"\")*(?:\"|$)/,null]);if(b.hashComments)if(b.cStyleComments){f.push([C,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\r\n]*)/,null,"#"]);i.push([A,/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/, null])}else f.push([C,/^#[^\r\n]*/,null,"#"]);if(b.cStyleComments){i.push([C,/^\/\/[^\r\n]*/,null]);i.push([C,/^\/\*[\s\S]*?(?:\*\/|$)/,null])}b.regexLiterals&&i.push(["lang-regex",RegExp("^"+Z+"(/(?=[^/*])(?:[^/\\x5B\\x5C]|\\x5C[\\s\\S]|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+/)")]);b=b.keywords.replace(/^\s+|\s+$/g,"");b.length&&i.push([R,RegExp("^(?:"+b.replace(/\s+/g,"|")+")\\b"),null]);f.push([z,/^\s+/,null," \r\n\t\u00a0"]);i.push([J,/^@[a-z_$][a-z_$@0-9]*/i,null],[S,/^@?[A-Z]+[a-z][A-Za-z_$@0-9]*/, null],[z,/^[a-z_$][a-z_$@0-9]*/i,null],[J,/^(?:0x[a-f0-9]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+\-]?\d+)?)[a-z]*/i,null,"0123456789"],[E,/^.[^\s\w\.$@\'\"\`\/\#]*/,null]);return B(f,i)}function $(b){function f(D){if(D>r){if(j&&j!==q){n.push("</span>");j=null}if(!j&&q){j=q;n.push('<span class="',j,'">')}var T=y(p(i.substring(r,D))).replace(e?d:c,"$1&#160;");e=k.test(T);n.push(T.replace(a,s));r=D}}var i=b.source,o=b.g,l=b.d,n=[],r=0,j=null,q=null,m=0,t=0,p=Y(window.PR_TAB_WIDTH),c=/([\r\n ]) /g, d=/(^| ) /gm,a=/\r\n?|\n/g,k=/[ \r\n]$/,e=true,h=window._pr_isIE6();h=h?b.b.tagName==="PRE"?h===6?"&#160;\r\n":h===7?"&#160;<br>\r":"&#160;\r":"&#160;<br />":"<br />";var g=b.b.className.match(/\blinenums\b(?::(\d+))?/),s;if(g){for(var v=[],w=0;w<10;++w)v[w]=h+'</li><li class="L'+w+'">';var F=g[1]&&g[1].length?g[1]-1:0;n.push('<ol class="linenums"><li class="L',F%10,'"');F&&n.push(' value="',F+1,'"');n.push(">");s=function(){var D=v[++F%10];return j?"</span>"+D+'<span class="'+j+'">':D}}else s=h; for(;;)if(m<o.length?t<l.length?o[m]<=l[t]:true:false){f(o[m]);if(j){n.push("</span>");j=null}n.push(o[m+1]);m+=2}else if(t<l.length){f(l[t]);q=l[t+1];t+=2}else break;f(i.length);j&&n.push("</span>");g&&n.push("</li></ol>");b.a=n.join("")}function u(b,f){for(var i=f.length;--i>=0;){var o=f[i];if(G.hasOwnProperty(o))"console"in window&&console.warn("cannot override language handler %s",o);else G[o]=b}}function Q(b,f){b&&G.hasOwnProperty(b)||(b=/^\s*</.test(f)?"default-markup":"default-code");return G[b]} function U(b){var f=b.f,i=b.e;b.a=f;try{var o,l=f.match(aa);f=[];var n=0,r=[];if(l)for(var j=0,q=l.length;j<q;++j){var m=l[j];if(m.length>1&&m.charAt(0)==="<"){if(!ba.test(m))if(ca.test(m)){f.push(m.substring(9,m.length-3));n+=m.length-12}else if(da.test(m)){f.push("\n");++n}else if(m.indexOf(V)>=0&&m.replace(/\s(\w+)\s*=\s*(?:\"([^\"]*)\"|'([^\']*)'|(\S+))/g,' $1="$2$3$4"').match(/[cC][lL][aA][sS][sS]=\"[^\"]*\bnocode\b/)){var t=m.match(W)[2],p=1,c;c=j+1;a:for(;c<q;++c){var d=l[c].match(W);if(d&& d[2]===t)if(d[1]==="/"){if(--p===0)break a}else++p}if(c<q){r.push(n,l.slice(j,c+1).join(""));j=c}else r.push(n,m)}else r.push(n,m)}else{var a;p=m;var k=p.indexOf("&");if(k<0)a=p;else{for(--k;(k=p.indexOf("&#",k+1))>=0;){var e=p.indexOf(";",k);if(e>=0){var h=p.substring(k+3,e),g=10;if(h&&h.charAt(0)==="x"){h=h.substring(1);g=16}var s=parseInt(h,g);isNaN(s)||(p=p.substring(0,k)+String.fromCharCode(s)+p.substring(e+1))}}a=p.replace(ea,"<").replace(fa,">").replace(ga,"'").replace(ha,'"').replace(ia," ").replace(ja, "&")}f.push(a);n+=a.length}}o={source:f.join(""),h:r};var v=o.source;b.source=v;b.c=0;b.g=o.h;Q(i,v)(b);$(b)}catch(w){if("console"in window)console.log(w&&w.stack?w.stack:w)}}var A="str",R="kwd",C="com",S="typ",J="lit",E="pun",z="pln",P="src",V="nocode",Z=function(){for(var b=["!","!=","!==","#","%","%=","&","&&","&&=","&=","(","*","*=","+=",",","-=","->","/","/=",":","::",";","<","<<","<<=","<=","=","==","===",">",">=",">>",">>=",">>>",">>>=","?","@","[","^","^=","^^","^^=","{","|","|=","||","||=", "~","break","case","continue","delete","do","else","finally","instanceof","return","throw","try","typeof"],f="(?:^^|[+-]",i=0;i<b.length;++i)f+="|"+b[i].replace(/([^=<>:&a-z])/g,"\\$1");f+=")\\s*";return f}(),L=/&/g,M=/</g,N=/>/g,X=/\"/g,ea=/&lt;/g,fa=/&gt;/g,ga=/&apos;/g,ha=/&quot;/g,ja=/&amp;/g,ia=/&nbsp;/g,ka=/[\r\n]/g,K=null,aa=RegExp("[^<]+|<!--[\\s\\S]*?--\>|<!\\[CDATA\\[[\\s\\S]*?\\]\\]>|</?[a-zA-Z](?:[^>\"']|'[^']*'|\"[^\"]*\")*>|<","g"),ba=/^<\!--/,ca=/^<!\[CDATA\[/,da=/^<br\b/i,W=/^<(\/?)([a-zA-Z][a-zA-Z0-9]*)/, la=x({keywords:"break continue do else for if return while auto case char const default double enum extern float goto int long register short signed sizeof static struct switch typedef union unsigned void volatile catch class delete false import new operator private protected public this throw true try typeof alignof align_union asm axiom bool concept concept_map const_cast constexpr decltype dynamic_cast explicit export friend inline late_check mutable namespace nullptr reinterpret_cast static_assert static_cast template typeid typename using virtual wchar_t where break continue do else for if return while auto case char const default double enum extern float goto int long register short signed sizeof static struct switch typedef union unsigned void volatile catch class delete false import new operator private protected public this throw true try typeof abstract boolean byte extends final finally implements import instanceof null native package strictfp super synchronized throws transient as base by checked decimal delegate descending event fixed foreach from group implicit in interface internal into is lock object out override orderby params partial readonly ref sbyte sealed stackalloc string select uint ulong unchecked unsafe ushort var break continue do else for if return while auto case char const default double enum extern float goto int long register short signed sizeof static struct switch typedef union unsigned void volatile catch class delete false import new operator private protected public this throw true try typeof debugger eval export function get null set undefined var with Infinity NaN caller delete die do dump elsif eval exit foreach for goto if import last local my next no our print package redo require sub undef unless until use wantarray while BEGIN END break continue do else for if return while and as assert class def del elif except exec finally from global import in is lambda nonlocal not or pass print raise try with yield False True None break continue do else for if return while alias and begin case class def defined elsif end ensure false in module next nil not or redo rescue retry self super then true undef unless until when yield BEGIN END break continue do else for if return while case done elif esac eval fi function in local set then until ", hashComments:true,cStyleComments:true,multiLineStrings:true,regexLiterals:true}),G={};u(la,["default-code"]);u(B([],[[z,/^[^<?]+/],["dec",/^<!\w[^>]*(?:>|$)/],[C,/^<\!--[\s\S]*?(?:-\->|$)/],["lang-",/^<\?([\s\S]+?)(?:\?>|$)/],["lang-",/^<%([\s\S]+?)(?:%>|$)/],[E,/^(?:<[%?]|[%?]>)/],["lang-",/^<xmp\b[^>]*>([\s\S]+?)<\/xmp\b[^>]*>/i],["lang-js",/^<script\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-css",/^<style\b[^>]*>([\s\S]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]),["default-markup", "htm","html","mxml","xhtml","xml","xsl"]);u(B([[z,/^[\s]+/,null," \t\r\n"],["atv",/^(?:\"[^\"]*\"?|\'[^\']*\'?)/,null,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/],[E,/^[=<>\/]+/],["lang-js",/^on\w+\s*=\s*\"([^\"]+)\"/i],["lang-js",/^on\w+\s*=\s*\'([^\']+)\'/i],["lang-js",/^on\w+\s*=\s*([^\"\'>\s]+)/i],["lang-css",/^style\s*=\s*\"([^\"]+)\"/i],["lang-css",/^style\s*=\s*\'([^\']+)\'/i], ["lang-css",/^style\s*=\s*([^\"\'>\s]+)/i]]),["in.tag"]);u(B([],[["atv",/^[\s\S]+/]]),["uq.val"]);u(x({keywords:"break continue do else for if return while auto case char const default double enum extern float goto int long register short signed sizeof static struct switch typedef union unsigned void volatile catch class delete false import new operator private protected public this throw true try typeof alignof align_union asm axiom bool concept concept_map const_cast constexpr decltype dynamic_cast explicit export friend inline late_check mutable namespace nullptr reinterpret_cast static_assert static_cast template typeid typename using virtual wchar_t where ", hashComments:true,cStyleComments:true}),["c","cc","cpp","cxx","cyc","m"]);u(x({keywords:"null true false"}),["json"]);u(x({keywords:"break continue do else for if return while auto case char const default double enum extern float goto int long register short signed sizeof static struct switch typedef union unsigned void volatile catch class delete false import new operator private protected public this throw true try typeof abstract boolean byte extends final finally implements import instanceof null native package strictfp super synchronized throws transient as base by checked decimal delegate descending event fixed foreach from group implicit in interface internal into is lock object out override orderby params partial readonly ref sbyte sealed stackalloc string select uint ulong unchecked unsafe ushort var ", hashComments:true,cStyleComments:true,verbatimStrings:true}),["cs"]);u(x({keywords:"break continue do else for if return while auto case char const default double enum extern float goto int long register short signed sizeof static struct switch typedef union unsigned void volatile catch class delete false import new operator private protected public this throw true try typeof abstract boolean byte extends final finally implements import instanceof null native package strictfp super synchronized throws transient ", cStyleComments:true}),["java"]);u(x({keywords:"break continue do else for if return while case done elif esac eval fi function in local set then until ",hashComments:true,multiLineStrings:true}),["bsh","csh","sh"]);u(x({keywords:"break continue do else for if return while and as assert class def del elif except exec finally from global import in is lambda nonlocal not or pass print raise try with yield False True None ",hashComments:true,multiLineStrings:true,tripleQuotedStrings:true}),["cv","py"]); u(x({keywords:"caller delete die do dump elsif eval exit foreach for goto if import last local my next no our print package redo require sub undef unless until use wantarray while BEGIN END ",hashComments:true,multiLineStrings:true,regexLiterals:true}),["perl","pl","pm"]);u(x({keywords:"break continue do else for if return while alias and begin case class def defined elsif end ensure false in module next nil not or redo rescue retry self super then true undef unless until when yield BEGIN END ",hashComments:true, multiLineStrings:true,regexLiterals:true}),["rb"]);u(x({keywords:"break continue do else for if return while auto case char const default double enum extern float goto int long register short signed sizeof static struct switch typedef union unsigned void volatile catch class delete false import new operator private protected public this throw true try typeof debugger eval export function get null set undefined var with Infinity NaN ",cStyleComments:true,regexLiterals:true}),["js"]);u(B([],[[A,/^[\s\S]+/]]), ["regex"]);window.PR_normalizedHtml=H;window.prettyPrintOne=function(b,f){var i={f:b,e:f};U(i);return i.a};window.prettyPrint=function(b){function f(){for(var t=window.PR_SHOULD_USE_CONTINUATION?j.now()+250:Infinity;q<o.length&&j.now()<t;q++){var p=o[q];if(p.className&&p.className.indexOf("prettyprint")>=0){var c=p.className.match(/\blang-(\w+)\b/);if(c)c=c[1];for(var d=false,a=p.parentNode;a;a=a.parentNode)if((a.tagName==="pre"||a.tagName==="code"||a.tagName==="xmp")&&a.className&&a.className.indexOf("prettyprint")>= 0){d=true;break}if(!d){a=p;if(null===K){d=document.createElement("PRE");d.appendChild(document.createTextNode('<!DOCTYPE foo PUBLIC "foo bar">\n<foo />'));K=!/</.test(d.innerHTML)}if(K){d=a.innerHTML;if("XMP"===a.tagName)d=y(d);else{a=a;if("PRE"===a.tagName)a=true;else if(ka.test(d)){var k="";if(a.currentStyle)k=a.currentStyle.whiteSpace;else if(window.getComputedStyle)k=window.getComputedStyle(a,null).whiteSpace;a=!k||k==="pre"}else a=true;a||(d=d.replace(/(<br\s*\/?>)[\r\n]+/g,"$1").replace(/(?:[\r\n]+[ \t]*)+/g, " "))}d=d}else{d=[];for(a=a.firstChild;a;a=a.nextSibling)H(a,d);d=d.join("")}d=d.replace(/(?:\r\n?|\n)$/,"");m={f:d,e:c,b:p};U(m);if(p=m.a){c=m.b;if("XMP"===c.tagName){d=document.createElement("PRE");for(a=0;a<c.attributes.length;++a){k=c.attributes[a];if(k.specified)if(k.name.toLowerCase()==="class")d.className=k.value;else d.setAttribute(k.name,k.value)}d.innerHTML=p;c.parentNode.replaceChild(d,c)}else c.innerHTML=p}}}}if(q<o.length)setTimeout(f,250);else b&&b()}for(var i=[document.getElementsByTagName("pre"), document.getElementsByTagName("code"),document.getElementsByTagName("xmp")],o=[],l=0;l<i.length;++l)for(var n=0,r=i[l].length;n<r;++n)o.push(i[l][n]);i=null;var j=Date;j.now||(j={now:function(){return(new Date).getTime()}});var q=0,m;f()};window.PR={combinePrefixPatterns:O,createSimpleLexer:B,registerLangHandler:u,sourceDecorator:x,PR_ATTRIB_NAME:"atn",PR_ATTRIB_VALUE:"atv",PR_COMMENT:C,PR_DECLARATION:"dec",PR_KEYWORD:R,PR_LITERAL:J,PR_NOCODE:V,PR_PLAIN:z,PR_PUNCTUATION:E,PR_SOURCE:P,PR_STRING:A, PR_TAG:"tag",PR_TYPE:S}})() ; // lang-sql.js // http://code.google.com/p/google-code-prettify/ PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\r \xA0]+/,null,"\t\n\r \u00a0"],["str",/^(?:"(?:[^\"\\]|\\.)*"|'(?:[^\'\\]|\\.)*')/,null,"\"'"]],[["com",/^(?:--[^\r\n]*|\/\*[\s\S]*?(?:\*\/|$))/],["kwd",/^(?:ADD|ALL|ALTER|AND|ANY|AS|ASC|AUTHORIZATION|BACKUP|BEGIN|BETWEEN|BREAK|BROWSE|BULK|BY|CASCADE|CASE|CHECK|CHECKPOINT|CLOSE|CLUSTERED|COALESCE|COLLATE|COLUMN|COMMIT|COMPUTE|CONSTRAINT|CONTAINS|CONTAINSTABLE|CONTINUE|CONVERT|CREATE|CROSS|CURRENT|CURRENT_DATE|CURRENT_TIME|CURRENT_TIMESTAMP|CURRENT_USER|CURSOR|DATABASE|DBCC|DEALLOCATE|DECLARE|DEFAULT|DELETE|DENY|DESC|DISK|DISTINCT|DISTRIBUTED|DOUBLE|DROP|DUMMY|DUMP|ELSE|END|ERRLVL|ESCAPE|EXCEPT|EXEC|EXECUTE|EXISTS|EXIT|FETCH|FILE|FILLFACTOR|FOR|FOREIGN|FREETEXT|FREETEXTTABLE|FROM|FULL|FUNCTION|GOTO|GRANT|GROUP|HAVING|HOLDLOCK|IDENTITY|IDENTITYCOL|IDENTITY_INSERT|IF|IN|INDEX|INNER|INSERT|INTERSECT|INTO|IS|JOIN|KEY|KILL|LEFT|LIKE|LINENO|LOAD|NATIONAL|NOCHECK|NONCLUSTERED|NOT|NULL|NULLIF|OF|OFF|OFFSETS|ON|OPEN|OPENDATASOURCE|OPENQUERY|OPENROWSET|OPENXML|OPTION|OR|ORDER|OUTER|OVER|PERCENT|PLAN|PRECISION|PRIMARY|PRINT|PROC|PROCEDURE|PUBLIC|RAISERROR|READ|READTEXT|RECONFIGURE|REFERENCES|REPLICATION|RESTORE|RESTRICT|RETURN|REVOKE|RIGHT|ROLLBACK|ROWCOUNT|ROWGUIDCOL|RULE|SAVE|SCHEMA|SELECT|SESSION_USER|SET|SETUSER|SHUTDOWN|SOME|STATISTICS|SYSTEM_USER|TABLE|TEXTSIZE|THEN|TO|TOP|TRAN|TRANSACTION|TRIGGER|TRUNCATE|TSEQUAL|UNION|UNIQUE|UPDATE|UPDATETEXT|USE|USER|VALUES|VARYING|VIEW|WAITFOR|WHEN|WHERE|WHILE|WITH|WRITETEXT)(?=[^\w-]|$)/i, null],["lit",/^[+-]?(?:0x[\da-f]+|(?:(?:\.\d+|\d+(?:\.\d*)?)(?:e[+\-]?\d+)?))/i],["pln",/^[a-z_][\w-]*/i],["pun",/^[^\w\t\n\r \xA0\"\'][^\w\t\n\r \xA0+\-\"\']*/]]),["sql"]) ; /* * jQuery Color Animations * Copyright 2007 John Resig * Released under the MIT and GPL licenses. */ (function (jQuery) { // We override the animation for all of these color styles jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function (i, attr) { jQuery.fx.step[attr] = function (fx) { if (!fx.colorInit) { fx.start = getColor(fx.elem, attr); fx.end = getRGB(fx.end); fx.colorInit = true; } fx.elem.style[attr] = "rgb(" + [ Math.max(Math.min(parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0), Math.max(Math.min(parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0), Math.max(Math.min(parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)].join(",") + ")"; } }); // Color Conversion functions from highlightFade // By Blair Mitchelmore // http://jquery.offput.ca/highlightFade/ // Parse strings looking for color tuples [255,255,255] function getRGB(color) { var result; // Check if we're already dealing with an array of colors if (color && color.constructor == Array && color.length == 3) return color; // Look for rgb(num,num,num) if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color)) return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])]; // Look for rgb(num%,num%,num%) if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color)) return [parseFloat(result[1]) * 2.55, parseFloat(result[2]) * 2.55, parseFloat(result[3]) * 2.55]; // Look for #a0b1c2 if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color)) return [parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16)]; // Look for #fff if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color)) return [parseInt(result[1] + result[1], 16), parseInt(result[2] + result[2], 16), parseInt(result[3] + result[3], 16)]; // Look for rgba(0, 0, 0, 0) == transparent in Safari 3 if (result = /rgba\(0, 0, 0, 0\)/.exec(color)) return colors['transparent']; // Otherwise, we're most likely dealing with a named color return colors[jQuery.trim(color).toLowerCase()]; } function getColor(elem, attr) { var color; do { color = jQuery.curCSS(elem, attr); // Keep going until we find an element that has color, or we hit the body if (color != '' && color != 'transparent' || jQuery.nodeName(elem, "body")) break; attr = "backgroundColor"; } while (elem = elem.parentNode); return getRGB(color); }; // Some named colors to work with // From Interface by Stefan Petre // http://interface.eyecon.ro/ var colors = { }; })(jQuery);
JavaScript
TestCase('PersonTest', { testWhoAreYou : function() { var p = new Person('John', 'Doe', 'P.'); assertEquals('Should have responded with full name', 'John P. Doe', p.whoAreYou()); }, testWhoAreYouWithNoMiddleName : function() { var p = new Person('John', 'Doe'); assertEquals('Should have used only first and last name', 'John Doe', p.whoAreYou()); } });
JavaScript
var Person = function(first, last, middle) { this.first = first; this.middle = middle; this.last = last; }; Person.prototype = { whoAreYou : function() { return this.first + (this.middle ? ' ' + this.middle: '') + ' ' + this.last; } };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains functions to manipulate tests. * * @author phu@google.com (Po Hu) */ goog.provide('rpf.Tests'); goog.require('bite.base.Helper'); goog.require('bite.console.Helper'); /** * A class for manipulating a group of RPF tests. * @constructor */ rpf.Tests = function() { /** * The project name. * @type {string} * @private */ this.projectName_ = ''; /** * The test array. * @type {!Array} * @private */ this.tests_ = []; /** * The place where the tests were loaded from. * @type {string} * @private */ this.loadFrom_ = ''; /** * The details. * @type {!Object} * @private */ this.details_ = {}; }; /** * Sets the project name. * @param {string} name The new project name. */ rpf.Tests.prototype.setProjectName = function(name) { this.projectName_ = name; }; /** * Gets the project name. * @return {string} The project name. */ rpf.Tests.prototype.getProjectName = function() { return this.projectName_; }; /** * Sets the tests. * @param {!Array} tests The test array. */ rpf.Tests.prototype.setTests = function(tests) { this.tests_ = tests; }; /** * @return {Array} The test array. */ rpf.Tests.prototype.getTests = function() { return this.tests_; }; /** * Sets the place where the tests were loaded from. * @param {string} loadFrom Where the tests were loaded from. */ rpf.Tests.prototype.setLoadFrom = function(loadFrom) { this.loadFrom_ = loadFrom; }; /** * Gets the place where the tests were loaded from. * @return {string} Where the tests were loaded from. */ rpf.Tests.prototype.getLoadFrom = function() { return this.loadFrom_; }; /** * Gets the info map by the given test name. * @param {string} testName The test name. * @return {Object} The info map. */ rpf.Tests.prototype.getInfoMapByTest = function(testName) { var tests = this.tests_; for (var i = 0, len = tests.length; i < len; ++i) { if (tests[i]['test_name'] == testName) { var testObj = bite.base.Helper.getTestObject(tests[i]['test']); var result = bite.console.Helper.trimInfoMap(testObj['datafile']); return result['infoMap']; } } return null; }; /** * Saves the info map back to the given test. * @param {string} testName The test name. * @param {Object} infoMap The info map. */ rpf.Tests.prototype.saveInfoMapToTest = function(testName, infoMap) { var tests = this.tests_; for (var i = 0, len = tests.length; i < len; ++i) { if (tests[i]['test_name'] == testName) { var testObj = bite.base.Helper.getTestObject(tests[i]['test']); var result = bite.console.Helper.trimInfoMap(testObj['datafile']); result['infoMap'] = infoMap; testObj['datafile'] = bite.console.Helper.appendInfoMap( result['infoMap'], result['datafile']); } } }; /** * Gets the line number that needs to be updated. * @param {string} stepId The step id that needs to be updated. * @param {string} testName The test name that the failure happened. * @return {number} The line number that failed in the given test. */ rpf.Tests.prototype.getFailureLineNumber = function(stepId, testName) { var tests = this.tests_; var script = null; var infoMap = null; var elemXpath = ''; for (var i = 0, len = tests.length; i < len; ++i) { var testObj = bite.base.Helper.getTestObject(tests[i]['test']); var result = bite.console.Helper.trimInfoMap(testObj['datafile']); var name = testObj['name']; var step = result['infoMap']['steps'][stepId]; if (step) { elemXpath = result['infoMap']['elems'][step['elemId']]['xpaths'][0]; } if (name == testName) { script = testObj['script']; infoMap = result['infoMap']; } } if (!elemXpath || !script) { return -1; } var lines = script.split('\n'); for (i = 0, len = lines.length; i < len; ++i) { var id = bite.base.Helper.getStepId(lines[i]); if (!id) { continue; } var elemId = infoMap['steps'][id]['elemId']; if (elemXpath == infoMap['elems'][elemId]['xpaths'][0]) { return i; } } return -1; }; /** * Sets the project details. * @param {!Object} details The details. */ rpf.Tests.prototype.setDetails = function(details) { this.details_ = details; }; /** * Gets the page map. * @return {Object} The page map. */ rpf.Tests.prototype.getPageMap = function() { return this.details_ ? this.details_['page_map'] : null; };
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Unit tests for validatedialog. * * @author phu@google.com (Po Hu) */ goog.require('goog.testing.MockControl'); goog.require('goog.testing.PropertyReplacer'); goog.require('rpf.ValidateDialog'); var stubs_ = new goog.testing.PropertyReplacer(); var mockControl_ = null; var chrome = {}; var JSON = {}; function setUp() { mockControl_ = new goog.testing.MockControl(); chrome.extension = {}; stubs_.set(goog.global, 'chrome', chrome); } function tearDown() { mockControl_.$tearDown(); mockControl_ = null; stubs_.reset(); } function testSetVisible() { } function testOpenValidationDialog() { }
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains the script manager. * * @author phu@google.com (Po Hu) */ goog.provide('rpf.ScriptManager'); goog.require('rpf.MiscHelper'); /** * A class for managing a given script. * @constructor * @export */ rpf.ScriptManager = function() { /** * The scripts array. * @type {Array} */ this.scripts = []; /** * The temp data file string. * @type {string} */ this.datafile = ''; /** * The user specified lib string. * @type {string} */ this.userLib = ''; /** * The script start url. * @type {string} */ this.startUrl = ''; /** * The test name. * @type {string} */ this.testName = ''; /** * The project name. * @type {string} */ this.projectName = ''; /** * The test id in the test deposit. * @type {string} */ this.idOnWeb = ''; /** * The element's css selectors. * @type {Array} */ this.selectors = []; /** * The data user inputs. * @type {string} */ this.content = ''; /** * The element's node tag. * @type {string} */ this.nodeTag = ''; /** * The user's action with page. * @type string */ this.action = ''; /** * The descriptive info of the element. * @type {string} */ this.descriptor = ''; /** * The element's variable name. * @type {string} */ this.elemVarName = ''; /** * The screenshots array. * @type {Array} */ this.screenShotsArray = []; }; /** * Enum for label values. * @enum {string} * @export */ rpf.ScriptManager.Labels = { URL: 'url', NAME: 'name', SCRIPT: 'script', DATAFILE: 'datafile', USER_LIB: 'userlib', PROJECT_NAME: 'projectname', SCREEN_SHOTS: 'screenshots' }; /** * Parses the json object from the cloud. * @param {Object} jsonObj An object of the test related info. * @export */ //TODO (phu): Consider creating an object for these fields. rpf.ScriptManager.prototype.parseJsonObj = function(jsonObj) { this.testName = jsonObj[rpf.ScriptManager.Labels.NAME]; this.startUrl = jsonObj[rpf.ScriptManager.Labels.URL]; this.scriptStr = jsonObj[rpf.ScriptManager.Labels.SCRIPT]; this.datafile = jsonObj[rpf.ScriptManager.Labels.DATAFILE]; this.userLib = jsonObj[rpf.ScriptManager.Labels.USER_LIB]; this.projectName = jsonObj[rpf.ScriptManager.Labels.PROJECT_NAME]; }; /** * Creates a Json serializable object by the test related info. * @param {string} name The test name. * @param {string} url The test start url. * @param {string} script The test script. * @param {string} datafile The test data file string. * @param {string} userLib The user specified lib string. * @param {string} projectName The project name. * @param {Array.<string>=} opt_screenshots The screenshots array. * @return {Object} The object of the test related info. * @export */ rpf.ScriptManager.prototype.createJsonObj = function( name, url, script, datafile, userLib, projectName, opt_screenshots) { var cmdsJsonObj = {}; this.testName = name; this.startUrl = url; this.scriptStr = script; this.datafile = datafile; this.userLib = userLib; this.projectName = projectName; cmdsJsonObj[rpf.ScriptManager.Labels.NAME] = name; cmdsJsonObj[rpf.ScriptManager.Labels.URL] = url; cmdsJsonObj[rpf.ScriptManager.Labels.SCRIPT] = script; cmdsJsonObj[rpf.ScriptManager.Labels.DATAFILE] = datafile; cmdsJsonObj[rpf.ScriptManager.Labels.USER_LIB] = userLib; cmdsJsonObj[rpf.ScriptManager.Labels.PROJECT_NAME] = projectName; if (opt_screenshots) { this.screenShotsArray = opt_screenshots; cmdsJsonObj[rpf.ScriptManager.Labels.SCREEN_SHOTS] = opt_screenshots; } return cmdsJsonObj; };
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains RPF's screenshot dialog. * * @author phu@google.com (Po Hu) */ goog.provide('rpf.ScreenShotDialog'); goog.require('bite.common.mvc.helper'); goog.require('bite.console.Screenshot'); goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.events'); goog.require('goog.style'); goog.require('goog.ui.Dialog'); goog.require('rpf.soy.Dialog'); /** * A class for showing screenshots. * @constructor * @export */ rpf.ScreenShotDialog = function() { /** * The screenshot dialog. * @type {Object} * @private */ this.screenShotDialog_ = new goog.ui.Dialog(); /** * The screenshot manager instance. * @type {bite.console.Screenshot} * @private */ this.screenshotMgr_ = new bite.console.Screenshot(); /** * Inits the screenshot dialog. */ this.initScreenshotDialog_(); }; /** * Sets the visibility of the screenshot dialog. * On setting dialog visible, redraw the screenshots. * @param {boolean} display Whether or not to show the dialog. * @export */ rpf.ScreenShotDialog.prototype.setVisible = function(display) { if (display) { this.updateScreenshotDialog_(); } this.screenShotDialog_.setVisible(display); }; /** * Inits the screenshot dialog. * @private */ rpf.ScreenShotDialog.prototype.initScreenshotDialog_ = function() { this.screenShotDialog_.setTitle('Screenshots'); this.screenShotDialog_.setButtonSet(null); this.screenShotDialog_.setVisible(true); this.screenShotDialog_.setVisible(false); this.resize(); }; /** * Updates the screenshot dialog. * @private */ rpf.ScreenShotDialog.prototype.updateScreenshotDialog_ = function() { var screenShots = this.screenshotMgr_.getScreenshots(); var dialogContainer = this.screenShotDialog_.getContentElement(); bite.common.mvc.helper.renderModelFor( dialogContainer, rpf.soy.Dialog.screenshotContent, {'screenshots': screenShots}); }; /** * @return {bite.console.Screenshot} The screenshot manager instance. * @export */ rpf.ScreenShotDialog.prototype.getScreenshotManager = function() { return this.screenshotMgr_; }; /** * Resizes the window. This is necessary because css overflow does not * play nicely with percentages. */ rpf.ScreenShotDialog.prototype.resize = function() { var dialogTitleHeight = 50; var dialogScreenPercentage = 0.8; var screenHeight = goog.dom.getViewportSize().height; var contentElem = this.screenShotDialog_.getContentElement(); goog.style.setHeight( contentElem, screenHeight * dialogScreenPercentage - dialogTitleHeight); };
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains a dialog for RPF validation. * * @author phu@google.com (Po Hu) */ goog.provide('rpf.ValidateDialog'); goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.events'); goog.require('goog.ui.CustomButton'); goog.require('goog.ui.Dialog'); goog.require('goog.ui.MenuItem'); goog.require('goog.ui.Select'); goog.require('rpf.Attributes'); goog.require('rpf.CodeGenerator'); goog.require('rpf.Console.Messenger'); goog.require('rpf.MiscHelper'); goog.require('rpf.soy.Dialog'); /** * A class for validation. * @param {rpf.Console.Messenger} messenger The messenger instance. * @param {function(Bite.Constants.UiCmds, Object, Event)} onUiEvents * The function to handle the specific event. * @constructor * @export */ rpf.ValidateDialog = function(messenger, onUiEvents) { /** * The first elem to validate. * @type Object * @private */ this.validationElem_ = {}; /** * The descriptor got from the page under record. * @type * * @private */ this.validDescriptor_ = {}; /** * The xpath string. * @type {string} * @private */ this.xpath_ = ''; /** * The attributes controller. * @type Object * @private */ this.attrControl_ = new rpf.Attributes( rpf.Attributes.UITypes.VALIDATION_DIALOG, onUiEvents); /** * The validation dialog. * @type Object * @private */ this.validationDialog_ = new goog.ui.Dialog(); /** * The messenger. * @type {rpf.Console.Messenger} * @private */ this.messenger_ = messenger; /** * The function to handle the specific event. * @type {function(Bite.Constants.UiCmds, Object, Event)} * @private */ this.onUiEvents_ = onUiEvents; /** * The action selector. * @type {goog.ui.Select} * @private */ this.actionSelector_ = null; /** * Inits the validation dialog. */ this.initValidationDialog_(); }; /** * Sets the visibility of the validation dialog. * @param {boolean} display Whether to show the dialog. * @export */ rpf.ValidateDialog.prototype.setVisible = function(display) { this.validationDialog_.setVisible(display); }; /** * Inits the playback runtime dialog. * @private */ rpf.ValidateDialog.prototype.initValidationDialog_ = function() { var dialogElem = this.validationDialog_.getContentElement(); var contentDiv = goog.dom.createDom(goog.dom.TagName.DIV, {'id': 'validationdialog', 'style': 'text-align:center;'}); dialogElem.appendChild(contentDiv); this.validationDialog_.setTitle('Validation'); this.validationDialog_.setButtonSet(null); this.validationDialog_.setVisible(true); this.initValidationChoices_(); this.validationDialog_.setVisible(false); }; /** * Inits the validation dialog. * @private */ rpf.ValidateDialog.prototype.initValidationChoices_ = function() { var validationDialog = goog.dom.getElement('validationdialog'); soy.renderElement(validationDialog, rpf.soy.Dialog.createValidationDialog); }; /** * Inits the action selector. * @private */ rpf.ValidateDialog.prototype.initActionSelector_ = function() { var selectorDiv = goog.dom.getElement('actions-select'); goog.dom.removeChildren(selectorDiv); this.actionSelector_ = new goog.ui.Select('Actions'); this.actionSelector_.addItem(new goog.ui.MenuItem('verify')); this.actionSelector_.addItem(new goog.ui.MenuItem('verifyNot')); this.actionSelector_.addItem(new goog.ui.MenuItem('move')); this.actionSelector_.setSelectedIndex(0); this.actionSelector_.render(selectorDiv); }; /** * Shows the validation UI for attributes. * @export */ rpf.ValidateDialog.prototype.displayAllAttributes = function() { this.clearChoiceView_(); var choiceView = goog.dom.getElement('choiceViewDiv'); this.attrControl_.createAttrTabs( choiceView, this.validDescriptor_, this.xpath_, goog.bind(this.generateDescriptor_, this)); soy.renderElement( goog.dom.getElement('action-name-in-validation-dialog'), rpf.soy.Dialog.createActionNames); this.initActionSelector_(); }; /** * Opens the validation dialog. * @param {Object} request An object contains element related info. * @export */ rpf.ValidateDialog.prototype.openValidationDialog = function(request) { if (this.validationElem_['descriptor'] && this.validationElem_['descriptor'] == request['descriptor']) { this.attrControl_.generateDescriptor_(); return; } this.validationElem_ = request; this.validDescriptor_ = goog.json.parse(request['descriptor']); this.xpath_ = request['xpaths'][0]; this.initValidationChoices_(); this.displayAllAttributes(); this.validationDialog_.setVisible(true); }; /** * Clears the choice view div. * @private */ rpf.ValidateDialog.prototype.clearChoiceView_ = function() { var choiceView = goog.dom.getElement('choiceViewDiv'); goog.dom.removeChildren(choiceView); var actions = goog.dom.getElement('action-name-in-validation-dialog'); goog.dom.removeChildren(actions); }; /** * Updates the editor with the new generated command. * @param {Object} response The response object. * @private */ rpf.ValidateDialog.prototype.updateEditorWithCommand_ = function(response) { var scriptInfo = response['scriptInfo']; this.onUiEvents_( Bite.Constants.UiCmds.ADD_NEW_COMMAND, {'pCmd': scriptInfo['cmd'], 'dCmd': scriptInfo['data'], 'cmdMap': scriptInfo['cmdMap']}, /** @type {Event} */ ({})); }; /** * Generates a the validation command. * @private */ rpf.ValidateDialog.prototype.generateDescriptor_ = function() { var content = this.validDescriptor_.elementText; if (typeof(content) != 'string') { content = content['value']; } var xpathInput = this.attrControl_.getXpathInput(); var xpaths = this.validationElem_['xpaths']; if (xpathInput && typeof xpaths == 'object') { xpaths[0] = xpathInput.value; } this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.GENERATE_NEW_COMMAND, 'params': { 'selectors': this.validationElem_['selectors'], 'content': escape(content), 'nodeType': this.validationElem_.nodeType, 'action': this.actionSelector_.getSelectedItem().getValue(), 'descriptor': JSON.stringify(this.validDescriptor_), 'elemVarName': this.validationElem_['elemVarName'], 'iframeInfo': this.validationElem_['iframeInfo'], 'xpaths': xpaths, 'className': this.validationElem_['className']}}, goog.bind(this.updateEditorWithCommand_, this)); this.clearChoiceView_(); this.setVisible(false); this.validationElem_ = {}; };
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains the misc helper, which * provides a bunch of handy functions. * * @author phu@google.com (Po Hu) */ goog.provide('rpf.MiscHelper'); goog.require('bite.base.Helper'); goog.require('goog.Uri'); goog.require('goog.date.DateTime'); goog.require('goog.json'); /** * @const The console html. * @type {string} * @private */ rpf.MiscHelper.CONSOLE_HTML_ = 'console.html'; /** * @const The common lib server. * @type {string} */ rpf.MiscHelper.COMMON_LIB_SERVER = 'http://suite-executor.appspot.com'; /** * Enum for modes values. * @enum {string} * @export */ rpf.MiscHelper.Modes = { NONE: '', WORKER: 'worker', CONSOLE: 'console', PLAYBACK: 'playback', AUTORUN: 'autorun' }; /** * Gets matching part of a string. * @param {Object} re A given regular expression. * @param {string} str A string. * @param {string=} opt_value The value by default. * @return {string} The matching string or the default string. * @export */ rpf.MiscHelper.getStr = function(re, str, opt_value) { var match = re.exec(str); return match ? match[1] : opt_value; }; /** * Gets the chrome version. * @param {string} agent The user agent. * @return {string} The chrome version. * @export */ rpf.MiscHelper.getChromeVersion = function(agent) { return rpf.MiscHelper.getStr(/\bChrome\/([0-9.]*)/, agent); }; /** * Resizes a screenshot captured. * @param {Function} callback The callback function. * @param {number} maxSideSize The new image height. * @param {Object} dimension The new dimension object. * @param {string} url The image data url. * @export */ rpf.MiscHelper.resizeImage = function( callback, maxSideSize, dimension, url) { var maxLen = maxSideSize || 600; var sourceImage = new Image(); sourceImage.onload = function() { // Create a canvas with the desired dimensions var canvas = document.createElement('canvas'); var newHeight = sourceImage.height; var newWidth = sourceImage.width; // Preserve width to height ratios. if (newHeight > maxLen && sourceImage.height > sourceImage.width) { newHeight = maxLen; newWidth = sourceImage.width / sourceImage.height * maxLen; } else if(newWidth > maxLen) { newHeight = sourceImage.height / sourceImage.width * maxLen; newWidth = maxLen; } canvas.width = newWidth; canvas.height = newHeight; // Scale and draw the source image to the canvas canvas.getContext('2d').drawImage( sourceImage, 0, 0, newWidth, newHeight); var canvas2 = document.createElement('canvas'); // Convert the canvas to a data URL in PNG format callback(canvas.toDataURL('img/png'), rpf.MiscHelper.sliceImage(dimension, canvas2, sourceImage, {'width': 9999, 'height': 9999})); }; sourceImage.src = url; }; /** * Crops a screenshot captured. * @param {Function} callback The callback function. * @param {Object} dimension The new dimension object. * @param {string} url The image data url. * @export */ rpf.MiscHelper.cropImage = function(callback, dimension, url) { var sourceImage = new Image(); sourceImage.onload = function() { var canvas = document.createElement('canvas'); canvas.width = dimension['sWidth']; canvas.height = dimension['sHeight']; canvas.getContext('2d').drawImage( sourceImage, dimension['sX'], dimension['sY'], dimension['sWidth'], dimension['sHeight'], 0, 0, dimension['sWidth'], dimension['sHeight']); // Convert the canvas to a data URL in PNG format callback(canvas.toDataURL('img/png'), ''); }; sourceImage.src = url; }; /** * Slices a screenshot captured. * @param {Object} dimension The new dimension object. * @param {Object} canvas The canvas object. * @param {Object} sourceImage The sourceImage object. * @param {!Object} maxDimension The max width and length in pixel. * @return {string} The data url string. * @export */ rpf.MiscHelper.sliceImage = function( dimension, canvas, sourceImage, maxDimension) { if (!dimension) { return ''; } var maxHeight = maxDimension['height'] || 100; var maxWidth = maxDimension['width'] || 300; var newHeight = dimension['sHeight']; var newWidth = dimension['sWidth']; if (newHeight > maxHeight) { newHeight = maxHeight; newWidth = dimension['sWidth'] / dimension['sHeight'] * maxHeight; } if (newWidth > maxWidth) { newHeight = dimension['sHeight'] / dimension['sWidth'] * maxWidth; newWidth = maxWidth; } canvas.width = newWidth; canvas.height = newHeight; canvas.getContext('2d').drawImage( sourceImage, dimension['sX'], dimension['sY'], dimension['sWidth'], dimension['sHeight'], 0, 0, newWidth, newHeight); return canvas.toDataURL('img/png'); }; /** * Gets the descriptor from a script cmd. * @param {string} script The generated script string. * @return {Object|string} The descriptor object. * @export */ rpf.MiscHelper.getDescriptor = function(script) { var descriptor = script.match(/parseElementDescriptor\(.*?}}\)/) + ''; if (descriptor == 'null') { return 'Parser error - Invalid descriptor info'; } try { descriptor = goog.json.parse(descriptor.substring( Bite.Constants.FUNCTION_PARSE_DESCRIPTOR.length + 1, descriptor.length - 1)); } catch (e) { console.log('Parse error - ' + e.message); return null; } return descriptor; }; /** * Gets the stringified string with spaces. * @param {string|Object} desc The descriptor string of object. * @param {number} numSpace The number of spaces. * @return {string} The string with spaces. * @export */ rpf.MiscHelper.getStringWithSpaces = function(desc, numSpace) { var objDesc = {}; if (typeof(desc) == 'string') { objDesc = goog.json.parse(desc); } else if (typeof(desc) == 'object') { objDesc = desc; } else { throw new Error('Not supported type.'); } var result = ''; result = JSON.stringify(objDesc, null, numSpace); return result.replace(/\n/g, ''); }; /** * Gets the command id. * @param {string} cmd The to be matched line of command. * @return {string} The command's id. * @export */ rpf.MiscHelper.getCmdId = function(cmd) { var m = /\/\*"""id[^/*]*"""\*\//g; var tempMatch = cmd.match(m); if (!tempMatch) { return ''; } var temp = tempMatch[0]; ///*"""id(blah)"""*/ return temp.substring(8, temp.length - 6); }; /** * Replace the descriptor from a script cmd. * @param {string} script The generated script string. * @param {string} newDesc The new descriptor string. * @return {string} The replaced string. * @export */ rpf.MiscHelper.replaceDescriptor = function( script, newDesc) { // parseElementDescriptor({'name': 'abc', 'parent': {}}) var descriptor = script.match(/parseElementDescriptor\(.*?}}\)/); if (!descriptor) { return script; } return script.replace(/parseElementDescriptor\(.*?}}\)/, 'parseElementDescriptor(' + newDesc + ')'); }; /** * Gets the time stamp. * @return {string} The time stamp. * @export */ rpf.MiscHelper.getTimeStamp = function() { var dateTime = new goog.date.DateTime(); return dateTime.toIsoString(true); }; /** * Removes a window. * @param {number} winId The window's id. * @export */ rpf.MiscHelper.removeWindowById = function(winId) { chrome.windows.remove(winId); }; /** * Returns a unique id in the given context. * @param {string} script The script string. * @return {number} The unique id. * @export */ rpf.MiscHelper.getUniqueId = function(script) { var existingIds = {}; var id = 0; var results = script.match(/\d+\);/gi); if (!results) { return 1; } for (var i = 0, len = results.length; i < len; i++) { id = parseInt(results[i].substring(0, results[i].length - 2), 10); existingIds[id] = true; } for (var i = 2; i < 1000000; i++) { if (!existingIds[i]) { return i; } } }; /** * Gets the elem info from a given cmd. * @param {string} cmd The cmd string. * @param {Object} infoMap The info map. * @return {Object} The elem info map. * @export */ rpf.MiscHelper.getElemMap = function(cmd, infoMap) { var id = bite.base.Helper.getStepId(cmd); return id ? infoMap['elems'][infoMap['steps'][id]['elemId']] : {}; }; /** * Adds id to a generated command. * @param {number|string} id The id. * @param {string} cmd The generated command. * @return {string} The new string. * @export */ rpf.MiscHelper.addIdToCommand = function(id, cmd) { var index = cmd.lastIndexOf(');'); return cmd.substring(0, index) + ', ' + id + cmd.substring(index, cmd.length); }; /** * Gets the url by the given parameters. * @param {string} serverUrl The server url. * @param {string} requestPath The request path of the server. * @param {!Object} paramMap The param map object. * @return {string} the request url. * @export */ rpf.MiscHelper.getUrl = function( serverUrl, requestPath, paramMap) { var request = goog.Uri.parse(serverUrl); request.setPath(requestPath); var data = goog.Uri.QueryData.createFromMap(paramMap); request.setQueryData(data); return request.toString(); };
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains the misc helper functions. */ goog.provide('common.client.MiscHelper'); /** * A class contains misc helper functions. * @constructor * @export */ common.client.MiscHelper = function() { }; /** * Resizes a screenshot captured. * @param {string} url The image data url. * @param {Function} callback The callback function. * @param {number?} opt_height The new image height. * @export */ common.client.MiscHelper.resizeImage = function(url, callback, opt_height) { var newHeight = opt_height || 250; var sourceImage = new Image(); sourceImage.onload = function() { // Create a canvas with the desired dimensions var canvas = document.createElement('canvas'); var newWidth = sourceImage.width * newHeight / sourceImage.height; canvas.width = newWidth; canvas.height = newHeight; // Scale and draw the source image to the canvas canvas.getContext('2d').drawImage( sourceImage, 0, 0, newWidth, newHeight); // Convert the canvas to a data URL in PNG format callback(canvas.toDataURL()); } sourceImage.src = url; }; /** * Changes the cursor style for all elements on the web page. * @param {string} cursorStyle The predefined cursor style, e.g. 'default', * 'crosshair', etc. * @export */ common.client.MiscHelper.setCursorStyle = function(cursorStyle) { var style = document.createElement('style'); style.innerHTML = '* {cursor: ' + cursorStyle + ' !important}\n'; style.id = 'tempCursor'; document.getElementsByTagName('head')[0].appendChild(style); }; /** * Restores the cursor style for all elements on the web page. * @export */ common.client.MiscHelper.restoreCursorStyle = function() { var style = document.getElementById('tempCursor'); if (style && style.parentNode) { style.parentNode.removeChild(style); } };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains testing framework to test multiple bite * related functionalities. ex. The accuracy of descriptor, etc. * * @author phu@google.com (Po Hu) */ goog.provide('bite.TestFramework'); goog.require('goog.Timer'); goog.require('goog.dom'); /** * The class for test framework. * @constructor * @export */ bite.TestFramework = function() { this.elemDescriptor_ = null; if (!common.client.ElementDescriptor) { alert('elementhelper not exists.'); return; } else { this.elemDescriptor_ = new common.client.ElementDescriptor(); } goog.Timer.callOnce(goog.bind(this.testSelectors_, this), 5000); }; /** * The tag names that will be ignored. * @type {Object} * @private */ bite.TestFramework.IGNORE_TAG_ARRAY_ = { 'script': true, 'style': true, 'meta': true, 'html': true, 'embed': true }; /** * Tests descriptors, which represents the JSON format info string we collect. * @private */ bite.TestFramework.prototype.testDescriptors_ = function() { var elems = this.getElements_(); console.log('The elems number is: ' + elems.length); var descriptor = null; var failedNum = 0; var startTime = goog.now(); for (var i = 0, len = elems.length; i < len; i++) { if (bite.TestFramework.IGNORE_TAG_ARRAY_[elems[i].tagName.toLowerCase()]) { continue; } descriptor = this.elemDescriptor_.generateElementDescriptor(elems[i], 2); failedNum += this.checkDescriptor_(elems[i], descriptor); } console.log('It took secs: ' + (goog.now() - startTime) / 1000); console.log('Failed number is: ' + failedNum); }; /** * Tests selectors, which represents the css selectors we collect for elements. * @private */ bite.TestFramework.prototype.testSelectors_ = function() { var elems = this.getElements_(); console.log('The elems number is: ' + elems.length); var failedNum = 0; var startTime = goog.now(); for (var i = 0, len = elems.length; i < len; i++) { if (bite.TestFramework.IGNORE_TAG_ARRAY_[elems[i].tagName.toLowerCase()]) { continue; } var selector = this.elemDescriptor_.generateSelector(elems[i]); var result = this.checkSelector_(elems[i], selector); if (result) { console.log('Failed elem selector is: ' + selector); console.log(elems[i]); } failedNum += result; } console.log('It took secs: ' + (goog.now() - startTime) / 1000); console.log('Failed number is: ' + failedNum); }; /** * Checks whether the given selector is correct. * @param {Node} elem The element node. * @param {string} selector The selector string. * @return {number} 0: success 1: failed. * @private */ bite.TestFramework.prototype.checkSelector_ = function(elem, selector) { var nodes = null; try { nodes = document.querySelectorAll(selector); } catch (e) { console.log('Failed selector is: ' + selector); console.log(elem); return 1; } return nodes && nodes.length == 1 && nodes[0].isSameNode(elem) ? 0 : 1; }; /** * Checks whether the given descriptor is correct. * @param {Node} elem The element node. * @param {string} descriptor The descriptor string. * @return {number} 0: success 1: failed. * @private */ bite.TestFramework.prototype.checkDescriptor_ = function(elem, descriptor) { var result = parseElementDescriptor(descriptor, true); if (result){ if (elem.isSameNode(result[0])) { return 0; } else { console.log('Found one elem, but not the one: '); } } else { console.log('Found multiple results: '); } console.log('The descriptor: ' + descriptor); console.log('Was looking for: '); console.log(elem); console.log('Actually found: '); console.log(result[0]); this.markElement_(elem); return 1; }; /** * Marks the element. * @param {Node} elem The element to be marked. * @private */ bite.TestFramework.prototype.markElement_ = function(elem) { elem.style.outline = 'medium solid yellow'; elem.onmouseover = function() { console.log(elem.outerHTML); }; }; /** * Gets an array from a given nodelist. * @param {Object} nodeList The nodeList. * @return {Array} The element array. * @private */ bite.TestFramework.prototype.getArrayFromNodeList_ = function(nodeList) { var elemArray = []; for (var i = 0, len = nodeList.length; i < len; i++) { elemArray.push(nodeList[i]); } return elemArray; }; /** * Gets a group of elements. * @return {Array} Returns a list of elements. * @private */ bite.TestFramework.prototype.getElements_ = function() { return this.getArrayFromNodeList_( goog.dom.getDocument().querySelectorAll('*')); }; new bite.TestFramework();
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file is used to generate rpf project data model file * which can be exported to users and imported back. * * For the raw data it is in a format of * {'name': ... * 'project_details': {'package': ...}, * 'tests': [{'script': ..., * 'datafile': {dataInput, infoMap: { * Please see biteconcolehelper for the details}}}, * 'name': ..., * 'url': ...} ...]} * * During the conversion, we'll trim off the info like selectors, which * is not needed in webdriver code. * * @author phu@google.com (Po Hu) */ goog.provide('rpf.DataModel'); goog.require('bite.base.Helper'); goog.require('bite.console.Helper'); goog.require('common.client.ElementDescriptor'); goog.require('goog.object'); goog.require('goog.json'); /** * A class for handling data model related operations. * @constructor */ rpf.DataModel = function() { }; /** * Consolidates the raw data of the descriptor string. * @param {Object} descriptor The original descriptor object which * contains element's attributes information. * @return {Object} The consolidated descriptor object. * @private */ rpf.DataModel.prototype.consolidateDescriptor_ = function(descriptor) { var newDescriptor = {'attributes': {}}; newDescriptor['tagName'] = descriptor['tagName']; var verifications = common.client.ElementDescriptor.getAttrsToVerify( descriptor, unescape); for (var name in verifications) { switch (name) { case 'elementText': newDescriptor['elementText'] = verifications['elementText']; break; case 'checked': newDescriptor['checked'] = verifications['checked']; break; case 'disabled': newDescriptor['disabled'] = verifications['disabled']; break; case 'selectedIndex': newDescriptor['selectedIndex'] = verifications['selectedIndex']; break; default: newDescriptor['attributes'][name] = verifications[name]; } } return newDescriptor; }; /** * Reverts to the raw data of the descriptor string.. * @param {Object} descriptor The consolidated descriptor object which * contains element's attributes information. * @return {Object} The raw descriptor object. * @private */ rpf.DataModel.prototype.revertDescriptor_ = function(descriptor) { function createMap(value) { return {'show': 'must', 'value': value}; } var newDescriptor = {'attributes': {}}; newDescriptor['tagName'] = descriptor['tagName']; for (var name in descriptor) { switch (name) { case 'elementText': case 'checked': case 'disabled': case 'selectedIndex': newDescriptor[name] = createMap(descriptor[name]); break; case 'attributes': for (var attr in descriptor[name]) { newDescriptor[name][attr] = createMap(descriptor[name][attr]); } break; } } return newDescriptor; }; /** * Consolidates the raw data of the information map. * @param {Object} infoMap The original information map object. * @return {Object} The consolidated information map object. * @private */ rpf.DataModel.prototype.consolidateInfoMap_ = function(infoMap) { var newInfoMap = { 'steps': {}, 'elems': {} }; for (var step in infoMap['steps']) { var curStep = infoMap['steps'][step]; newInfoMap['steps'][step] = { 'elemId': curStep['elemId'], 'action': curStep['action'], 'stepName': curStep['stepName'], 'varName': curStep['varName'], 'tagName': curStep['tagName'], 'pageName': curStep['pageName'] }; } for (var elem in infoMap['elems']) { var curElem = infoMap['elems'][elem]; newInfoMap['elems'][elem] = { 'xpaths': curElem['xpaths'], 'descriptor': this.consolidateDescriptor_(curElem['descriptor']), 'iframeInfo': curElem['iframeInfo'] }; } return newInfoMap; }; /** * Reverts to the raw data of the information map. * @param {Object} infoMap The consolidated information map object. * @return {Object} The raw information map object. * @private */ rpf.DataModel.prototype.revertInfoMap_ = function(infoMap) { var newInfoMap = { 'steps': {}, 'elems': {} }; for (var step in infoMap['steps']) { var curStep = infoMap['steps'][step]; newInfoMap['steps'][step] = { 'elemId': curStep['elemId'], 'action': curStep['action'], 'stepName': curStep['stepName'], 'varName': curStep['varName'], 'tagName': curStep['tagName'], 'pageName': curStep['pageName'] }; } for (var elem in infoMap['elems']) { var curElem = infoMap['elems'][elem]; newInfoMap['elems'][elem] = { 'xpaths': curElem['xpaths'], 'descriptor': this.revertDescriptor_(curElem['descriptor']), 'iframeInfo': curElem['iframeInfo'] }; } return newInfoMap; }; /** * Consolidates the project.project_details.js_files. * This should extract the file names and contents out, and only leave * the names in the consolidated data.rpf file. There should be * separate JS files created along with data.rpf. * @param {!Object} details The project details. * @return {Object} The modified data file and the JS files string. * @private */ rpf.DataModel.prototype.consolidateProjectDetails_ = function(details) { if (!details['js_files'] || details['js_files'].length == 0) { return {'details': details, 'jsFiles': ''}; } var newDetails = goog.object.unsafeClone(details); var jsFiles = []; var files = newDetails['js_files']; for (var i = 0; i < files.length; ++i) { jsFiles.push({'name': files[i]['name'], 'code': files[i]['code']}); delete files[i]['code']; } return {'details': newDetails, 'jsFiles': goog.json.serialize(jsFiles)}; }; /** * Consolidates the raw data of the project object. * @param {{name: string, tests: Array}} projectInfo * The project information map, which contains * project specific information and a group of test information. * @return {!Object} The consolidated project info object. */ rpf.DataModel.prototype.consolidateData = function(projectInfo) { var newDetails = this.consolidateProjectDetails_( projectInfo['project_details']); var jsFiles = newDetails['jsFiles']; var result = {'name': projectInfo['name'], 'project_details': newDetails['details'], 'tests': []}; var tests = projectInfo['tests']; for (var i = 0, len = tests.length; i < len; ++i) { var testObj = bite.base.Helper.getTestObject(tests[i]['test']); var data = bite.console.Helper.trimInfoMap(testObj['datafile']); testObj['datafile'] = data['datafile']; testObj['infoMap'] = this.consolidateInfoMap_(data['infoMap']); result['tests'].push(testObj); } return {'data': result, 'jsFiles': jsFiles}; }; /** * Converts the data model object to raw information object. * @param {!Object} projectInfo The project information map, which contains * project specific information and a group of test information. * @return {!Object} The raw project info object. */ rpf.DataModel.prototype.convertDataToRaw = function(projectInfo) { var newProject = {}; newProject['project_details'] = projectInfo['project_details']; newProject['userId'] = projectInfo['userId']; newProject['name'] = projectInfo['name']; newProject['tests'] = []; var tests = projectInfo['tests']; for (var i = 0, len = tests.length; i < len; ++i) { var testObj = tests[i]; testObj['datafile'] = bite.console.Helper.appendInfoMap( this.revertInfoMap_(testObj['infoMap']), testObj['datafile']); newProject['tests'].push({'test_name': testObj['name'], 'test': goog.json.serialize(testObj)}); } return newProject; };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains the bite console helper functions. * * @author phu@google.com (Po Hu) */ goog.provide('bite.console.Helper'); goog.provide('bite.console.Screenshot'); goog.require('bite.base.Helper'); goog.require('goog.events'); /** * @type {string} */ bite.console.Helper.INFO_MAP_START = '/*InfoMap starts*/'; /** * @type {string} */ bite.console.Helper.INFO_MAP_END = '/*InfoMap ends*/'; /** * Gets the doc string of the generated code. * @param {string} domain The recorded page's domain. * @param {string} authorId The author's id. * @return {string} The doc string. * @export */ bite.console.Helper.getDocString = function(domain, authorId) { return ( '/**\n' + ' * @fileoverview This is an auto-generated test on ' + domain + '.\n' + ' * The generated commands are in the format of:\n' + ' * ACTION(ELEMENT, OPT_TEXT);\n' + ' * @author ' + authorId + '\n' + ' */\n\n\n'); }; /** * Merges the given model files into one. * @param {Array} infoMaps The info map objects. * @return {Object} The infoMap object. * @export */ bite.console.Helper.mergeInfoMaps = function(infoMaps) { var infoMap = {'steps': {}, 'elems': {}}; for (var i = 0, len = infoMaps.length; i < len; ++i) { var steps = infoMaps[i]['steps']; for (var step in steps) { infoMap['steps'][step] = steps[step]; } var elems = infoMaps[i]['elems']; for (var elem in elems) { infoMap['elems'][elem] = elems[elem]; } } return infoMap; }; /** * InfoMap is the basic model to store all the recorded info. The model * could be used as a glue for all the rpf components and features. * @param {Object} infoMap The info map object. * @param {Object} cmdMap The command map. * @export */ bite.console.Helper.assignInfoMap = function(infoMap, cmdMap) { if (!infoMap['steps']) { infoMap['steps'] = {}; infoMap['elems'] = {}; } infoMap['steps'][cmdMap['id']] = { 'elemId': cmdMap['elemId'], 'action': cmdMap['action'], 'varName': cmdMap['varName'], 'stepName': cmdMap['id'], 'tagName': cmdMap['tagName'], 'comments': '', 'pageName': cmdMap['className'], 'returnPageName': '', 'url': '' }; // TODO(phu): Need to ignore duplicated elems. infoMap['elems'][cmdMap['elemId']] = { 'selectors': cmdMap['selectors'], 'xpaths': cmdMap['xpaths'], 'descriptor': cmdMap['descriptor'], 'iframeInfo': cmdMap['iframeInfo'] }; }; /** * Appends infoMap to datafile. * @param {Object} infoMap The info map object. * @param {string} datafile The old datafile. * @return {string} The new datafile string. * @export */ bite.console.Helper.appendInfoMap = function(infoMap, datafile) { return datafile + bite.console.Helper.INFO_MAP_START + goog.json.serialize(infoMap) + bite.console.Helper.INFO_MAP_END; }; /** * Trims infoMap from datafile. * @param {string} datafile The old datafile. * @return {Object} The object containing infoMap and datafile. * @export */ bite.console.Helper.trimInfoMap = function(datafile) { var infoMap = null; var startIndex = datafile.indexOf(bite.console.Helper.INFO_MAP_START); if (startIndex == -1) { return {'infoMap': {}, 'datafile': datafile}; } var mapStartIndex = startIndex + bite.console.Helper.INFO_MAP_START.length; var endIndex = datafile.indexOf(bite.console.Helper.INFO_MAP_END); try { infoMap = goog.json.parse( datafile.substring(mapStartIndex, endIndex)); } catch (e) { console.log(e.message); } endIndex += bite.console.Helper.INFO_MAP_END.length; datafile = datafile.substring(0, startIndex) + datafile.substring(endIndex, datafile.length); return {'infoMap': infoMap, 'datafile': datafile}; }; /** * @type {Object} */ bite.console.Helper.ID_SCREENSHOT_MAP = {}; /** * Change the screenshot. * @param {string} id The screenshot id string. * @param {string} elemId The element's id. * @export */ bite.console.Helper.changeScreen = function(id, elemId) { goog.dom.getElement(elemId).src = bite.console.Helper.ID_SCREENSHOT_MAP[id]['screen']; }; /** * Registers the screenshot change events. * @param {Object} steps The steps info. * @param {Function} callback The callback function. * @export */ bite.console.Helper.registerScreenChangeEvents = function(steps, callback) { for (var index in steps) { var id = steps[index]['id']; var elem = goog.dom.getElement(id); if (elem) { goog.events.listen(elem, goog.events.EventType.MOUSEOVER, callback); } } }; /** * Gets the steps info. * @param {bite.console.Screenshot} scnShotMgr The screenshot manager. * @param {Object} infoMap The info map object. * @param {string} code The code string. * @return {Object} The steps object. * @export */ bite.console.Helper.getStepsInfo = function(scnShotMgr, infoMap, code) { var steps = [{}]; var index = 0; bite.console.Helper.ID_SCREENSHOT_MAP = scnShotMgr.getIdScreenShotMap(); var lines = code.split('\n'); var tempComment = ''; var curId = ''; bite.base.Helper.evalDatafile(goog.dom.getElement( Bite.Constants.RpfConsoleId.DATA_CONTAINER).value); for (var i = 0; i < lines.length; i++, tempComment = '') { while (lines[i].indexOf('//') == 0) { tempComment += lines[i]; i++; } if (goog.string.trim(lines[i]) == '') { continue; } if (curId = bite.base.Helper.getStepId(lines[i])) { var stepInfo = infoMap['steps'][curId]; var data = bite.base.Helper.dataFile[stepInfo['varName']]; var transSurfix = data ? ' "' + data + '" ' : ''; steps[index]['translation'] = stepInfo['action'].charAt(0).toUpperCase() + stepInfo['action'].slice(1); steps[index]['data'] = transSurfix; steps[index]['id'] = curId; steps[index++]['icon'] = bite.console.Helper.ID_SCREENSHOT_MAP[curId]['icon']; steps[index] = {}; } } return steps; }; /** * A class for managing the screenshots. * TODO (phu): Replace the arrays with a map object. * @constructor * @export */ bite.console.Screenshot = function() { /** * The time stamp array. * @type {Array} * @private */ this.timeStamps_ = []; /** * The generated command that related with the screenshot. * @type {Array} * @private */ this.generatedCmds_ = []; /** * The screen shots array, which contains a bunch of data urls. * @type {Array} * @private */ this.screenshots_ = []; /** * The screen shots icon array, which contains partial image data urls. * @type {Array} * @private */ this.iconShots_ = []; /** * The command index array. This is used to record the corresponding * index of generated command in the original script. * @type {Array} * @private */ this.cmdIndices_ = []; }; /** * Adds a screenshot. * @param {string} url The screenshot image url. * @param {string} iconUrl The screenshot icon url. * @param {string=} opt_index The command index. * @export */ bite.console.Screenshot.prototype.addScreenShot = function( url, iconUrl, opt_index) { var index = opt_index || ''; console.log(' Added screenshot' + index); this.screenshots_.push(url); this.iconShots_.push(iconUrl); if (index) { this.addIndex(index); } }; /** * Resets screenshots. * @param {Object} screenshots The screenshot objects. * @export */ bite.console.Screenshot.prototype.resetScreenShots = function(screenshots) { this.clear(); for (var step in screenshots) { this.addScreenShot(screenshots[step]['data'], screenshots[step]['icon'], screenshots[step]['index']); } }; /** * Clean up the screen shots. * @export */ bite.console.Screenshot.prototype.clear = function() { this.timeStamps_ = []; this.generatedCmds_ = []; this.screenshots_ = []; this.cmdIndices_ = []; }; /** * Adds an index for the screenshot. * @param {string} screenshotId string. * @export */ bite.console.Screenshot.prototype.addIndex = function(screenshotId) { console.log(' Added screenshot index:' + screenshotId); this.cmdIndices_.push(screenshotId); }; /** * Adds a generated command which matches the screenshot. * @param {string} cmd The generated command. * @export */ bite.console.Screenshot.prototype.addGeneratedCmd = function(cmd) { this.generatedCmds_.push(cmd); }; /** * Remove the screenshot at the given line. * @param {number} line The line to be removed. * @export */ bite.console.Screenshot.prototype.deleteItem = function(line) { for (var i = 0; i < this.cmdIndices_.length; i++) { if (this.cmdIndices_[i] == line) { this.cmdIndices_.splice(i, 1); this.screenshots_.splice(i, 1); } } }; /** * Get the screen shot by a given index. * @param {string} index The index. * @return {?string} The screenshot data url. * @export */ bite.console.Screenshot.prototype.getScreenById = function(index) { for (var i = 0; i < this.cmdIndices_.length; i++) { if (this.cmdIndices_[i] == index) { return this.screenshots_[i]; } } return null; }; /** * @return {Array} The time stamp array. * @export */ bite.console.Screenshot.prototype.getTimeStamps = function() { return this.timeStamps_; }; /** * @return {Array} The generated command that related with the screenshot. * @export */ bite.console.Screenshot.prototype.getGeneratedCmds = function() { return this.generatedCmds_; }; /** * @return {Array} The screen shots array, which contains a bunch of data urls. * @export */ bite.console.Screenshot.prototype.getScreenshots = function() { return this.screenshots_; }; /** * @return {Array} The command index array. * @export */ bite.console.Screenshot.prototype.getCmdIndices = function() { return this.cmdIndices_; }; /** * @return {Object} The id and screenshot map. * @export */ bite.console.Screenshot.prototype.getIdScreenShotMap = function() { var map = {}; for (var i = 0, len = this.screenshots_.length; i < len; i++) { map[this.cmdIndices_[i]] = {}; map[this.cmdIndices_[i]]['screen'] = this.screenshots_[i]; map[this.cmdIndices_[i]]['icon'] = this.iconShots_[i]; } return map; };
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains the tests' save and load manager. * * @author phu@google.com (Po Hu) */ goog.provide('rpf.SaveLoadManager'); goog.require('Bite.Constants'); goog.require('bite.options.constants'); goog.require('bite.options.data'); goog.require('goog.Uri'); goog.require('goog.net.XhrIo'); goog.require('rpf.DataModel'); goog.require('rpf.MiscHelper'); goog.require('rpf.ScriptManager'); goog.require('rpf.StatusLogger'); /** * A class for saving and loading tests from locally or cloud. * @param {rpf.ScriptManager} scriptMgr The script manager. * @param {function(Object, function(*)=)} sendMessageToConsole The * function to send message to console world. * @param {function(Object, Object, function(Object))} eventMgrListener * The listener registered in eventsManager. * TODO(phu): Consider splitting this into saveManager and loadManager. * @constructor */ rpf.SaveLoadManager = function(scriptMgr, sendMessageToConsole, eventMgrListener) { this.scriptMgr_ = scriptMgr; // TODO(phu): Put the test data in get method. this.server = bite.options.data.get(bite.options.constants.Id.SERVER_CHANNEL); /** * The function to send message to console world. * @type {function(Object, function(*)=)} * @private */ this.sendMessageToConsole_ = sendMessageToConsole; /** * The event lisnener registered on event manager. * @type {function(Object, Object, function(Object))} * @private */ this.eventMgrListener_ = eventMgrListener; }; /** * The url path on the server to use for storage requests. * @const * @type {string} * @private */ rpf.SaveLoadManager.STORAGE_SERVER_PATH_ = '/storage'; /** * The test steps depository server. * @const * @type {string} * @private */ rpf.SaveLoadManager.STEPS_DEPOSIT_SERVER_ = 'http://suite-executor.appspot.com'; /** * The local storage name. * @const * @type {string} * @private */ rpf.SaveLoadManager.LOCAL_STORAGE_NAME_ = 'rpfscripts'; /** * The default project name. * @const * @type {string} * @private */ rpf.SaveLoadManager.WEB_DEFAULT_PROJECT_ = 'rpf'; /** * Gets all the test names from cloud and updates the loader dialog. * @param {string} projectName The project name. * @param {function(Object)} sendResponse The response function. * @export */ rpf.SaveLoadManager.prototype.getAllFromWeb = function( projectName, sendResponse) { var requestUrl = rpf.MiscHelper.getUrl( this.server, rpf.SaveLoadManager.STORAGE_SERVER_PATH_ + '/getalltestsasjson', {'test_flavor': 'json', 'project': projectName}); // TODO(phu): If this causes memory leak, move it out. goog.net.XhrIo.send(requestUrl, function() { var jsonObj = this.getResponseJson(); sendResponse({'jsonObj': jsonObj}); }); }; /** * Gets project details and all its tests from cloud and updates. * @param {string} name The project name. * @param {string} userId A string representation of the current user. * @param {function(Object)} sendResponse The response function. * @export */ rpf.SaveLoadManager.prototype.getProject = function(name, userId, sendResponse) { var requestUrl = this.server + rpf.SaveLoadManager.STORAGE_SERVER_PATH_ + '/getproject'; var parameters = goog.Uri.QueryData.createFromMap({'name': name}).toString(); goog.net.XhrIo.send(requestUrl, goog.partial(function(userId, e) { var xhr = e.target; if (xhr.isSuccess()) { var jsonObj = this.getResponseJson(); jsonObj['userId'] = userId; jsonObj['name'] = name; sendResponse({'jsonObj': jsonObj, 'location': 'web'}); } else { sendResponse({'jsonObj': {'error': true}}); } }, userId), 'POST', parameters); }; /** * Gets project details and all its tests from cloud and updates. * @param {string} name The project name. * @param {string} data A json string version of the project details. * @param {function(Object)} sendResponse The response function. * @export */ rpf.SaveLoadManager.prototype.saveProject = function(name, data, sendResponse) { var requestUrl = this.server + rpf.SaveLoadManager.STORAGE_SERVER_PATH_ + '/saveproject'; var parameters = goog.Uri.QueryData.createFromMap({ 'name': name, 'data': data }).toString(); goog.net.XhrIo.send(requestUrl, function(e) { var xhr = e.target; if (xhr.isSuccess()) { sendResponse({'success': true}); } else { sendResponse({'success': false}); } }, 'POST', parameters); }; /** * Deletes a test from wtf. * @param {Array} jsonIds The tests ids. * @param {Function=} opt_callback The optional callback function. * @export */ rpf.SaveLoadManager.prototype.deleteTestOnWtf = function( jsonIds, opt_callback) { var callback = opt_callback || null; var parameters = goog.Uri.QueryData.createFromMap( {'ids': goog.json.serialize(jsonIds)}).toString(); var requestUrl = this.server + rpf.SaveLoadManager.STORAGE_SERVER_PATH_ + '/deletetest'; goog.net.XhrIo.send(requestUrl, function() { if (callback) { callback(); } }, 'POST', parameters); }; /** * Create a new test in the cloud. * @param {string} jsonName the test name. * @param {Object} jsonObj the test object. * @param {string=} opt_projectName The project name. * @param {Object=} opt_screens The optional screen data url. * @param {string=} opt_url The optional url. * @param {function(Object)=} opt_callback The response function. * @param {string=} opt_userLib The user library. * @export */ rpf.SaveLoadManager.prototype.createNewTestOnWeb = function( jsonName, jsonObj, opt_projectName, opt_screens, opt_url, opt_callback, opt_userLib) { var projectName = opt_projectName || rpf.SaveLoadManager.WEB_DEFAULT_PROJECT_; var url = opt_url || ''; var screens = opt_screens || ''; var requestUrl = rpf.MiscHelper.getUrl( this.server, rpf.SaveLoadManager.STORAGE_SERVER_PATH_ + '/addtest', {}); var params = { 'project': projectName, 'name': jsonName, 'url_to_test': url, 'test_flavor': 'json', 'json': goog.json.serialize(jsonObj)}; if (opt_userLib) { params['jsFiles'] = opt_userLib; } var parameters = goog.Uri.QueryData.createFromMap(params).toString(); goog.net.XhrIo.send(requestUrl, goog.bind(function(e) { var xhr = e.target; if (xhr.isSuccess()) { var idStr = xhr.getResponseText().split('=')[1]; if (opt_callback) { opt_callback({'message': rpf.StatusLogger.SAVE_SUCCESS, 'color': 'green', 'success': true}); } this.getJsonFromWTF(idStr, null); if (screens) { this.saveScreens_(idStr, screens); } } else { if (opt_callback) { opt_callback({'message': rpf.StatusLogger.SAVE_FAILED, 'color': 'red', 'success': false}); } throw new Error('Failed to create the new test. Error status: ' + xhr.getStatus()); } }, this), 'POST', parameters); }; /** * Saves the screenshots. * @param {string} idStr The test id. * @param {Object} screens The screen shots. * @private */ rpf.SaveLoadManager.prototype.saveScreens_ = function(idStr, screens) { var requestUrl = ''; var parameters = ''; requestUrl = rpf.MiscHelper.getUrl( rpf.SaveLoadManager.STEPS_DEPOSIT_SERVER_, '/requests', {}); parameters = goog.Uri.QueryData.createFromMap( {'cmd': '23', 'id': idStr, 'steps': goog.json.serialize(screens)}).toString(); goog.net.XhrIo.send(requestUrl, function() {}, 'POST', parameters); }; /** * Updates an existing test in the cloud. * @param {string} jsonName the test name. * @param {Object} jsonObj the test object. * @param {string} jsonId the test id. * @param {string=} opt_projectName The project name. * @param {Object=} opt_screens The optional screen data url object. * @param {function(Object)=} opt_callback The response function. * @param {string=} opt_userLib The user library. * @export */ rpf.SaveLoadManager.prototype.updateTestOnWeb = function( jsonName, jsonObj, jsonId, opt_projectName, opt_screens, opt_callback, opt_userLib) { var projectName = opt_projectName || rpf.SaveLoadManager.WEB_DEFAULT_PROJECT_; var screens = opt_screens || null; var requestUrl = rpf.MiscHelper.getUrl( this.server, rpf.SaveLoadManager.STORAGE_SERVER_PATH_ + '/updatetest', {}); var params = { 'id': jsonId, 'project': projectName, 'name': jsonName, 'url_to_test': 'na', 'test_flavor': 'json', 'json': goog.json.serialize(jsonObj)}; if (opt_userLib) { params['jsFiles'] = opt_userLib; } var parameters = goog.Uri.QueryData.createFromMap(params).toString(); goog.net.XhrIo.send(requestUrl, goog.bind(function(e) { var xhr = e.target; if (xhr.isSuccess()) { if (opt_callback) { opt_callback({'message': rpf.StatusLogger.SAVE_SUCCESS, 'color': 'green', 'success': true}); } this.getJsonFromWTF(jsonId, null); } else { if (opt_callback) { opt_callback({'message': rpf.StatusLogger.SAVE_FAILED, 'color': 'red', 'success': false}); } throw new Error('Failed to update the test. Error status: ' + xhr.getStatus()); } }, this), 'POST', parameters); if (screens) { this.saveScreens_(jsonId, screens); } }; /** * Updates an existing test in the cloud. * @param {string} jsonId the test id. * @param {Function=} opt_callback The optional callback function. * @export */ rpf.SaveLoadManager.prototype.getJsonFromWTF = function(jsonId, opt_callback) { var requestUrl = rpf.MiscHelper.getUrl( this.server, rpf.SaveLoadManager.STORAGE_SERVER_PATH_ + '/gettestasjson', {'id': jsonId}); goog.net.XhrIo.send(requestUrl, goog.bind(function(e) { var xhr = e.target; if (xhr.isSuccess()) { var jsonObj = goog.json.parse(xhr.getResponseText()); var jsonObjprop = goog.json.parse(jsonObj[0].json); this.scriptMgr_.parseJsonObj(jsonObjprop); this.scriptMgr_.idOnWeb = jsonObj[0].id; var scriptInfo = { 'name': jsonObjprop['name'], 'url': jsonObjprop['url'], 'script': jsonObjprop['script'], 'datafile': jsonObjprop['datafile'], 'userlib': jsonObjprop['userlib'], 'id': jsonId, 'projectname': jsonObjprop['projectname']}; if (opt_callback) { opt_callback({'message': rpf.StatusLogger.LOAD_TEST_SUCCESS, 'color': 'green', 'success': true, 'scriptInfo': scriptInfo}); } } else { if (opt_callback) { opt_callback({'message': rpf.StatusLogger.LOAD_TEST_FAILED, 'color': 'red', 'success': false}); } } }, this)); // Saves the screenshots to server. requestUrl = rpf.MiscHelper.getUrl( rpf.SaveLoadManager.STEPS_DEPOSIT_SERVER_, '/requests', {'cmd': '24', 'id': jsonId}); var that = this; goog.net.XhrIo.send(requestUrl, function() { var jsonObj = this.getResponseJson(); that.sendMessageToConsole_( {'command': Bite.Constants.UiCmds.RESET_SCREENSHOTS, 'params': {'screenshots': jsonObj}}); }); }; /** * Creates new or updates an existing script. * @param {string} name Test name. * @param {string} url Test start url. * @param {string} script Test script. * @param {string} datafile Test datafile. * @param {string} userLib User's own lib for the project. * @param {string} projectName Project name. * @param {Object} screenshots The img data url. * @param {string} scriptId The script id. * @param {function(Object)} sendResponse The response function. * @export */ rpf.SaveLoadManager.prototype.updateOnWeb = function( name, url, script, datafile, userLib, projectName, screenshots, scriptId, sendResponse) { // Tests are saved as new all the time, if recorded not from rpf Console UI. if (scriptId) { this.updateTestOnWeb( name, this.scriptMgr_.createJsonObj( name, url, script, datafile, '', projectName), this.scriptMgr_.idOnWeb, projectName, screenshots, sendResponse, userLib); } else { this.createNewTestOnWeb( name, this.scriptMgr_.createJsonObj( name, url, script, datafile, '', projectName), projectName, screenshots, url, sendResponse, userLib); } }; /** * Gets all the local projects. Returns a map of project names to project * objects. If the input project name is not already in the map, adds it. * @param {string} projectName The project name. If no project exists, then * creates one. * @return {Object} The projects object. * @private */ rpf.SaveLoadManager.prototype.getAllLocalProjects_ = function(projectName) { var allEntries = {}; if (goog.global.localStorage[rpf.SaveLoadManager.LOCAL_STORAGE_NAME_]) { allEntries = goog.json.parse( goog.global.localStorage[rpf.SaveLoadManager.LOCAL_STORAGE_NAME_]); } if (!allEntries[projectName]) { allEntries[projectName] = {'project_details': {}, 'tests': {}}; } return allEntries; }; /** * Saves the test in JSON format locally. * The local storage has the following format: * 'rpfscripts': {projectName: { project_details: {...}, * tests: {...}}} * * @param {string} jsonName the test name. * @param {Object} jsonObj the test object. * @param {string} projectName The project name. * @param {function({message: string, color: string})} callback * The callback to update status. * @param {string} userLib The user lib string. * @export */ rpf.SaveLoadManager.prototype.saveJsonLocally = function( jsonName, jsonObj, projectName, callback, userLib) { try { var allEntries = this.getAllLocalProjects_(projectName); allEntries[projectName]['tests'][jsonName] = jsonObj; this.updateLocalProjectDetails_( allEntries[projectName], {'js_files': userLib, 'name': projectName}); goog.global.localStorage[rpf.SaveLoadManager.LOCAL_STORAGE_NAME_] = goog.json.serialize(allEntries); callback({'message': rpf.StatusLogger.SAVE_SUCCESS, 'color': 'green', 'success': true}); this.getJsonLocally(jsonName, projectName, goog.nullFunction); } catch (e) { callback({'message': rpf.StatusLogger.SAVE_FAILED, 'color': 'red', 'success': false}); } }; /** * Updates the local project's details property. * @param {Object} project The local project. * @param {Object} details The details object. * @private */ rpf.SaveLoadManager.prototype.updateLocalProjectDetails_ = function( project, details) { if (!project['project_details']) { project['project_details'] = {}; } if (!project['project_details']['page_map']) { project['project_details']['page_map'] = {}; } if (!project['project_details']['java_package_path']) { project['project_details']['java_package_path'] = ''; } for (var key in details) { // js_files is in the format of JSON string, need to parse it first. if (key == 'js_files') { project['project_details'][key] = goog.json.parse(details[key]); } else { project['project_details'][key] = details[key]; } } }; /** * Loads the project data model from user's local server. * @param {string} path The path where the data.rpf is stored. * @param {function(Object)} callback The callback function after the data * is fetched from local server. */ rpf.SaveLoadManager.prototype.loadProjectFromLocalServer = function( path, callback) { var requestUrl = rpf.MiscHelper.getUrl( 'http://localhost:7171', '', {'command': 'getDatafile', 'datafilePath': path.split('.').join('/'), 'fileName': 'data.rpf'}); goog.net.XhrIo.send(requestUrl, goog.bind(function(e) { var xhr = e.target; if (xhr.isSuccess()) { try { var project = xhr.getResponseJson(); var dataModel = new rpf.DataModel(); callback(dataModel.convertDataToRaw(project)); } catch (exception) { alert('Invalid json: ' + exception.message()); } } else { alert('Error reading the data file.'); } }, this), 'GET'); }; /** * Gets the specified project from localStorage. * @param {string} name The project name. * @param {string} userId A string representation of the current user. * @param {function(Object)} sendResponse The response function. */ rpf.SaveLoadManager.prototype.getLocalProject = function( name, userId, sendResponse) { var allEntries = {}; var names = []; if (goog.global.localStorage[rpf.SaveLoadManager.LOCAL_STORAGE_NAME_]) { allEntries = goog.json.parse( goog.global.localStorage[rpf.SaveLoadManager.LOCAL_STORAGE_NAME_]); } var project = allEntries[name]; if (!project) { sendResponse({'jsonObj': {'error': true}}); return; } project['userId'] = userId; var tests = project['tests']; var testMetaArr = []; for (var test in tests) { testMetaArr.push({ 'test_name': test, 'test': tests[test]}); } project['tests'] = testMetaArr; project['name'] = name; sendResponse({'jsonObj': project, 'location': 'local'}); }; /** * Saves the meta data from the export dialog to localStorage. * @param {string} name The project name. * @param {string} data A json string version of the project details. * @param {function(Object)} sendResponse The response function. */ rpf.SaveLoadManager.prototype.saveProjectMetadataLocally = function( name, data, sendResponse) { var allEntries = this.getAllLocalProjects_(name); allEntries[name]['project_details'] = goog.json.parse(data); allEntries[name]['project_details']['name'] = name; goog.global.localStorage[rpf.SaveLoadManager.LOCAL_STORAGE_NAME_] = goog.json.serialize(allEntries); sendResponse({'success': true}); }; /** * Saves the project information from localserver to * localStorage including the tests and project details. * @param {function(Object.<string, string>)} callback The callback function. * @param {Object} project The project information object. */ rpf.SaveLoadManager.prototype.saveProjectLocally = function( callback, project) { var projectName = project['name']; var tests = project['tests']; var details = project['project_details']; try { var allEntries = this.getAllLocalProjects_(projectName); // Overwrites all of the tests of the project locally. if (details) { allEntries[projectName]['project_details'] = details; } allEntries[projectName]['tests'] = {}; for (var i = 0, len = tests.length; i < len; ++i) { var testObj = bite.base.Helper.getTestObject(tests[i]['test']); var testName = testObj['name']; allEntries[projectName]['tests'][testName] = this.scriptMgr_.createJsonObj(testName, testObj['url'], testObj['script'], testObj['datafile'], testObj['userlib'], testObj['projectname'], []); } goog.global.localStorage[rpf.SaveLoadManager.LOCAL_STORAGE_NAME_] = goog.json.serialize(allEntries); callback({'message': 'Saved the project to localStorage successfully.', 'color': 'green', 'project': projectName}); } catch (exception) { callback({'message': 'Failed to save the project to localStorage.', 'color': 'red'}); } this.eventMgrListener_( {'command': Bite.Constants.CONSOLE_CMDS.EVENT_COMPLETED, 'params': {'eventType': Bite.Constants.COMPLETED_EVENT_TYPES.PROJECT_SAVED_LOCALLY}}, {}, goog.nullFunction); }; /** * Sends an update message to the console with the specified test. * @param {string} testName the test name. * @param {string} projectName The project name. * @param {function({message: string, color: string})} callback * The callback function to update the status on console. * @export */ rpf.SaveLoadManager.prototype.getJsonLocally = function( testName, projectName, callback) { try { var allEntries = goog.json.parse( goog.global.localStorage[rpf.SaveLoadManager.LOCAL_STORAGE_NAME_]); var jsonTestObject = allEntries[projectName]['tests'][testName]; this.scriptMgr_.parseJsonObj(jsonTestObject); // TODO(phu): Implement idOnWeb related part. this.scriptMgr_.idOnWeb = ''; var scriptInfo = { 'name': jsonTestObject['name'], 'url': jsonTestObject['url'], 'script': jsonTestObject['script'], 'datafile': jsonTestObject['datafile'], 'userlib': jsonTestObject['userlib'], 'projectname': projectName}; callback({'message': rpf.StatusLogger.LOAD_TEST_SUCCESS, 'color': 'green', 'success': true, 'scriptInfo': scriptInfo}); } catch (e) { callback({'message': rpf.StatusLogger.LOAD_TEST_FAILED, 'color': 'red', 'success': false}); } }; /** * Gets all the test names locally. * @param {string} projectName The project name. * @return {Array} The tests of the project. * @export */ rpf.SaveLoadManager.prototype.getTestNamesLocally = function(projectName) { var allEntries = {}; var tests = []; if (goog.global.localStorage[rpf.SaveLoadManager.LOCAL_STORAGE_NAME_]) { allEntries = goog.json.parse( goog.global.localStorage[rpf.SaveLoadManager.LOCAL_STORAGE_NAME_]); } var project = allEntries[projectName]; if (!project) { return []; } for (var entry in project['tests']) { tests.push({'test_name': entry, 'test': project['tests'][entry]}); } return tests; }; /** * Deletes a test locally. * @param {string} project The project name. * @param {Array} testNames The test names. * @param {Function=} opt_callback The optional callback function. * @export */ rpf.SaveLoadManager.prototype.deleteLocalTest = function( project, testNames, opt_callback) { var callback = opt_callback || null; var allEntries = this.getAllLocalProjects_(project); // delete all of the tests required. for (var i = 0, len = testNames.length; i < len; ++i) { delete allEntries[project]['tests'][testNames[i]]; } goog.global.localStorage.setItem( rpf.SaveLoadManager.LOCAL_STORAGE_NAME_, goog.json.serialize(allEntries)); if (callback) { callback(); } }; /** * Sends an array of file strings to server and download a zip file. * @param {Object.<string, string|Object>} files The file strings. * @param {Function} callback To open a new page and download the zip. * @export */ rpf.SaveLoadManager.prototype.saveZip = function(files, callback) { var jsonObj = { 'title': 'tests.zip', 'files': files }; var requestUrl = rpf.MiscHelper.getUrl( this.server, rpf.SaveLoadManager.STORAGE_SERVER_PATH_ + '/savezip', {}); var parameters = goog.Uri.QueryData.createFromMap( {'json': goog.json.serialize(jsonObj)}).toString(); goog.net.XhrIo.send(requestUrl, goog.bind(function(e) { var xhr = e.target; if (xhr.isSuccess()) { var key = xhr.getResponseText(); var url = rpf.MiscHelper.getUrl( this.server, rpf.SaveLoadManager.STORAGE_SERVER_PATH_ + '/getzip', {'key': key}); callback({'url': url}); } else { throw new Error('Failed to save the zip. Error status: ' + xhr.getStatus()); } }, this), 'POST', parameters); }; /** * Gets all of the project names from local. * @param {function(Object.<string, Array>)} callback * The callback function. */ rpf.SaveLoadManager.prototype.getProjectNamesFromLocal = function(callback) { var allEntries = {}; var temp = goog.global.localStorage.getItem( rpf.SaveLoadManager.LOCAL_STORAGE_NAME_); if (temp) { allEntries = goog.json.parse(temp); } var names = []; for (var project in allEntries) { names.push(project); } callback({'names': names}); }; /** * Gets all of the project names from web. * @param {function(Object.<string, Array>)} callback The callback function. */ rpf.SaveLoadManager.prototype.getProjectNamesFromWeb = function(callback) { var requestUrl = rpf.MiscHelper.getUrl( this.server, rpf.SaveLoadManager.STORAGE_SERVER_PATH_ + '/getprojectnames', {}); goog.net.XhrIo.send(requestUrl, goog.bind(function(e) { var xhr = e.target; if (xhr.isSuccess()) { var names = xhr.getResponseJson(); callback({'names': names}); } else { throw new Error('Failed to get the project names. Error status: ' + xhr.getStatus()); } }, this), 'GET'); };
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains the recording manager, * which has functions to communicate with the page under * record, for example: init page, start recording, etc.. * * @author phu@google.com (Po Hu) */ goog.provide('rpf.RecordManager'); goog.require('rpf.ScriptManager'); /** * A class for managing the recorder part of RPF. * @param {rpf.ScriptManager} scriptMgr The script manager. * @param {function()} initAllListeners To init all the listeners. * @param {function()} removeAllListeners To remove all the listeners. * @param {function()} addTestTabRemovedListener To add the test tab removed * listener. * @param {function(Object, function(*)=)} sendMessageToConsole The * function to send message to console world. * @param {function(Array, number, boolean, number, function()=)} * executeMultipleScripts The function to execute multiple scripts. * @constructor * @export */ rpf.RecordManager = function(scriptMgr, initAllListeners, removeAllListeners, addTestTabRemovedListener, sendMessageToConsole, executeMultipleScripts) { /** * The script manager. * @type {rpf.ScriptManager} * @private */ this.scriptMgr_ = scriptMgr; /** * To init all the listeners. * @type {function()} * @private */ this.initAllListeners_ = initAllListeners; /** * To remove all the listeners. * @type {function()} * @private */ this.removeAllListeners_ = removeAllListeners; /** * To add the test tab removed listener. * @type {function()} * @private */ this.addTestTabRemovedListener_ = addTestTabRemovedListener; /** * The function to send message to console world. * @type {function(Object, function(*)=)} * @private */ this.sendMessageToConsole_ = sendMessageToConsole; /** * The function to send message to console world. * @type {function(Array, number, boolean, number, function()=)} * @private */ this.executeMultipleScripts_ = executeMultipleScripts; /** * Whether the page has been initialized. * @type {boolean} * @private */ this.pageInitialized_ = false; /** * The tab id of the page under test. * @type {number} * @private */ this.testTabId_ = -1; /** * The window id of the page under test. * @type {number} * @private */ this.testWindowId_ = 0; /** * The latest recorded event type. * @type {string} * @private */ this.latestEvent_ = ''; /** * Whether it is recording. * @type {boolean} * @private */ this.isRecording_ = false; /** * The recording mode. * @type {string} * @private */ this.recordingMode_ = ''; /** * The recording info. * @type {Object} * @private */ this.recordingInfo_ = {}; }; /** * @const The user action related JS lib. * @type {string} * @private */ rpf.RecordManager.GET_ACTION_INFO_JS_ = 'getactioninfo_script.js'; /** * @const The element's descriptive info related JS lib. * @type {string} * @export */ rpf.RecordManager.ELEMENT_HELPER = 'elementhelper_script.js'; /** * Starts recording. * @param {Object=} opt_info The optional recording config info. * @param {number=} opt_tabId The tab id. * @param {number=} opt_windowId The window id. * @return {boolean} Whether it successfully started recording. */ rpf.RecordManager.prototype.startRecording = function( opt_info, opt_tabId, opt_windowId) { var info = opt_info || {}; if (opt_tabId && opt_windowId) { this.setRecordingTab(opt_tabId, opt_windowId); } this.startRecording_(info); return true; }; /** * Callback after checking whether the tab under record exists. * @param {Function} callback The callback function. * @param {Object} injectedTabs The injected tabs. * @param {Tab} tab The tab. * @private */ rpf.RecordManager.prototype.checkTestTabExistsCallback_ = function( callback, injectedTabs, tab) { var result = {}; if (!tab) { result['success'] = false; result['message'] = 'The tab under record is missing.' + 'Please set a new one first.'; } else { if (injectedTabs[tab.id]) { result['success'] = true; result['url'] = tab.url; this.scriptMgr_.startUrl = tab.url; } else { result['success'] = false; result['message'] = 'Your tab under record is not ready.' + 'Please refresh the tab.'; } } callback(result); }; /** * Checks whether the tab under record exists. * @param {Function} callback The callback function. * @param {Object} tabs The tabs that have injection. */ rpf.RecordManager.prototype.checkTestTabExists = function(callback, tabs) { chrome.tabs.get( this.testTabId_, goog.bind(this.checkTestTabExistsCallback_, this, callback, tabs)); }; /** * Starts recording. * @param {Object} info The recording config info. * @private */ rpf.RecordManager.prototype.startRecording_ = function(info) { this.recordingMode_ = 'rpf'; this.recordingInfo_ = info; this.initAllListeners_(); this.isRecording_ = true; this.recordingIconOn_(); this.highlightRecordTab(); this.executePageInit(goog.bind(this.startRecordingInPage, this)); }; /** * Enum for commands will be run in page. * @enum {string} * @export */ rpf.RecordManager.CmdCode = { CLEAR: 'recordHelper.stopRecording();', BLOCK_MODE: 'recordHelper.validator_.setWaitBlockElemMode();', ELEMS_IN_BLOCK_MODE: 'recordHelper.validator_.setWaitElemsInBlockMode();', CLEAR_BLOCK_MODE: 'recordHelper.validator_.clearBlockMode();', START: 'recordHelper.startRecording();' }; /** * Clears the listeners inside the page under test. * @param {rpf.RecordManager.CmdCode|string} cmd * The command that will be run in page. * @param {boolean=} opt_allFrame Whether to execute the command in all frames. * @export */ rpf.RecordManager.prototype.runCode = function(cmd, opt_allFrame) { var allFrame = opt_allFrame || false; var wrappedCmd = 'try {' + cmd + '} catch(e) {console.log("The cmd was not found.")}'; chrome.tabs.executeScript( this.testTabId_, {code: wrappedCmd, allFrames: allFrame}); }; /** * Stops recording. * @export */ rpf.RecordManager.prototype.stopRecording = function() { this.recordingIconOff_(); this.isRecording_ = false; this.removeAllListeners_(); if (this.testTabId_ > 0) { chrome.tabs.sendRequest( this.testTabId_, {recordAction: Bite.Constants.RECORD_ACTION.STOP_RECORDING, params: {}}); } }; /** * Change the tab's extension icon to indicate that the tab is being * recorded. * @private */ rpf.RecordManager.prototype.recordingIconOn_ = function() { var iconDetails = { 'path': 'imgs/bite_logo_recording_19.png', 'tabId': this.testTabId_}; chrome.browserAction.setIcon(iconDetails); var tooltipDetails = { 'title': 'BITE: Recording', 'tabId': this.testTabId_}; chrome.browserAction.setTitle(tooltipDetails); }; /** * Change the tab's extension icon back to normal. * @private */ rpf.RecordManager.prototype.recordingIconOff_ = function() { var iconDetails = { 'path': 'imgs/bite_logo_19.png', 'tabId': this.testTabId_}; chrome.browserAction.setIcon(iconDetails); var tooltipDetails = { 'title': 'BITE', 'tabId': this.testTabId_}; chrome.browserAction.setTitle(tooltipDetails); }; /** * Sets the tab and window ids of the page under test. * @param {number=} opt_tabId The sender tab id. * @param {number=} opt_windowId The sender window id. * @export */ rpf.RecordManager.prototype.setRecordingTab = function( opt_tabId, opt_windowId) { if (opt_tabId && opt_windowId) { this.setStatusBeforeRecording_(opt_tabId, opt_windowId); } else { chrome.tabs.getSelected( null, goog.bind(this.callbackSetRecordingTab_, this)); } }; /** * Sets the tab and window ids. * @param {Object} tab Chrome tab object. * @private */ rpf.RecordManager.prototype.callbackSetRecordingTab_ = function(tab) { this.setStatusBeforeRecording_(tab.id, tab.windowId); }; /** * Sets status and to prepare recording. * @param {number} tabId The sender tab id. * @param {number} windowId The sender window id. * @private */ rpf.RecordManager.prototype.setStatusBeforeRecording_ = function( tabId, windowId) { this.testTabId_ = tabId; this.testWindowId_ = windowId; this.addTestTabRemovedListener_(); }; /** * Brings the tab under record foreground. * @param {(function ((Tab|null)): undefined|undefined)} opt_callback * An optional callback function. * @export */ rpf.RecordManager.prototype.highlightRecordTab = function(opt_callback) { var callback = opt_callback || undefined; chrome.tabs.update(this.testTabId_, { selected: true }, callback); chrome.windows.update(this.testWindowId_, { focused: true }, callback); }; /** * Enters updater mode. * @export */ rpf.RecordManager.prototype.enterUpdaterMode = function() { this.recordingMode_ = 'updater'; this.highlightRecordTab(); chrome.tabs.executeScript(this.testTabId_, {code: 'recordHelper.enterUpdaterMode();'}); }; /** * Ends updater mode. * @export */ rpf.RecordManager.prototype.endUpdaterMode = function() { chrome.tabs.executeScript(this.testTabId_, {code: 'recordHelper.endUpdaterMode();'}); }; /** * Tests a locator. * @param {Array} locators The locator array. * @param {function(Object)} callback The callback function. * @export */ rpf.RecordManager.prototype.testLocator = function(locators, callback) { chrome.tabs.sendRequest( this.testTabId_, {command: 'testLocator', locators: locators}, /** @type {function(*)} */ (callback)); }; /** * Tests a descriptor in the page under test. * @param {Object} descriptor A descriptor object for an element. * @private */ rpf.RecordManager.prototype.testDescriptor_ = function(descriptor) { this.highlightRecordTab(); chrome.tabs.executeScript(this.testTabId_, {code: 'recordHelper.outlineElems_(' + descriptor + ');'}); }; /** * Tests a descriptor in the page under test. * @param {Object} descriptor A descriptor object for an element. * @export */ rpf.RecordManager.prototype.testDescriptor = function(descriptor) { var descStr = JSON.stringify(descriptor); console.log('Test descriptor in page!'); this.executePageInit(goog.bind(this.testDescriptor_, this, descStr)); }; /** * Tests block validation in the page under test. * @param {Object} blockObj An object of block info. * @export */ rpf.RecordManager.prototype.testBlockValidation = function(blockObj) { var blockStr = JSON.stringify(blockObj); chrome.tabs.sendRequest( this.testTabId_, {command: 'testValidateBlock', descriptor: blockStr}, function(response) { if (response.result != Bite.Constants.WorkerResults.PASS) { console.log('Testing Error:' + response.result); } }); }; /** * Gets the root array. * @return {Array} The root element array. * @private */ rpf.RecordManager.prototype.getRoots_ = function() { var results = []; if (this.recordingInfo_ && this.recordingInfo_['pageMap']) { var pageMap = this.recordingInfo_['pageMap']; if (typeof pageMap == 'string') { pageMap = goog.json.parse(pageMap); } for (var item in pageMap) { results.push( {'xpath': item, 'className': pageMap[item]}); } } return results; }; /** * Starts recording in content script. * @export */ rpf.RecordManager.prototype.startRecordingInPage = function() { if (this.recordingMode_ == 'updater') { this.enterUpdaterMode(); } else { var roots = this.getRoots_(); chrome.tabs.sendRequest( this.testTabId_, {recordAction: Bite.Constants.RECORD_ACTION.START_RECORDING, params: {'rootArr': roots, 'xpathFinderOn': this.recordingInfo_['xpathFinderOn']}}); } }; /** * Executes three content scripts to initialize recording on a page. * @param {function()=} opt_callback An optional callback function. * @export */ rpf.RecordManager.prototype.executePageInit = function(opt_callback) { if (this.pageInitialized_) { this.pageInitialized_ = false; this.runCode(rpf.RecordManager.CmdCode.CLEAR, true); } this.pageInitialized_ = true; if (opt_callback) { opt_callback(); } }; /** * @return {boolean} Whether is recording. * @export */ rpf.RecordManager.prototype.isRecording = function() { return this.isRecording_; }; /** * @return {number} The tab id of the page under test. * @export */ rpf.RecordManager.prototype.getTestTabId = function() { return this.testTabId_; }; /** * @param {number} tabId The tab id of the page under test. * @export */ rpf.RecordManager.prototype.setTestTabId = function(tabId) { this.testTabId_ = tabId; }; /** * @return {number} The tab id of the page under test. * @export */ rpf.RecordManager.prototype.getTestWindowId = function() { return this.testWindowId_; }; /** * @param {number} windowId The tab id of the page under test. * @export */ rpf.RecordManager.prototype.setTestWindowId = function(windowId) { this.testWindowId_ = windowId; };
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains the events manager, which * has all the events related functions. * * @author phu@google.com (Po Hu) */ goog.provide('rpf.EventsManager'); goog.require('Bite.Constants'); goog.require('goog.json'); goog.require('goog.string'); goog.require('rpf.Automator'); goog.require('rpf.CodeGenerator'); goog.require('rpf.MiscHelper'); goog.require('rpf.PlayBackManager'); goog.require('rpf.RecordManager'); goog.require('rpf.SaveLoadManager'); goog.require('rpf.ScriptManager'); goog.require('rpf.WorkerManager'); /** * A class for managing all the events. * * @constructor * @export */ rpf.EventsManager = function() { /** * The latest created window id. * @type {number} * @private */ this.latestCreatedWinId_ = 0; /** * @type {rpf.ScriptManager} * @private */ this.scriptMgr_ = new rpf.ScriptManager(); /** * @type {rpf.CodeGenerator} * @private */ this.codeGen_ = new rpf.CodeGenerator(); /** * @type {rpf.SaveLoadManager} * @private */ this.saveLoadMgr_ = null; /** * The callback function for receiving an action event. * @type {Function} * @private */ this.onReceiveActionCallback_ = null; /** * The rpf console's tab id. * @type {number} * @private */ this.consoleTabId_ = -1; /** * The content script sender tab id. * @type {number} * @private */ this.senderTabId_ = 0; /** * The user id. * @type {string} * @private */ this.userId_ = ''; /** * The latest time stamp that an enter was recorded. * @type {number} * @private */ this.latestEnterTime_ = 0; /** * The map of the tabs that have content script injected. * @type {Object} * @private */ this.injectedTabs_ = {}; /** * Logger for logging. * @type {rpf.ConsoleLogger} * @private */ this.logger_ = rpf.ConsoleLogger.getInstance(); /** * The rpf automator which automates rpf actions. * @type {rpf.Automator} * @private */ this.automator_ = null; /** * The rpf automator for worker manager which automates rpf actions. * @type {rpf.Automator} * @private */ this.workerAutomator_ = null; /** * The manager for running multiple tests. * @type {rpf.WorkerManager} * @private */ this.workerMgr_ = null; //These are necessary because goog.bind() returns a different // function each time. As a result, when you try to do // chrome.extension.onRequest.removeListener() (or something // similar), the listener won't be removed. These variables // ensure we only have one copy of each bound function. // // TODO(michaelwill): This should probably be refactored // to make it a little less tedious. e.g. using a map of // functions might be better. this.boundOnRequestFunc = goog.bind(this.callBackOnRequest, this); this.boundOnMessageFunc = goog.bind(this.callBackOnMessageReceived, this); this.boundTabUpdatedFunc = goog.bind(this.callBackTabUpdated_, this); this.boundOnWindowCreatedFunc = goog.bind( this.callBackWindowCreated_, this); this.boundAddTestTabRemovedFunc = goog.bind( this.callBackAddTestTabRemoved, this); /** * @type {rpf.PlayBackManager} * @private */ this.playbackMgr_ = new rpf.PlayBackManager( this.scriptMgr_, rpf.EventsManager.isLoadingReadyForPlayback, goog.bind(this.removeTabUpdatedListener, this), goog.bind(this.addTabUpdatedListener, this), this.logger_, goog.bind(this.sendMessageToConsole_, this), this.boundOnMessageFunc); /** * @type {rpf.RecordManager} * @private */ this.recordMgr_ = new rpf.RecordManager( this.scriptMgr_, goog.bind(this.initAllRecordListeners, this), goog.bind(this.removeAllListeners, this), goog.bind(this.addTestTabRemovedListener, this), goog.bind(this.sendMessageToConsole_, this), goog.bind(this.executeMultipleScripts, this)); this.refresh(); this.registerOneClickToRun_(); chrome.extension.onRequest.addListener(this.boundOnMessageFunc); chrome.extension.onRequest.addListener(this.boundOnRequestFunc); }; goog.addSingletonGetter(rpf.EventsManager); /** * Whether loading is ready for recording. * @type {boolean} * @private */ rpf.EventsManager.loadingReadyForRecord_ = false; /** * The default URL of the tab under record. * @type {string} * @private */ rpf.EventsManager.defaultRecordUrl_ = 'http://www.google.com'; /** * @return {boolean} Whether loading is ready for recording. * @export */ rpf.EventsManager.isLoadingReadyForRecord = function() { return rpf.EventsManager.loadingReadyForRecord_; }; /** * Whether takes screnshots or not. * @type {boolean} * @private */ rpf.EventsManager.isTakingScreenshots_ = true; /** * Whether loading is ready for playback. * @type {boolean} * @private */ rpf.EventsManager.loadingReadyForPlayback_ = false; /** * @return {boolean} Whether loading is ready for playback. * @export */ rpf.EventsManager.isLoadingReadyForPlayback = function() { return rpf.EventsManager.loadingReadyForPlayback_; }; /** * Enum for tab change status. * @enum {string} * @private */ rpf.EventsManager.TabStatus_ = { LOADING: 'loading', COMPLETE: 'complete' }; /** * Refreshes the components that need refreshes. * @export */ rpf.EventsManager.prototype.refresh = function() { this.scriptMgr_ = new rpf.ScriptManager(); this.logger_.clearLogs(); this.saveLoadMgr_ = new rpf.SaveLoadManager( this.scriptMgr_, goog.bind(this.sendMessageToConsole_, this), this.boundOnMessageFunc); }; /** * Gets the recorder. * @return {rpf.RecordManager} The recording manager. */ rpf.EventsManager.prototype.getRecorder = function() { return this.recordMgr_; }; /** * Tests the UI automation. */ rpf.EventsManager.prototype.testAutomation = function() { this.sendMessageToConsole_( {'command': Bite.Constants.UiCmds.START_RECORDING, 'params': {}}); }; /** * Adds listener for one click to run feature. * @private */ rpf.EventsManager.prototype.registerOneClickToRun_ = function() { chrome.tabs.onUpdated.addListener( goog.bind(this.onUpdateHandler_, this)); }; /** * Executes multiple scripts in sequence. * @param {Array} scriptsAry The scripts Array. * @param {number} index The current index. * @param {boolean} allFrame Whether executes in all frames. * @param {number} tabId The tab id. * @param {function()=} opt_callback The optional callback function. * @export */ rpf.EventsManager.prototype.executeMultipleScripts = function( scriptsAry, index, allFrame, tabId, opt_callback) { if (index < scriptsAry.length) { chrome.tabs.executeScript( tabId, {file: scriptsAry[index], allFrames: allFrame}, goog.bind( this.executeMultipleScripts, this, scriptsAry, ++index, allFrame, tabId, opt_callback)); } else { if (opt_callback) { opt_callback.apply(null); } } }; /** * The tabs onupdated handler. * @param {number} tabId The tab id. * @param {{status: string, url: string, pinned: boolean}} * changeInfo The changeinfo object. * @param {Tab} tab The updated tab. * @private */ rpf.EventsManager.prototype.onUpdateHandler_ = function( tabId, changeInfo, tab) { if (!changeInfo['url']) { return; } var uri = new goog.Uri(changeInfo['url']); if (uri.getDomain() == Bite.Constants.SUITE_EXECUTOR_URL && uri.getPath() == Bite.Constants.CLICK_LINK_TO_RUN_HANDLER) { var testId = uri.getParameterValue('testId'); // TODO(phu): Uses the rpfautomator to handle the auto run. } }; /** * Sets up the common functions. * @param {function(Object, Object, function(Object))} rpfListener * The listener in rpf.js. * @export */ rpf.EventsManager.prototype.setupCommonFuncs = function(rpfListener) { this.automator_ = new rpf.Automator( goog.bind(this.sendMessageToConsole_, this), this.boundOnMessageFunc, rpfListener); this.workerAutomator_ = new rpf.Automator( goog.bind(this.sendMessageToConsole_, this), this.boundOnMessageFunc, rpfListener); this.workerMgr_ = new rpf.WorkerManager( this.playbackMgr_, this.workerAutomator_, this.logger_, this.boundOnMessageFunc, goog.bind(this.sendMessageToConsole_, this)); }; /** * Inits all the listeners. * @export */ rpf.EventsManager.prototype.initAllRecordListeners = function() { this.removeAllListeners(); this.addTabUpdatedListener(); }; /** * Adds tabUpdated listener. * @export */ rpf.EventsManager.prototype.addTabUpdatedListener = function() { this.removeTabUpdatedListener(); chrome.tabs.onUpdated.addListener(this.boundTabUpdatedFunc); }; /** * Removes TabUpdated listener. * @export */ rpf.EventsManager.prototype.removeTabUpdatedListener = function() { chrome.tabs.onUpdated.removeListener(this.boundTabUpdatedFunc); }; /** * Removes all the listeners. * @export */ rpf.EventsManager.prototype.removeAllListeners = function() { this.removeTabUpdatedListener(); }; /** * Adds the onWindowCreated listener. * @export */ rpf.EventsManager.prototype.addOnWindowCreatedListener = function() { this.removeOnCreatedListener(); chrome.windows.onCreated.addListener(this.boundOnWindowCreatedFunc); }; /** * Removes the onCreated listener. * @export */ rpf.EventsManager.prototype.removeOnCreatedListener = function() { chrome.windows.onCreated.removeListener(this.boundOnWindowCreatedFunc); }; /** * Adds the tabRemoved listener. * @export */ rpf.EventsManager.prototype.addTestTabRemovedListener = function() { chrome.tabs.onRemoved.removeListener(this.boundAddTestTabRemovedFunc); chrome.tabs.onRemoved.addListener(this.boundAddTestTabRemovedFunc); }; /** * Callback after a tab updated. * @param {number} tabId The tab id. * @param {{status: string, url: string, pinned: boolean}} * changeInfo The tab change object. * @param {Tab} tab The tab object. * @private */ rpf.EventsManager.prototype.callBackTabUpdated_ = function(tabId, changeInfo, tab) { if (tabId == this.recordMgr_.getTestTabId() && this.recordMgr_.isRecording()) { if (changeInfo['status'] == rpf.EventsManager.TabStatus_.LOADING) { rpf.EventsManager.loadingReadyForRecord_ = true; console.log('Caught the url is changing to:' + changeInfo['url']); if (changeInfo['url'] && this.recordMgr_.latestEvent && ( this.recordMgr_.latestEvent == 'click' || this.recordMgr_.latestEvent == 'change' || this.recordMgr_.latestEvent == 'type' || this.recordMgr_.latestEvent == 'submit')) { goog.Timer.callOnce( goog.bind(function() { this.writeUrlChangeToConsole( rpf.CodeGenerator.getRedirectUrl(changeInfo['url'])); }, this), 400); } } if (rpf.EventsManager.loadingReadyForRecord_ && changeInfo['status'] == rpf.EventsManager.TabStatus_.COMPLETE) { console.log('Caught the url is changed.'); this.recordMgr_.pageInitialized = false; this.recordMgr_.executePageInit( goog.bind(this.recordMgr_.startRecordingInPage, this.recordMgr_)); rpf.EventsManager.loadingReadyForRecord_ = false; } } if (tabId == this.playbackMgr_.getPlaybackTabId()) { if (changeInfo['status'] == rpf.EventsManager.TabStatus_.LOADING) { rpf.EventsManager.loadingReadyForPlayback_ = true; console.log('caught an event of replay tab is changing to:' + changeInfo['url']); return; } if (rpf.EventsManager.loadingReadyForPlayback_ && changeInfo['status'] == rpf.EventsManager.TabStatus_.COMPLETE) { console.log('caught an event of replay tab is changed.'); this.playbackMgr_.initReplayPage( this.playbackMgr_.callBackAfterTabUpdated); if (this.playbackMgr_.isReplayTabReady()) { console.log('Currently only the first url change is counted.'); } rpf.EventsManager.loadingReadyForPlayback_ = false; return; } } }; /** * Sets whether to take screenshots. * @param {boolean} takes Whether or not to take. * @export */ rpf.EventsManager.prototype.setTakeScreenshot = function(takes) { rpf.EventsManager.isTakingScreenshots_ = takes; }; /** * Callback after a window is created. * @param {Window} win The window object. * @private */ rpf.EventsManager.prototype.callBackWindowCreated_ = function(win) { console.log('A new window was created with winId:' + win['id']); this.latestCreatedWinId_ = win['id']; }; /** * Gets the latest created window id. * @return {number} The latest created windows id. * @export */ rpf.EventsManager.prototype.getLatestCreatedWinId = function() { return this.latestCreatedWinId_; }; /** * Enum for received results types. * @enum {string} * @private */ rpf.EventsManager.ResultTypes_ = { PASS: 'passed', ERROR: 'Error: ', FAILED: 'failed' }; /** * Enum for received commands. * @enum {string} * @private */ rpf.EventsManager.CmdTypes_ = { GET_ACTION_INFO: 'GetActionInfo', LOG: 'log', INIT_READY: 'initReady', CMD_DONE: 'cmdDone', ACTIVATE_VALIDATION: 'activateValidation', BLOCK_VALIDATE: 'blockValidate', MATCH_HTML: 'setLastMatchHtml', KEY_DOWN: 'catchKeyDown', KEY_UP: 'catchKeyUp' }; /** * A mock function to send message to the console event handler. * This is used for calls from background world to console world. * @param {Object} request The request object. * @param {function(*)=} opt_callback The callback function. * @private */ rpf.EventsManager.prototype.sendMessageToConsole_ = function( request, opt_callback) { chrome.tabs.sendRequest(this.consoleTabId_, request, opt_callback); }; /** * Sends a message to console UI to stop recording. */ rpf.EventsManager.prototype.stopRecordingFromUi = function() { chrome.tabs.sendRequest( this.consoleTabId_, {'command': Bite.Constants.UiCmds.STOP_RECORDING, 'params': {}}); }; /** * Sends message to the content script. * @param {Object} request The request object. * @param {function(*)=} opt_callback The callback function. * @private */ rpf.EventsManager.prototype.sendMessageToContent_ = function( request, opt_callback) { chrome.tabs.sendRequest(this.senderTabId_, request, opt_callback); }; /** * Writes a command to console. * @param {Array} selectors The element css selectors. * @param {string} content The input content. * @param {rpf.CodeGenerator.DomTags} nodeType The nodetype of the element. * @param {rpf.CodeGenerator.RecordActions} action The user's action. * @param {string} descriptor The descriptive info of the element. * @param {string} elemVarName The variable name of the element. * @param {number=} opt_index The command's index string. * @param {Object=} opt_iframeInfo The iframe info where the element was from. * @param {Array=} opt_xpaths The optional xpath array. * @param {string=} opt_mode The optional mode string. * @param {string=} opt_className The class name for the action. * @export */ rpf.EventsManager.prototype.writeUserActionToConsole = function( selectors, content, nodeType, action, descriptor, elemVarName, opt_index, opt_iframeInfo, opt_xpaths, opt_mode, opt_className) { var cmdInfo = this.codeGen_.generateScriptAndDataFileForCmd( selectors, content, nodeType, action, descriptor, elemVarName, opt_iframeInfo, opt_xpaths, opt_className); if (action == rpf.CodeGenerator.RecordActions.VERIFY && opt_mode == 'updater') { if (this.onReceiveActionCallback_) { this.onReceiveActionCallback_({ 'cmd': cmdInfo['cmd'], 'data': cmdInfo['data'], 'index': opt_index, 'cmdMap': cmdInfo['cmdMap']}); } this.onReceiveActionCallback_ = null; } else { this.sendMessageToConsole_( {'command': Bite.Constants.UiCmds.ADD_GENERATED_CMD, 'params': {'cmd': cmdInfo['cmd']}}); var translation = ''; try { translation = this.codeGen_.translateCmd( cmdInfo['cmd'], cmdInfo['data'], goog.json.parse(descriptor)); } catch (e) { console.log('The translation process failed.. ' + e.message); } this.writeACmdToConsole(cmdInfo['cmd'], cmdInfo['data'], opt_index, cmdInfo['cmdMap'], translation); } }; /** * Writes a url change to console. * @param {string} pCmd The generated command. * @export */ rpf.EventsManager.prototype.writeUrlChangeToConsole = function(pCmd) { this.writeACmdToConsole(pCmd + '\n'); }; /** * Writes a command to console. In case of recording started not from * rpf Console UI, it sends a command to content script. * @param {string} pCmd The generated command. * @param {string=} opt_dCmd The data file entry. * @param {number=} opt_index The command's index string. * @param {Object=} opt_cmdMap The cmd map. * @param {string=} opt_translation The plain English. */ rpf.EventsManager.prototype.writeACmdToConsole = function( pCmd, opt_dCmd, opt_index, opt_cmdMap, opt_translation) { this.sendMessageToConsole_( {'command': Bite.Constants.UiCmds.ADD_NEW_COMMAND, 'params': {'pCmd': pCmd, 'dCmd': opt_dCmd, 'cmdMap': opt_cmdMap, 'index': opt_index, 'readableCmd': opt_translation}}); }; /** * @return {rpf.PlayBackManager} The playback manager instance. * @export */ rpf.EventsManager.prototype.getPlaybackManager = function() { return this.playbackMgr_; }; /** * A mock function to send message to the callBackOnRequest handler. * This is used for calls from inside background world. * @param {Object} request The request object. * @param {function(Object)=} opt_callback The callback function. * @export */ rpf.EventsManager.prototype.sendMessage = function(request, opt_callback) { this.callBackOnMessageReceived( request, /** @type {MessageSender} */ ({}), opt_callback || goog.nullFunction); }; /** * Captures a screenshot for the visible tab. * @param {number} testWindowId The id of window under test. * @param {function(string)} callback The callback function. * @param {number=} opt_delay The optional delay time. * @export */ rpf.EventsManager.prototype.captureVisibleTab = function( testWindowId, callback, opt_delay) { var delay = opt_delay || 0; goog.Timer.callOnce( goog.partial(chrome.tabs.captureVisibleTab, testWindowId, callback), delay); }; /** * Executes a given script in page. * @param {number} id The tab id. * @param {string} script The script to be executed. * @param {boolean=} opt_allFrames Whether to run it in all of the frames. * @private */ rpf.EventsManager.prototype.executeScriptStr_ = function( id, script, opt_allFrames) { chrome.tabs.executeScript( id, {code: script, allFrames: opt_allFrames || false} ); }; /** * Generates a commmand based on the info from the page under recording. * @param {Object} request The request object. * @private */ rpf.EventsManager.prototype.generateCmdBasedOnRecording_ = function( request) { var content = request['content']; var action = request['action']; var selectors = request['selectors']; var xpaths = request['xpaths']; var iframeInfo = request['iframeInfo']; var position = request['position']; this.logger_.saveLogAndHtml('Caught an event: ' + action); if (action == 'rightclick') { if (request['mode'] == 'rpf') { this.sendMessageToConsole_( {'command': Bite.Constants.UiCmds.OPEN_VALIDATION_DIALOG, 'params': {'request': request}}); return; } else { // Rightclick corresponds to a verify command in this case. action = rpf.CodeGenerator.RecordActions.VERIFY; } } this.recordMgr_.latestEvent = action; var delayTime = 0; switch (action) { case 'enter': this.latestEnterTime_ = goog.now(); return; case 'click': delayTime = 0; //Revert to 300 if necessary. break; case 'submit': if (goog.now() - this.latestEnterTime_ > 500) { // We only record submit event if it's triggered by an enter input. return; } break; default: break; } if (rpf.EventsManager.isTakingScreenshots_) { this.captureVisibleTab( this.recordMgr_.getTestWindowId(), goog.partial( rpf.MiscHelper.resizeImage, goog.bind(this.callBackCaptureTab, this), 600, {'sX': position['x'], 'sY': position['y'], 'sWidth': position['width'], 'sHeight': position['height']}), delayTime); } goog.Timer.callOnce(goog.bind( this.writeUserActionToConsole, this, selectors, content, request['nodeType'], action, request['descriptor'], request['elemVarName'], -1, iframeInfo, xpaths, request['mode'], request['className']), delayTime); }; /** * Callback on a request received. * @param {Object} request The request object. * @param {MessageSender} sender The sender object. * @param {function(Object)} sendResponse The response object. */ rpf.EventsManager.prototype.callBackOnRequest = function( request, sender, sendResponse) { if (!request['command']) { return; } var params = request['params']; switch (request['command']) { case rpf.EventsManager.CmdTypes_.GET_ACTION_INFO: this.senderTabId_ = sender.tab.id; this.generateCmdBasedOnRecording_(request); break; case rpf.EventsManager.CmdTypes_.LOG: console.log(request['log']); break; case rpf.EventsManager.CmdTypes_.INIT_READY: console.log('Got init ready response from PageUnderPlayback.'); this.playbackMgr_.setReplayTabReady(true); // Assume this is because a following cmd is already being executing. if (!this.playbackMgr_.isPreCmdDone()) { console.log('Rerun the following cmd after another url change found.'); this.playbackMgr_.setPreCmdDone(true); } break; case rpf.EventsManager.CmdTypes_.CMD_DONE: console.log('Result:' + request['result']); if (request['index'] != this.playbackMgr_.getCurrentStep()) { console.log(' Returned step:' + request['index'] + '; Expected:' + this.playbackMgr_.getCurrentStep()); return; } var result = rpf.EventsManager.ResultTypes_.PASS; if (!goog.string.contains( request['result'], rpf.EventsManager.ResultTypes_.PASS)) { result = rpf.EventsManager.ResultTypes_.FAILED; this.playbackMgr_.setFailureLog(request['result']); } this.playbackMgr_.callBackAfterExecCmds(result, request['result']); if (request['realTimeMap']) { this.playbackMgr_.realTimeBag = request['realTimeMap']; } break; case rpf.EventsManager.CmdTypes_.BLOCK_VALIDATE: console.log('Got block: ' + request['rtnObj']); break; case rpf.EventsManager.CmdTypes_.MATCH_HTML: console.log(' *** The matching html changes to:' + request['html']); this.playbackMgr_.setLastMatchHtml(request['html']); break; case rpf.EventsManager.CmdTypes_.KEY_DOWN: console.log(' caught an keydown event!!!!' + request['keyCode']); break; case rpf.EventsManager.CmdTypes_.KEY_UP: //console.log(' caught an keyup event!!!!' + request['keyCode']); break; default: break; } }; /** * Automates RPF behaviors to simplify user's steps to update the script. * @param {Object} params The parameters map. */ rpf.EventsManager.prototype.automateRpf = function(params) { switch (params['command']) { case Bite.Constants.RPF_AUTOMATION.LOAD_AND_RUN_FROM_LOCAL: var stepArr = []; var temp = this.automator_.getStepObject( Bite.Constants.ListenerDestination.RPF, Bite.Constants.CONTROL_CMDS.CREATE_WINDOW, {'refresh': true}, Bite.Constants.COMPLETED_EVENT_TYPES.RPF_CONSOLE_OPENED); stepArr.push(temp); temp = this.automator_.getStepObject( Bite.Constants.ListenerDestination.EVENT_MANAGER, Bite.Constants.CONSOLE_CMDS.LOAD_PROJECT_FROM_LOCAL_SERVER, {'path': params['path']}, Bite.Constants.COMPLETED_EVENT_TYPES.PROJECT_SAVED_LOCALLY); stepArr.push(temp); temp = this.automator_.getStepObject( Bite.Constants.ListenerDestination.CONSOLE, Bite.Constants.UiCmds.AUTOMATE_DIALOG_LOAD_TEST, {'project': params['project'], 'test': params['testName'], 'isWeb': false}, Bite.Constants.COMPLETED_EVENT_TYPES.TEST_LOADED); stepArr.push(temp); if (params['autoPlay']) { // Automatically playback the loaded script. temp = this.automator_.getStepObject( Bite.Constants.ListenerDestination.CONSOLE, Bite.Constants.UiCmds.SHOW_PLAYBACK_RUNTIME, {}, Bite.Constants.COMPLETED_EVENT_TYPES.PLAYBACK_DIALOG_OPENED); stepArr.push(temp); temp = this.automator_.getStepObject( Bite.Constants.ListenerDestination.CONSOLE, Bite.Constants.UiCmds.SET_PLAYBACK_ALL, {}, Bite.Constants.COMPLETED_EVENT_TYPES.PLAYBACK_STARTED); stepArr.push(temp); } else { // Highlights on a step and wait for updates. temp = this.automator_.getStepObject( Bite.Constants.ListenerDestination.CONSOLE, Bite.Constants.UiCmds.HIGHLIGHT_LINE, {'testName': params['testName'], 'stepId': params['stepId']}, Bite.Constants.COMPLETED_EVENT_TYPES.HIGHLIGHTED_LINE); stepArr.push(temp); } this.automator_.start(stepArr); break; case Bite.Constants.RPF_AUTOMATION.PLAYBACK_MULTIPLE: if (params['projectName'] && params['location']) { this.startAutoPlayMultipleTests_( params['projectName'], params['location'], {}, true); } else { // Assume all of the tests are from the same project for now. // This will no longer be true once we open suite creation to users. var testInfo = {}; for (var name in params['data']) { testInfo = params['data'][name]; } testInfo = goog.json.parse(testInfo); this.startAutoPlayMultipleTests_( testInfo['projectName'], testInfo['testLocation'], params['data']); } break; case Bite.Constants.RPF_AUTOMATION.AUTOMATE_SINGLE_SCRIPT: this.automateSingleScript_( params['projectName'], params['location'], params['scriptName'], params['autoPlay']); break; } }; /** * Start the automation to load and possibly playback a script. * @param {string} project The project name. * @param {string} location Where the project comes from. * @param {string} script The script name. * @param {boolean} autoPlay Whether to auto play the script. * @private */ rpf.EventsManager.prototype.automateSingleScript_ = function( project, location, script, autoPlay) { var stepArr = []; var temp = this.automator_.getStepObject( Bite.Constants.ListenerDestination.RPF, Bite.Constants.CONTROL_CMDS.CREATE_WINDOW, {'refresh': true}, Bite.Constants.COMPLETED_EVENT_TYPES.RPF_CONSOLE_OPENED); stepArr.push(temp); temp = this.automator_.getStepObject( Bite.Constants.ListenerDestination.EVENT_MANAGER, Bite.Constants.CONSOLE_CMDS.STOP_GROUP_TESTS, {}, Bite.Constants.COMPLETED_EVENT_TYPES.STOPPED_GROUP_TESTS); stepArr.push(temp); temp = this.automator_.getStepObject( Bite.Constants.ListenerDestination.CONSOLE, Bite.Constants.UiCmds.AUTOMATE_DIALOG_LOAD_TEST, {'project': project, 'test': script, 'isWeb': location == 'web'}, Bite.Constants.COMPLETED_EVENT_TYPES.TEST_LOADED); stepArr.push(temp); if (autoPlay) { // Automatically playback the loaded script. temp = this.automator_.getStepObject( Bite.Constants.ListenerDestination.CONSOLE, Bite.Constants.UiCmds.SHOW_PLAYBACK_RUNTIME, {}, Bite.Constants.COMPLETED_EVENT_TYPES.PLAYBACK_DIALOG_OPENED); stepArr.push(temp); temp = this.automator_.getStepObject( Bite.Constants.ListenerDestination.CONSOLE, Bite.Constants.UiCmds.SET_PLAYBACK_ALL, {}, Bite.Constants.COMPLETED_EVENT_TYPES.PLAYBACK_STARTED); stepArr.push(temp); } this.automator_.start(stepArr); }; /** * Start the automation to playback multiple tests. * @param {string} project The project name. * @param {string} location Where the project comes from. * @param {Object} testInfo The tests info. * @param {boolean=} opt_runAll Whether to run all of the tests. * @private */ rpf.EventsManager.prototype.startAutoPlayMultipleTests_ = function( project, location, testInfo, opt_runAll) { var stepArr = []; var temp = this.automator_.getStepObject( Bite.Constants.ListenerDestination.RPF, Bite.Constants.CONTROL_CMDS.CREATE_WINDOW, {'refresh': true}, Bite.Constants.COMPLETED_EVENT_TYPES.RPF_CONSOLE_OPENED); stepArr.push(temp); temp = this.automator_.getStepObject( Bite.Constants.ListenerDestination.EVENT_MANAGER, Bite.Constants.CONSOLE_CMDS.STOP_GROUP_TESTS, {}, Bite.Constants.COMPLETED_EVENT_TYPES.STOPPED_GROUP_TESTS); stepArr.push(temp); temp = this.automator_.getStepObject( Bite.Constants.ListenerDestination.CONSOLE, Bite.Constants.UiCmds.AUTOMATE_DIALOG_LOAD_PROJECT, {'project': project, 'isWeb': location == 'web'}, Bite.Constants.COMPLETED_EVENT_TYPES.PROJECT_LOADED); stepArr.push(temp); temp = this.automator_.getStepObject( Bite.Constants.ListenerDestination.CONSOLE, Bite.Constants.UiCmds.AUTOMATE_PLAY_MULTIPLE_TESTS, {'testInfo': testInfo, 'runAll': opt_runAll || false}, Bite.Constants.COMPLETED_EVENT_TYPES.RUN_PLAYBACK_STARTED); stepArr.push(temp); this.automator_.start(stepArr); }; /** * Dispatches the given event. * @param {Bite.Constants.COMPLETED_EVENT_TYPES} eventType The event type. */ rpf.EventsManager.prototype.dispatchEventOnAutomator_ = function(eventType) { this.automator_.getEventTarget().dispatchEvent(eventType); this.workerAutomator_.getEventTarget().dispatchEvent(eventType); }; /** * Callback on the controlling messages received. * @param {Object} request The request object. * @param {MessageSender} sender The sender object. * @param {function(Object)} sendResponse The response function. */ rpf.EventsManager.prototype.callBackOnMessageReceived = function( request, sender, sendResponse) { if (!request['command']) { return; } var params = request['params']; switch (request['command']) { case Bite.Constants.CONSOLE_CMDS.EVENT_COMPLETED: this.dispatchEventOnAutomator_(params['eventType']); break; case Bite.Constants.CONSOLE_CMDS.AUTOMATE_RPF: this.automateRpf(params); break; case Bite.Constants.CONSOLE_CMDS.SET_CONSOLE_TAB_ID: this.setConsoleTabId(params['id']); break; case Bite.Constants.CONSOLE_CMDS.GET_LOGS_AS_STRING: sendResponse(this.logger_.getLogsAsString()); break; case Bite.Constants.CONSOLE_CMDS.SAVE_LOG_AND_HTML: this.logger_.saveLogAndHtml( params['log'], params['level'], params['color']); break; case Bite.Constants.CONSOLE_CMDS.EXECUTE_SCRIPT_IN_RECORD_PAGE: this.executeScriptStr_( this.recordMgr_.getTestTabId(), params['code'], params['allFrames']); break; case Bite.Constants.CONSOLE_CMDS.SET_PLAYBACK_INTERVAL: this.playbackMgr_.setPlaybackInterval(params['interval']); break; case Bite.Constants.CONSOLE_CMDS.SET_DEFAULT_TIMEOUT: this.playbackMgr_.setDefaultTimeout(params['time']); break; case Bite.Constants.CONSOLE_CMDS.SET_MAXIMUM_RETRY_TIME: this.playbackMgr_.setMaximumRetryTime(params['time']); break; case Bite.Constants.CONSOLE_CMDS.SET_TAKE_SCREENSHOT: this.setTakeScreenshot(params['isTaken']); break; case Bite.Constants.CONSOLE_CMDS.SET_USE_XPATH: this.playbackMgr_.setUseXpath(params['use']); break; case Bite.Constants.CONSOLE_CMDS.SAVE_PROJECT_LOCALLY: this.saveLoadMgr_.saveProjectLocally(sendResponse || goog.nullFunction, params['project']); break; case Bite.Constants.CONSOLE_CMDS.LOAD_PROJECT_FROM_LOCAL_SERVER: this.saveLoadMgr_.loadProjectFromLocalServer( params['path'], goog.bind(this.saveLoadMgr_.saveProjectLocally, this.saveLoadMgr_, sendResponse || goog.nullFunction)); break; case Bite.Constants.CONSOLE_CMDS.SAVE_JSON_LOCALLY: this.saveLoadMgr_.saveJsonLocally( params['testName'], this.scriptMgr_.createJsonObj( params['testName'], params['startUrl'], params['scripts'], params['datafile'], '', params['projectName'], []), params['projectName'], sendResponse, params['userLib']); break; case Bite.Constants.CONSOLE_CMDS.UPDATE_ON_WEB: this.saveLoadMgr_.updateOnWeb( params['testName'], params['startUrl'], params['scripts'], params['datafile'], params['userLib'], params['projectName'], params['screenshots'], params['scriptId'], sendResponse); break; case Bite.Constants.CONSOLE_CMDS.DELETE_CMD: var scriptLen = this.playbackMgr_.getScriptsLen(); this.playbackMgr_.removeStep(params['deleteLine'] - 1); sendResponse( {'needOverride': scriptLen == params['deleteLine']}); break; case Bite.Constants.CONSOLE_CMDS.GET_LAST_MATCH_HTML: sendResponse({'html': this.playbackMgr_.getLastMatchHtml()}); break; case Bite.Constants.CONSOLE_CMDS.FINISH_CURRENT_RUN: this.playbackMgr_.finishCurrentRun( params['status'], params['log']); break; case Bite.Constants.CONSOLE_CMDS.CALLBACK_AFTER_EXEC_CMDS: this.playbackMgr_.callBackAfterExecCmds( params['status']); break; case Bite.Constants.CONSOLE_CMDS.PREPARE_RECORD_PLAYBACK_PAGE: this.recordMgr_.setTestTabId(this.playbackMgr_.getPlaybackTabId()); this.recordMgr_.setTestWindowId(this.playbackMgr_.getPlaybackWindowId()); sendResponse({}); break; case Bite.Constants.CONSOLE_CMDS.USER_SET_STOP: this.playbackMgr_.userSetStop(); break; case Bite.Constants.CONSOLE_CMDS.SET_INFO_MAP_IN_PLAYBACK: this.playbackMgr_.setInfoMap(params['infoMap']); break; case Bite.Constants.CONSOLE_CMDS.USER_SET_PAUSE: this.playbackMgr_.userSetPause(); break; case Bite.Constants.CONSOLE_CMDS.FETCH_DATA_FROM_BACKGROUND: sendResponse({'userId': this.getUserId()}); break; case Bite.Constants.CONSOLE_CMDS.SET_USER_SPECIFIED_PAUSE_STEP: this.playbackMgr_.setUserSpecifiedPauseStep( params['userPauseStep']); break; case Bite.Constants.CONSOLE_CMDS.UPDATE_TEST_RESULT_ON_SERVER: this.workerMgr_.increaseFinishedTestsNum(); this.sendMessageToConsole_( {'command': Bite.Constants.UiCmds.SET_FINISHED_TESTS_NUMBER, 'params': {'num': this.workerMgr_.getFinishedTestsNum()}}); this.playbackMgr_.updateTestResultOnServer(); break; case Bite.Constants.CONSOLE_CMDS.CHECK_PLAYBACK_OPTION_AND_RUN: if (params['preparationDone']) { this.playbackMgr_.setPreparationDone(!!params['preparationDone']); } this.playbackMgr_.checkPlaybackOptionAndRun( params['method'], params['startUrl'], params['scripts'], params['datafile'], params['userLib'], params['infoMap'], params['continueOnFailure'], params['testName'], params['testId'], params['projectName'], params['testLocation']); sendResponse({'isPrepDone': this.playbackMgr_.isPreparationDone()}); break; case Bite.Constants.CONSOLE_CMDS.INSERT_CMDS_WHILE_PLAYBACK: this.playbackMgr_.insertCmdsWhilePlayback( params['scriptStr'], params['data']); break; case Bite.Constants.CONSOLE_CMDS.START_RECORDING: this.recordMgr_.startRecording(params['info']); break; case Bite.Constants.CONSOLE_CMDS.SET_TAB_AND_START_RECORDING: var started = this.recordMgr_.startRecording( null, sender.tab.id, sender.tab.windowId); if (started) { this.setConsoleTabId(sender.tab.id); } break; case Bite.Constants.CONSOLE_CMDS.SAVE_ZIP: this.saveLoadMgr_.saveZip(params['files'], sendResponse); break; case Bite.Constants.CONSOLE_CMDS.GET_JSON_LOCALLY: this.saveLoadMgr_.getJsonLocally( params['name'], params['projectName'], sendResponse); break; case Bite.Constants.CONSOLE_CMDS.GET_PROJECT_NAMES_FROM_WEB: this.saveLoadMgr_.getProjectNamesFromWeb(sendResponse); break; case Bite.Constants.CONSOLE_CMDS.GET_PROJECT_NAMES_FROM_LOCAL: this.saveLoadMgr_.getProjectNamesFromLocal(sendResponse); break; case Bite.Constants.CONSOLE_CMDS.GET_ALL_FROM_WEB: this.saveLoadMgr_.getAllFromWeb( params['project'], sendResponse); break; case Bite.Constants.CONSOLE_CMDS.GET_PROJECT: this.saveLoadMgr_.getProject(params['name'], this.userId_, sendResponse); break; case Bite.Constants.CONSOLE_CMDS.GET_LOCAL_PROJECT: this.saveLoadMgr_.getLocalProject( params['name'], this.userId_, sendResponse); break; case Bite.Constants.CONSOLE_CMDS.SAVE_PROJECT_METADATA_LOCALLY: this.saveLoadMgr_.saveProjectMetadataLocally( params['name'], params['data'], sendResponse); break; case Bite.Constants.CONSOLE_CMDS.SAVE_PROJECT: this.saveLoadMgr_.saveProject(params['name'], params['data'], sendResponse); break; case Bite.Constants.CONSOLE_CMDS.GET_TEST_NAMES_LOCALLY: sendResponse( {'name': params['project'], 'tests': this.saveLoadMgr_.getTestNamesLocally(params['project'])}); break; case Bite.Constants.CONSOLE_CMDS.TEST_DESCRIPTOR: this.recordMgr_.testDescriptor(params['descriptor']); break; case Bite.Constants.CONSOLE_CMDS.RUN_TEST: this.playbackMgr_.runTest( params['startUrl'], params['scripts'], params['datafile'], params['userLib']); break; case Bite.Constants.CONSOLE_CMDS.RUN_GROUP_TESTS: this.workerMgr_.runGroupTests(params['testNames'], params['tests'], params['runName'], params['location']); break; case Bite.Constants.CONSOLE_CMDS.STOP_GROUP_TESTS: this.workerMgr_.stopGroupTests(); this.dispatchEventOnAutomator_( Bite.Constants.COMPLETED_EVENT_TYPES.STOPPED_GROUP_TESTS); break; case Bite.Constants.CONSOLE_CMDS.GENERATE_NEW_COMMAND: var scriptInfo = this.codeGen_.generateScriptAndDataFileForCmd( params['selectors'], params['content'], params['nodeType'], params['action'], params['descriptor'], params['elemVarName'], params['iframeInfo'], params['xpaths'], params['className']); sendResponse({'scriptInfo': scriptInfo}); break; case Bite.Constants.CONSOLE_CMDS.DELETE_TEST_ON_WTF: this.saveLoadMgr_.deleteTestOnWtf(params['jsonIds'], sendResponse); break; case Bite.Constants.CONSOLE_CMDS.DELETE_TEST_LOCAL: this.saveLoadMgr_.deleteLocalTest( params['project'], params['testNames'], sendResponse); break; case Bite.Constants.CONSOLE_CMDS.GET_JSON_FROM_WTF: this.saveLoadMgr_.getJsonFromWTF(params['jsonId'], sendResponse); break; case Bite.Constants.CONSOLE_CMDS.STOP_RECORDING: this.recordMgr_.stopRecording(); break; case Bite.Constants.CONSOLE_CMDS.SET_RECORDING_TAB: this.recordMgr_.setRecordingTab(); break; case Bite.Constants.CONSOLE_CMDS.ENTER_UPDATER_MODE: this.initAllRecordListeners(); this.recordMgr_.enterUpdaterMode(); break; case Bite.Constants.CONSOLE_CMDS.SET_ACTION_CALLBACK: this.onReceiveActionCallback_ = sendResponse; break; case Bite.Constants.CONSOLE_CMDS.END_UPDATER_MODE: this.removeAllListeners(); this.recordMgr_.endUpdaterMode(); break; case Bite.Constants.CONSOLE_CMDS.RECORD_PAGE_LOADED_COMPLETE: this.setInjectedTab_(sender.tab.id); break; case Bite.Constants.CONSOLE_CMDS.TEST_LOCATOR: this.recordMgr_.testLocator(params['locators'], sendResponse); break; case Bite.Constants.CONSOLE_CMDS.START_AUTO_RECORD: goog.Timer.callOnce(goog.bind(this.testAutomation, this), 1500); break; case Bite.Constants.CONSOLE_CMDS.CHECK_READY_TO_RECORD: this.recordMgr_.checkTestTabExists(sendResponse, this.injectedTabs_); break; } }; /** * Sets the console tab id. * @param {number} id The tab id. * @private */ rpf.EventsManager.prototype.setInjectedTab_ = function(id) { if (id) { this.injectedTabs_[id] = true; } }; /** * Sets the console tab id. * @param {number} id The console's tab id. * @export */ rpf.EventsManager.prototype.setConsoleTabId = function(id) { this.consoleTabId_ = id; }; /** * Gets the console tab id. * @return {number} The console's tab id. * @export */ rpf.EventsManager.prototype.getConsoleTabId = function() { return this.consoleTabId_; }; /** * Gets the user id. * @return {string} The user id. * @export */ rpf.EventsManager.prototype.getUserId = function() { return this.userId_; }; /** * Sets the user id. * @param {string} id The user id. * @export */ rpf.EventsManager.prototype.setUserId = function(id) { this.userId_ = id; }; /** * Callback after capturing a tab screenshot. * @param {string} dataUrl The screenshot data url. * @param {string} iconUrl The icon data url. * @export */ rpf.EventsManager.prototype.callBackCaptureTab = function(dataUrl, iconUrl) { this.sendMessageToConsole_( {'command': Bite.Constants.UiCmds.ADD_SCREENSHOT, 'params': {'dataUrl': dataUrl, 'iconUrl': iconUrl}}); }; /** * Callback after the tab under record is created. * @param {Tab} tab The tab. * @private */ rpf.EventsManager.prototype.recordTabCreatedCallback_ = function(tab) { this.recordMgr_.setRecordingTab(tab.id, tab.windowId); }; /** * Creates a new tab for recording. * @private */ rpf.EventsManager.prototype.createTabUnderRecord_ = function() { chrome.tabs.create( {'url': rpf.EventsManager.defaultRecordUrl_, 'selected': true}, goog.bind(this.recordTabCreatedCallback_, this)); }; /** * Callback after the tab under test is removed. * @param {number} tabId The tab id. * @export */ rpf.EventsManager.prototype.callBackAddTestTabRemoved = function(tabId) { if (this.recordMgr_.getTestTabId() == tabId) { this.sendMessageToConsole_( {'command': Bite.Constants.UiCmds.RECORD_TAB_CLOSED, 'params': {}}); } };
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview In this file, the Record Mode Manager class is defined. * * @author alexto@google.com (Alexis O. Torres) */ goog.provide('common.client.RecordModeManager'); goog.require('common.client.MiscHelper'); goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.fx.dom'); goog.require('goog.style'); /** * Class for managing recording sessions. * * This class is used to record user interactions with the page, specifically, * MouseMove and Click events. Each time the user clicks on a element, function * provided to the {@code enterRecordingMode()} method is called back with the * last element the user moused over a a parameter. * * As an example, here is a simple use of this class that caused an alert dialog * to show up each time the user click on an element of the page: * * {@code * recordManager = new RecordModeManager(); * recordManager.enterRecordingMode(function(elmnt) { * alert('ID of the element clicked: ' + elmnt.id); * }; * } * * While in recording mode, clicking on elements of the page should not trigger * the default action associated with that element (e.g. clicking on a hyperlink * should not cause the browser to navigate to that link's URI). * * @constructor */ common.client.RecordModeManager = function() { }; /** * Whether or not the recording manager is in recording mode. * @type {boolean} * @private */ common.client.RecordModeManager.prototype.isRecording_ = false; /** * ID used for the highlight box element. * @type {string} * @private */ common.client.RecordModeManager.prototype.highlightBoxId_ = 'recordingHighlightBox'; /** * Element used as the highlight box. * @type {Element} * @private */ common.client.RecordModeManager.prototype.highlightDiv_ = null; /** * Stores the value of document.onclick before the start of the * recording session. * @type {?function(...)} The original value of * {@code goog.global.document.onclick}. * @private */ common.client.RecordModeManager.prototype.originalOnClick_ = null; /** * Stores the value of document.onmousemove before the start of the * recording session. * @type {?function(...)} The original value of * {@code goog.global.document.onmousemove}. * @private */ common.client.RecordModeManager.prototype.originalMouseMove_ = null; /** * Used to track the last element the mouse was over. * @type {Element} * @private */ common.client.RecordModeManager.prototype.currElement_ = null; /** * @return {Element} Currently selected element. * @export */ common.client.RecordModeManager.prototype.getCurrElement = function() { return this.currElement_; }; /** * Whether or not the highlight box is being animated. * @type {boolean} * @private */ common.client.RecordModeManager.prototype.isAnimating_ = false; /** * A callback handler called when a click action occurs. * The element clicked by the user is passed as an argument to the function. * @type {?function(Element)} * @private */ common.client.RecordModeManager.prototype.onClickCallback_ = null; /** * @return {boolean} Whether or not we are currently in recording mode. * @export */ common.client.RecordModeManager.prototype.isRecording = function() { return this.isRecording_; }; /** * Gets the string value used as the ID property of the highlight box. * @return {string} ID value of the highlight box. * @export */ common.client.RecordModeManager.prototype.getHighlightBoxId = function() { return this.highlightBoxId_; }; /** * Sets string used as the ID property of the the highlight box. * @param {string} newId New ID value to use for the highlight box. * @export */ common.client.RecordModeManager.prototype.setHighlightBoxId = function(newId) { this.highlightBoxId_ = newId; if (this.highlightDiv_) { this.highlightDiv_.id = newId; } }; /** * Enters recording mode. When recording, clicking on an Element, such a link * or a button, will not cause the default action to fire. Each time the use * clicks on the page, the clickOverride method is called with the element that * was clicked as an argument. * * Throws an {@code Error} if the method is called without the * {@code clickOverride} parameter, or it is called more than once before the * {@code exitRecordMode()} method is called. * @param {function(Element)} clickOverride A callback handler called * when a click action occurs. * @export */ common.client.RecordModeManager.prototype.enterRecordingMode = function(clickOverride) { if (!clickOverride) { throw new Error( 'enterRecordingMode: clickOverride parameter is required ' + 'and cannot be null.'); } if (this.isRecording_) { throw new Error( 'enterRecordingMode: cannot start another recording session. Call ' + 'exitRecordMode() before calling enterRecordingMode a second time.'); } this.isRecording_ = true; this.originalOnClick_ = goog.global.document.onclick; this.originalMouseMove_ = goog.global.document.onmousemove; this.onClickCallback_ = clickOverride; goog.global.document.onclick = goog.bind(this.clickOverride_, this); goog.global.document.onmousemove = goog.bind(this.onMouseMove_, this); common.client.MiscHelper.setCursorStyle('crosshair'); }; /** * Used to override all onclick event handling while in recording mode. * @return {boolean} Always returns false, which prevents the click event from * propagating. * @private */ common.client.RecordModeManager.prototype.clickOverride_ = function() { if (this.currElement_) { this.onClickCallback_(this.currElement_); } return false; }; /** * Used to override all onmousemove event handling while in recording mode. * @param {MouseEvent} evt MouseEvent object containing, among other things, the * source element that generated the event. * @private */ common.client.RecordModeManager.prototype.onMouseMove_ = function(evt) { if (this.highlightDiv_ && evt.srcElement == this.highlightDiv_) { goog.style.showElement(this.highlightDiv_, false); var elementUnderMouse = goog.dom.getDocument().elementFromPoint( evt.clientX, evt.clientY); goog.style.showElement(this.highlightDiv_, true); if (this.currElement_ == elementUnderMouse) { // Nothing to do, end early. return; } this.currElement_ = elementUnderMouse; } else { this.currElement_ = evt.srcElement; } if (!this.highlightDiv_) { // Init the highlight box if none is available. this.highlightDiv_ = goog.dom.createDom(goog.dom.TagName.DIV, { 'id' : this.highlightBoxId_, 'style' : 'position:absolute;' }); goog.dom.appendChild(document.body, this.highlightDiv_); } this.positionHighlightBox_(); }; /** * Positions the highlight box on top of the last element moused over. * @private */ common.client.RecordModeManager.prototype.positionHighlightBox_ = function() { goog.style.setPosition( this.highlightDiv_, goog.style.getPageOffset(this.currElement_)); goog.style.setSize( this.highlightDiv_, goog.style.getSize(this.currElement_)); }; /** * Exits the recording mode. This restores window.document.onmousemove and * window.document.onclick to it's original values (those set before the * recording session was entered) and restore the dom to the state it was * before the recording started. * Throws an {@code Error} when this method is called before the * {@code enterRecordingMode()} is called. * @export */ common.client.RecordModeManager.prototype.exitRecordingMode = function() { if (!this.isRecording_) { throw new Error( 'exitRecordingMode: cannot end a non-started recording session. ' + 'Call enterRecordingMode() before calling exitRecordingMode.'); } goog.global.document.onclick = this.originalOnClick_; goog.global.document.onmousemove = this.originalMouseMove_; if (this.highlightDiv_) { goog.dom.removeNode(this.highlightDiv_); } this.currElement_ = null; this.onClickCallback_ = null; this.highlightDiv_ = null; this.isRecording_ = false; common.client.MiscHelper.restoreCursorStyle(); }; goog.exportSymbol( 'common.client.RecordModeManager', common.client.RecordModeManager); goog.exportProperty( common.client.RecordModeManager.prototype, 'isRecording', common.client.RecordModeManager.prototype.isRecording); goog.exportProperty( common.client.RecordModeManager.prototype, 'enterRecordingMode', common.client.RecordModeManager.prototype.enterRecordingMode); goog.exportProperty( common.client.RecordModeManager.prototype, 'exitRecordingMode', common.client.RecordModeManager.prototype.exitRecordingMode); goog.exportProperty( common.client.RecordModeManager.prototype, 'getHighlightBoxId', common.client.RecordModeManager.prototype.getHighlightBoxId); goog.exportProperty( common.client.RecordModeManager.prototype, 'setHighlightBoxId', common.client.RecordModeManager.prototype.setHighlightBoxId);
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Unit tests for loaddialog. * * @author phu@google.com (Po Hu) */ goog.require('goog.net.XhrIo'); goog.require('goog.testing.MockControl'); goog.require('goog.testing.PropertyReplacer'); goog.require('goog.testing.mockmatchers'); goog.require('rpf.LoaderDialog'); var stubs_ = new goog.testing.PropertyReplacer(); var mockControl_ = null; var chrome = {}; var localStorage = {'getItem': function() {}, 'setItem': function() {}}; var consoleMgr = {'changeMode_': function() {}}; var JSON = {}; function setUp() { mockControl_ = new goog.testing.MockControl(); chrome.extension = {}; stubs_.set(goog.global, 'chrome', chrome); } function tearDown() { mockControl_.$tearDown(); mockControl_ = null; stubs_.reset(); } function testLoadSelectedTest() { }
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Unit tests for misc helper. * * @author phu@google.com (Po Hu) */ goog.require('goog.testing.MockControl'); goog.require('goog.testing.PropertyReplacer'); goog.require('goog.testing.mockmatchers'); goog.require('rpf.MiscHelper'); var stubs_ = new goog.testing.PropertyReplacer(); var mockControl_ = null; var chrome = {}; function setUp() { mockControl_ = new goog.testing.MockControl(); chrome.extension = {}; chrome.tabs = {}; stubs_.set(goog.global, 'chrome', chrome); } function tearDown() { mockControl_.$tearDown(); mockControl_ = null; stubs_.reset(); }
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Unit tests for quick commands dialog. * * @author phu@google.com (Po Hu) */ goog.require('goog.testing.MockControl'); goog.require('goog.testing.PropertyReplacer'); goog.require('rpf.QuickCmdDialog'); var stubs_ = new goog.testing.PropertyReplacer(); var mockControl_ = null; var chrome = {}; function setUp() { mockControl_ = new goog.testing.MockControl(); chrome.extension = {}; chrome.extension.getURL = function(url) {return 'url'}; var foo = function(a, b) {}; chrome.extension.getViews = function() { return [{'location': {'href': 'url'}, 'consoleMgr': {}, 'addNewCommand': foo}]; }; stubs_.set(goog.global, 'chrome', chrome); } function tearDown() { mockControl_.$tearDown(); mockControl_ = null; stubs_.reset(); } function testWriteSleepCmd() { } function testWriteUrlChangeCmd() { }
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains the console manager. * * @author phu@google.com (Po Hu) */ goog.provide('rpf.SaveDialog'); /** * A class for handling console's save function. * @constructor * @export */ rpf.SaveDialog = function() {};
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This class provides an interface to the Ace instance. * @author phu@google.com (Po Hu) */ goog.provide('rpf.EditorManager'); goog.require('bite.base.Helper'); goog.require('goog.async.ConditionalDelay'); goog.require('goog.dom'); /** * A class that provides an interface to the editor. * Do not use this class until the initFinished boolean is true. * We have to load editor related files asynchronously, so the class * may not be ready to use right when it's instantiated. * You may also use the initCallback to deal with this. * * @param {string} editorContainerId The html id of the editor container. * @param {function()=} opt_initCallback A function to call when initialization * has finished. * @param {function()=} opt_getViewMode The function to return the * view mode. * @param {function()=} opt_getInfoMap The function to return the * infoMap. * @constructor * @export */ rpf.EditorManager = function( editorContainerId, opt_initCallback, opt_getViewMode, opt_getInfoMap) { /** * The initialization callback. * @type {function()} * @private */ this.initCallback_ = opt_initCallback || goog.nullFunction; /** * The initialization callback. * @type {function()} * @private */ this.getViewMode_ = opt_getViewMode || goog.nullFunction; /** * The get infoMap function. * @type {function()} * @private */ this.getInfoMap_ = opt_getInfoMap || goog.nullFunction; /** * Variable which switches to true when this instance has finished * initializing. * @private */ this.initFinished_ = false; /** * The editor instance. * @private */ this.editor_ = null; /** * The temp code in editor. * @type {string} * @private */ this.tempCode_ = ''; /** * The html container for the editor instance. * @type {Element} * @private */ this.container_ = goog.dom.getElement(editorContainerId); /** * A dictionary containing the gutter decoration classes of each gutter row. * @type {Object.<number, string>} * @private */ this.gutterDecorationDict_ = {}; this.editor_ = ace.edit(editorContainerId); var javaScriptMode = require('ace/mode/javascript').Mode; this.editor_.getSession().setMode(new javaScriptMode()); this.editor_.renderer.setHScrollBarAlwaysVisible(false); this.editor_.getSession().setUseWrapMode(false); this.editor_.getSession().setWrapLimitRange(49, 49); this.finishInit_(); }; /** * Classes used to set gutter decorations in the editor. * @enum {string} * @private */ rpf.EditorManager.GutterClasses_ = { FAILING: 'rpf-gutter-failing', PASSING: 'rpf-gutter-passing', RUNNING: 'rpf-gutter-running' }; /** * Callback used to finish initializing this object when * all the editor related files have finished loading. * * @private */ rpf.EditorManager.prototype.finishInit_ = function() { if (this.initCallback_) { this.initCallback_(); } }; /** * @return {Element} The html container for the editor instance. */ rpf.EditorManager.prototype.getContainer = function() { return this.container_; }; /** * Gets the total number of lines currently in the editor view. * @return {number} The total line count. * @export */ rpf.EditorManager.prototype.getTotalLineCount = function() { return this.editor_.getSession().getLength(); }; /** * Get the line of text at the given line. * @param {number} lineNumber The line number (starting from 0). * @return {string} The line of text or null if no line of text exists * for the given line. * @export */ rpf.EditorManager.prototype.getTextAtLine = function(lineNumber) { if (this.editor_.getSession().getLength() < lineNumber) { return ''; } return this.editor_.getSession().getLine(lineNumber); }; /** * Gets the current cursor selection in the editor. * * @return {Object} An ace selection object containing * start, end, rows, and columns of the current selection. * @export */ rpf.EditorManager.prototype.getCurrentSelection = function() { return this.editor_.getSelectionRange(); }; /** * Gets the current code in the editor. * * @return {string} The current contents of the editor. * @export */ rpf.EditorManager.prototype.getCode = function() { return this.editor_.getSession().getValue(); }; /** * Sets the editor contents to the code passed in. * * @param {string} newCode The code to put in the editor. * @export */ rpf.EditorManager.prototype.setCode = function(newCode) { this.editor_.getSession().setValue(newCode); }; /** * Adds a running class to a line number. * @param {number} num The editor line number. * @export */ rpf.EditorManager.prototype.addRunningClass = function(num) { this.editor_.renderer.addGutterDecoration( num, rpf.EditorManager.GutterClasses_.RUNNING); this.gutterDecorationDict_[num] = rpf.EditorManager.GutterClasses_.RUNNING; }; /** * Adds a passed class to a line number. * @param {number} num The editor line number. * @export */ rpf.EditorManager.prototype.addPassedClass = function(num) { this.editor_.renderer.addGutterDecoration( num, rpf.EditorManager.GutterClasses_.PASSING); this.gutterDecorationDict_[num] = rpf.EditorManager.GutterClasses_.PASSING; }; /** * Adds a failed class to a line number. * @param {number} num The editor line number. * @export */ rpf.EditorManager.prototype.addFailedClass = function(num) { this.editor_.renderer.addGutterDecoration( num, rpf.EditorManager.GutterClasses_.FAILING); this.gutterDecorationDict_[num] = rpf.EditorManager.GutterClasses_.FAILING; }; /** * Clears all images from the gutter. * @export */ rpf.EditorManager.prototype.clearGutterDecoration = function() { for (var rowNum in this.gutterDecorationDict_) { var num = parseInt(rowNum, 10); var className = this.gutterDecorationDict_[num]; this.editor_.renderer.removeGutterDecoration(num, className); } this.gutterDecorationDict_ = {}; }; /** * Get the original line of code. * @param {number} line The line number. * @return {string} line The line number in the original scripts. * @export */ rpf.EditorManager.prototype.getOriginalLineAt = function(line) { var script = ''; if (this.getViewMode_() == Bite.Constants.ViewModes.CODE) { script = this.getCode().split('\n')[line]; } else if (this.getViewMode_() == Bite.Constants.ViewModes.READABLE) { var scripts = this.tempCode_.split('\n'); script = scripts[line]; } return script; }; /** * Get the original code. * @return {string} The code or translation. * @export */ rpf.EditorManager.prototype.getOriginalCode = function() { if (this.getViewMode_() == Bite.Constants.ViewModes.CODE) { return this.getCode(); } else if (this.getViewMode_() == Bite.Constants.ViewModes.READABLE) { return this.tempCode_; } return ''; }; /** * Display in the selected mode. * @param {string} code The code to be displayed. * @export */ rpf.EditorManager.prototype.displayInEditor = function(code) { if (this.getViewMode_() == Bite.Constants.ViewModes.CODE) { this.setCode(code); } else if (this.getViewMode_() == Bite.Constants.ViewModes.READABLE) { this.tempCode_ = code; this.setReadableCode(); } }; /** * @return {string} The temp code in editor. * @export */ rpf.EditorManager.prototype.getTempCode = function() { return this.tempCode_; }; /** * @param {string} code The temp code in editor. * @export */ rpf.EditorManager.prototype.setTempCode = function(code) { this.tempCode_ = code; }; /** * Set the readable code in editor. * @export */ rpf.EditorManager.prototype.setReadableCode = function() { var readable = []; var scripts = this.tempCode_.split('\n'); var infoMap = this.getInfoMap_(); for (var i = 0; i < scripts.length; i++) { readable.push(this.getTranslatedText_(scripts[i], infoMap)); } readable = readable.join('\n'); this.setCode(readable); }; /** * Check if the given line of command has descriptor. * @param {number} lineNumber The line number for which we should check * for a description. * @return {Object} The descriptor or null. * @export */ rpf.EditorManager.prototype.checkHasDesc = function(lineNumber) { var script = ''; if (this.getViewMode_() == Bite.Constants.ViewModes.CODE) { script = this.getTextAtLine(lineNumber); if (!script) { return null; } } else if (this.getViewMode_() == Bite.Constants.ViewModes.READABLE) { var scripts = this.tempCode_.split('\n'); script = scripts[lineNumber]; } console.log(' Got this script:' + script); var desc = rpf.MiscHelper.getDescriptor(script); var translation = this.getTranslatedText_(script); if (typeof(desc) == 'object') { return {'desc': desc, 'translation': translation}; } else { return null; } }; /** * Gets the translated text. * @param {string} cmd The command script. * @param {Object=} opt_infoMap The info map of the script. * @return {string} The translated text. * @private */ rpf.EditorManager.prototype.getTranslatedText_ = function(cmd, opt_infoMap) { var data = goog.dom.getElement( Bite.Constants.RpfConsoleId.DATA_CONTAINER).value; var descriptor = null; if (opt_infoMap) { var stepId = bite.base.Helper.getStepId(cmd); if (stepId && opt_infoMap['steps'][stepId]) { var elemId = opt_infoMap['steps'][stepId]['elemId']; descriptor = opt_infoMap['elems'][elemId]['descriptor']; } } var codeGen = new rpf.CodeGenerator(); return codeGen.translateCmd(cmd, data, descriptor); }; /** * Replaces a generated command in console text fields. * @param {string} pCmd The generated puppet command. * @param {number} index Replace the commmand at the given line. * @export */ rpf.EditorManager.prototype.replaceCommand = function(pCmd, index) { var code = this.tempCode_; if (this.getViewMode_() == Bite.Constants.ViewModes.CODE) { code = this.getCode(); } var newCode = ''; if (index != -1) { var allLines = code.split('\n'); allLines.splice(index, 1, pCmd); newCode = allLines.join('\n'); } else { newCode = code + pCmd + '\n'; } if (this.getViewMode_() == Bite.Constants.ViewModes.CODE) { this.setCode(newCode); } else { this.tempCode_ = newCode; this.setReadableCode(); } }; /** * Remove the line from editor. * @param {number} line The line number. * @export */ rpf.EditorManager.prototype.removeCurrentLine = function(line) { var lines = this.getOriginalCode().split('\n'); lines.splice(line, 1); this.displayInEditor(lines.join('\n')); }; /** * Get the total line number. * @return {number} The total line number. * @export */ rpf.EditorManager.prototype.getTotalLineNum = function() { return this.getTotalLineCount(); }; /** * Move the line down by one. * @param {number} line The current line. * @export */ rpf.EditorManager.prototype.moveDown = function(line) { if (line >= this.getTotalLineNum()) { return; } var lines = this.getOriginalCode().split('\n'); var currentLine = lines[line]; lines[line] = lines[line + 1]; lines[line + 1] = currentLine; this.displayInEditor(lines.join('\n')); }; /** * Move the line up by one. * @param {number} line The current line. * @export */ rpf.EditorManager.prototype.moveUp = function(line) { if (line < 1) { return; } var lines = this.getOriginalCode().split('\n'); var currentLine = lines[line]; lines[line] = lines[line - 1]; lines[line - 1] = currentLine; this.displayInEditor(lines.join('\n')); }; /** * Forces the editor to do a resize. This takes no parameters, * and resizes the editor to fit its container. * @export */ rpf.EditorManager.prototype.resize = function() { this.editor_.resize(); };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview The main class for rpf. * * TODO(michaelwill): This class is a work in progress. * There's still a bunch of state in here that probably does not * belong. If you happen to be reading this, and you notice that * something is particulary hacky, feel free to fix it :). * * @author phu@google.com (Po Hu) * michaelwill@google.com (Michael Williamson) */ goog.provide('rpf.Rpf'); goog.require('bite.common.net.xhr.async'); goog.require('goog.json'); goog.require('goog.structs.Set'); goog.require('rpf.ConsoleLogger'); goog.require('rpf.EventsManager'); /** * The primary class for rpf. * Encapsulates all the sub-objects that rpf depends on. * @constructor * @export */ rpf.Rpf = function() { /** * @type {number} * @private */ this.windowId_ = -1; // TODO(michaelwill): This is a bit of a dependency nightmare. // Ideally, each object would just be passed copies of the other // singletons that it depends on. Unfortunately, the code right now // has circular depdendencies which make this impossible. // // As a result, // most of the objects here gain access to the others through a reference // back to this global object. This is very hacky, and needs to be redone. // The circular dependencies in all these sub objects need to be weeded out. /** * @type {rpf.ConsoleLogger} * @private */ this.logger_ = rpf.ConsoleLogger.getInstance(); /** * @type {rpf.EventsManager} * @private */ this.eventsMgr_ = rpf.EventsManager.getInstance(); this.eventsMgr_.setupCommonFuncs(goog.bind(this.callBackOnRequest, this)); /** * @type {Object} * @private */ this.commonLibs_ = {}; this.boundOnRequestFunc = goog.bind(this.callBackOnRequest, this); chrome.windows.onRemoved.addListener(goog.bind( this.windowDestroyed_, this)); chrome.extension.onRequest.addListener( this.boundOnRequestFunc); }; goog.addSingletonGetter(rpf.Rpf); /** * @const The console's html file. * @type {string} * @private */ rpf.Rpf.CONSOLE_HTML_FILE_ = 'console.html'; /** * @const The name of the rpf console. * @type {string} * @private */ rpf.Rpf.CONSOLE_NAME_ = 'Rpf'; /** * @const The name of the tab under record. * @type {string} */ rpf.Rpf.TAB_UNDER_RECORD_TITLE = 'TabUnderRecord'; /** * @const The console's left margin. * @type {number} * @private */ rpf.Rpf.CONSOLE_LEFT_MARGIN_ = 5; /** * @const The console's top margin. * @type {number} * @private */ rpf.Rpf.CONSOLE_TOP_MARGIN_ = 5; /** * @const The console's width. * @type {number} * @private */ rpf.Rpf.CONSOLE_WIDTH_ = 500; /** * @const The console's height. * @type {number} * @private */ rpf.Rpf.CONSOLE_HEIGHT_ = 800; /** * @const Whether or not the console is resizable. * @type {string} * @private */ rpf.Rpf.CONSOLE_RESIZABLE_ = 'yes'; /** * @const Whether or not to have scroll bar. * @type {string} * @private */ rpf.Rpf.CONSOLE_SCROLLBARS_ = 'no'; /** * Callback on a request received. * @param {Object} request The request object. * @param {Object} sender The sender object. * @param {function(Object)} sendResponse The response object. */ rpf.Rpf.prototype.callBackOnRequest = function( request, sender, sendResponse) { if (!request['command']) { return; } switch (request['command']) { case Bite.Constants.CONTROL_CMDS.REMOVE_WINDOW: this.removeWindow(); break; case Bite.Constants.CONTROL_CMDS.CREATE_WINDOW: this.createWindow(request['params']['refresh']); break; case Bite.Constants.CONTROL_CMDS.OPEN_CONSOLE_AUTO_RECORD: sendResponse({'result': this.checkAndStartAutoRecording_(sender.tab.id, request)}); break; } }; /** * @return {rpf.ConsoleLogger} The logger object. * @export */ rpf.Rpf.prototype.getLogger = function() { return this.logger_; }; /** * @return {rpf.EventsManager} Gets the events manager. * @export */ rpf.Rpf.prototype.getEventsManager = function() { return this.eventsMgr_; }; /** * @param {string} userId Sets the user id. * @export */ rpf.Rpf.prototype.setUserId = function(userId) { this.eventsMgr_.setUserId(userId); }; /** * Creates the physical rpf window if it does not yet * already exist. * @private */ rpf.Rpf.prototype.createRpfWindow_ = function() { this.eventsMgr_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.SET_RECORDING_TAB}); this.eventsMgr_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.STOP_RECORDING}); var options = { url: rpf.Rpf.CONSOLE_HTML_FILE_, type: 'popup', left: rpf.Rpf.CONSOLE_LEFT_MARGIN_, top: rpf.Rpf.CONSOLE_TOP_MARGIN_, height: rpf.Rpf.CONSOLE_HEIGHT_, width: rpf.Rpf.CONSOLE_WIDTH_ }; var viewSet = new goog.structs.Set(); viewSet.addAll(chrome.extension.getViews()); chrome.windows.create(options, goog.bind(function(win) { this.windowId_ = win.id; chrome.tabs.getAllInWindow(win.id, goog.bind(function(tabs) { // Using 0 because it's the only created tab of the created window. this.eventsMgr_.setConsoleTabId(tabs[0].id);}, this)); var newViews = chrome.extension.getViews(); for (var i = 0; i < newViews.length; i++) { // Here we manually find the view that didn't exist before // the call to chrome.windows.create(). This hack is necessary // because of chrome bug // http://code.google.com/p/chromium/issues/detail?id=74958 where // chrome.extension.getViews() passing in the window id // does not work. var view = newViews[i]; if (!viewSet.contains(view)) { // This manual resize is necessary because of chrome bug // http://code.google.com/p/chromium/issues/detail?id=72980 // chrome.windows.create() ignores the size of windows // with type 'popup'. view.resizeTo(rpf.Rpf.CONSOLE_WIDTH_, rpf.Rpf.CONSOLE_HEIGHT_); break; } } }, this)); }; /** * Creates the physical rpf console window if it doesn't already exist. * * @param {boolean=} opt_forceRefresh An optional parameter that forces * the console window to be redrawn, even if one already exists. * @export */ rpf.Rpf.prototype.createWindow = function(opt_forceRefresh) { if (opt_forceRefresh) { this.removeWindow(); this.windowId_ = -1; } if (this.windowId_ >= 0) { this.eventsMgr_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.STOP_RECORDING}); this.eventsMgr_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.SET_RECORDING_TAB}); this.focusRpf(); } else { this.eventsMgr_.refresh(); this.createRpfWindow_(); } }; /** * Checks and starts auto recording. * @param {string} tabId The tab id. * @param {Object} request The request object. * @private * @return Whether auto recording is on. */ rpf.Rpf.prototype.checkAndStartAutoRecording_ = function(tabId, request) { if (this.windowId_ < 0) { this.createWindow(); return true; } return (this.eventsMgr_.getRecorder().getTestTabId() && this.eventsMgr_.getRecorder().getTestTabId() == tabId); }; /** * Removes the rpf window, if it exists. * * @export */ rpf.Rpf.prototype.removeWindow = function() { if (this.windowId_ < 0) { return; } rpf.MiscHelper.removeWindowById(this.windowId_); }; /** * Callback used when the rpf window goes away. * * @param {number} windowId The numeric id of the window. * @private */ rpf.Rpf.prototype.windowDestroyed_ = function(windowId) { if (windowId != this.windowId_) { return; } this.windowId_ = -1; this.eventsMgr_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.STOP_RECORDING}); chrome.tabs.onRemoved.removeListener( this.eventsMgr_.callBackAddTestTabRemoved); }; /** * Returns true if the rpf window has previously been created * and is currently visible on the screen. * * @return {boolean} true if the window is created. * @export */ rpf.Rpf.prototype.windowCreated = function() { return this.windowId_ >= 0; }; /** * @return {number} The main RPF window. * @export */ rpf.Rpf.prototype.getWindowId = function() { return this.windowId_; }; /** * Sets the main RPF window. * @param {number} winId The window id. * @export */ rpf.Rpf.prototype.setWindowId = function(winId) { this.windowId_ = winId; }; /** * Focuses the rpf window. */ rpf.Rpf.prototype.focusRpf = function() { chrome.windows.update(this.windowId_, { focused: true }); this.eventsMgr_.stopRecordingFromUi(); };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * The wrapper functions for the third party library - browser automation, * which provides functions like click, type and etc. * * @author phu@google.com (Po Hu) */ goog.provide('bite.rpf.BotHelper'); goog.require('bite.rpf.ActionsHelper'); goog.require('bot'); goog.require('bot.Keyboard.Keys'); goog.require('bot.Mouse'); goog.require('bot.action'); goog.require('bot.events'); goog.require('bot.locators.xpath'); goog.require('common.client.ElementDescriptor'); goog.require('goog.Timer'); goog.require('goog.dom'); /** * The bot actions wrapper. * @constructor * @extends {bite.rpf.ActionsHelper} * @export */ bite.rpf.BotHelper = function() { goog.base(this); this.init_(); }; goog.inherits(bite.rpf.BotHelper, bite.rpf.ActionsHelper); /** * Inits the bot helper and sets the global methods. Note that for every * wrapper it needs to implement the following interfaces that simulate * user's actions. * @private */ bite.rpf.BotHelper.prototype.init_ = function() { BiteRpfAction.click = goog.bind(this.click, this); BiteRpfAction.drag = goog.bind(this.drag, this); BiteRpfAction.enter = goog.bind(this.enter, this); BiteRpfAction.select = goog.bind(this.select, this); BiteRpfAction.type = goog.bind(this.type, this); BiteRpfAction.input = goog.bind(this.input, this); BiteRpfAction.submit = goog.bind(this.submit, this); BiteRpfAction.doubleClick = goog.bind(this.doubleClick, this); BiteRpfAction.verify = goog.bind(this.verify, this); BiteRpfAction.move = goog.bind(this.move, this); BiteRpfAction.call = goog.bind(this.call, this); BiteRpfAction.verifyNot = goog.bind(this.verifyNot, this); }; /** * Flashes the element. * @param {Element} elem The element. * @private */ bite.rpf.BotHelper.prototype.flash_ = function(elem) { // TODO(phu): We should save the previous outline style and then revert. goog.style.setStyle(elem, 'outline', 'medium solid red'); goog.Timer.callOnce( function() {goog.style.setStyle(elem, 'outline', '');}, 400); }; /** * Gets the element. * @param {string|Element} elem The element info. * @return {!Element} The element that was found. * @private */ bite.rpf.BotHelper.prototype.getElement_ = function(elem) { var elemType = typeof elem; var log = ''; if (elemType == 'string') { log = 'xpath - ' + elem; elem = bot.locators.xpath.single( /** @type {string} */ (elem), goog.dom.getDocument()); } else { log = 'tagName - ' + elem.tagName; } if (elem) { this.flash_(/** @type {Element} */ (elem)); return /** @type {!Element} */ (elem); } throw new Error('Could not find the element: ' + log); }; /** * Clicks the given element. * @param {string|Element} elem The element to be clicked. */ bite.rpf.BotHelper.prototype.click = function(elem) { elem = this.getElement_(elem); try { bot.action.click(elem); } catch (e) { // Since bot.action.click needs the element to be shown, we have to // do this workaround for legacy code. var doc = goog.dom.getOwnerDocument(elem); goog.style.scrollIntoContainerView(elem, goog.userAgent.WEBKIT ? doc.body : doc.documentElement); var size = goog.style.getSize(elem); var opt_coords = new goog.math.Coordinate(size.width / 2, size.height / 2); var mouse = new bot.Mouse(); mouse.move(elem, opt_coords); var pos = goog.style.getClientPosition(elem); var args = { clientX: pos.x + opt_coords.x, clientY: pos.y + opt_coords.y, button: 0, altKey: false, ctrlKey: false, shiftKey: false, metaKey: false, relatedTarget: null }; bot.events.fire(elem, bot.events.EventType.MOUSEDOWN, args); bot.events.fire(elem, bot.events.EventType.MOUSEUP, args); bot.events.fire(elem, bot.events.EventType.CLICK, args); } }; /** * Hits the enter key on the given element. * @param {string|Element} elem The element to hit enter on. */ bite.rpf.BotHelper.prototype.enter = function(elem) { elem = this.getElement_(elem); bot.action.type(elem, bot.Keyboard.Keys.ENTER); }; /** * Selects the given element. * @param {string|Element} elem The element to be selected. * @param {string} value The value to be selected. */ bite.rpf.BotHelper.prototype.select = function(elem, value) { var options = this.getElement_(elem).options; for (var i = 0, len = options.length; i < len; ++i) { if (options[i].value == value) { bot.action.click(options[i]); break; } } }; /** * Moves the cursor to the given element. * @param {string|Element} elem The element to be moved to. */ bite.rpf.BotHelper.prototype.move = function(elem) { elem = this.getElement_(elem); var doc = goog.dom.getOwnerDocument(elem); goog.style.scrollIntoContainerView(elem, goog.userAgent.WEBKIT ? doc.body : doc.documentElement); var size = goog.style.getSize(elem); var opt_coords = new goog.math.Coordinate(size.width / 2, size.height / 2); var mouse = new bot.Mouse(); mouse.move(elem, opt_coords); }; /** * Drags the given element. * @param {string|Element} elem The element to be dragged. * @param {number} dX The difference of x coordinates. * @param {number} dY The difference of y coordinates. */ bite.rpf.BotHelper.prototype.drag = function(elem, dX, dY) { bot.action.drag(this.getElement_(elem), dX, dY); }; /** * Inputs text in the given element by changing the element's value attribute. * @param {string|Element} elem The element to have text input. * @param {string} text The text input. */ bite.rpf.BotHelper.prototype.input = function(elem, text) { elem = this.getElement_(elem); if (elem.value != text) { elem.value = text; bot.events.fire(elem, bot.events.EventType.CHANGE); } }; /** * Inputs text character by character in the given element. * @param {string|Element} elem The element to have text input. * @param {string} text The text input. */ bite.rpf.BotHelper.prototype.type = function(elem, text) { elem = this.getElement_(elem); elem.value = ''; elem.focus(); bot.action.type(elem, text); }; /** * Submits the form. * @param {string|Element} elem The form to be submitted. */ bite.rpf.BotHelper.prototype.submit = function(elem) { bot.action.submit(this.getElement_(elem)); }; /** * Double clicks the given element. * @param {string|Element} elem The element to be double clicked. */ bite.rpf.BotHelper.prototype.doubleClick = function(elem) { bot.action.doubleClick(this.getElement_(elem)); }; /** * Verifies the specified element does not exist. * @param {string|Element} elem The element. * @param {string} content The content to verify. */ bite.rpf.BotHelper.prototype.verifyNot = function(elem, content) { if (!elem) { return; } elem = this.getElement_(elem); var result = common.client.ElementDescriptor.getElement( BiteRpfAction.currCmdMap, 'descriptor'); if (result['elem']) { throw new Error('VerifyNot failed: Element found.'); } }; /** * Verifies the specified element exists. * @param {string|Element} elem The element. * @param {string} content The content to verify. */ bite.rpf.BotHelper.prototype.verify = function(elem, content) { elem = this.getElement_(elem); var result = common.client.ElementDescriptor.getElement( BiteRpfAction.currCmdMap, 'descriptor'); if (!result['elem']) { throw new Error(result['log']); } };
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains logic to playback a script. * * @author phu@google.com (Po Hu) */ goog.provide('rpf.PlayBackManager'); goog.require('goog.Timer'); goog.require('goog.events'); goog.require('goog.string'); goog.require('rpf.CodeGenerator'); goog.require('rpf.ConsoleLogger'); goog.require('rpf.ScriptManager'); /** * A class for playing back the recorded script. * @param {rpf.ScriptManager} scriptMgr The script manager. * @param {function():boolean} isLoadingReadyForPlayback Whether loading is * ready. * @param {function()} removeTabUpdatedListener Removes the on-tab-updated * listener. * @param {function()} addTabUpdatedListener The function to add the * onTabUpdated listener. * @param {rpf.ConsoleLogger} logger The console logger instance. * @param {function(Object, function(*)=)} sendMessageToConsole The * function to send message to console world. * @param {function(Object, Object, function(Object))} eventMgrListener * The listener registered in eventsManager. * @constructor * @export */ rpf.PlayBackManager = function( scriptMgr, isLoadingReadyForPlayback, removeTabUpdatedListener, addTabUpdatedListener, logger, sendMessageToConsole, eventMgrListener) { /** * The script manager. * @type {rpf.ScriptManager} * @private */ this.scriptMgr_ = scriptMgr; /** * The console logger. * @type {rpf.ConsoleLogger} * @private */ this.logger_ = logger; /** * The function to send message to console world. * @type {function(Object, function(*)=)} * @private */ this.sendMessageToConsole_ = sendMessageToConsole; /** * The event lisnener registered on event manager. * @type {function(Object, Object, function(Object))} * @private */ this.eventMgrListener_ = eventMgrListener; /** * The function to check whether loading is ready. * @type {function():boolean} * @private */ this.isLoadingReadyForPlayback_ = isLoadingReadyForPlayback; /** * The function to remove the onTabUpdated listener when playback is done. * @type {function()} * @private */ this.removeTabUpdatedListener_ = removeTabUpdatedListener; /** * The function to add the onTabUpdated listener. * @type {function()} * @private */ this.addTabUpdatedListener_ = addTabUpdatedListener; /** * The tab id of the page under playback. * @type {number} * @private */ this.playbackTabId_ = 0; /** * The start url of a playback script. * @type {string} * @private */ this.playbackStartUrl_ = ''; /** * The current step number. * @type {number} * @private */ this.currentStep_ = 0; /** * The current running test name. * @type {string} * @private */ this.currentTestName_ = ''; /** * The current running project name. * @type {string} * @private */ this.currentProjectName_ = ''; /** * The current running test's location. * @type {string} * @private */ this.currentTestLocation_ = ''; /** * The current running test id. * @type {string} * @private */ this.currentTestId_ = ''; /** * The current run status. * @type {string} * @private */ this.currentRunStatus_ = ''; /** * The command of current step. * @type {string} * @private */ this.currentCmd_ = ''; /** * whether tab updates ready. * @type {boolean} * @private */ this.replayTabReady_ = true; /** * Whether the previous command is done. * @type {boolean} * @private */ this.previousCmdDone_ = true; /** * Whether ready for command after sleep. * @type {boolean} * @private */ this.sleepReady_ = true; /** * Whether ready for command after user pause. * @type {boolean} * @private */ this.userPauseReady_ = true; /** * Whether is in step playback mode. * @type {boolean} * @private */ this.stepMode_ = false; /** * Whether user explicitly stops the run. * @type {boolean} * @private */ this.userStop_ = false; /** * Whether uses xpath. * @type {boolean} * @private */ this.useXpath_ = false; /** * The scripts for playback. * @type {Array} * @private */ this.scripts_ = []; /** * The corresponding datafile for playback. * @type {string} * @private */ this.datafile_ = ''; /** * The user specified library for playback. * @type {string} * @private */ this.userLib_ = ''; /** * The start time for each command including overhead. * @type {number} * @private */ this.startTimeEachRun_ = 0; /** * The timer object for playback. * @type {goog.Timer} * @private */ this.playbackTimer_ = new goog.Timer(rpf.PlayBackManager.rpfPlaybackInterval_); /** * Whether is playing back a script. * @type {boolean} * @private */ this.onPlayback_ = false; /** * The window id of the page under playback. * @type {number} * @private */ this.playbackWinId_ = 0; /** * The retried times. * @type {number} * @private */ this.failureRetryTimes_ = 0; /** * The user specified sleep time. * @type {number} * @private */ this.userSetSleepTime_ = 0; /** * The user specified sleep starts time. * @type {number} * @private */ this.userSetSleepStart_ = 0; /** * The user specified step for a pause. * @type {number} * @private */ this.userSpecifiedPauseStep_ = -1; /** * Whether the preparation for playback is done. * @type {boolean} * @private */ this.preparationDone_ = false; /** * The last matching html. * @type {string} * @private */ this.lastMatchHtml_ = ''; /** * The maximum retry times. * @type {number} * @private */ this.maxRetryTimes_ = rpf.PlayBackManager.FAILURE_TOTAL_RETRY_TIMES_; /** * The default timeout. * @type {number} * @private */ this.defaultTimeout_ = rpf.PlayBackManager.PLAYBACK_TIMEOUT_EACHRUN_; /** * The step timeout. * @type {number} * @private */ this.eachCmdTimeout_ = rpf.PlayBackManager.EACH_CMD_TIMEOUT_; /** * The original datafile. * @type {string} * @private */ this.originalDataFile_ = ''; /** * The original user lib. * @type {string} * @private */ this.originalUserLib_ = ''; /** * The failure reason. * @type {string} * @private */ this.failureReason_ = ''; /** * The realtime parameters bag. * @type string * @private */ this.realTimeBack_ = ''; /** * The failure log. * @type {string} * @private */ this.failureLog_ = ''; /** * The elapsed time. * @type {string} * @private */ this.elapsedTime_ = ''; /** * The newly generated code. * @type {string} * @private */ this.newCode_ = ''; /** * The info map. * @type {Object} * @private */ this.infoMap_ = {}; /** * Whether it should continue or show updating options UI on failure. * @type {boolean} * @private */ this.continueOnFailure_ = false; }; /** * @const The maximum retry times. * @type {number} * @private */ rpf.PlayBackManager.FAILURE_TOTAL_RETRY_TIMES_ = 5; /** * The default playback interval. * @type {number} * @private */ rpf.PlayBackManager.rpfPlaybackInterval_ = 700; /** * @const The default timeout for each client command. * @type {number} * @private */ rpf.PlayBackManager.EACH_CMD_TIMEOUT_ = 6 * 1000; /** * @const The default timeout for every command including all the overheads. * @type {number} * @private */ rpf.PlayBackManager.PLAYBACK_TIMEOUT_EACHRUN_ = 40 * 1000; /** * Sets up the callbacks for worker manager. * @param {function():number} getAutoRunningTestId Get the auto test id. * @param {function(Bite.Constants.WorkerResults, number, string, string=)} * runNext The function to run the next job. * @export */ rpf.PlayBackManager.prototype.setupWorkerCallbacks = function( getAutoRunningTestId, runNext) { this.getAutoRunningTestId_ = getAutoRunningTestId; this.runNext_ = runNext; }; /** * Sets the newly generated code. * @param {string} code The newly generated code. * @export */ rpf.PlayBackManager.prototype.setNewCode = function(code) { this.newCode_ = code; }; /** * Sets the playback interval. * @param {number} sec The interval in seconds. * @export */ rpf.PlayBackManager.prototype.setPlaybackInterval = function(sec) { rpf.PlayBackManager.rpfPlaybackInterval_ = sec * 1000; }; /** * Gets the current date. * @return {Date} A new date object. * @private */ rpf.PlayBackManager.prototype.getDate_ = function() { return new Date(); }; /** * Sets the start url for playback. * @param {string} url The start url. * @export */ rpf.PlayBackManager.prototype.setStartUrl = function(url) { this.playbackStartUrl_ = url; }; /** * Gets all the commands from a script string. * @param {string} scriptStr The script string. * @return {Array} An array of commands. * @export */ rpf.PlayBackManager.prototype.getAllStepsFromScript = function(scriptStr) { // By default, assume each line is a command. var allSteps = []; var allRawSteps = scriptStr.split('\n'); for (var i = 0; i < allRawSteps.length; i++) { allSteps.push(allRawSteps[i]); } return allSteps; }; /** * Init the resuming playbck. * @private */ rpf.PlayBackManager.prototype.initResumePlayback_ = function() { this.addTabUpdatedListener_(); this.replayTabReady_ = false; this.initReplayPage(this.callBackAfterTabUpdated); this.startTimer(); }; /** * Starts running a test script including the preparation. * @param {string} url The start url. * @param {string} scriptStr The raw script string. * @param {string} datafile The corresponding data file. * @param {string} userLib The user specified library. * @export */ rpf.PlayBackManager.prototype.runTest = function( url, scriptStr, datafile, userLib) { if ('string' != typeof(scriptStr)) { var log = 'Error: script string type is ' + typeof(scriptStr); this.logger_.saveLogAndHtml(log, rpf.ConsoleLogger.LogLevel.ERROR, rpf.ConsoleLogger.Color.RED); throw new Error(log); } this.setStartUrl(url); this.preparationDone_ = false; this.scripts_ = this.getAllStepsFromScript(scriptStr); this.datafile_ = datafile; this.originalDataFile_ = datafile; this.userLib_ = userLib; this.originalUserLib_ = userLib; if (this.playbackTimer_.enabled) { this.playbackTimer_.stop(); } this.playbackTimer_ = new goog.Timer(rpf.PlayBackManager.rpfPlaybackInterval_); this.onPlayback_ = true; this.replayTabReady_ = true; this.previousCmdDone_ = true; this.realTimeBack_ = ''; this.failureRetryTimes_ = 0; this.addTabUpdatedListener_(); this.startReplay_(null); }; /** * Starts replay by creating a playback window. * @param {?function()=} opt_callback The optional callback function. * @private */ rpf.PlayBackManager.prototype.startReplay_ = function(opt_callback) { // If screen.width is twice larger than screen.height, // then we could just use half of the screen width. var callback = opt_callback || null; var playbackWinWidth = screen.width; if (playbackWinWidth > 2 * screen.height) { playbackWinWidth = screen.width / 2; } chrome.windows.create( {url: this.playbackStartUrl_, width: playbackWinWidth - 650, height: screen.height - 50, top: 25, left: 650}, goog.bind(function(win) { this.callbackStartReplayOne_(callback, win); }, this)); }; /** * Sets the playback window id. * @param {function()} callback The callback function. * @param {Object} win The window object. * @private */ rpf.PlayBackManager.prototype.callbackStartReplayOne_ = function( callback, win) { this.playbackWinId_ = win.id; chrome.tabs.getAllInWindow(win.id, goog.bind(function(tabs) { this.callbackStartReplayTwo_(callback, tabs); }, this)); }; /** * Sets the playback tab id. * @param {function()} callback The callback function. * @param {Array} tabs The tabs of the playback window. * @private */ rpf.PlayBackManager.prototype.callbackStartReplayTwo_ = function( callback, tabs) { this.playbackTabId_ = tabs[0].id; if (callback) { callback(); } else { this.initReplayPage(this.kickOffTest_); } }; /** * Inits the playback page by executing content scripts. * @param {function()} callbackFunc The callback function after init. * @export */ rpf.PlayBackManager.prototype.initReplayPage = function(callbackFunc) { chrome.tabs.executeScript( this.playbackTabId_, {code: 'try {removeListener();} catch(e) {console.log(e.message);}', allFrames: true}); this.callbackInitReplayPageTwo_(callbackFunc); }; /** * Executes user library if specified. * @param {function()} callbackFunc The callback function after init. * @private */ rpf.PlayBackManager.prototype.callbackInitReplayPageTwo_ = function( callbackFunc) { if (this.userLib_) { chrome.tabs.executeScript(this.playbackTabId_, {code: this.userLib_, allFrames: true}, goog.bind(callbackFunc, this)); } else { if (callbackFunc) { callbackFunc.apply(this, []); } } }; /** * Kicks off the test after all the preparation. * @private */ rpf.PlayBackManager.prototype.kickOffTest_ = function() { this.currentStep_ = 0; this.startTimeEachRun_ = 0; this.replayTabReady_ = false; this.preparationDone_ = true; this.playbackTimer_.start(); goog.events.listen(this.playbackTimer_, goog.Timer.TICK, goog.bind(this.waitForElementReadyAndExecCmds, this)); }; /** * Checks the tab updates ready. * @return {boolean} Whether the page is ready. * @private */ rpf.PlayBackManager.prototype.checkPageReady_ = function() { return this.replayTabReady_; }; /** * Checks the previous command is done. * @return {boolean} Whether the previous command is done. * @export */ rpf.PlayBackManager.prototype.isPreCmdDone = function() { return this.previousCmdDone_; }; /** * Sets the previous command is done. * @param {boolean} done Whether the previous command is done. * @export */ rpf.PlayBackManager.prototype.setPreCmdDone = function(done) { this.previousCmdDone_ = done; }; /** * Sets whether to use xpath. * @param {boolean} use Whether uses the xpath. * @export */ rpf.PlayBackManager.prototype.setUseXpath = function(use) { this.useXpath_ = use; }; /** * Checks the user pause is done. * @return {boolean} Whether the user pause is done. * @private */ rpf.PlayBackManager.prototype.checkUserPauseReady_ = function() { return !(this.stepMode_ && !this.userPauseReady_); }; /** * @return {number} Gets the current step number. * @export */ rpf.PlayBackManager.prototype.getCurrentStep = function() { return this.currentStep_; }; /** * @param {number} step Sets the current step number. * @export */ rpf.PlayBackManager.prototype.setCurrentStep = function(step) { this.currentStep_ = step; }; /** * Sets the maximum retry times. * @param {number=} opt_times The maximum times for failure retry. * @export */ rpf.PlayBackManager.prototype.setMaximumRetryTime = function(opt_times) { var maxTimes = 0; if (opt_times != 0) { maxTimes = opt_times || rpf.PlayBackManager.FAILURE_TOTAL_RETRY_TIMES_; } this.maxRetryTimes_ = maxTimes; }; /** * Sets the default time out. * @param {number=} opt_timeout The default time out. * @export */ rpf.PlayBackManager.prototype.setDefaultTimeout = function(opt_timeout) { var timeout = opt_timeout || rpf.PlayBackManager.PLAYBACK_TIMEOUT_EACHRUN_; this.defaultTimeout_ = timeout; }; /** * Gets the length of scripts. * @return {number} The length. * @export */ rpf.PlayBackManager.prototype.getScriptsLen = function() { return this.scripts_.length; }; /** * Removes a step from scripts_. * @param {number} index The index to be removed from scripts. * @export */ rpf.PlayBackManager.prototype.removeStep = function(index) { this.scripts_.splice(index, 1); }; /** * Checks the sleep is done and updates info if not. * @return {boolean} Whether the sleep is done. * @private */ rpf.PlayBackManager.prototype.checkSleepReady_ = function() { if (!this.sleepReady_) { var now = this.getDate_().getTime(); if (now - this.userSetSleepStart_ >= this.userSetSleepTime_) { this.sleepReady_ = true; this.userSetSleepStart_ = 0; this.userSetSleepTime_ = 0; } } return this.sleepReady_; }; /** * Creates the actual playback script which is consisted of * both script and test data parts. * @param {string} datafile The test data. * @return {string} The real script for playback. * @export */ rpf.PlayBackManager.prototype.createPlayBackScript = function(datafile) { var index = 0; // By default, assign the first data value. return goog.string.buildString( 'var ContentMap = {};', datafile, 'try { for (var v in ContentMap) {', 'if (typeof(ContentMap[v]) == "object")', '{ ContentMap[v] = unescape(ContentMap[v][', index, ']);} else if (typeof(ContentMap[v]) == "string")', ' {ContentMap[v] = unescape(ContentMap[v]);}} } catch(e) ', '{console.log(e.toString())}', 'var cmdIndex = ', this.currentStep_, ';'); }; /** * Sets the user pause status. * @param {boolean} ready Whether the pause is done. * @export */ rpf.PlayBackManager.prototype.setUserPauseReady = function(ready) { this.userPauseReady_ = ready; if (ready) { this.startTimer(); } else { this.stopTimer(); } }; /** * Sets whether is in step mode. * @param {boolean} stepMode Whether is step mode. * @export */ rpf.PlayBackManager.prototype.setStepMode = function(stepMode) { this.stepMode_ = stepMode; if (!stepMode) { this.startTimeEachRun_ = this.getDate_().getTime(); } }; /** * Sets the elapsed time. * @private */ rpf.PlayBackManager.prototype.setElapseTime_ = function() { this.elapsedTime_ = parseInt((this.getDate_().getTime() - this.startTimeEachRun_) / 1000, 10) + ' seconds'; }; /** * Checks if it's ready to play the next command. * @return {boolean} Whether ready for the next command. * @private */ rpf.PlayBackManager.prototype.checkReadyForNext_ = function() { var urlChange = this.checkPageReady_(); var preCmdDone = this.isPreCmdDone(); var sleepReady = this.checkSleepReady_(); var userPauseReady = this.checkUserPauseReady_(); var logText = ''; this.elapsedTime_ = ''; if (this.startTimeEachRun_ != 0) { this.setElapseTime_(); } if (!urlChange) { logText = ('The url change has not finished. Elapsed: ' + this.elapsedTime_); console.log(logText); this.updateRuntimeStatus_(logText, 'red'); } if (!preCmdDone) { logText = 'The previous command has not finished. Elapsed: ' + this.elapsedTime_; console.log(logText); this.updateRuntimeStatus_(logText, 'red'); } if (!sleepReady) { logText = 'Still waiting for the sleep. Elapsed: ' + this.elapsedTime_; console.log(logText); this.updateRuntimeStatus_(logText, 'black'); } if (!userPauseReady) { console.log('Waiting for user pause'); } //Make sure both loading and complete events are caught between two cmds. if (this.isLoadingReadyForPlayback_()) { console.log('The url change status is not complete yet!'); urlChange = false; } return urlChange && preCmdDone && sleepReady && userPauseReady; }; /** * Sets a user stop status. * @param {boolean} userStop Whether there is a user specified stop. * @export */ rpf.PlayBackManager.prototype.setUserStop = function(userStop) { if (this.onPlayback_) { this.userStop_ = userStop; } }; /** * The cleanup part called after the playback is done. * @param {Bite.Constants.WorkerResults} status The result status. * @param {string} log The log. * @export */ rpf.PlayBackManager.prototype.finishCurrentRun = function(status, log) { this.currentRunStatus_ = status; this.removeTabUpdatedListener_(); if (!this.getAutoRunningTestId_()) { // This is to make the corresponding UI change. this.sendMessageToConsole_( {'command': Bite.Constants.UiCmds.UPDATE_WHEN_RUN_FINISHED, 'params': {'status': status, 'uiOnly': true}}); } this.onPlayback_ = false; this.preparationDone_ = false; this.stepMode_ = false; this.userPauseReady_ = true; this.userStop_ = false; this.failureRetryTimes_ = 0; this.userSpecifiedPauseStep_ = -1; this.playbackTimer_.stop(); this.eventMgrListener_( {'command': Bite.Constants.CONSOLE_CMDS.EVENT_COMPLETED, 'params': {'eventType': Bite.Constants.COMPLETED_EVENT_TYPES.FINISHED_RUNNING_TEST}}, {}, goog.nullFunction); }; /** * Updates the test result on server. */ rpf.PlayBackManager.prototype.updateTestResultOnServer = function() { if (this.currentRunStatus_ == Bite.Constants.WorkerResults.FAILED || this.currentRunStatus_ == Bite.Constants.WorkerResults.STOPPED) { chrome.tabs.captureVisibleTab(this.playbackWinId_, null, goog.bind(this.callBackAfterScreenShot_, this, Bite.Constants.WorkerResults.FAILED)); } else { var log = this.createLogJsonStr_( '', this.currentCmd_, '', '', this.currentStep_); this.runNext_(Bite.Constants.WorkerResults.PASS, this.playbackWinId_, '', log); } }; /** * Calls method to run the next test case. * @param {string} status The status of the test. * @param {string} dataUrl The screenshot string url. * @private */ rpf.PlayBackManager.prototype.callBackAfterScreenShot_ = function( status, dataUrl) { // TODO(phu): Add failed html in the result. var failureStr = this.createLogJsonStr_( 'Failed to finish.', this.currentCmd_, 'Failed to finish.', '', this.currentStep_); this.runNext_(status, this.playbackWinId_, dataUrl, failureStr); }; /** * Callback function for getting the failed html. * @param {string} status The status of the test. * @param {string} dataUrl The screenshot string url. * @param {Object} response The repsonse object. * @private */ rpf.PlayBackManager.prototype.getFailedHtmlCallback_ = function( status, dataUrl, response) { var failureReason = 'Error: URL change was taking too long!'; if (this.replayTabReady_) { failureReason = this.getAndClearFailureLog(); } var failureStr = this.createLogJsonStr_( response['failedHtml'], this.currentCmd_, failureReason, response['pageUrl'], this.currentStep_); this.runNext_(status, this.playbackWinId_, dataUrl, failureStr); }; /** * Calls to run the next test. * @param {string} status The status of the test. * @param {string} dataUrl The screenshot string url. * @param {number} currentId The current running test's id. * @private */ rpf.PlayBackManager.prototype.callRunNextOnce_ = function( status, dataUrl, currentId) { if (currentId == this.getAutoRunningTestId_()) { console.log('No response from content script. Run next here.'); var failureReason = 'Error: URL change was taking too long!'; if (this.replayTabReady_) { failureReason = this.getAndClearFailureLog(); } var failureStr = this.createLogJsonStr_( 'no html collected.', this.currentCmd_, failureReason, '', this.currentStep_); this.runNext_(status, this.playbackWinId_, dataUrl, failureStr); } }; /** * Creates the result log string for debugging purpose. * @param {string} failedHtml The failed page's html. * @param {string} cmd The current command. * @param {string} failureReason The last known failure reason. * @param {string} pageUrl The failed page's url. * @param {number} stepIndex The current step index. * @return {string} The failure json string. * @private */ rpf.PlayBackManager.prototype.createLogJsonStr_ = function( failedHtml, cmd, failureReason, pageUrl, stepIndex) { var timeStamp = rpf.MiscHelper.getTimeStamp(); var result = {}; result['timeStamp'] = timeStamp; result['failedHtml'] = failedHtml; result['cmd'] = cmd; result['failureReason'] = failureReason; result['pageUrl'] = pageUrl; result['stepIndex'] = stepIndex; result['testName'] = this.currentTestName_; result['projectName'] = this.currentProjectName_; result['testLocation'] = this.currentTestLocation_; return JSON.stringify(result); }; /** * The playback finishes successfully. * @private */ rpf.PlayBackManager.prototype.onSuccess_ = function() { var log = 'Finished replay!'; this.finishCurrentRun(Bite.Constants.WorkerResults.PASS, log); console.log(log); this.logger_.saveLogAndHtml(log, rpf.ConsoleLogger.LogLevel.INFO, rpf.ConsoleLogger.Color.GREEN); }; /** * Stops the playback timer. * @export */ rpf.PlayBackManager.prototype.stopTimer = function() { if (this.playbackTimer_.enabled) { this.playbackTimer_.stop(); } }; /** * Starts the playback timer. * @export */ rpf.PlayBackManager.prototype.startTimer = function() { if (!this.playbackTimer_.enabled) { this.playbackTimer_.start(); } }; /** * User sets pause during a playback. * @export */ rpf.PlayBackManager.prototype.userSetPause = function() { this.stopTimer(); if (!this.checkUserPauseReady_()) { return; } this.setStepMode(true); this.setUserPauseReady(false); if (!this.replayTabReady_ || !this.previousCmdDone_) { this.failureReason_ = 'UserPauseFailure'; if (!this.getAutoRunningTestId_()) { this.sendMessageToConsole_( {'command': Bite.Constants.UiCmds.UPDATE_CURRENT_STEP, 'params': {'curStep': this.currentStep_}}); } this.onFailed_(); } }; /** * The playback encountered a failure. * @private */ rpf.PlayBackManager.prototype.onFailed_ = function() { var log = goog.string.buildString('Error: Timeout at this step(', this.currentStep_, '):', this.scripts_[this.currentStep_]); this.logger_.saveLogAndHtml(log, rpf.ConsoleLogger.LogLevel.ERROR, rpf.ConsoleLogger.Color.RED); console.log('On failed: ' + log); if (this.continueOnFailure_) { this.finishCurrentRun(Bite.Constants.WorkerResults.FAILED, log); } else { this.stopTimer(); this.userSetPause(); this.sendMessageToConsole_( {'command': Bite.Constants.UiCmds.UPDATE_WHEN_ON_FAILED, 'params': {'failureReason': this.failureReason_, 'failureLog': this.getAndClearFailureLog(), 'currentStep': this.currentStep_, 'uiOnly': true}}); } }; /** * Checks if the current step is a redirection. * @param {string} step The current running step. * @private * @return {boolean} Whether the step is a redirection. */ rpf.PlayBackManager.prototype.isRedirection_ = function(step) { if (step.indexOf(rpf.CodeGenerator.PlaybackActions.REDIRECT) == 0 || step.indexOf(rpf.CodeGenerator.PlaybackActions.REDIRECT_TO) == 0) { return true; } return false; }; /** * Executes a client command in content script. * @export */ rpf.PlayBackManager.prototype.executeCmd = function() { this.previousCmdDone_ = false; // TODO(phu): Remove this check after making sure each run cmd can get back. var nextStep = this.currentStep_ + 1; if (nextStep < this.scripts_.length && this.isRedirection_(this.scripts_[nextStep])) { // The redirection happens immediately after the action, so we need to // set the flag beforehand. this.replayTabReady_ = false; console.log('The next step is an URL change, so set ready to false'); } chrome.tabs.sendRequest( this.playbackTabId_, {script: this.createPlayBackScript(this.datafile_), realTimeBag: this.realTimeBack_, stepCommand: this.currentCmd_, useXpath: this.useXpath_, cmdMap: rpf.MiscHelper.getElemMap(this.currentCmd_, this.infoMap_)}, goog.bind(this.callBackWhileExecCmds, this)); }; /** * Sets the break point. * @param {number} step The step for a pause. * @export */ rpf.PlayBackManager.prototype.setUserSpecifiedPauseStep = function(step) { if (step == this.getCurrentStep()) { step -= 1; } this.userSpecifiedPauseStep_ = step; }; /** * Enum for command types. * @enum {string} * @export */ rpf.PlayBackManager.CmdTypes = { CLIENT_CMD: 'run(', SLEEP: 'sleep', CHANGE_URL: 'changeUrl' }; /** * Sets the timeout for this step. * @private */ rpf.PlayBackManager.prototype.setStepTimeout_ = function() { // TODO(phu): Get the cmd timeout value. var temp = 0; this.eachCmdTimeout_ = temp + rpf.PlayBackManager.rpfPlaybackInterval_ * 2; if (this.isLoadingReadyForPlayback_() && this.eachCmdTimeout_ < this.defaultTimeout_) { this.eachCmdTimeout_ = this.defaultTimeout_; } console.log('The specified timeout for this command is: ' + this.eachCmdTimeout_ + ' ms'); }; /** * User explicitly stops the current playback. * @export */ rpf.PlayBackManager.prototype.userSetStop = function() { if (this.userStop_) { return; } this.userStop_ = true; var log = 'Run has been stopped.'; this.finishCurrentRun(Bite.Constants.WorkerResults.STOPPED, log); this.logger_.saveLogAndHtml(log); }; /** * Waits for ready and executes a command. * @export */ rpf.PlayBackManager.prototype.waitForElementReadyAndExecCmds = function() { console.log('This run elapsed:' + (this.getDate_().getTime() - this.startTimeEachRun_)); if (this.userStop_) { console.log('This is going to be removed, if this line' + 'will not show up any more.'); this.userSetStop(); return; } if (this.userSpecifiedPauseStep_ == this.currentStep_) { this.userSetPause(); this.sendMessageToConsole_( {'command': Bite.Constants.UiCmds.SET_PLAYBACK_PAUSE, 'params': {'uiOnly': true}}); } if (!this.stepMode_ && this.startTimeEachRun_ != 0 && this.getDate_().getTime() - this.startTimeEachRun_ > this.eachCmdTimeout_) { this.checkFailureCondition(); } if (this.checkReadyForNext_()) { this.eachCmdTimeout_ = rpf.PlayBackManager.EACH_CMD_TIMEOUT_; this.currentCmd_ = this.scripts_[this.currentStep_]; console.log('Running:' + this.currentCmd_ + '//' + this.currentStep_ + '//' + this.scripts_.length); if (!this.getAutoRunningTestId_()) { this.sendMessageToConsole_( {'command': Bite.Constants.UiCmds.UPDATE_CURRENT_STEP, 'params': {'curStep': this.currentStep_}}); } if (!this.failureRetryTimes_) { this.startTimeEachRun_ = this.getDate_().getTime(); } if (this.stepMode_) { this.setUserPauseReady(false); } var commandType = rpf.CodeGenerator.testCmdType(this.currentCmd_); if (commandType == 0 || commandType == 1) { this.executeCmd(); } else if (this.currentCmd_.indexOf( rpf.CodeGenerator.PlaybackActions.REDIRECT) === 0 || this.currentCmd_.indexOf( rpf.CodeGenerator.PlaybackActions.REDIRECT_TO) === 0) { this.callBackAfterExecCmds(''); } else if (this.currentCmd_.indexOf( rpf.PlayBackManager.CmdTypes.SLEEP) === 0) { this.userSetSleepTime_ = parseInt(this.currentCmd_.match(/\d+/), 10); this.eachCmdTimeout_ = this.userSetSleepTime_ + rpf.PlayBackManager.rpfPlaybackInterval_ * 2; this.userSetSleepStart_ = this.getDate_().getTime(); console.log('The current step will sleep for ' + this.userSetSleepTime_); this.sleepReady_ = false; this.callBackAfterExecCmds(''); } else if (this.currentCmd_.indexOf( rpf.PlayBackManager.CmdTypes.CHANGE_URL) === 0) { var newUrl = this.currentCmd_.substring(10, this.currentCmd_.length - 2); console.log('The new url is: ' + newUrl); this.replayTabReady_ = false; chrome.tabs.update(this.playbackTabId_, {url: newUrl}); this.callBackAfterExecCmds(''); } else { console.log('Encountered an unknown line.' + this.currentCmd_); this.callBackAfterExecCmds(''); } // this.setStepTimeout_(); } else { console.log('waiting...'); } }; /** * Callback from client content script (not necessary done). * @param {Object} response Contains the result. * @export */ rpf.PlayBackManager.prototype.callBackWhileExecCmds = function(response) { }; /** * Sets the failure log. * @param {string} log The failure log. * @export */ rpf.PlayBackManager.prototype.setFailureLog = function(log) { this.failureLog_ = log; }; /** * Gets and clears the failure log. * @return {string} The failure log. * @export */ rpf.PlayBackManager.prototype.getAndClearFailureLog = function() { var failureLog = this.failureLog_; this.failureLog_ = ''; return failureLog; }; /** * Updates the playback runtime status. * @param {string} text The status text. * @param {string} color The text color. * @private */ rpf.PlayBackManager.prototype.updateRuntimeStatus_ = function(text, color) { if (!this.getAutoRunningTestId_()) { this.sendMessageToConsole_( {'command': Bite.Constants.UiCmds.UPDATE_PLAYBACK_STATUS, 'params': {'text': text, 'color': color}}); } }; /** * Checks post condition when a step fails. * @export */ rpf.PlayBackManager.prototype.checkFailureCondition = function() { console.log('Replay was forced out because of failures!'); this.failureReason_ = 'MultipleRetryFindElemFailure'; this.onFailed_(); }; /** * The callback after the executing a command. * @param {string} result The result string. * @param {string=} opt_log The optional log. * @export */ rpf.PlayBackManager.prototype.callBackAfterExecCmds = function(result, opt_log) { var log = 'Result for:' + this.currentStep_ + 'is:' + result; console.log(log); this.logger_.saveLogAndHtml(log, rpf.ConsoleLogger.LogLevel.INFO, rpf.ConsoleLogger.Color.BLUE); this.previousCmdDone_ = true; if (result == 'failed') { this.failureRetryTimes_ += 1; this.replayTabReady_ = true; var logText = 'Failed because "' + opt_log + '"\n' + 'Already elapsed: ' + this.elapsedTime_; console.log(logText); this.updateRuntimeStatus_(logText, 'red'); return; } this.updateRuntimeStatus_('Successfully finished the current step.', 'green'); this.failureRetryTimes_ = 0; this.setNextRunnableCmd_(); if (this.currentStep_ >= this.scripts_.length) { this.onSuccess_(); return; } if (this.isRedirection_(this.scripts_[this.currentStep_])) { this.eachCmdTimeout_ = this.defaultTimeout_; } }; /** * Set to the next runnable step. * @private */ rpf.PlayBackManager.prototype.setNextRunnableCmd_ = function() { while (true) { this.currentStep_++; if (this.currentStep_ == this.scripts_.length) { return; } var cmd = this.scripts_[this.currentStep_]; if (rpf.CodeGenerator.testCmdType(cmd) != 3) { return; } } }; /** * Starts the listeners inside content script. * @export */ rpf.PlayBackManager.prototype.callBackAfterTabUpdated = function() { console.log('finished page init and set replay tab ready.' + 'Now it should be able to run the next CMD!'); chrome.tabs.executeScript(this.playbackTabId_, {code: 'startListener();', allFrames: true}); }; /** * Checks the playback option and starts playing back. * @param {string} method The method of playback. * @param {string} startUrl The start url. * @param {string} scripts The raw script string. * @param {string} datafile The corresponding data file. * @param {string} userLib The user specified library. * @param {Object=} opt_infoMap The info map. * @param {boolean=} opt_continueOnFailure Whether should continue or * show update UI on failure. * @param {string=} opt_testName The test name. * @param {string=} opt_testId The test id. * @param {string=} opt_projectName The project name. * @param {string=} opt_testLocation The test location. */ rpf.PlayBackManager.prototype.checkPlaybackOptionAndRun = function( method, startUrl, scripts, datafile, userLib, opt_infoMap, opt_continueOnFailure, opt_testName, opt_testId, opt_projectName, opt_testLocation) { this.continueOnFailure_ = opt_continueOnFailure || false; this.currentTestName_ = opt_testName || ''; this.currentProjectName_ = opt_projectName || ''; this.currentTestLocation_ = opt_testLocation || ''; this.currentTestId_ = opt_testId || ''; this.infoMap_ = opt_infoMap || {}; if (this.isPreparationDone()) { this.initResumePlayback_(); if (method == Bite.Constants.PlayMethods.ALL) { this.setStepMode(false); } else { this.setStepMode(true); } this.setUserPauseReady(true); } else { if (method == Bite.Constants.PlayMethods.STEP) { this.setStepMode(true); this.setUserPauseReady(true); } this.runTest(startUrl, scripts, datafile, userLib); } }; /** * Sets the infoMap object. * @param {Object} infoMap The info map. */ rpf.PlayBackManager.prototype.setInfoMap = function(infoMap) { this.infoMap_ = infoMap; }; /** * Inserts commands while playing back a script. * @param {string} scriptStr The script string. * @param {string} data The data file string. * @export */ rpf.PlayBackManager.prototype.insertCmdsWhilePlayback = function(scriptStr, data) { var newScripts = this.getAllStepsFromScript(scriptStr); for (var i = newScripts.length - 1; i >= 0; i--) { this.scripts_.splice(this.currentStep_, 0, newScripts[i]); } this.datafile_ += data; this.currentStep_ += newScripts.length; }; /** * @return {string} The current test name. * @export */ rpf.PlayBackManager.prototype.getCurrentTestName = function() { return this.currentTestName_; }; /** * @return {string} The current test id. * @export */ rpf.PlayBackManager.prototype.getCurrentTestId = function() { return this.currentTestId_; }; /** * @return {string} The last matched html. * @export */ rpf.PlayBackManager.prototype.getLastMatchHtml = function() { return this.lastMatchHtml_; }; /** * @param {string} html The last matches html. * @export */ rpf.PlayBackManager.prototype.setLastMatchHtml = function(html) { this.lastMatchHtml_ = html; }; /** * @return {number} The tab id of the page under playback. * @export */ rpf.PlayBackManager.prototype.getPlaybackTabId = function() { return this.playbackTabId_; }; /** * @param {number} tabId The tab id of the page under playback. * @export */ rpf.PlayBackManager.prototype.setPlaybackTabId = function(tabId) { this.playbackTabId_ = tabId; }; /** * @return {number} The window id of the page under playback. * @export */ rpf.PlayBackManager.prototype.getPlaybackWindowId = function() { return this.playbackWinId_; }; /** * @return {boolean} Whether the preparation for playback is done. * @export */ rpf.PlayBackManager.prototype.isPreparationDone = function() { return this.preparationDone_; }; /** * @param {boolean} done Sets the preparationDone variable. * @export */ rpf.PlayBackManager.prototype.setPreparationDone = function(done) { this.preparationDone_ = done; }; /** * @return {string} The command of current step. * @export */ rpf.PlayBackManager.prototype.getCurrentCmd = function() { return this.currentCmd_; }; /** * @return {boolean} whether tab updates ready. * @export */ rpf.PlayBackManager.prototype.isReplayTabReady = function() { return this.replayTabReady_; }; /** * @param {boolean} isReady whether tab updates ready. * @export */ rpf.PlayBackManager.prototype.setReplayTabReady = function(isReady) { this.replayTabReady_ = isReady; };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * The wrapper functions for browser actions, which RPF uses to simulate * user's action like click, type, input, doubleclick, etc. * This file also contains a listener which listens * to commands from the background page, executes them and sends the result * back to the background. * * @author phu@google.com (Po Hu) */ goog.provide('BiteRpfAction'); goog.provide('bite.rpf.ActionsHelper'); goog.require('Bite.Constants'); goog.require('common.client.ElementDescriptor'); goog.require('goog.Timer'); /** * The bite browser actions wrapper. * @constructor * @export */ bite.rpf.ActionsHelper = function() { }; /** * Periodically executes a function until it returns true or timeout. * @param {Function} func The function to run. * @param {number} timeout The timeout in secs. * @param {Function} nextFunc The function to run on success. */ bite.rpf.ActionsHelper.prototype.retry = function( func, timeout, nextFunc) { var len = arguments.length; if (len >= 4) { var realArgs = []; for (var i = 3; i < len; i++) { realArgs.push(arguments[i]); } this.funcStartTime_ = goog.now(); this.funcRunTimeout_ = timeout * 1000; this.retry_(func, realArgs, nextFunc); } else { console.log('Not enough arguments.'); } }; /** * Retries a function until it succeeds or timeout. * @param {Function} func The function to retry. * @param {Array} args The argument array. * @param {Function} nextFunc The next function to run on success. * @private */ bite.rpf.ActionsHelper.prototype.retry_ = function( func, args, nextFunc) { try { func.apply(this, args); if (nextFunc) { goog.Timer.callOnce(nextFunc, 1500); } } catch (e) { var elapsed = goog.now() - this.funcStartTime_; if (elapsed > this.funcRunTimeout_) { throw new Error(' Failed to execute ' + func.toString()); } else { goog.Timer.callOnce(goog.bind( this.retry_, this, func, args, nextFunc), 3000); } } }; /** * Clicks the given element. * @param {string|Element} elem The element to be clicked. */ bite.rpf.ActionsHelper.prototype.click = function(elem) { }; /** * Presses the enter key. * @param {string|Element} elem The element to press enter on. */ bite.rpf.ActionsHelper.prototype.enter = function(elem) { }; /** * Selects the given element. * @param {string|Element} elem The element to be selected. * @param {string} value The value to be selected. */ bite.rpf.ActionsHelper.prototype.select = function(elem, value) { }; /** * Drags the given element. * @param {string|Element} elem The element to be dragged. * @param {number} dX The difference of x coordinates. * @param {number} dY The difference of y coordinates. */ bite.rpf.ActionsHelper.prototype.drag = function(elem, dX, dY) { }; /** * Inputs text in the given element by changing the element's value attribute. * @param {string|Element} elem The element to have text input. * @param {string} text The text input. */ bite.rpf.ActionsHelper.prototype.input = function(elem, text) { }; /** * Inputs text character by character in the given element. * @param {string|Element} elem The element to have text input. * @param {string} text The text input. */ bite.rpf.ActionsHelper.prototype.type = function(elem, text) { }; /** * Submits the form. * @param {string|Element} elem The form to be submitted. */ bite.rpf.ActionsHelper.prototype.submit = function(elem) { }; /** * Double clicks the given element. * @param {string|Element} elem The element to be double clicked. */ bite.rpf.ActionsHelper.prototype.doubleClick = function(elem) { }; /** * Verifies the specified element does not exist. * @param {string|Element} elem The element. * @param {string} content The content to verify. */ bite.rpf.ActionsHelper.prototype.verifyNot = function(elem, content) { }; /** * Verifies the specified element exists. * @param {string|Element} elem The element. * @param {string} content The content to verify. */ bite.rpf.ActionsHelper.prototype.verify = function(elem, content) { }; /** * Calls the given function with parameters. * An example of a call to custom JS function is: * For aysnc call: * call(true, sendResultToBackground, myCustomFunction, myArg1, myArg2); * For sync call: * call(false, sendResultToBackground, myCustomFunction, myArg1, myArg2); * or * call(myCustomFunction, myArg1, myArg2); */ bite.rpf.ActionsHelper.prototype.call = function() { // Assume the first parameter represents whether is a async call. // Given the async parameter, the second parameter is the callback function. // In this case, it should be sendResultToBackground. // The third parameter is the function name, and the rest are arguments. // Note that if async is not given, then the first parameter will be the // function name. var func = null; var async = false; var args = []; // Assume this is always the immediate next of the function name parameter. var firstArgIndex = 1; if (typeof arguments[0] == 'boolean') { if (typeof arguments[1] != 'function' || typeof arguments[2] != 'function') { throw new Error('The given command is malformatted.'); } async = arguments[0]; BiteRpfAction.isAsync = async; // The arguments[1] is the callback function. args.push(arguments[1]); func = arguments[2]; firstArgIndex = 3; } else { func = arguments[0]; } for (var i = firstArgIndex; i < arguments.length; ++i) { args.push(arguments[i]); } func.apply(null, args); }; /** * Moves the mouse cursor to a given element. * @param {string|Element} elem The element. */ bite.rpf.ActionsHelper.prototype.move = function(elem) { }; /** * The retry wrapper. * @type {function(Function, number, Function)} */ BiteRpfAction.retry = goog.nullFunction; /** * The click wrapper. * @type {function((string|Element))} */ BiteRpfAction.click = goog.nullFunction; /** * The enter key wrapper. * @type {function((string|Element))} */ BiteRpfAction.enter = goog.nullFunction; /** * The select wrapper. * @type {function((string|Element))} */ BiteRpfAction.select = goog.nullFunction; /** * The drag wrapper. * @type {function((string|Element))} */ BiteRpfAction.drag = goog.nullFunction; /** * The type wrapper. * @type {function((string|Element), string)} */ BiteRpfAction.type = goog.nullFunction; /** * The input wrapper. * @type {function((string|Element), string)} */ BiteRpfAction.input = goog.nullFunction; /** * The submit wrapper. * @type {function((string|Element))} */ BiteRpfAction.submit = goog.nullFunction; /** * The double click wrapper. * @type {function((string|Element))} * @export */ BiteRpfAction.doubleClick = goog.nullFunction; /** * The verify wrapper. * @type {function((string|Element))} */ BiteRpfAction.verify = goog.nullFunction; /** * The custom JS function executing wrapper. * @type {function((string|Element))} */ BiteRpfAction.call = goog.nullFunction; /** * The mouse move wrapper. * @type {function((string|Element))} */ BiteRpfAction.move = goog.nullFunction; /** * The verify not wrapper. * @type {function((string|Element))} */ BiteRpfAction.verifyNot = goog.nullFunction; /** * The current step's information map which contains descriptor, xpath, etc. * @type {!Object} */ BiteRpfAction.currCmdMap = {}; /** * The locator finding method. * @type {string} */ BiteRpfAction.locatorMethodString = ''; /** * The element info. * @type {!Object} */ BiteRpfAction.elemInfo = {}; /** * Whether it's an async call. * @type {boolean} */ BiteRpfAction.isAsync = false; /** * The current command's index. * @type {number} */ BiteRpfAction.cmdIndex = 0; /** * The current command's content map. * @type {Object} */ BiteRpfAction.contentMap = {}; /** * The onRequest callback handler. * @param {Object} request The request object. * @param {MessageSender} sender The sender object. * @param {function(Object)} sendResponse The response object. */ function onRequestCallback(request, sender, sendResponse) { var win = goog.global.window; if (request['getFailedHtml']) { var outerHtml = goog.dom.getDocument().documentElement.outerHTML; if (win == win.parent) { sendResponse({failedHtml: outerHtml, pageUrl: document.location.href}); } } else if (request['script']) { try { function checkCorrectWindow() { // For legacy code. if (!request['cmdMap']) { return true; } var iframeInfo = request['cmdMap']['iframeInfo']; // For main window. if (win == win.parent && !iframeInfo) { return true; } var host = win.location.host; var pathname = win.location.pathname; // For iframe window. if (iframeInfo && host == iframeInfo['host'] && pathname == iframeInfo['pathname']) { return true; } return false; } if (!checkCorrectWindow()) { return; } // Executes the contentMap code. eval(request['script']); BiteRpfAction.cmdIndex = cmdIndex; if (request['realTimeBag']) { var bagObj = goog.json.parse(request['realTimeBag']); for (var key in bagObj) { ContentMap[key] = bagObj[key]; } } var locatorMethodString = request['useXpath'] ? 'xpath' : 'descriptor'; BiteRpfAction.currCmdMap = request['cmdMap']; BiteRpfAction.locatorMethodString = locatorMethodString; BiteRpfAction.contentMap = ContentMap; BiteRpfAction.isAsync = false; var cmd = common.client.ElementDescriptor.parseCommandToRunnable( request['stepCommand']); eval(cmd); // During eval the command, if it's making a async JS call, then // BiteRpfAction.isAync will be set to true. In this case, it needs // skip sending the result to background to finish the execution. // Instead, in user's JS function they should explicitly call // sendResultToBackground to finish the JS function execution. if (!BiteRpfAction.isAsync) { sendResultToBackground(true, cmd); } console.log('Succesfully executed the command.'); } catch (e) { if (!e) { var errorMessage = BiteRpfAction.elemInfo['log']; } else { var errorMessage = e.message; } var resultStr = 'Error: ' + errorMessage; chrome.extension.sendRequest( {command: 'cmdDone', result: resultStr, index: BiteRpfAction.cmdIndex}); } finally { // The sendResponse is called to close the request. // TODO(phu): Use it to send back the results. BiteRpfAction.isAsync = false; sendResponse({}); } } } /** * Sends the result to background page. * @param {boolean} passed Whether the result is a pass or not. * @param {string} log The log entry for the test result. * @export */ function sendResultToBackground(passed, log) { var result = passed ? 'passed: ' + log : 'Error: ' + log; chrome.extension.sendRequest( {command: 'cmdDone', result: result, index: BiteRpfAction.cmdIndex, realTimeMap: goog.json.serialize(BiteRpfAction.contentMap)}); } /** * Gets the element. * @param {string} stepId The step id. * @return {!Element} The result element. * @export */ function getElem(stepId) { BiteRpfAction.elemInfo = common.client.ElementDescriptor.getElement( BiteRpfAction.currCmdMap, BiteRpfAction.locatorMethodString) || {}; var elem = BiteRpfAction.elemInfo['elem']; if (!elem) { throw new Error(BiteRpfAction.elemInfo['log']); } return elem; } /** * Starts to listen to requests. * @export */ function startListener() { chrome.extension.onRequest.removeListener(onRequestCallback); chrome.extension.onRequest.addListener(onRequestCallback); chrome.extension.sendRequest({command: 'initReady', result: true}); } /** * Stops listening to requests. * @export */ function removeListener() { chrome.extension.onRequest.removeListener(onRequestCallback); }
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains how to automatically generate code. * * @author phu@google.com (Po Hu) */ goog.provide('rpf.CodeGenerator'); goog.provide('rpf.CodeNode'); goog.require('bite.base.Helper'); goog.require('goog.math'); goog.require('goog.string'); goog.require('rpf.MiscHelper'); /** * A class for the generated tree node. * @param {rpf.CodeNode.NodeType} nodeType The node type. * @param {string} value The node value. * @param {Object} opt_info The optional info. * @constructor */ rpf.CodeNode = function(nodeType, value, opt_info) { /** * The type of the node. * @type {rpf.CodeNode.NodeType} * @private */ this.type_ = nodeType; /** * The value on this node. * @type {string} * @private */ this.value_ = value; /** * The additional info. * @type {Object} * @private */ this.additionalInfo_ = opt_info || {}; /** * The children nodes. * @type {Array} * @private */ this.children_ = []; /** * The parent node. * @type {rpf.CodeNode} * @private */ this.parent_ = null; }; /** * Enum for the node type. * @enum {string} * @export */ rpf.CodeNode.NodeType = { ROOT: 'root', IMPORT: 'import', CLASS: 'class', METHOD: 'method', PROPERTY: 'property', COMMAND: 'command', COMMENT: 'comment' }; /** * Gets the parent node. * @return {rpf.CodeNode} The parent node. * @export */ rpf.CodeNode.prototype.getParent = function() { return this.parent_; }; /** * Sets the parent node. * @param {rpf.CodeNode} pNode The parent node. * @export */ rpf.CodeNode.prototype.setParent = function(pNode) { this.parent_ = pNode; }; /** * Gets the next sibling node. * @return {rpf.CodeNode} The next sibling node. * @export */ rpf.CodeNode.prototype.getNext = function() { var siblings = this.parent_.children_; for (var i = 0, len = siblings.length; i < len; i++) { if (siblings[i] == this) { return siblings[i + 1] || null; } } return null; }; /** * Adds a child node. * @param {rpf.CodeNode} node The child node. * @export */ rpf.CodeNode.prototype.addChild = function(node) { this.children_.push(node); node.setParent(this); }; /** * Gets all the children nodes. * @return {Array} All of the children nodes. * @export */ rpf.CodeNode.prototype.getChildren = function() { return this.children_; }; /** * Gets the type of the node. * @return {rpf.CodeNode.NodeType} The type of the node. * @export */ rpf.CodeNode.prototype.getType = function() { return this.type_; }; /** * Gets the value of the node. * @return {string} The value of the node. * @export */ rpf.CodeNode.prototype.getValue = function() { return this.value_; }; /** * Gets the additional info. * @param {string} name The parameter's name. * @return {Object} The additional info object. * @export */ rpf.CodeNode.prototype.getAdditional = function(name) { return this.additionalInfo_[name] || null; }; /** * Sets the additional info. * @param {string} name The info name. * @param {string} value The info value. * @export */ rpf.CodeNode.prototype.setAdditional = function(name, value) { this.additionalInfo_[name] = value; }; /** * A class for generating the test script. * @constructor */ rpf.CodeGenerator = function() { /** * The generated code tree. * @type {rpf.CodeNode} * @private */ this.codeTree_ = null; }; /** * @const * @type {string} * @private */ rpf.CodeGenerator.VARIABLE_CONTENT_MAP_ = 'ContentMap'; /** * The bite action namespace. * @const * @type {string} * @private */ rpf.CodeGenerator.BITE_ACTION_NAMESPACE_ = 'bite.rpf.'; /** * Enum for the dom action values. * @enum {string} * @export */ rpf.CodeGenerator.RecordActions = { CHANGE: 'change', CLICK: 'click', DBLCLICK: 'doubleClick', DRAG: 'drag', ENTER: 'enter', KEYUP: 'keyup', MOVE: 'move', REPLACE_HTML: 'replaceHtml', SELECT: 'select', SUBMIT: 'submit', TYPE: 'type', VERIFY: 'verify', VERIFYNOT: 'verifyNot' }; /** * Enum for the dom tags. * @enum {string} * @export */ rpf.CodeGenerator.DomTags = { SELECT: 'select', TEXTAREA: 'textarea' }; /** * Enum for the client action values. * @enum {string} * @export */ rpf.CodeGenerator.PlaybackActions = { CLICK: 'click', CALL: 'call', DBLCLICK: 'doubleClick', ENTER: 'enter', RUN: 'run', SELECT: 'select', INPUT: 'input', TYPE: 'type', SUBMIT: 'submit', FIND: 'find', VERIFY: 'verify', WAIT: 'wait', MOUSE: 'mouse', MOVE: 'move', COMPARE: 'comparePosition', CHANGE_URL: 'changeUrl', SLEEP: 'sleep', VALIDATE_BLOCK: 'validateBlock', REDIRECT: '<<<>>>', REDIRECT_TO: 'redirectTo', REPLACE_HTML: 'replaceHtml', DRAG: 'drag' }; /** * Gets the generated code for a url redirection. * @param {string} url The url it redirects to. * @return {string} The generated cmd string. * @export */ rpf.CodeGenerator.getRedirectUrl = function(url) { return goog.string.buildString( rpf.CodeGenerator.PlaybackActions.REDIRECT_TO, '("', url, '");'); }; /** * Tests the command type. * @param {string} cmd The command string. * @return {number} 0: Old executable. 1: New executable. 2: Others commands. * 3: The rest cases. * @export */ rpf.CodeGenerator.testCmdType = function(cmd) { var actions = rpf.CodeGenerator.PlaybackActions; if (goog.string.startsWith(cmd, actions.RUN)) { return 0; } else if ( goog.string.startsWith(cmd, actions.CLICK) || goog.string.startsWith(cmd, actions.DBLCLICK) || goog.string.startsWith(cmd, actions.ENTER) || goog.string.startsWith(cmd, actions.SELECT) || goog.string.startsWith(cmd, actions.INPUT) || goog.string.startsWith(cmd, actions.MOVE) || goog.string.startsWith(cmd, actions.TYPE) || goog.string.startsWith(cmd, actions.SUBMIT) || goog.string.startsWith(cmd, actions.VERIFY) || goog.string.startsWith(cmd, actions.CALL) || goog.string.startsWith(cmd, actions.DRAG) || goog.string.startsWith(cmd, actions.REPLACE_HTML)) { return 1; } else if ( goog.string.startsWith(cmd, actions.REDIRECT) || goog.string.startsWith(cmd, actions.REDIRECT_TO) || goog.string.startsWith(cmd, actions.SLEEP) || goog.string.startsWith(cmd, actions.CHANGE_URL)) { return 2; } else { return 3; } }; /** * Gets the generated code tree. * @return {rpf.CodeNode} The generated code tree. * @export */ rpf.CodeGenerator.prototype.getCodeTree = function() { return this.codeTree_; }; /** * Gets the url in a generated redirect command. * @param {string} cmd The generated command. * @return {string} The url. * @export */ rpf.CodeGenerator.getUrlInRedirectCmd = function(cmd) { // Support either the new version of the redirect command, // redirectTo("url"), and the old redirectTo(url). var urlRegexp = /\("?([^"]*)"?\)/; return urlRegexp.exec(cmd)[1]; }; /** * Gets the indentation. * @param {number} number The number of spaces. * @return {string} The indentation. * @export */ rpf.CodeGenerator.prototype.getIndentation = function(number) { var indent = ''; for (var i = 0; i < number; i++) { indent += ' '; } return indent; }; /** * Generates the command for sleeping. * @param {string} sleepTime The sleeping time. * @return {string} The command for a sleep command. * @export */ rpf.CodeGenerator.generateSleepCmd = function(sleepTime) { return goog.string.buildString( rpf.CodeGenerator.PlaybackActions.SLEEP, '(', sleepTime, ');'); }; /** * Generates the command for adding a customized function. * @param {string} signature The function signature. * @return {string} The command for a function call. * @export */ rpf.CodeGenerator.generateFunctionCmd = function(signature) { return goog.string.buildString( rpf.CodeGenerator.PlaybackActions.RUN, '(', signature, ');'); }; /** * Generates the command for adding a invocation to a test. * @param {string} testId The test id. * @param {string} testName The test name. * @return {string} The command for the invocation. * @export */ rpf.CodeGenerator.generateInvocationCmd = function( testId, testName) { return goog.string.buildString( rpf.CodeGenerator.PlaybackActions.RUN, '(invoke, \'calls ', testName, ' module.\');/*"""call(', testId, ')"""*/'); }; /** * Gets the value of an attribute. * @param {Object|string} attrValue The attribute value. * @return {string} The value of the attribute. * @private */ rpf.CodeGenerator.prototype.getsAttrValue_ = function(attrValue) { if (!attrValue) { return ''; } if (typeof(attrValue) == 'string') { return attrValue; } else { return attrValue['value']; } }; /** * Gets the tag name from the new generated code. * @param {string} cmd The cmd string. * @return {string} The tagname. * @private */ rpf.CodeGenerator.prototype.getTagNameFromNewCode_ = function(cmd) { var id = bite.base.Helper.getStepId(cmd); return id.split('-')[1]; }; // TODO(phu): add info per existence in attributes. /** * Extract the important info from the given descriptor. * @param {string} script The script string. * @param {string} content The content string. * @param {Object=} opt_descriptor The optional descriptor object. * @return {string} The important info of the descriptor. * @export */ rpf.CodeGenerator.prototype.extractInfo = function( script, content, opt_descriptor) { try { var descriptor = opt_descriptor || rpf.MiscHelper.getDescriptor(script); var tagName = descriptor.tagName || ''; var info = ''; var text = descriptor['elementText'] || ''; if (content) { info = ' "' + content + '" in'; } var tagNameValue = tagName ? this.getsAttrValue_(tagName) : this.getTagNameFromNewCode_(script); info += ' the ' + tagNameValue + ' with'; if (!descriptor.attributes) { var id = descriptor.id || ''; var class_ = descriptor['class_'] || ''; var value = descriptor.value || ''; var name = descriptor.name || ''; } else { var id = descriptor.attributes.id || ''; var class_ = descriptor.attributes['class'] || ''; var value = descriptor.attributes.value || ''; var name = descriptor.attributes.name || ''; } if (text) { info += ' TEXT "' + this.getsAttrValue_(text) + '"'; } else if (value) { info += ' VALUE "' + this.getsAttrValue_(value) + '"'; } else { if (id) { info += ' ID ' + this.getsAttrValue_(id); } if (class_) { info += ' CLASS ' + this.getsAttrValue_(class_); } if (name) { info += ' NAME ' + this.getsAttrValue_(name); } } } catch (e) { info = 'Error: ' + e.message; } return info; }; /** * Gets the action if it is an action string. * @param {string} cmd The command string. * @return {string} The action. */ rpf.CodeGenerator.getAction = function(cmd) { var result = cmd.match(/run\(([a-z]+),/); if (result && result.length >= 2) { // The second element is the action. The format of cmd looks like // run(click, ...); return result[1]; } result = cmd.match(/([a-z]+)\(()/); if (result && result.length >= 2) { // This is to match click(... format. return result[1]; } return ''; }; /** * Translates the generated command into English. * @param {string} script The generated script string. * @param {string=} opt_data The data string. * @param {Object=} opt_descriptor The optional descriptor object. * @return {string} The human readable script. * @export */ rpf.CodeGenerator.prototype.translateCmd = function( script, opt_data, opt_descriptor) { var data = opt_data || ''; var dataStr = goog.string.buildString('var ContentMap = {};', data); try { eval(dataStr); if (!script) { return ''; } var content = script.match(/ContentMap\[\".*\"\]/) + ''; if (content != 'null') { eval('content = ' + content + ';'); } if (goog.isArray(content)) { content = content[0]; } } catch (e) { var content = 'a customized function'; } var humanReadable = ''; if (script.indexOf(rpf.CodeGenerator.PlaybackActions.SLEEP) === 0) { humanReadable = 'Sleep ' + script.match(/\d+/) + 'ms'; } else if (script.indexOf( rpf.CodeGenerator.PlaybackActions.CHANGE_URL) === 0 || script.indexOf(rpf.CodeGenerator.PlaybackActions.REDIRECT_TO) === 0) { humanReadable = 'Redirect to ' + rpf.CodeGenerator.getUrlInRedirectCmd(script); } else if (script.indexOf( rpf.CodeGenerator.PlaybackActions.REDIRECT) === 0) { humanReadable = 'Redirect to the next page...'; } else if (script.indexOf(rpf.CodeGenerator.PlaybackActions.CALL) == 0) { humanReadable = 'Runs a custom JS function.'; } else { var action = rpf.CodeGenerator.getAction(script); switch (action) { case rpf.CodeGenerator.PlaybackActions.CLICK: case rpf.CodeGenerator.PlaybackActions.FIND: case rpf.CodeGenerator.PlaybackActions.DBLCLICK: case rpf.CodeGenerator.PlaybackActions.MOVE: case rpf.CodeGenerator.PlaybackActions.SUBMIT: humanReadable = action + this.extractInfo(script, '', opt_descriptor); break; case rpf.CodeGenerator.PlaybackActions.SELECT: case rpf.CodeGenerator.PlaybackActions.INPUT: case rpf.CodeGenerator.PlaybackActions.VERIFY: case rpf.CodeGenerator.PlaybackActions.COMPARE: case rpf.CodeGenerator.PlaybackActions.TYPE: humanReadable = action + this.extractInfo(script, content, opt_descriptor); break; } } if (!humanReadable) { humanReadable = script; } return humanReadable; }; /** * Generates the command for url changes. * @param {string} url The URL will be changed to. * @return {string} The command for a URL change. * @export */ rpf.CodeGenerator.generateUrlChange = function(url) { return goog.string.buildString( rpf.CodeGenerator.PlaybackActions.CHANGE_URL, '(', url, ');'); }; /** * Generates command with one arg. * @param {rpf.CodeGenerator.PlaybackActions} action The action string. * @param {string} getElem The get elem string. * @param {Object} cmdMap The command info map. * @return {Object} The result object. * @private */ rpf.CodeGenerator.prototype.generateCmdOneArg_ = function( action, getElem, cmdMap) { var playbackCmd = goog.string.buildString(action, '(', getElem, ');'); return {'cmd': playbackCmd, 'cmdMap': cmdMap}; }; /** * Generates command with two args. * @param {rpf.CodeGenerator.PlaybackActions} action The action string. * @param {string} getElem The get elem string. * @param {Object} cmdMap The command info map. * @param {string} elemVarName The element variable name. * @param {string} content The content string. * @return {Object} The result object. * @private */ rpf.CodeGenerator.prototype.generateCmdTwoArgs_ = function( action, getElem, cmdMap, elemVarName, content) { var playbackCmd = goog.string.buildString( action, '(', getElem, ', ', rpf.CodeGenerator.VARIABLE_CONTENT_MAP_, '["', elemVarName, '"]);'); var datafileCmd = goog.string.buildString( rpf.CodeGenerator.VARIABLE_CONTENT_MAP_, '["', elemVarName, '"] = "', content, '";'); return {'cmd': playbackCmd, 'data': datafileCmd, 'cmdMap': cmdMap}; }; /** * Gets a random id. * @param {string} action The action string. * @param {string} tagName The elem's tag name. * @param {string} descriptor The descriptor string. * @return {string} A unique cmd id. * @export */ rpf.CodeGenerator.getCmdUniqueId = function( action, tagName, descriptor) { function getText(strOrObj) { if (!strOrObj) { return ''; } if (typeof(strOrObj) == 'object') { return strOrObj['value']; } return strOrObj; } var result = [action.toLowerCase(), tagName.toLowerCase()]; try { var descObj = goog.json.parse(descriptor); var text = getText(descObj['elementText']); var value = getText(descObj['attributes']['value']); var cmdClass = getText(descObj['attributes']['class']); var cmdId = getText(descObj['attributes']['id']); var temp = text ? text : value ? value : cmdId ? cmdId : cmdClass; if (temp) { result.push(bite.base.Helper.getNonWordRemoved(temp, 20)); } } catch (e) { console.log('Error occurred: ' + e.message); } result.push(goog.math.randomInt(1000)); return result.join('-'); }; /** * Gets the string for getting elem by id. * @param {string} id The elem's id. * @return {string} The cmd for getting elem by id. * @export */ rpf.CodeGenerator.getElemByIdCmd = function(id) { return 'getElem("' + id + '")'; }; /** * Generates the corresponding JS and data commands for a captured interaction. * @param {Array} selectors The css selectors of the element. * @param {string} content The user's inputs or changes. * @param {rpf.CodeGenerator.DomTags} nodeType The element's tag name. * @param {rpf.CodeGenerator.RecordActions} action The recorded action. * @param {string} descriptor The descriptive info object of the element. * @param {string} elemVarName The variable name for the data input. * @param {Object=} opt_iframeInfo The iframe info that the element was from. * @param {Array=} opt_xpaths The xpath array. * @param {string=} opt_className The class name string. * @return {Object} The result object. * @export */ rpf.CodeGenerator.prototype.generateScriptAndDataFileForCmd = function( selectors, content, nodeType, action, descriptor, elemVarName, opt_iframeInfo, opt_xpaths, opt_className) { var playbackCmd = ''; var cmdMap = {}; var playAction = action; var tagNameLower = nodeType.toLowerCase(); cmdMap['descriptor'] = goog.json.parse(descriptor); cmdMap['selectors'] = selectors; cmdMap['id'] = rpf.CodeGenerator.getCmdUniqueId( action, tagNameLower, descriptor); cmdMap['elemId'] = 'id' + goog.string.getRandomString(); cmdMap['iframeInfo'] = opt_iframeInfo; cmdMap['action'] = action; cmdMap['varName'] = elemVarName; cmdMap['tagName'] = nodeType; cmdMap['xpaths'] = opt_xpaths; cmdMap['className'] = opt_className; if (playAction == rpf.CodeGenerator.RecordActions.CLICK || playAction == rpf.CodeGenerator.RecordActions.MOVE || playAction == rpf.CodeGenerator.RecordActions.DBLCLICK || playAction == rpf.CodeGenerator.RecordActions.ENTER || playAction == rpf.CodeGenerator.RecordActions.SUBMIT || playAction == rpf.CodeGenerator.RecordActions.VERIFYNOT) { return this.generateCmdOneArg_( /** @type {rpf.CodeGenerator.PlaybackActions} */ (playAction), rpf.CodeGenerator.getElemByIdCmd(cmdMap['id']), cmdMap); } else if (playAction == rpf.CodeGenerator.RecordActions.REPLACE_HTML || playAction == rpf.CodeGenerator.RecordActions.TYPE || playAction == rpf.CodeGenerator.RecordActions.CHANGE || playAction == rpf.CodeGenerator.RecordActions.SELECT || playAction == rpf.CodeGenerator.RecordActions.VERIFY) { if (playAction == rpf.CodeGenerator.RecordActions.CHANGE) { playAction = rpf.CodeGenerator.PlaybackActions.INPUT; } return this.generateCmdTwoArgs_( /** @type {rpf.CodeGenerator.PlaybackActions} */ (playAction), rpf.CodeGenerator.getElemByIdCmd(cmdMap['id']), cmdMap, elemVarName, content); } else if (playAction == rpf.CodeGenerator.RecordActions.DRAG) { var cords = content.split('x'); playbackCmd = goog.string.buildString( rpf.CodeGenerator.PlaybackActions.DRAG, '(', rpf.CodeGenerator.getElemByIdCmd(cmdMap['id']), ', ' + cords[0] + ', ' + cords[1] + ');'); return {'cmd': playbackCmd, 'cmdMap': cmdMap}; } };
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains RPF's playback dialog. * It gets popped up when user clicks playback button. * * @author phu@google.com (Po Hu) */ goog.provide('rpf.PlayDialog'); goog.require('bite.common.mvc.helper'); goog.require('element.helper.Templates.locatorsUpdater'); goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.events'); goog.require('goog.ui.Dialog'); goog.require('rpf.Console.Messenger'); goog.require('rpf.soy.Dialog'); /** * A class for playing back a test. * TODO(phu): The fault tolerant options are still not ideal. * We might consider adding a skip option to skip a few steps on failure. * So that, we don't need to automatically increase the this.currentStep_ * while inserting in new recorded steps in playbackmanager. * * @param {rpf.Console.Messenger} messenger The messenger instance. * @param {function(Bite.Constants.UiCmds, Object, Event, Function=)} onUiEvents * The function to handle the specific event. * @constructor * @export */ rpf.PlayDialog = function(messenger, onUiEvents) { /** * The playback dialog. * @type {goog.ui.Dialog} * @private */ this.playDialog_ = new goog.ui.Dialog(); /** * The temporary command. * @type {string} */ this.tempCmd = ''; /** * The temporary data. * @type {string} */ this.tempData = ''; /** * The test ids. * @type {!Array.<string>} * @private */ this.testIds_ = []; /** * The messenger. * @type {rpf.Console.Messenger} * @private */ this.messenger_ = messenger; /** * The function to handle the specific event. * @type {function(Bite.Constants.UiCmds, Object, Event, Function=)} * @private */ this.onUiEvents_ = onUiEvents; /** * Inits the playback dialog. */ this.initPlaybackRuntimeDialog_(); }; /** * Enum for image path. * @enum {string} * @export */ rpf.PlayDialog.Images = { PLAY_ALL: 'imgs/rpf/playall.png', PAUSE_GREY: 'imgs/rpf/pause-disabled.png', PLAY_STEP: 'imgs/rpf/playstep.png', PLAY_STOP_GREY: 'imgs/rpf/playstop-disabled.png', PLAY_ALL_GREY: 'imgs/rpf/playall-disabled.png', PLAY_STEP_GREY: 'imgs/rpf/playstep-disabled.png', PLAY_STOP: 'imgs/rpf/playstop.png', PAUSE: 'imgs/rpf/pause.png' }; /** * Sets the visibility of the playback dialog. * @param {boolean} display Whether or not to show the dialog. * @export */ rpf.PlayDialog.prototype.setVisible = function(display) { this.playDialog_.setVisible(display); }; /** * Automates this dialog. * @param {Array} testInfo The tests to be selected in selector. * @param {boolean} runAll Whether to run all of the tests. */ rpf.PlayDialog.prototype.automateDialog = function(testInfo, runAll) { if (runAll || testInfo) { var selector = goog.dom.getElement('playdialog-tests'); for (var i = 0; i < selector.options.length; ++i) { if (runAll || testInfo[selector.options[i].value]) { selector.options[i].selected = true; } } } this.onUiEvents_( Bite.Constants.UiCmds.SET_PLAYBACK_ALL, {}, /** @type {Event} */ ({})); }; /** * Inits the playback runtime dialog. * @private */ rpf.PlayDialog.prototype.initPlaybackRuntimeDialog_ = function() { var dialogElem = this.playDialog_.getContentElement(); bite.common.mvc.helper.renderModelFor( dialogElem, rpf.soy.Dialog.playContent); this.playDialog_.setTitle('Playback Runtime'); this.playDialog_.setButtonSet(null); this.playDialog_.setVisible(true); this.playDialog_.setVisible(false); this.setMultipleTestsVisibility(false); this.setTestSelectorVisibility(false); goog.events.listen( goog.dom.getElement('playall'), 'click', goog.partial( this.onUiEvents_, Bite.Constants.UiCmds.SET_PLAYBACK_ALL, {})); goog.events.listen( goog.dom.getElement('playstep'), 'click', goog.partial( this.onUiEvents_, Bite.Constants.UiCmds.SET_PLAYBACK_STEP, {})); goog.events.listen( goog.dom.getElement('playpause'), 'click', goog.partial( this.onUiEvents_, Bite.Constants.UiCmds.SET_PLAYBACK_PAUSE, {})); goog.events.listen( goog.dom.getElement('playstop'), 'click', goog.partial( this.onUiEvents_, Bite.Constants.UiCmds.SET_PLAYBACK_STOP, {})); goog.events.listen( goog.dom.getElement('stopAllTests'), 'click', goog.partial( this.onUiEvents_, Bite.Constants.UiCmds.SET_PLAYBACK_STOP_ALL, {})); }; /** * Sets the total Tests number. * @param {boolean} visible Whether set the multiple tests info visible. */ rpf.PlayDialog.prototype.setMultipleTestsVisibility = function(visible) { goog.style.showElement(goog.dom.getElement('rpf-multiple-tests-info'), visible); }; /** * Sets the total Tests number. * @param {number} totalNumber The total tests number. */ rpf.PlayDialog.prototype.setTotalNumber = function(totalNumber) { goog.dom.getElement('totalRunningTestsNumber').innerHTML = '/ Total: ' + totalNumber; }; /** * Sets the finished Tests number. * @param {number} finishedNumber The finished tests number. */ rpf.PlayDialog.prototype.setFinishedNumber = function(finishedNumber) { goog.dom.getElement('finishedTestsNumber').innerHTML = 'Finished: ' + finishedNumber; }; /** * Gets all of the selected test names. * @return {!Array.<string>} The selected names. */ rpf.PlayDialog.prototype.getSelectedTests = function() { var selector = goog.dom.getElement('playdialog-tests'); var results = []; for (var i = 0; i < selector.options.length; ++i) { if (selector.options[i].selected) { results.push(selector.options[i].value); } } return results; }; /** * Updates the tests selector. * @param {!Array.<string>} names The test names. * @param {!Array.<string>} testIds The test ids. */ rpf.PlayDialog.prototype.updateTestSelection = function(names, testIds) { var selector = goog.dom.getElement('playdialog-tests'); this.testIds_ = testIds || []; selector.innerHTML = ''; for (var i = 0; i < names.length; i++) { var opt = new Option(names[i], names[i]); selector.add(opt, null); } this.setTestSelectorVisibility(true); }; /** * Plays back all the rest steps. * @export */ rpf.PlayDialog.prototype.setPlaybackAll = function() { goog.dom.getElement('playall').src = rpf.PlayDialog.Images.PLAY_ALL_GREY; goog.dom.getElement('playstep').src = rpf.PlayDialog.Images.PLAY_STEP_GREY; goog.dom.getElement('playpause').src = rpf.PlayDialog.Images.PAUSE; goog.dom.getElement('playstop').src = rpf.PlayDialog.Images.PLAY_STOP; var userPauseStep = goog.string.trim( goog.dom.getElement('playbackcurrentstep').value); if (!userPauseStep) { userPauseStep = -1; } else { userPauseStep = parseInt(userPauseStep, 10) - 1; } this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.SET_USER_SPECIFIED_PAUSE_STEP, 'params': {'userPauseStep': userPauseStep}}); }; /** * Plays back step by step. * @export */ rpf.PlayDialog.prototype.setPlaybackStep = function() { this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.SET_USER_SPECIFIED_PAUSE_STEP, 'params': {'userPauseStep': -1}}); }; /** * Update comments div. * @param {string} id The user ID. * @param {string} comment The user's comment. * @export */ rpf.PlayDialog.prototype.updateComment = function( id, comment) { }; /** * Pauses the current playback. * @param {boolean=} opt_uiOnly Whether to involve the call to * the backend. * @export */ rpf.PlayDialog.prototype.setPlaybackPause = function( opt_uiOnly) { var uiOnly = opt_uiOnly || false; goog.dom.getElement('playall').src = rpf.PlayDialog.Images.PLAY_ALL; goog.dom.getElement('playstep').src = rpf.PlayDialog.Images.PLAY_STEP; goog.dom.getElement('playpause').src = rpf.PlayDialog.Images.PAUSE_GREY; if (!uiOnly) { this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.USER_SET_PAUSE}); } }; /** * Stops the current playback. * @param {boolean=} opt_uiOnly Whether to involve the call to * the backend. * @export */ rpf.PlayDialog.prototype.setPlaybackStop = function( opt_uiOnly) { var uiOnly = opt_uiOnly || false; goog.dom.getElement('playall').src = rpf.PlayDialog.Images.PLAY_ALL; goog.dom.getElement('playstep').src = rpf.PlayDialog.Images.PLAY_STEP; goog.dom.getElement('playpause').src = rpf.PlayDialog.Images.PAUSE_GREY; goog.dom.getElement('playstop').src = rpf.PlayDialog.Images.PLAY_STOP; this.switchChoiceSet(false); if (!uiOnly) { this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.USER_SET_STOP}); } }; /** * Shows the choices on failure. * @param {boolean} turnOn Whether or not to show the options. * @export */ rpf.PlayDialog.prototype.switchChoiceSet = function(turnOn) { if (!turnOn) { goog.dom.removeChildren(goog.dom.getElement('choiceset')); goog.dom.removeChildren(goog.dom.getElement('playbackstatus')); goog.dom.removeChildren(goog.dom.getElement('matchHtmlDiv')); } else { var deleteCmd = new goog.ui.CustomButton('Delete'); var overrideCmd = new goog.ui.CustomButton('Override'); var updateCmd = new goog.ui.CustomButton('Update'); var insertCmd = new goog.ui.CustomButton('Insert'); var failCmd = new goog.ui.CustomButton('Fail'); var deleteCmdDiv = goog.dom.createDom(goog.dom.TagName.DIV, { 'id': 'deleteCmd', 'style': 'display: inline' }); var overrideCmdDiv = goog.dom.createDom(goog.dom.TagName.DIV, { 'id': 'overrideCmd', 'style': 'display: inline' }); var updateCmdDiv = goog.dom.createDom(goog.dom.TagName.DIV, { 'id': 'updateCmd', 'style': 'display: inline' }); var insertCmdDiv = goog.dom.createDom(goog.dom.TagName.DIV, { 'id': 'insertCmd', 'style': 'display: inline' }); var failCmdDiv = goog.dom.createDom(goog.dom.TagName.DIV, { 'id': 'failCmd', 'style': 'display: inline' }); var choiceSet = goog.dom.getElement('choiceset'); goog.dom.removeChildren(choiceSet); choiceSet.appendChild(deleteCmdDiv); choiceSet.appendChild(overrideCmdDiv); choiceSet.appendChild(updateCmdDiv); choiceSet.appendChild(insertCmdDiv); choiceSet.appendChild(failCmdDiv); deleteCmd.render(goog.dom.getElement('deleteCmd')); overrideCmd.render(goog.dom.getElement('overrideCmd')); updateCmd.render(goog.dom.getElement('updateCmd')); insertCmd.render(goog.dom.getElement('insertCmd')); failCmd.render(goog.dom.getElement('failCmd')); deleteCmd.setTooltip('delete the step'); overrideCmd.setTooltip('mark the step as passed and continue'); updateCmd.setTooltip( 'update the locator by right clicking the element in page'); insertCmd.setTooltip('add one or more actions after the step'); failCmd.setTooltip('fail the step and add or associate a bug'); goog.events.listen( deleteCmd, goog.ui.Component.EventType.ACTION, goog.partial( this.onUiEvents_, Bite.Constants.UiCmds.DELETE_CMD, {})); goog.events.listen( failCmd, goog.ui.Component.EventType.ACTION, goog.partial( this.onUiEvents_, Bite.Constants.UiCmds.FAIL_CMD, {})); goog.events.listen( overrideCmd, goog.ui.Component.EventType.ACTION, goog.partial( this.onUiEvents_, Bite.Constants.UiCmds.OVERRIDE_CMD, {})); goog.events.listen( updateCmd, goog.ui.Component.EventType.ACTION, goog.partial( this.onUiEvents_, Bite.Constants.UiCmds.UPDATE_CMD, {})); goog.events.listen( insertCmd, goog.ui.Component.EventType.ACTION, goog.partial( this.onUiEvents_, Bite.Constants.UiCmds.INSERT_CMD, {})); } }; /** * Insert commands before this line. * @return {number} The line number to be inserted. * @export */ rpf.PlayDialog.prototype.insertCmd = function() { var line = parseInt(goog.dom.getElement('playbackcurrentstep').value, 10); this.setVisible(false); this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.PREPARE_RECORD_PLAYBACK_PAGE}, goog.bind(this.callbackRecordPup_, this)); return line; }; /** * Updates the corresponding element of the current command. * @export */ rpf.PlayDialog.prototype.updateCmd = function() { this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.PREPARE_RECORD_PLAYBACK_PAGE}, goog.bind(this.callbackStartUpdateMode_, this)); }; /** * Callback when receiving the event for updating element. * @param {Object} response The response object. * @private */ rpf.PlayDialog.prototype.callbackStartUpdateMode_ = function(response) { this.onUiEvents_( Bite.Constants.UiCmds.CHECK_TAB_READY_TO_UPDATE, {}, /** @type {Event} */ ({})); this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.SET_ACTION_CALLBACK}, goog.bind(this.callbackOnReceiveAction_, this)); }; /** * Sets the matchHtmlDiv field. * @param {string} html The html string. * @export */ rpf.PlayDialog.prototype.setHtmlDiv = function(html) { var matchHtmlDiv = goog.dom.getElement('matchHtmlDiv'); matchHtmlDiv.innerHTML = html; }; /** * Callback when receiving the event for updating element. * @param {Object} response The response object. * @private */ rpf.PlayDialog.prototype.callbackOnReceiveAction_ = function(response) { var line = parseInt(goog.dom.getElement('playbackcurrentstep').value, 10); var message = 'The xpath was updated to: ' + response['cmdMap']['xpaths'][0]; this.updatePlaybackStatus(message, 'green'); this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.END_UPDATER_MODE, 'params': {}}); this.onUiEvents_( Bite.Constants.UiCmds.UPDATE_ELEMENT_AT_LINE, {'line': line - 1, 'cmdMap': response['cmdMap']}, /** @type {Event} */ ({}), goog.bind(this.showUpdateAllUI_, this)); }; /** * Callback when prepare record the playback page is ready. * @param {Object} response The response object. * @private */ rpf.PlayDialog.prototype.callbackRecordPup_ = function( response) { this.onUiEvents_( Bite.Constants.UiCmds.START_RECORDING, {'passChecking': true}, /** @type {Event} */ ({})); }; /** * Mark the step as passed and continue. * @export */ rpf.PlayDialog.prototype.overrideCmd = function() { this.switchChoiceSet(false); this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.CALLBACK_AFTER_EXEC_CMDS, 'params': {'status': 'passed'}}); }; /** * Callback on deleting a cmd. * @param {Object} response The response object. * @private */ rpf.PlayDialog.prototype.callbackDeleteCmd_ = function( response) { if (response['needOverride']) { this.overrideCmd(); } }; /** * Deletes the current command. * @return {number} The line number to be deleted. * @export */ rpf.PlayDialog.prototype.deleteCmd = function() { goog.dom.removeChildren(goog.dom.getElement('playbackstatus')); goog.dom.removeChildren(goog.dom.getElement('matchHtmlDiv')); var deleteLine = parseInt(goog.dom.getElement('playbackcurrentstep').value, 10); this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.DELETE_CMD, 'params': {'deleteLine': deleteLine}}, goog.bind(this.callbackDeleteCmd_, this)); return deleteLine; }; /** * Stops the current playback. * @export */ rpf.PlayDialog.prototype.failCmd = function() { this.switchChoiceSet(false); var userLibDiv = goog.dom.getElement('playbackstatus'); goog.dom.removeChildren(userLibDiv); this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.FINISH_CURRENT_RUN, 'params': {'status': Bite.Constants.WorkerResults.STOPPED, 'log': 'Set stop from playback.'}}); this.setPlaybackStop(); }; /** * Set the visibility of the tests selector. * @param {boolean} visible Whether to show the selector. */ rpf.PlayDialog.prototype.setTestSelectorVisibility = function(visible) { goog.style.showElement( goog.dom.getElement('rpf-multiple-test-selector'), visible); }; /** * Clears the match html field. * @export */ rpf.PlayDialog.prototype.clearMatchHtml = function() { var matchHtmlDiv = goog.dom.getElement('matchHtmlDiv'); matchHtmlDiv.innerHTML = ''; }; /** * Sets visibility of choiceset area. * @param {boolean} visible Whether is visible. * @export */ rpf.PlayDialog.prototype.setChoiceSetVisibility = function(visible) { var choiceset = goog.dom.getElement('choiceset'); goog.style.showElement(choiceset, visible); }; /** * Cancels the current batch updates. * @private */ rpf.PlayDialog.prototype.cancelUpdateAllUi_ = function() { this.setHtmlDiv(''); this.setChoiceSetVisibility(true); }; /** * Shows the UI for suggesting the users to update all of the similar steps. * @param {Function} registerEvents The function to register events on * buttons in the UI. * @param {string} html The html string of the UI. * @private */ rpf.PlayDialog.prototype.showUpdateAllUI_ = function(registerEvents, html) { this.setHtmlDiv(html); registerEvents(goog.bind(this.cancelUpdateAllUi_, this)); this.setChoiceSetVisibility(false); }; /** * Updates the playback status. * @param {string} status The status string. * @param {string} color The color code. * @export */ rpf.PlayDialog.prototype.updatePlaybackStatus = function( status, color) { var userLibDiv = goog.dom.getElement('playbackstatus'); var statusStyle = 'text-align:center;padding-top:10px;' + 'padding-bottom:10px;color:' + color; goog.dom.setProperties(userLibDiv, {'style': statusStyle}); userLibDiv.innerHTML = status; }; /** * Shows the UI to create a new command on failure. * @param {string} failureReason The failure reason. * @param {string=} opt_failureLog The failure log. * @export */ rpf.PlayDialog.prototype.makeChoiceAfterFailure = function(failureReason, opt_failureLog) { var matchHtmlDiv = goog.dom.getElement('matchHtmlDiv'); switch (failureReason) { case Bite.Constants.PlaybackFailures.MULTIPLE_RETRY_FIND_ELEM: if (opt_failureLog) { goog.dom.getElement('matchHtmlDiv').innerHTML = opt_failureLog; } this.updatePlaybackStatus( 'This step failed finding element:', 'red'); break; case Bite.Constants.PlaybackFailures.MULTIPLE_RETRY_CUSTOM_JS: matchHtmlDiv.innerHTML = ''; this.updatePlaybackStatus( 'Customized function failed.', 'red'); break; case Bite.Constants.PlaybackFailures.TIMEOUT: matchHtmlDiv.innerHTML = ''; this.updatePlaybackStatus( 'This step failed because deadline exceeded.', 'red'); break; case Bite.Constants.PlaybackFailures.UNSUPPORTED_COMMAND_FAILURE: matchHtmlDiv.innerHTML = ''; this.updatePlaybackStatus( 'Failed because this step is unsupported.', 'red'); break; case Bite.Constants.PlaybackFailures.USER_PAUSE_FAILURE: matchHtmlDiv.innerHTML = ''; this.updatePlaybackStatus( 'Manually pause the failure.', 'red'); break; default: this.updatePlaybackStatus( 'Unknown playback error.', 'red'); } this.switchChoiceSet(true); };
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains RPF's quick commands dialog. * This dialog provides users with an easy way to generate certain commands, * like sleep and url changes. * * @author phu@google.com (Po Hu) */ goog.provide('rpf.QuickCmdDialog'); goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.events'); goog.require('goog.ui.CustomButton'); goog.require('goog.ui.Dialog'); goog.require('rpf.CodeGenerator'); goog.require('rpf.MiscHelper'); /** * A class for quick commands dialog. * @param {function(Bite.Constants.UiCmds, Object, Event)} onUiEvents * The function to handle the specific event. * @constructor * @export */ rpf.QuickCmdDialog = function(onUiEvents) { /** * The quick commands dialog. * @type Object * @private */ this.quickCmdDialog_ = new goog.ui.Dialog(); /** * The invoke test select control. * @type {Object} * @private */ this.invokeSelectCtrl_ = null; /** * The invoke test ids. * @type {Array.<string>} * @private */ this.testIds_ = []; /** * The function to handle the specific event. * @type {function(Bite.Constants.UiCmds, Object, Event)} * @private */ this.onUiEvents_ = onUiEvents; /** * Inits the quick commands dialog. */ this.initQuickCmdDialog_(); }; /** * Enum for quick commands. * @enum {string} * @export */ rpf.QuickCmdDialog.Commands = { SLEEP: 'sleep', CHANGE_URL: 'changeUrl', FUNCTION: 'function', INVOKE: 'invoke' }; /** * Enum for quick commands description. * @enum {string} * @export */ rpf.QuickCmdDialog.CmdDesc = { SLEEP: 'Sleep (ms)', CHANGE_URL: 'Change Url to', FUNCTION: 'Add customized function', INVOKE: 'Invoke another test' }; /** * Inits the quick commands dialog. * @private */ rpf.QuickCmdDialog.prototype.initQuickCmdDialog_ = function() { var dialogElem = this.quickCmdDialog_.getContentElement(); var contentDiv = goog.dom.createDom(goog.dom.TagName.TABLE, { 'id': 'quickCmdsTable', 'width': '100%' }); for (var key in rpf.QuickCmdDialog.Commands) { var row = this.addRowOfCmd_(rpf.QuickCmdDialog.CmdDesc[key], key); contentDiv.appendChild(row); } dialogElem.appendChild(contentDiv); this.quickCmdDialog_.setTitle('Quick Commands'); this.quickCmdDialog_.setButtonSet(null); this.quickCmdDialog_.setVisible(true); this.quickCmdDialog_.setVisible(false); this.prepareInvokeTests_(); }; /** * Updates the select box of tests. * @param {Array.<string>} names The test names. * @param {Array.<string>} ids The test ids. * @export */ rpf.QuickCmdDialog.prototype.updateInvokeSelect = function( names, ids) { this.testIds_ = ids; this.invokeSelectCtrl_.innerHTML = ''; for (var i = 0; i < names.length; i++) { var opt = new Option(names[i], names[i]); this.invokeSelectCtrl_.add(opt, null); } }; /** * Generates the invocation command. * @private */ rpf.QuickCmdDialog.prototype.generateInvocation_ = function() { for (var i = 0; i < this.invokeSelectCtrl_.options.length; i++) { if (this.invokeSelectCtrl_.options[i].selected == true) { var generatedCmd = rpf.CodeGenerator.generateInvocationCmd( this.testIds_[i], this.invokeSelectCtrl_.options[i].value); this.onUiEvents_( Bite.Constants.UiCmds.ADD_NEW_COMMAND, {'pCmd': generatedCmd, 'dCmd': ''}, /** @type {Event} */ ({})); break; } } }; /** * Prepares the select box of tests. * @private */ rpf.QuickCmdDialog.prototype.prepareInvokeTests_ = function() { var inputId = 'INVOKE_text'; var input = goog.dom.getElement(inputId); var td = input.parentNode; goog.dom.removeChildren(td); goog.dom.appendChild(td, this.invokeSelectCtrl_ = goog.dom.createDom(goog.dom.TagName.SELECT, {'id': 'selectInvokeInQuickCmd'})); }; /** * Sets the visibility of the quick commands dialog. * @param {boolean} display Whether or not to show the dialog. * @export */ rpf.QuickCmdDialog.prototype.setVisible = function(display) { this.quickCmdDialog_.setVisible(display); }; /** * Adds a row for a command. * @param {string} description The cmd's description. * @param {string} id The cmd's id. * @return {Element} The generated row element. * @private */ rpf.QuickCmdDialog.prototype.addRowOfCmd_ = function( description, id) { var tdOne = {}; var tdTwo = {}; var tdThree = {}; var text = {}; var buttonDiv = {}; var input = {}; var row = goog.dom.createDom(goog.dom.TagName.TR, {}, tdOne = goog.dom.createDom(goog.dom.TagName.TD, {'align': 'right', 'width': '40%', 'style': 'font: bold 13px verdana;'}, text = goog.dom.createDom(goog.dom.TagName.DIV, {})), tdTwo = goog.dom.createDom(goog.dom.TagName.TD, {'align': 'left', 'width': '40%'}, input = goog.dom.createDom('input', { 'id': id + '_text', 'type': 'text'})), tdThree = goog.dom.createDom(goog.dom.TagName.TD, {'width': '20%'}, buttonDiv = goog.dom.createDom(goog.dom.TagName.DIV, {'style': 'font: bold 13px verdana;'}))); var button = new goog.ui.CustomButton('Add'); button['id'] = id; button.render(buttonDiv); goog.events.listen(button, goog.ui.Component.EventType.ACTION, this.onAddCmd_, false, this); goog.dom.setTextContent(text, description); return row; }; /** * Adds a command to the editor. * @param {Object} e The event. * @private */ rpf.QuickCmdDialog.prototype.onAddCmd_ = function(e) { var id = e.target.id; if (id == 'INVOKE') { this.generateInvocation_(); return; } var value = goog.dom.getElement(id + '_text').value; var cmd = rpf.QuickCmdDialog.Commands[id]; this.writeCmd(cmd, value); }; /** * Writes a command to the editor. * @param {rpf.QuickCmdDialog.Commands} cmd The command. * @param {string} value The given value for the command. * @export */ rpf.QuickCmdDialog.prototype.writeCmd = function(cmd, value) { if (cmd == rpf.QuickCmdDialog.Commands.SLEEP) { var generatedCmd = rpf.CodeGenerator.generateSleepCmd(value); this.onUiEvents_( Bite.Constants.UiCmds.ADD_NEW_COMMAND, {'pCmd': generatedCmd, 'dCmd': ''}, /** @type {Event} */ ({})); } else if (cmd == rpf.QuickCmdDialog.Commands.CHANGE_URL) { var generatedCmd = rpf.CodeGenerator.generateUrlChange(value); this.onUiEvents_( Bite.Constants.UiCmds.ADD_NEW_COMMAND, {'pCmd': generatedCmd, 'dCmd': ''}, /** @type {Event} */ ({})); this.onUiEvents_( Bite.Constants.UiCmds.ADD_NEW_COMMAND, {'pCmd': rpf.CodeGenerator.getRedirectUrl(value), 'dCmd': ''}, /** @type {Event} */ ({})); } else if (cmd == rpf.QuickCmdDialog.Commands.FUNCTION) { var generatedCmd = rpf.CodeGenerator.generateFunctionCmd(value); this.onUiEvents_( Bite.Constants.UiCmds.ADD_NEW_COMMAND, {'pCmd': generatedCmd, 'dCmd': ''}, /** @type {Event} */ ({})); } else { throw new Error('Not supported command!'); } };
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains a dialog for RPF validation. * * @author phu@google.com (Po Hu) */ goog.provide('rpf.DetailsDialog'); goog.require('bite.common.mvc.helper'); goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.events'); goog.require('goog.ui.CustomButton'); goog.require('goog.ui.Dialog'); goog.require('goog.ui.MenuItem'); goog.require('goog.ui.Toolbar'); goog.require('goog.ui.ToolbarButton'); goog.require('goog.ui.ToolbarMenuButton'); goog.require('goog.ui.Tooltip'); goog.require('rpf.Console.Messenger'); goog.require('rpf.EditorManager'); goog.require('rpf.MiscHelper'); goog.require('rpf.ScreenShotDialog'); goog.require('rpf.soy.Dialog'); /** * A class for command detailed info. * @param {rpf.Console.Messenger} messenger The messenger instance. * @param {function(Bite.Constants.UiCmds, Object, Event)} onUiEvents * The function to handle the specific event. * @param {rpf.EditorManager} editorMgr The editor manager. * @param {rpf.ScreenShotDialog} scnshotMgr * The screenshot manager. * @constructor * @export */ rpf.DetailsDialog = function( messenger, onUiEvents, editorMgr, scnshotMgr) { /** * The details dialog. * @type {goog.ui.Dialog} * @private */ this.detailsDialog_ = new goog.ui.Dialog(); /** * The attributes controller. * @type {rpf.Attributes} * @private */ this.attrControl_ = new rpf.Attributes( rpf.Attributes.UITypes.DETAILS_DIALOG, onUiEvents); /** * The descriptor object. * @type {Object} * @private */ this.descriptor_ = null; /** * The xpath string. * @type {string} * @private */ this.xpath_ = ''; /** * Whether the editor shows. * @type {boolean} * @private */ this.editorShown_ = false; /** * Current line number. * @type {number} * @private */ this.curLine_ = 0; /** * The messenger. * @type {rpf.Console.Messenger} * @private */ this.messenger_ = messenger; /** * The function to handle the specific event. * @type {function(Bite.Constants.UiCmds, Object, Event)} * @private */ this.onUiEvents_ = onUiEvents; /** * The editor manager. * @type {rpf.EditorManager} * @private */ this.editorMgr_ = editorMgr; /** * The editor manager. * @type {rpf.ScreenShotDialog} * @private */ this.scnshotMgr_ = scnshotMgr; /** * The screenshot div. * @type {Element} * @private */ this.screenDiv_ = null; /** * The attributes div. * @type {Element} * @private */ this.editorDiv_ = null; /** * The more info div. * @type {Element} * @private */ this.moreInfoDiv_ = null; /** * Inits the validation dialog. */ this.initDetailsnDialog_(); goog.events.listen( this.detailsDialog_, goog.ui.Dialog.EventType.AFTER_HIDE, goog.partial( this.onUiEvents_, Bite.Constants.UiCmds.UPDATE_HIGHLIGHT_LINE, {'lineNum': -1})); }; /** * Updates the command info on the dialog. * @param {Object} descriptor The descriptor object. * @param {number} line The line number. * @param {string} translation The command's translation. * @param {string} cmdId The command id. * @param {string} xpath The xpath string. * @param {Object} infoMap The information map of the current test. * @export */ rpf.DetailsDialog.prototype.updateInfo = function(descriptor, line, translation, cmdId, xpath, infoMap) { this.curLine_ = line; var dialogElem = this.detailsDialog_.getContentElement(); var screenSrc = this.scnshotMgr_.getScreenshotManager().getScreenById(cmdId); bite.common.mvc.helper.renderModelFor(dialogElem, rpf.soy.Dialog.detailsContent, {'screenSrc': screenSrc, 'line': line + 1}); var prevBtn = goog.dom.getElement('rpf-prev-line'); var nextBtn = goog.dom.getElement('rpf-next-line'); cmdId = cmdId || line + ''; this.screenDiv_ = goog.dom.getElement('rpf-details-screenshot'); this.editorDiv_ = goog.dom.getElement('rpf-details-editor'); this.moreInfoDiv_ = goog.dom.getElement('rpf-details-moreinfo'); goog.events.listen( prevBtn, 'click', goog.partial( this.onUiEvents_, Bite.Constants.UiCmds.ON_PREV_PAGE, {})); goog.events.listen( nextBtn, 'click', goog.partial( this.onUiEvents_, Bite.Constants.UiCmds.ON_NEXT_PAGE, {})); var saveStepButton = new goog.ui.CustomButton('Save'); saveStepButton.setTooltip('Saves the step name.'); saveStepButton.render(goog.dom.getElement('saveStepName')); var saveClassButton = new goog.ui.CustomButton('Save'); saveClassButton.setTooltip('Saves the class name this step belongs to.'); saveClassButton.render(goog.dom.getElement('saveClassName')); goog.events.listen( saveStepButton, goog.ui.Component.EventType.ACTION, goog.bind(this.saveStepName_, this, infoMap, cmdId)); goog.events.listen( saveClassButton, goog.ui.Component.EventType.ACTION, goog.bind(this.saveClassName_, this, infoMap, cmdId)); this.descriptor_ = descriptor; this.xpath_ = xpath; this.drawCmdToolbar_(line); this.setStepInfo_(infoMap, cmdId); if (!this.editorShown_) { this.turnOnScreenView_(); } else { this.turnOnAttributesView_(); } this.detailsDialog_.setVisible(true); }; /** * Set the step name in the details dialog. * @param {Object} infoMap The information map. * @param {string} id The command id. * @private */ rpf.DetailsDialog.prototype.setStepInfo_ = function(infoMap, id) { if (!infoMap || !infoMap['steps'] || !infoMap['steps'][id]) { return; } var stepName = infoMap['steps'][id]['stepName']; var className = infoMap['steps'][id]['pageName']; var stepNameInput = goog.dom.getElement('stepNameInput'); var classNameInput = goog.dom.getElement('classNameInput'); stepNameInput.value = stepName; classNameInput.value = className; new goog.ui.Tooltip(stepNameInput, 'Please follow JS naming convention.'); new goog.ui.Tooltip(classNameInput, 'Please set the class name that associates with the step.'); }; /** * Saves the step name in the details dialog. * @param {Object} infoMap The information map. * @param {string} id The command id. * @private */ rpf.DetailsDialog.prototype.saveStepName_ = function(infoMap, id) { var stepName = goog.dom.getElement('stepNameInput').value; infoMap['steps'][id]['stepName'] = stepName; }; /** * Saves the class name in the details dialog. * @param {Object} infoMap The information map. * @param {string} id The command id. * @private */ rpf.DetailsDialog.prototype.saveClassName_ = function(infoMap, id) { var className = goog.dom.getElement('classNameInput').value; infoMap['steps'][id]['pageName'] = className; }; /** * Draw command manipulation toolbar. * @param {number} line The line number of the selected line. * @private */ rpf.DetailsDialog.prototype.drawCmdToolbar_ = function(line) { var actionMenu = new goog.ui.ToolbarMenuButton('Actions'); var upMenuItem = new goog.ui.MenuItem('moveUp'); var downMenuItem = new goog.ui.MenuItem('moveDown'); var aboveMenuItem = new goog.ui.MenuItem('insertAbove'); var belowMenuItem = new goog.ui.MenuItem('insertBelow'); var deleteMenuItem = new goog.ui.MenuItem('deleteRow'); actionMenu.addItem(upMenuItem); actionMenu.addItem(downMenuItem); actionMenu.addItem(aboveMenuItem); actionMenu.addItem(belowMenuItem); actionMenu.addItem(deleteMenuItem); goog.events.listen( upMenuItem, goog.ui.Component.EventType.ACTION, goog.partial( this.onUiEvents_, Bite.Constants.UiCmds.ON_CMD_MOVE_UP, {})); goog.events.listen( downMenuItem, goog.ui.Component.EventType.ACTION, goog.partial( this.onUiEvents_, Bite.Constants.UiCmds.ON_CMD_MOVE_DOWN, {})); goog.events.listen( aboveMenuItem, goog.ui.Component.EventType.ACTION, goog.partial( this.onUiEvents_, Bite.Constants.UiCmds.ON_INSERT_ABOVE, {})); goog.events.listen( belowMenuItem, goog.ui.Component.EventType.ACTION, goog.partial( this.onUiEvents_, Bite.Constants.UiCmds.ON_INSERT_BELOW, {})); goog.events.listen( deleteMenuItem, goog.ui.Component.EventType.ACTION, goog.partial( this.onUiEvents_, Bite.Constants.UiCmds.ON_REMOVE_CUR_LINE, {})); actionMenu.render(goog.dom.getElement('rpf-details-toolbar')); this.attr_ = new goog.ui.CustomButton('Switch to details'); this.attrControl_.createAttrTabs( this.editorDiv_, this.descriptor_, this.xpath_, goog.bind(this.replaceLine, this), line); goog.events.listen( this.attr_, goog.ui.Component.EventType.ACTION, goog.partial( this.onUiEvents_, Bite.Constants.UiCmds.ON_EDIT_CMD, {})); this.attr_.render(goog.dom.getElement('rpf-details-toolbar')); }; /** * Clears the UI for adding settings to command. * @private */ rpf.DetailsDialog.prototype.clearUiForSettings_ = function() { var screenDiv = goog.dom.getElement('screenDiv'); var editorDiv = goog.dom.getElement('editorDiv'); goog.dom.removeChildren(screenDiv); goog.dom.removeChildren(editorDiv); }; /** * Remove this line of code. * @export */ rpf.DetailsDialog.prototype.onRemoveCurLine = function() { this.scnshotMgr_.getScreenshotManager().deleteItem(this.curLine_); this.editorMgr_.removeCurrentLine(this.curLine_); this.setVisible(false); }; /** * Move the current line up by 1. * @export */ rpf.DetailsDialog.prototype.onCmdMoveUp = function() { if (this.curLine_ < 1) { console.log('Can not move up any more.'); return; } this.editorMgr_.moveUp(this.curLine_); this.curLine_ -= 1; goog.dom.getElement('curlineInput').value = this.curLine_ + 1 + ''; this.onUiEvents_( Bite.Constants.UiCmds.UPDATE_HIGHLIGHT_LINE, {'lineNum': this.curLine_}, /** @type {Event} */ ({})); }; /** * Move the current line down by 1. * @export */ rpf.DetailsDialog.prototype.onCmdMoveDown = function() { if (this.curLine_ >= this.editorMgr_.getTotalLineNum()) { console.log('Can not move down any more.'); return; } this.editorMgr_.moveDown(this.curLine_); this.curLine_ += 1; goog.dom.getElement('curlineInput').value = this.curLine_ + 1 + ''; this.onUiEvents_( Bite.Constants.UiCmds.UPDATE_HIGHLIGHT_LINE, {'lineNum': this.curLine_}, /** @type {Event} */ ({})); }; /** * Inits the details dialog. * @private */ rpf.DetailsDialog.prototype.initDetailsnDialog_ = function() { this.detailsDialog_.setTitle('Detailed info:'); this.detailsDialog_.setButtonSet(null); this.detailsDialog_.setVisible(true); this.detailsDialog_.setVisible(false); }; /** * Turns on screen view. * @private */ rpf.DetailsDialog.prototype.turnOnScreenView_ = function() { goog.style.showElement(this.editorDiv_, false); goog.style.showElement(this.moreInfoDiv_, false); goog.style.showElement(this.screenDiv_, true); this.attr_.setContent('Switch to details'); }; /** * Turns on attributes view. * @private */ rpf.DetailsDialog.prototype.turnOnAttributesView_ = function() { goog.style.showElement(this.screenDiv_, false); goog.style.showElement(this.editorDiv_, true); goog.style.showElement(this.moreInfoDiv_, true); this.attr_.setContent('Switch to screenshots'); }; /** * Edit the current line. * @export */ rpf.DetailsDialog.prototype.onEditCmd = function() { if (this.editorShown_) { this.turnOnScreenView_(); this.editorShown_ = false; } else { this.turnOnAttributesView_(); this.editorShown_ = true; } }; /** * Replace the selected line of code. * @export */ rpf.DetailsDialog.prototype.replaceLine = function() { var oldLine = this.editorMgr_.getOriginalLineAt(this.curLine_); var newCode = rpf.MiscHelper.replaceDescriptor( oldLine, rpf.MiscHelper.getStringWithSpaces(this.descriptor_, 1)); this.editorMgr_.replaceCommand(newCode, this.curLine_); this.attrControl_.updateElementInfo(); }; /** * Gets the current line number. * @return {number} The current line number. * @export */ rpf.DetailsDialog.prototype.getCurLineNum = function() { return this.curLine_; }; /** * Sets the visibility of the details dialog. * @param {boolean} display Whether to show the dialog. * @export */ rpf.DetailsDialog.prototype.setVisible = function(display) { this.detailsDialog_.setVisible(display); };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains the console messages related functions. * * @author phu@google.com (Po Hu) */ goog.provide('rpf.StatusLogger'); goog.require('goog.fx'); goog.require('goog.fx.dom'); /** * A class for handling messages related functions. * @constructor */ rpf.StatusLogger = function() { /** * The status input element. * @type {Element} * @private */ this.statusArea_ = goog.dom.getElement(rpf.StatusLogger.ID_); this.anim_ = new goog.fx.dom.FadeInAndShow(this.statusArea_, 600); this.setStatus(rpf.StatusLogger.DEFAULT); }; goog.addSingletonGetter(rpf.StatusLogger); /** * The status Element id. * @type {string} * @private */ rpf.StatusLogger.ID_ = 'statusLog'; /** * Default messages. * @type {string} */ rpf.StatusLogger.DEFAULT = [ 'Click Record/Playback option in popup to switch the tab under record ' + '(You might need to refresh the tab)', 'Double click on a step to view the details.'].join('<br>'); /** * Starts recording messages. * @type {string} */ rpf.StatusLogger.START_RECORDING = [ 'Started recording (You might need to refresh the tab' + ' if elements are not highlighting on hover)', 'Right click on an element to verify attributes.'].join('<br>'); /** * Stops recording messages. * @type {string} */ rpf.StatusLogger.STOP_RECORDING = [ 'Stopped recording'].join('<br>'); /** * Starts loading a test messages. * @type {string} */ rpf.StatusLogger.LOAD_TEST = ['Loading...'].join('<br>'); /** * Starts loading a test messages. * @type {string} */ rpf.StatusLogger.LOAD_NO_TEST_ERROR = [ 'Please select a test.', '(You might want to load a project first)'].join('<br>'); /** * Loads a test successfully message. * @type {string} */ rpf.StatusLogger.LOAD_TEST_SUCCESS = [ 'Load Successful.'].join('<br>'); /** * Loads a test unsuccessfully message. * @type {string} */ rpf.StatusLogger.LOAD_TEST_FAILED = [ 'Failed loading...'].join('<br>'); /** * Project missing details. * @type {string} */ rpf.StatusLogger.PROJECT_MISSING_DETAILS = [ 'Project missing details...'].join('<br>'); /** * Project has no tests. * @type {string} */ rpf.StatusLogger.PROJECT_NO_TESTS = ['Project has no tests...'].join('<br>'); /** * Project not found. * @type {string} */ rpf.StatusLogger.PROJECT_NOT_FOUND = ['Project not found...'].join('<br>'); /** * Saving messages. * @type {string} */ rpf.StatusLogger.SAVING = ['Saving...'].join('<br>'); /** * Starts playback messages. * @type {string} */ rpf.StatusLogger.START_PLAYBACK = [ 'Started playback the test.', '(Stop button can clear status)' ].join('<br>'); /** * Finishes playback successfully messages. * @type {string} */ rpf.StatusLogger.PLAYBACK_SUCCESS = [ 'Finished playback the test successfully!'].join('<br>'); /** * Finishes playback unsuccessfully messages. * @type {string} */ rpf.StatusLogger.PLAYBACK_FAILED = [ 'Failed to playback the test.'].join('<br>'); /** * Manually stopped the playback. * @type {string} */ rpf.StatusLogger.PLAYBACK_STOPPED = ['The playback was stopped.'].join('<br>'); /** * Saving failure messages. * @type {string} */ rpf.StatusLogger.SAVE_FAILED = [ 'Failed saving... (There might be a server hiccup,' + 'please try again later)'].join('<br>'); /** * Saving success messages. * @type {string} */ rpf.StatusLogger.SAVE_SUCCESS = [ 'Saved successfully.'].join('<br>'); /** * Sets the console status. * @param {string} status Status string. * @param {string=} opt_color Status color. * @export */ rpf.StatusLogger.prototype.setStatus = function(status, opt_color) { var color = opt_color || 'black'; var statusDiv = '<div style="color:' + color + '">' + status + '</div>'; this.statusArea_.innerHTML = statusDiv; this.anim_.play(); }; /** * Sets the console status when being called back. * @param {Object.<string, string>} response * The callback function to set status. * @export */ rpf.StatusLogger.prototype.setStatusCallback = function(response) { this.setStatus(response['message'], response['color']); };
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains content script for * recording and validation. * * @author phu@google.com (Po Hu) */ goog.provide('rpf.ContentScript.RecordHelper'); goog.require('Bite.Constants'); goog.require('bite.client.Container'); goog.require('bite.client.Templates'); goog.require('bite.rpf.BotHelper'); goog.require('common.client.ElementDescriptor'); goog.require('element.helper.Templates.locatorsUpdater'); goog.require('goog.Timer'); goog.require('goog.Uri'); goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.events'); goog.require('goog.events.EventHandler'); goog.require('goog.events.KeyCodes'); goog.require('goog.style'); /** * The helper class for recording. * @constructor * @export */ rpf.ContentScript.RecordHelper = function() { /** * The current element under cursor. * @type {Element} * @private */ this.elemUnderCursor_ = null; /** * The outline style of the current selected element. * @type {string} * @private */ this.outlineOfCurrentElem_ = ''; /** * The current element with mouse down. * @type {Element} * @private */ this.curMouseDownElement_ = null; /** * The recording mode. * @type {string} * @private */ this.recordingMode_ = ''; /** * Whether to show attributes. * @type {boolean} * @private */ this.hoverToShowAttr_ = true; /** * Manages the UI listeners for the locator finder. * @type {goog.events.EventHandler} * @private */ this.attrEventHandler_ = new goog.events.EventHandler(this); /** * The original contextmenu handler. * @type {function()|null} * @private */ this.originalContextMenu_ = null; /** * The element's cursor position object. * @type {Object} */ this.currentElemCursorPos = {'x': 0, 'y': 0}; /** * The element descriptor instance. * @type {common.client.ElementDescriptor} * @private */ this.elemDescriptor_ = new common.client.ElementDescriptor(); /** * The element in locator finder. * @type {Element} * @private */ this.elemInLocatorFinder_ = null; /** * The element and xpath mapper. * @type {!Object} * @private */ this.elementXpathMap_ = {}; /** * Whether the xpath finder dialog should be shown. * @type {boolean} * @private */ this.xpathFinderOn_ = true; /** * The mousedown event handler. * @type {function(Event)} * @private */ this.onMouseDownHandler_ = goog.bind(this.mouseDownHandler_, this); /** * The mouseover event handler. * @type {function(Event)} * @private */ this.onMouseOverHandler_ = goog.bind(this.mouseOverHandler_, this); /** * The mouseout event handler. * @type {function(Event)} * @private */ this.onMouseOutHandler_ = goog.bind(this.mouseOutHandler_, this); /** * The onchange event handler. * @type {function(Event)} * @private */ this.onChangeHandler_ = goog.bind(this.changeHandler_, this); /** * The onsubmit event handler. * @type {function(Event)} * @private */ this.onSubmitHandler_ = goog.bind(this.submitHandler_, this); /** * The keydown event handler. * @type {function(Event)} * @private */ this.onKeyDownHandler_ = goog.bind(this.keyDownHandler_, this); /** * The dblclick event handler. * @type {function(Event)} * @private */ this.onDblClickHandler_ = goog.bind(this.dblClickHandler_, this); /** * The mouseup event handler. * @type {function(Event)} * @private */ this.onMouseUpHandler_ = goog.bind(this.mouseUpHandler_, this); /** * The xpath finder console. * @type {bite.client.Container} * @private */ this.finderConsole_ = null; new bite.rpf.BotHelper(); this.rootArr_ = []; }; /** * The max index. * @type {number} * @private */ rpf.ContentScript.RecordHelper.MAX_ = 999; /** * The elements that could not trigger drag events. * @type {Object} * @private */ rpf.ContentScript.RecordHelper.DRAG_FILTER_ = { 'select': true }; /** * Opens the locator helper dialog. * TODO(phu): Move the bite console to common lib and call it directly. * @private */ rpf.ContentScript.RecordHelper.prototype.openLocatorDialog_ = function() { if (goog.dom.getElement('bite-locator-console-container')) { this.finderConsole_.show(); return; } this.finderConsole_ = new bite.client.Container( '', 'bite-locator-console-container', 'Xpath Finder', '', true, false, 'Press Shift to pause & resume Xpath changes'); this.finderConsole_.setContentFromHtml( element.helper.Templates.locatorsUpdater.showHelperContent({})); var size = goog.dom.getViewportSize(); this.finderConsole_.updateConsolePosition( {'position': {'x': size.width - 535, 'y': size.height - 345}, 'size': {'width': 530, 'height': 340}}); this.registerAncestorEvents_(); this.registerOnClose_(); }; /** * Registers on close event for xpath finder. * @private */ rpf.ContentScript.RecordHelper.prototype.registerOnClose_ = function() { var hideConsole = goog.dom.getElementByClass( 'bite-close-button', this.finderConsole_.getRoot()); if (hideConsole) { goog.events.listen( hideConsole, goog.events.EventType.CLICK, goog.bind(this.hideFinderConsole_, this)); } }; /** * Hides the finder console. * @private */ rpf.ContentScript.RecordHelper.prototype.hideFinderConsole_ = function() { this.finderConsole_.hide(); }; /** * The handler for saving a specified selector. * @private */ rpf.ContentScript.RecordHelper.prototype.onSaveSelector_ = function() { var xpath = goog.dom.getElement('cssSelectorInput').value; // This xpath is the default xpath of the element, which is used as the index. var defaultXpath = this.elemDescriptor_.generateXpath( this.elemInLocatorFinder_, {'id': null}, {'id': null}); this.elementXpathMap_[defaultXpath] = xpath; this.finderConsole_.showInfoMessage('The new xpath was saved.', 2); }; /** * The handler for pinging a specified selector. * TODO(phu): This also should call a common lib function to ping. * @private */ rpf.ContentScript.RecordHelper.prototype.onPingSelector_ = function() { var xpath = goog.dom.getElement('cssSelectorInput').value; var doc = goog.dom.getDocument(); try { var elems = doc.evaluate(xpath, doc, null, XPathResult.ANY_TYPE, null); var firstR = elems.iterateNext(); firstR.style.outline = 'medium solid blue'; goog.Timer.callOnce(function() {firstR.style.outline = '';}, 1500); } catch (e) { console.log('Failed to find elements through xpath ' + xpath); } }; /** * Registers all of the attribute checkboxes of the ancestors. * @private */ rpf.ContentScript.RecordHelper.prototype.registerAncestorEvents_ = function() { goog.events.listen( goog.dom.getElement('saveSelector'), 'click', goog.bind(this.onSaveSelector_, this)); goog.events.listen( goog.dom.getElement('pingSelector'), 'click', goog.bind(this.onPingSelector_, this)); var elems = goog.dom.getDocument().getElementsByName('ancestorLocatorCheck'); for (var i = 0, len = elems.length; i < len; ++i) { goog.events.listen( elems[i], 'click', goog.bind(this.checkboxHandler_, this)); } }; /** * Registers all of the attribute checkboxes of the element. * @private */ rpf.ContentScript.RecordHelper.prototype.registerElementEvents_ = function() { var elems = goog.dom.getDocument().getElementsByName('elementLocatorCheck'); var contains = goog.dom.getDocument().getElementsByName('elementContain'); for (var i = 0, len = elems.length; i < len; ++i) { this.attrEventHandler_.listen( elems[i], 'click', goog.bind(this.checkboxHandler_, this)); this.attrEventHandler_.listen( contains[i], 'click', goog.bind(this.checkboxHandler_, this)); } }; /** * Gets the element id which is connected by '-'. * @param {!Array.<string>} parts The parts that will be connected with '-'. * @return The id in the standard format. * @private */ rpf.ContentScript.RecordHelper.prototype.getElemId_ = function(parts) { return parts.join('-'); }; /** * Gets the checkbox value array of a given element name. * @param {string} name The element name. * @return {Object.<string, Object>} The key is the element's attribute and * the value is an object which contains the attribute's value and whether * the value should be exact or contained. * @private */ rpf.ContentScript.RecordHelper.prototype.getValueArr_ = function(name) { var elems = goog.dom.getDocument().getElementsByName(name); var results = {}; for (var i = 0, len = elems.length; i < len; ++i) { if (elems[i].checked) { var attr = elems[i].value; // For the ancestor elements, they don't have the value input boxes. if (!goog.dom.getElement(this.getElemId_(['value', name, attr]))) { results[attr] = null; } else { var value = goog.dom.getElement( this.getElemId_(['value', name, attr])).value; var isExact = !goog.dom.getElement( this.getElemId_(['contains', name, attr])).checked; results[attr] = {'value': value, 'isExact': isExact}; } } } return results; }; /** * Handlers for all of the attribute checkboxes. * @param {Event} e The event object. * @private */ rpf.ContentScript.RecordHelper.prototype.checkboxHandler_ = function(e) { goog.dom.getElement('cssSelectorInput').value = this.elemDescriptor_.generateXpath( this.elemInLocatorFinder_, this.getValueArr_('ancestorLocatorCheck'), this.getValueArr_('elementLocatorCheck')); }; /** * Shows the locator finding methods in helper dialog. * @private */ rpf.ContentScript.RecordHelper.prototype.showLocatorMethods_ = function() { if (!this.hoverToShowAttr_) { return; } var table = goog.dom.getElement('locatorMethodsTable'); if (!table) { return; } this.elemInLocatorFinder_ = this.elemUnderCursor_; var attrs = common.client.ElementDescriptor.getAttributeArray( this.elemUnderCursor_); soy.renderElement( table, element.helper.Templates.locatorsUpdater.showMethodsContent, {'data': attrs}); var xpath = this.elemDescriptor_.generateXpath( this.elemInLocatorFinder_, this.getValueArr_('ancestorLocatorCheck'), this.getValueArr_('elementLocatorCheck')); if (this.elementXpathMap_[xpath]) { xpath = this.elementXpathMap_[xpath]; } goog.dom.getElement('cssSelectorInput').value = xpath; this.attrEventHandler_.removeAll(); this.registerElementEvents_(); }; /** * Creates a variable name to an element. * @param {Object} elem The element. * @param {number=} opt_maxLen The maximum length. * @return {string} The generated unique variable name. * @private */ rpf.ContentScript.RecordHelper.prototype.createVarName_ = function( elem, opt_maxLen) { var maxLen = opt_maxLen || 10; var url = goog.dom.getDocument().URL.replace(/\W+/g, ''); var starts = 0; if (url.length > maxLen) { starts = url.length - maxLen; } return (elem.tagName + this.getElemIndexWithSameTag_(elem) + '-' + rpf.ContentScript.RecordHelper.randomInt()); }; /** * Gets the index of the element within all the elements having the same * tag name. * @param {Object} elem The input element. * @return {number} The index. * @private */ rpf.ContentScript.RecordHelper.prototype.getElemIndexWithSameTag_ = function(elem) { var elemsWithSameTag = goog.dom.getElementsByTagNameAndClass(elem.tagName); for (var i = 0; i < elemsWithSameTag.length; i++) { if (elemsWithSameTag[i] == elem) { return i; } } return -1; }; /** * Callback on a get context menu event. * @param {Event} event The get context event. * @private */ rpf.ContentScript.RecordHelper.prototype.getContextMenu_ = function(event) { event.stopPropagation(); event.preventDefault(); }; /** * Call back function for catching the onblur event on related divs. * @param {Event} event The event object. * @private */ rpf.ContentScript.RecordHelper.prototype.contentEditableOnBlur_ = function(event) { event.stopPropagation(); var elem = event.srcElement; this.sendActionBack(elem, elem.innerHTML, 'replaceHtml', event); }; /** * Add listeners to content editable divs. * @private */ rpf.ContentScript.RecordHelper.prototype.addListenersToContentEditables_ = function() { var attrName = 'contenteditable'; var divs = goog.dom.getElementsByTagNameAndClass(goog.dom.TagName.DIV); for (var i = 0; i < divs.length; i++) { var attr = divs[i].attributes.getNamedItem(attrName); if (attr) { divs[i].onblur = goog.bind(this.contentEditableOnBlur_, this); } } }; /** * Checks if the given element is within the recording area. * @param {Element} elem The element object. * @return {boolean} Wether the element is in recording area. * @private */ rpf.ContentScript.RecordHelper.prototype.checkInRecordingArea_ = function( elem) { if (elem) { var biteConsole = goog.dom.getElement('bite-locator-console-container'); if (biteConsole && goog.dom.contains(biteConsole, elem)) { return false; } } return true; }; /** * Mouse click handler. * @param {Event} e The event object. * @private */ rpf.ContentScript.RecordHelper.prototype.mouseUpHandler_ = function(e) { if (e.button == 0) { var dx = e.screenX - this.currentElemCursorPos['x']; var dy = e.screenY - this.currentElemCursorPos['y']; if ((dx < 10 && dx > -10) && (dy < 10 && dy > -10)) { return; } else { var tagName = this.curMouseDownElement_.tagName.toLowerCase(); if (this.checkInRecordingArea_(this.curMouseDownElement_) && !rpf.ContentScript.RecordHelper.DRAG_FILTER_[tagName]) { this.sendActionBack( this.curMouseDownElement_, dx + 'x' + dy, 'drag', e); } } } }; /** * Mouse click handler. * @param {Event} e The event object. * @private */ rpf.ContentScript.RecordHelper.prototype.mouseDownHandler_ = function(e) { if (!this.elemUnderCursor_) { this.elemUnderCursor_ = /** @type {Element} */ (e.target); } var content = this.elemDescriptor_.getText(this.elemUnderCursor_); if (e.button == 0 && this.recordingMode_ == 'rpf') { this.currentElemCursorPos = {'x': e.screenX, 'y': e.screenY}; this.curMouseDownElement_ = this.elemUnderCursor_; if (this.elemUnderCursor_.tagName.toLowerCase() != 'select') { this.sendActionBack(this.elemUnderCursor_, content, 'click', e); } } else if (e.button == 2) { this.sendActionBack(this.elemUnderCursor_, content, 'rightclick', e); } }; /** * Mouse click handler. * @param {Event} e The event object. * @private */ rpf.ContentScript.RecordHelper.prototype.submitHandler_ = function(e) { this.sendActionBack(/** @type {Element} */ (e.target), '', 'submit', e); }; /** * Toggles to show attributes in dialog on hover over. * @private */ rpf.ContentScript.RecordHelper.prototype.toggleHoverShowAttr_ = function() { this.hoverToShowAttr_ = !this.hoverToShowAttr_; }; /** * Mouse click handler. * @param {Event} e The event object. * @private */ rpf.ContentScript.RecordHelper.prototype.keyDownHandler_ = function(e) { var keynum = e.keyCode; if (this.recordingMode_ == 'rpf' && keynum == goog.events.KeyCodes.ENTER && e.target.tagName.toLowerCase() == 'input') { this.sendActionBack(/** @type {Element} */ (e.target), '', 'enter', e); } else if (keynum == goog.events.KeyCodes.SHIFT) { this.toggleHoverShowAttr_(); } }; /** * Mouse click handler. * @param {Event} e The event object. * @private */ rpf.ContentScript.RecordHelper.prototype.changeHandler_ = function(e) { console.log('onchange event caught.'); var elem = /** @type {Element} */ (e.target); if (!this.checkApplicableAsInput_(elem)) { console.log('The element is a checkbox or radio button, discard.'); return; } var eventType = 'change'; var upperTagName = elem.tagName.toUpperCase(); if (upperTagName == goog.dom.TagName.INPUT) { eventType = 'type'; } else if (upperTagName == goog.dom.TagName.SELECT) { eventType = 'select'; } this.sendActionBack(elem, elem.value, eventType, e); }; /** * Reverts the outline style back to element's original style. * @param {Element} elem The element. * @return {Element} The element whose outline is reverted. * @private */ rpf.ContentScript.RecordHelper.prototype.revertOutline_ = function(elem) { goog.style.setStyle(elem, 'outline', this.outlineOfCurrentElem_); return elem; }; /** * Highlights the outline style. * @param {Element} elem The element. * @param {string=} opt_outline The optional outline. * @private */ rpf.ContentScript.RecordHelper.prototype.highlightOutline_ = function( elem, opt_outline) { elem.style.outline = opt_outline || 'medium solid yellow'; }; /** * Mouse click handler. * @param {Event} e The event object. * @private */ rpf.ContentScript.RecordHelper.prototype.mouseOverHandler_ = function(e) { if (this.elemUnderCursor_) { this.revertOutline_(this.elemUnderCursor_); } this.elemUnderCursor_ = /** @type {Element} */ (e.target); this.outlineOfCurrentElem_ = this.elemUnderCursor_.style.outline; // Outline elements on mouse over, if rpf Console UI is constructed. if (this.checkInRecordingArea_(this.elemUnderCursor_)) { this.showLocatorMethods_(); this.highlightOutline_(this.elemUnderCursor_); } }; /** * Mouse click handler. * @param {Event} e The event object. * @private */ rpf.ContentScript.RecordHelper.prototype.mouseOutHandler_ = function(e) { e.target.style.outline = ''; }; /** * Mouse click handler. * @param {Event} e The event object. * @private */ rpf.ContentScript.RecordHelper.prototype.dblClickHandler_ = function(e) { if (!this.elemUnderCursor_) { this.elemUnderCursor_ = /** @type {Element} */ (e.target); } this.sendActionBack( this.elemUnderCursor_, this.elemDescriptor_.getText(this.elemUnderCursor_), 'doubleClick', e); }; /** * The on request handler. * @param {!Object.<string, string, Object>} request Object Data sent in * the request. * @param {MessageSender} sender An object containing information about the * script context that sent the request. * @param {function(!*): void} callback Function to call when the request * completes. * @export */ rpf.ContentScript.RecordHelper.prototype.onRequest = function( request, sender, callback) { switch (request['recordAction']) { case Bite.Constants.RECORD_ACTION.START_RECORDING: this.rootArr_ = request['params']['rootArr']; this.xpathFinderOn_ = request['params']['xpathFinderOn']; this.startRecording(); break; case Bite.Constants.RECORD_ACTION.STOP_RECORDING: this.rootArr_ = []; this.stopRecording(); break; case Bite.Constants.RECORD_ACTION.START_UPDATE_MODE: this.rootArr_ = request['params']['rootArr']; this.xpathFinderOn_ = request['params']['xpathFinderOn']; this.enterUpdaterMode(); break; } }; /** * Stops recording mode experiment. * @export */ rpf.ContentScript.RecordHelper.prototype.stopRecording = function() { goog.events.unlisten(goog.global.document, 'mousedown', this.onMouseDownHandler_, true); goog.events.unlisten(goog.global.document, 'mouseover', this.onMouseOverHandler_, true); goog.events.unlisten(goog.global.document, 'mouseout', this.onMouseOutHandler_, true); goog.events.unlisten(goog.global.document, 'change', this.onChangeHandler_, true); goog.events.unlisten(goog.global.document, 'submit', this.onSubmitHandler_, true); goog.events.unlisten(goog.global.document, 'keydown', this.onKeyDownHandler_, true); goog.events.unlisten(goog.global.document, 'dblclick', this.onDblClickHandler_, true); goog.events.unlisten(goog.global.document, 'mouseup', this.onMouseUpHandler_, true); goog.global.document.oncontextmenu = this.originalContextMenu_; if (this.finderConsole_) { this.hideFinderConsole_(); } }; /** * Starts recording mode experiment. * @export */ rpf.ContentScript.RecordHelper.prototype.startRecording = function() { this.recordingMode_ = 'rpf'; this.stopRecording(); goog.events.listen(goog.global.document, 'mousedown', this.onMouseDownHandler_, true); goog.events.listen(goog.global.document, 'mouseover', this.onMouseOverHandler_, true); goog.events.listen(goog.global.document, 'mouseout', this.onMouseOutHandler_, true); goog.events.listen(goog.global.document, 'change', this.onChangeHandler_, true); goog.events.listen(goog.global.document, 'submit', this.onSubmitHandler_, true); goog.events.listen(goog.global.document, 'keydown', this.onKeyDownHandler_, true); goog.events.listen(goog.global.document, 'dblclick', this.onDblClickHandler_, true); goog.events.listen(goog.global.document, 'mouseup', this.onMouseUpHandler_, true); this.originalContextMenu_ = goog.global.document.oncontextmenu; goog.global.document.oncontextmenu = goog.bind(this.getContextMenu_, this); this.addListenersToContentEditables_(); if (window == window.parent && this.xpathFinderOn_) { this.openLocatorDialog_(); } }; /** * Check whether this is applicable. * @param {Object} elem The element was interacted with. * @return {boolean} Whether the event triggered as input is applicable. * @private */ rpf.ContentScript.RecordHelper.prototype.checkApplicableAsInput_ = function(elem) { return !(elem && elem.type && (elem.type == 'checkbox' || elem.type == 'radio')); }; /** * Gets the xpath of the given element. * @param {Element} elem The element was interacted with. * @return {string} The xpath string. * @private */ rpf.ContentScript.RecordHelper.prototype.getXpathStr_ = function(elem) { // This is the default xpath which will be used to find the custom xpath. var defaultXpath = this.elemDescriptor_.generateXpath( elem, {'id': null}, {'id': null}); for (var xpath in this.elementXpathMap_) { if (xpath == defaultXpath) { return this.elementXpathMap_[xpath]; } } return defaultXpath; }; /** * Returns the class name if the element is a descendant of a root element. * @param {Element} elem The element was interacted with. * @return {string} The class name. * @private */ rpf.ContentScript.RecordHelper.prototype.checkForClassName_ = function(elem) { for (var i = 0, len = this.rootArr_.length; i < len; ++i) { var xpath = this.rootArr_[i]['xpath']; var rootElem = null; try { rootElem = bot.locators.xpath.single( /** @type {string} */ (xpath), goog.dom.getDocument()); } catch (e) { continue; } if (rootElem) { if (goog.dom.contains(rootElem, elem)) { return this.rootArr_[i]['className']; } } } return ''; }; /** * Sends an action related info to background page. * @param {Element} elem The target element. * @param {string} content The content in the target element. * @param {string} action The action performed. * @param {Event} event The event object. * @export */ rpf.ContentScript.RecordHelper.prototype.sendActionBack = function( elem, content, action, event) { if (!this.checkInRecordingArea_(elem)) { return; } var descriptorStr = this.elemDescriptor_.generateElementDescriptor( this.revertOutline_(elem), 2, false); this.highlightOutline_(elem); var elemVarName = this.createVarName_(elem); var selectors = [this.elemDescriptor_.generateSelector(elem), this.elemDescriptor_.generateSelectorPath( /** @type {!Node} */ (elem))]; var xpaths = [this.getXpathStr_(elem)]; var tagName = elem.tagName; this.sendActionBack_( selectors, content, tagName, action, descriptorStr, elemVarName, elem, event, xpaths); }; /** * Sends an action related info to background page. * @param {Array} selectors The array of selectors. * @param {string} content The content in the target element. * @param {string} nodeType The node type of the element. * @param {string} action The action performed. * @param {string} descriptor The descriptor of the element. * @param {string=} opt_elemVarName The variable name of the element. * @param {Element=} opt_elem The element. * @param {Event=} opt_event The event object. * @param {Array=} opt_xpaths The xpath array. * @private */ rpf.ContentScript.RecordHelper.prototype.sendActionBack_ = function( selectors, content, nodeType, action, descriptor, opt_elemVarName, opt_elem, opt_event, opt_xpaths) { if (!this.checkInRecordingArea_(opt_elem || this.elemUnderCursor_)) { return; } var elemVarName = opt_elemVarName || ''; var xpaths = opt_xpaths || []; console.log('Caught event: ' + action); var iframeInfo = null; // Assign the iframeInfo only if it's in an iframe window. if (window != window.parent) { iframeInfo = {'host': window.location.host, 'pathname': window.location.pathname}; } var position = null; var className = ''; if (opt_elem) { var pos = goog.style.getClientPosition(opt_elem); var size = goog.style.getSize(opt_elem); var eX = 0; var eY = 0; if (opt_event) { eX = opt_event.clientX; eY = opt_event.clientY; } position = {'x': pos.x, 'y': pos.y, 'width': size.width, 'height': size.height, 'eX': eX, 'eY': eY}; className = this.checkForClassName_(opt_elem); } chrome.extension.sendRequest({'command': 'GetActionInfo', 'selectors': selectors, 'content': escape(content), 'nodeType': nodeType, 'action': action, 'descriptor': descriptor, 'elemVarName': elemVarName, 'iframeInfo': iframeInfo, 'position': position, 'mode': this.recordingMode_, 'xpaths': xpaths, 'className': className}); }; /** * Enum for the received request command. * @enum {string} * @export */ rpf.ContentScript.RecordHelper.ReqCmds = { TEST_DESCRIPTOR: 'testDescriptor', TEST_LOCATOR: 'testLocator' }; /** * Callback for the onRequest listener. * @param {Object} request The request object. * @param {Object} sender The sender object. * @param {function(Object)} sendResponse The sendResponse object used * to send back results. * @private */ rpf.ContentScript.RecordHelper.prototype.callBackAddOnRequest_ = function( request, sender, sendResponse) { switch (request.command) { case rpf.ContentScript.RecordHelper.ReqCmds.TEST_DESCRIPTOR: var result = 'pass'; try { var desc = (/** @type {string} */ request['descriptor']); this.outlineElems_(desc); } catch (e) { result = e.message; } sendResponse({result: result}); break; case rpf.ContentScript.RecordHelper.ReqCmds.TEST_LOCATOR: var results = []; var locators = request['locators']; for (var i = 0, len = locators.length; i < len; ++i) { var loc = locators[i]; var passed = false; var elem = common.client.ElementDescriptor.getElemBy( loc['method'], loc['value']); if (elem && elem.style) { if (loc['show']) { elem.style.outline = 'medium solid red'; } else { elem.style.outline = ''; } passed = true; } results.push({'id': loc['id'], 'passed': passed, 'show': loc['show']}); } sendResponse({'results': results}); break; } }; /** * Enters locator updater mode. * @export */ rpf.ContentScript.RecordHelper.prototype.enterUpdaterMode = function() { this.recordingMode_ = 'updater'; goog.events.listen(goog.dom.getDocument(), 'mousedown', this.onMouseDownHandler_, true); goog.events.listen(goog.dom.getDocument(), 'mouseover', this.onMouseOverHandler_, true); goog.events.listen(goog.dom.getDocument(), 'mouseout', this.onMouseOutHandler_, true); goog.events.listen(goog.dom.getDocument(), 'keydown', this.onKeyDownHandler_, true); chrome.extension.onRequest.removeListener( goog.bind(this.callBackAddOnRequest_, this)); chrome.extension.onRequest.addListener( goog.bind(this.callBackAddOnRequest_, this)); if (goog.global.window == goog.global.window.parent) { this.openLocatorDialog_(); } }; /** * Ends locator updater mode. * @export */ rpf.ContentScript.RecordHelper.prototype.endUpdaterMode = function() { goog.events.unlisten(goog.dom.getDocument(), 'mousedown', this.onMouseDownHandler_, true); goog.events.unlisten(goog.dom.getDocument(), 'mouseover', this.onMouseOverHandler_, true); goog.events.unlisten(goog.dom.getDocument(), 'mouseout', this.onMouseOutHandler_, true); goog.events.unlisten(goog.dom.getDocument(), 'keydown', this.onKeyDownHandler_, true); chrome.extension.onRequest.removeListener( goog.bind(this.callBackAddOnRequest_, this)); if (this.finderConsole_) { this.hideFinderConsole_(); } }; /** * Adds the onRequest listener. * @export */ rpf.ContentScript.RecordHelper.prototype.addOnRequestListener = function() { chrome.extension.onRequest.removeListener( goog.bind(this.callBackAddOnRequest_, this)); chrome.extension.onRequest.addListener( goog.bind(this.callBackAddOnRequest_, this)); }; /** * Outlines the found elements. * @param {string} descriptor The descriptor object. * @private */ rpf.ContentScript.RecordHelper.prototype.outlineElems_ = function( descriptor) { var result = this.elemDescriptor_.parseElementDescriptor(descriptor); if (!result['elems']) { // TODO(phu): Display info on console instead of alerts. alert('There is no matched element.'); return; } var elems = result['elems']; elems = elems.length == undefined ? [elems] : elems; for (var i = 0; i < elems.length; ++i) { var elem = elems[i]; goog.style.setStyle(elem, 'outline', 'medium solid blue'); goog.Timer.callOnce( function() {goog.style.setStyle(elem, 'outline', '');}, 1500); } }; /** * The RecordHelper instance. * @export */ var recordHelper = new rpf.ContentScript.RecordHelper(); /** * Get a random int. * @return {number} A random int number. * @export */ rpf.ContentScript.RecordHelper.randomInt = function() { return Math.floor(Math.random() * rpf.ContentScript.RecordHelper.MAX_); }; /** * Sent the page loaded message to background page. * @export */ rpf.ContentScript.RecordHelper.run = function() { chrome.extension.sendRequest( {command: Bite.Constants.CONSOLE_CMDS.RECORD_PAGE_LOADED_COMPLETE, url: window.location.href}); }; /** * Starts auto recording. * @private */ rpf.ContentScript.RecordHelper.startAutoRecord_ = function() { chrome.extension.sendRequest( {command: Bite.Constants.CONTROL_CMDS.OPEN_CONSOLE_AUTO_RECORD}, rpf.ContentScript.RecordHelper.startAutoRecordCallback); }; /** * The callback for starting auto record. * @param {Object} response The response object. * @export */ rpf.ContentScript.RecordHelper.startAutoRecordCallback = function(response) { if (response['result']) { chrome.extension.sendRequest( {command: Bite.Constants.CONSOLE_CMDS.START_AUTO_RECORD}); rpf.ContentScript.RecordHelper.randomActions(); } }; /** * Randomly click on a link in a page. * @export */ rpf.ContentScript.RecordHelper.randomActions = function() { var aTags = document.querySelectorAll('a'); if (!aTags) { return; } var selectedElem = aTags[Math.floor(Math.random() * aTags.length)]; goog.Timer.callOnce( function() {rpf.ContentScript.RecordHelper.randomActions();}, 4000); }; /** * Sends a message to background page to start a sequence of commands. * @param {Object} params The parameters. * @private */ rpf.ContentScript.RecordHelper.automateRpf_ = function(params) { chrome.extension.sendRequest({ 'command': Bite.Constants.CONSOLE_CMDS.AUTOMATE_RPF, 'params': params}); }; /** * Groups the parameters in URL to an object. * @param {string} url The current page url. * @private */ rpf.ContentScript.RecordHelper.getParamsFromUrl_ = function(url) { var uri = new goog.Uri(href); var queryData = uri.getQueryData(); var keys = queryData.getKeys(); var parameters = {}; for (var i = 0, len = keys.length; i < len; ++i) { parameters[keys[i]] = queryData.get(keys[i]); } return parameters; }; // Execute the run function only if it's in the main window. if (window == window.parent) { rpf.ContentScript.RecordHelper.run(); var href = window.location.href; var parameters = null; if (href.indexOf('localhost:7171') != -1) { parameters = rpf.ContentScript.RecordHelper.getParamsFromUrl_(href); parameters['command'] = Bite.Constants.RPF_AUTOMATION.LOAD_AND_RUN_FROM_LOCAL; rpf.ContentScript.RecordHelper.automateRpf_(parameters); } else if (href.indexOf('.com/automateRpf') != -1) { parameters = rpf.ContentScript.RecordHelper.getParamsFromUrl_(href); if (parameters['projectName'] && parameters['location']) { parameters['command'] = Bite.Constants.RPF_AUTOMATION.PLAYBACK_MULTIPLE; if (parameters['scriptName']) { parameters['command'] = Bite.Constants.RPF_AUTOMATION.AUTOMATE_SINGLE_SCRIPT; } rpf.ContentScript.RecordHelper.automateRpf_(parameters); } } goog.dom.getDocument().addEventListener('rpfLaunchEvent', function(e) { var parameters = { 'command': Bite.Constants.RPF_AUTOMATION.PLAYBACK_MULTIPLE}; parameters['data'] = goog.json.parse( goog.dom.getElement('rpfLaunchData').innerHTML); rpf.ContentScript.RecordHelper.automateRpf_(parameters); }, false); } chrome.extension.onRequest.addListener( goog.bind(recordHelper.onRequest, recordHelper));
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Tests for the Record Mode Manager class. * * @author alexto@google.com (Alexis O. Torres) */ goog.require('common.client.RecordModeManager'); goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.testing.PropertyReplacer'); /** * Mock Document object used to facilitate testing */ MockDocument = function() { }; /** * Mocks the onmousemove event handler of the document. */ MockDocument.prototype.onmousemove = null; /** * Mocks the onclick event handler of the document. */ MockDocument.prototype.onclick = null; var stubs_ = new goog.testing.PropertyReplacer(); var mockDocument_ = null; function setUp() { this.stubs_.set(goog.global, 'document', new MockDocument()); } function tearDown() { this.stubs_.reset(); this.mockDocument_ = null; } function testEnterExitRecordingMode() { var recordMan = new common.client.RecordModeManager(); assertFalse(recordMan.isRecording()); recordMan.enterRecordingMode(goog.nullFunction); assertTrue(recordMan.isRecording()); recordMan.exitRecordingMode(); assertFalse(recordMan.isRecording()); } function testOnClickAndMouseMove() { // Reset while we create a new element. this.stubs_.reset(); var testElement = goog.dom.createDom( goog.dom.TagName.DIV, {'id': 'testDiv'}); goog.dom.appendChild(document.body, testElement); // Mock the global document. this.stubs_.set(goog.global, 'document', new MockDocument()); // Enter recording mode. var actualElement = null; var recordMan = new common.client.RecordModeManager(); recordMan.enterRecordingMode(function(elmnt) { actualElement = elmnt; }); var mockMouseEvent = {srcElement: testElement}; // Call the mousemove and click events handlers. goog.global.document.onmousemove(mockMouseEvent); goog.global.document.onclick(mockMouseEvent); assertNotNull(actualElement); assertEquals(testElement, actualElement); } function testHighlightBoxId() { var recordMan = new common.client.RecordModeManager(); recordMan.enterRecordingMode(function(elmnt) {}); assertEquals('recordingHighlightBox', recordMan.getHighlightBoxId()); recordMan.setHighlightBoxId('testingBoxId'); assertEquals('testingBoxId', recordMan.getHighlightBoxId()); }
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains the methods to update elements * locators info. * * @author phu@google.com (Po Hu) */ goog.provide('bite.locators.Updater'); goog.require('bite.base.Helper'); goog.require('element.helper.Templates.locatorsUpdater'); goog.require('goog.dom'); goog.require('goog.dom.xml'); goog.require('goog.format.HtmlPrettyPrinter'); goog.require('goog.events'); goog.require('goog.ui.tree.TreeControl'); goog.require('goog.ui.tree.TreeNode'); goog.require('rpf.Console.Messenger'); /** * A class for maintaining element locators info. * @param {rpf.Console.Messenger} messenger The messenger instance. * @constructor * @export */ bite.locators.Updater = function(messenger) { /** * The document tree. * @type {Document} * @private */ this.domTree_ = null; /** * The ui tree. * @type {goog.ui.tree.TreeControl} * @private */ this.uiTree_ = null; /** * The dynamic id counter. * @type {number} * @private */ this.counter_ = 0; /** * The selected locator's id which is to be updated. * @type {string} * @private */ this.selectedId_ = ''; /** * The messenger. * @type {rpf.Console.Messenger} * @private */ this.messenger_ = messenger; }; /** * The known methods to locate elements. * @type {Object} */ bite.locators.Updater.knownMethods = { 'id': true, 'xpath': true, 'selector': true, 'linktext': true, 'name': true, 'class': true }; /** * Overrides the original enterDocument method to avoid a couple events. * Adds FOCUSOUT, FOCUSIN, MOUSEDOWN, CLICK events listeners. * @suppress {duplicate} Overriding TreeControl methods? sigh */ goog.ui.tree.TreeControl.prototype.enterDocument = function() { goog.ui.tree.TreeControl.superClass_.enterDocument.call(this); var el = this.getElement(); el.className = this.getConfig().cssRoot; el.setAttribute('hideFocus', 'true'); this.attachEvents(); this.initAccessibility(); }; /** * Overrides the original enterDocument method to avoid a couple events. * Adds FOCUSOUT, FOCUSIN, MOUSEDOWN, CLICK events listeners. */ goog.ui.tree.TreeControl.prototype.attachEvents = function() { var el = this.getElement(); el.tabIndex = 0; var kh = this.keyHandler_ = new goog.events.KeyHandler(el); var fh = this.focusHandler_ = new goog.events.FocusHandler(el); this.getHandler(). listen(fh, goog.events.FocusHandler.EventType.FOCUSOUT, this.handleBlur_). listen(fh, goog.events.FocusHandler.EventType.FOCUSIN, this.handleFocus_). listen(el, goog.events.EventType.MOUSEDOWN, this.handleMouseEvent_). listen(el, goog.events.EventType.CLICK, this.handleMouseEvent_); }; /** * Renders the UI in the given element. * @param {Element} elem The dom element to render UI. * @export */ bite.locators.Updater.prototype.render = function(elem) { soy.renderElement( elem, element.helper.Templates.locatorsUpdater.showUI, {}); goog.events.listen( goog.dom.getElement('generateTree'), goog.events.EventType.CLICK, goog.bind(this.onGenerate_, this)); goog.events.listen( goog.dom.getElement('saveToXml'), goog.events.EventType.CLICK, goog.bind(this.getXmlFromUiTree_, this)); }; /** * Generates a locator tree. * @param {Event} e The event object. * @private */ bite.locators.Updater.prototype.onGenerate_ = function(e) { this.counter_ = 0; var data = goog.dom.getElement('xmlData').value; var xmlTree = goog.dom.getElement('xmlTree'); xmlTree.innerHTML = ''; this.constructTreeFromXml_(data); this.uiTree_.render(xmlTree); this.uiTree_.setShowLines(false); this.uiTree_.setShowRootLines(false); this.uiTree_.expandAll(); this.addShowBtnListeners_(); this.addUpdateBtnListeners_(); goog.style.showElement(goog.dom.getElement('saveToXml'), true); }; /** * Adds the showBtn listeners. * @private */ bite.locators.Updater.prototype.addShowBtnListeners_ = function() { var btns = goog.dom.getDocument().getElementsByName('showBtn'); for (var i = 0, len = btns.length; i < len; ++i) { goog.events.listen( btns[i], goog.events.EventType.CLICK, goog.bind(this.onShowBtnClicked_, this)); } }; /** * Adds the updateBtn listeners. * @private */ bite.locators.Updater.prototype.addUpdateBtnListeners_ = function() { var btns = goog.dom.getDocument().getElementsByName('updateBtn'); for (var i = 0, len = btns.length; i < len; ++i) { goog.events.listen( btns[i], goog.events.EventType.CLICK, goog.bind(this.onUpdateBtnClicked_, this)); } }; /** * UpdateBtn click handler. * @param {Event} e The click event. * @private */ bite.locators.Updater.prototype.onUpdateBtnClicked_ = function(e) { this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.SET_ACTION_CALLBACK, 'params': {}}, goog.bind(this.updateLocator, this)); var selectedNode = this.uiTree_.getSelectedItem(); this.selectedId_ = this.getNodeId_(selectedNode); }; /** * Update the selected locator. * @param {Object} infoMap The map containing element info. * @export */ bite.locators.Updater.prototype.updateLocator = function(infoMap) { goog.dom.getElement('name' + this.selectedId_).value = 'selector'; goog.dom.getElement('value' + this.selectedId_).value = infoMap['cmdMap']['selectors'][0]; }; /** * ShowBtn click handler. * @param {Event} e The click event. * @private */ bite.locators.Updater.prototype.onShowBtnClicked_ = function(e) { var selectedNode = this.uiTree_.getSelectedItem(); var show = this.getShowBtnAction_(selectedNode); this.setShowBtnValue_(selectedNode, show); var locators = []; this.getSubLocators_(locators, selectedNode, show); this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.TEST_LOCATOR, 'params': {'locators': locators}}, goog.bind(this.updateTestResult_, this)); }; /** * Updates the results of the tests. * @param {Object} response The response object. * @private */ bite.locators.Updater.prototype.updateTestResult_ = function(response) { var results = response['results']; for (var i = 0, len = results.length; i < len; ++i) { var result = results[i]; try { var elem = goog.dom.getElement('node' + result['id']); if (result['show']) { elem.src = result['passed'] ? 'imgs/test-pass.png' : 'imgs/test-fail.png'; } else { elem.src = ''; } } catch (e) { console.log('Error: ' + e.message); } } }; /** * Sets the showBtn value to the node including all the descendants. * @param {goog.ui.tree.BaseNode} node The tree node. * @private */ bite.locators.Updater.prototype.getShowBtn_ = function(node) { return goog.dom.getElement('show' + this.getNodeId_(node)); }; /** * Sets the showBtn value to the node including all the descendants. * @param {goog.ui.tree.BaseNode} node The tree node. * @param {boolean} show Whether to show the element or not. * @private */ bite.locators.Updater.prototype.setShowBtnValue_ = function(node, show) { var btn = this.getShowBtn_(node); if (btn) { btn.value = show ? 'hide' : 'show'; } }; /** * Gets the action on a showBtn click, which depends on the btn value. * @param {goog.ui.tree.BaseNode} node The tree node. * @return {boolean} Whether to show or hide the element. * @private */ bite.locators.Updater.prototype.getShowBtnAction_ = function(node) { var btn = this.getShowBtn_(node); return btn.value == 'show'; }; /** * Gets locators in all the descendants. * @param {Array} arr The locator array. * @param {goog.ui.tree.BaseNode} node The ui tree node. * @param {boolean} show Whether to show or hide the element. * @private */ bite.locators.Updater.prototype.getSubLocators_ = function( arr, node, show) { var children = node.getChildren(); for (var i = 0, len = children.length; i < len; ++i) { var curNode = children[i]; var values = this.getNodeValues_(curNode); var nameLowerCase = values['name'].toLowerCase(); if (bite.locators.Updater.knownMethods[nameLowerCase] && values['value']) { arr.push({'method': nameLowerCase, 'value': values['value'], 'show': show, 'id': this.getNodeId_(curNode)}); return; } this.setShowBtnValue_(curNode, show); this.getSubLocators_(arr, curNode, show); } }; /** * Reads an xml string and constructs a dom tree. * @param {string} xml The xml string. * @private */ bite.locators.Updater.prototype.constructTreeFromXml_ = function(xml) { this.domTree_ = goog.dom.xml.loadXml(xml); var treeConfig = goog.ui.tree.TreeControl.defaultConfig; treeConfig['cleardotPath'] = 'imgs/rpf/cleardot.gif'; treeConfig['indentWidth'] = 57; this.uiTree_ = new goog.ui.tree.TreeControl('root', treeConfig); this.addData_(this.uiTree_, this.domTree_.documentElement); console.log(this.uiTree_); }; /** * Generates an xml file. * @private */ bite.locators.Updater.prototype.getXmlFromUiTree_ = function() { this.uiTree_.expandAll(); var values = this.getNodeValues_(this.uiTree_); this.domTree_ = goog.dom.xml.createDocument(values['name']); this.updateDomTree_(this.uiTree_, this.domTree_.documentElement); var xml = goog.dom.xml.serialize(this.domTree_); goog.dom.getElement('xmlData').value = bite.base.Helper.formatXml(xml); }; /** * Gets the name and value. * @param {goog.ui.tree.BaseNode} node The tree node object. * @return {Object} The name and value pair. * @private */ bite.locators.Updater.prototype.getNodeValues_ = function(node) { var ids = node['controls']; var name = goog.dom.getElement(ids['nameId']).value; var value = ids['valueId'] ? goog.dom.getElement(ids['valueId']).value : ''; return {'name': name, 'value': value}; }; /** * Gets the node id. * @param {goog.ui.tree.BaseNode} node The tree node object. * @return {string} The node id. * @private */ bite.locators.Updater.prototype.getNodeId_ = function(node) { return node['controls']['id']; }; /** * Updates the dom tree based on the UI tree values. * @param {goog.ui.tree.BaseNode} node The tree node object. * @param {Element} elem The dom element. * @private */ bite.locators.Updater.prototype.updateDomTree_ = function(node, elem) { var children = node.getChildren(); for (var i = 0, len = children.length; i < len; ++i) { var curNode = children[i]; var values = this.getNodeValues_(curNode); var newElem = goog.dom.createDom(values['name'], {}, values['value']); goog.dom.appendChild(elem, newElem); this.updateDomTree_(curNode, newElem); } }; /** * Constructs tree from a dom object. * @param {goog.ui.tree.TreeControl} node The tree node object. * @param {Element} elem The dom element. * @private */ bite.locators.Updater.prototype.addData_ = function(node, elem) { var children = goog.dom.getChildren(elem); for (var i = 0, len = children.length; i < len; ++i) { var curElem = children[i]; var newNode = node.getTree().createNode(''); node.add(newNode); this.addData_(newNode, curElem); } var value = ''; if (children.length == 0) { value = goog.dom.getTextContent(elem); } var nameId = 'name' + this.counter_; var id = '' + this.counter_; var valueId = 'value' + this.counter_++; var folder = element.helper.Templates.locatorsUpdater.getNode( {'data': {'name': elem.tagName, 'nameId': nameId, 'value': value, 'valueId': valueId, 'nodeId': 'node' + id, 'showBtnId': 'show' + id, 'updateBtnId': 'update' + id}}); node['controls'] = {'nameId': nameId}; node['controls']['id'] = id; if (value) { node['controls']['valueId'] = valueId; } node.setHtml(folder); };
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains how RPF loads tests. * * @author phu@google.com (Po Hu) */ goog.provide('rpf.LoaderDialog'); goog.require('bite.common.mvc.helper'); goog.require('goog.Uri'); goog.require('goog.array'); goog.require('goog.dom'); goog.require('goog.events'); goog.require('goog.style'); goog.require('goog.ui.AutoComplete.Basic'); goog.require('goog.ui.ComboBox'); goog.require('goog.ui.Dialog'); goog.require('rpf.Console.Messenger'); goog.require('rpf.StatusLogger'); goog.require('rpf.soy.Dialog'); /** * A class for loading tests from locally or cloud. * @param {rpf.Console.Messenger} messenger The messenger instance. * @param {function(Bite.Constants.UiCmds, Object, Event, function(Object)=)} * onUiEvents The function to handle the specific event. * @constructor * @export */ rpf.LoaderDialog = function(messenger, onUiEvents) { /** * The ids of the tests. * @type {Array.<string>} * @private */ this.uniqueIds_ = null; /** * The names of the tests. * @type {Array} * @private */ this.testNames_ = []; /** * The messenger. * @type {rpf.Console.Messenger} * @private */ this.messenger_ = messenger; /** * The function to handle the specific event. * @type {function(Bite.Constants.UiCmds, Object, Event, function(Object)=)} * @private */ this.onUiEvents_ = onUiEvents; /** * The current responded project object. * @type {Object} * @private */ this.curProject_ = null; }; /** * Enum for location values. * @enum {string} */ rpf.LoaderDialog.Locations = { WEB: 'web', LOCAL: 'local' }; /** * Loads the current specified project. * @param {string} projectName The project name. * @param {Function} callback The */ rpf.LoaderDialog.prototype.loadProject = function(projectName, callback) { this.showTests_(callback, projectName); }; /** * Automates the dialog. * @param {boolean} isWeb Whether the location is the web. * @param {string} project The project name. * @param {string} test The test name. * @param {function(Object)} callback The callback function. */ rpf.LoaderDialog.prototype.automateDialog = function( isWeb, project, test, callback) { }; /** * Gets the storage location. * @return {string} The storage location. */ rpf.LoaderDialog.prototype.getStorageLocation = function() { var locations = goog.dom.getDocument().getElementsByName('projectLocation'); for (var i = 0, len = locations.length; i < len; ++i) { if (locations[i].checked) { return locations[i].value; } } alert('Please select a location.'); throw new Error('No location was specified.'); }; /** * Shows tests from locally or cloud. * @param {Function} callback The callback. * @param {string} projectName The project name. * @private */ rpf.LoaderDialog.prototype.showTests_ = function( callback, projectName) { var names = []; var storageLocation = this.getStorageLocation(); if (!projectName) { rpf.StatusLogger.getInstance().setStatus( 'Please enter a project name.', 'red'); return; } var command = storageLocation == rpf.LoaderDialog.Locations.WEB ? Bite.Constants.CONSOLE_CMDS.GET_PROJECT : Bite.Constants.CONSOLE_CMDS.GET_LOCAL_PROJECT; var newCallback = goog.bind(this.updateNamesAndIds_, this, callback); this.messenger_.sendMessage( {'command': command, 'params': {'name': projectName}}, newCallback); }; /** * Update names and ids in load dialog. * @param {Function} callback The callback function. * @param {Object} response The response object. * @private */ rpf.LoaderDialog.prototype.updateNamesAndIds_ = function( callback, response) { var jsonObj = response['jsonObj']; if (jsonObj['error']) { callback({'success': false}); return; } this.curProject_ = jsonObj; var tests = jsonObj['tests']; var project_details = jsonObj['project_details']; var projectName = jsonObj['name']; var names = []; var ids = response['location'] == 'web' ? [] : null; goog.array.sortObjectsByKey(tests, 'test_name'); for (var i = 0; i < tests.length; ++i) { names.push(tests[i]['test_name']); if (response['location'] == 'web') { ids.push(tests[i]['id']); } } this.testNames_ = names; this.uniqueIds_ = ids; this.onUiEvents_( Bite.Constants.UiCmds.UPDATE_INVOKE_SELECT, {'names': this.testNames_, 'ids': this.uniqueIds_}, /** @type {Event} */ ({})); this.onUiEvents_( Bite.Constants.UiCmds.SET_PROJECT_INFO, {'name': projectName, 'tests': tests, 'details': project_details, 'from': 'web'}, /** @type {Event} */ ({})); callback(this.testNames_, {'success': true}); }; /** * Loads the specified test. * @param {function(Object)} callback The load test callback function. * @param {string} project The optional project name. * @param {string} test The optional test name. */ rpf.LoaderDialog.prototype.loadSelectedTest = function( callback, project, test) { var testId = this.getIdByName(test); var locationStorage = this.getStorageLocation(); if (locationStorage == rpf.LoaderDialog.Locations.WEB) { this.onUiEvents_(Bite.Constants.UiCmds.LOAD_TEST_FROM_WTF, {'jsonId': testId, 'mode': rpf.MiscHelper.Modes.CONSOLE}, /** @type {Event} */ ({})); } else { this.onUiEvents_(Bite.Constants.UiCmds.LOAD_TEST_FROM_LOCAL, {'name': test, 'projectName': project}, /** @type {Event} */ ({})); } }; /** * Gets the id by test name. Note, this assumes there is no duplicated test * name. * @param {string} name The test name. * @return {string} The id of the test. */ rpf.LoaderDialog.prototype.getIdByName = function(name) { if (!this.uniqueIds_ || !name) { return ''; } for (var i = 0, len = this.testNames_.length; i < len; ++i) { if (name == this.testNames_[i]) { return this.uniqueIds_[i]; } } }; /** * @return {Array.<string>} The ids of the tests. */ rpf.LoaderDialog.prototype.getUniqueIds = function() { return this.uniqueIds_; }; /** * @return {Array} The names of the tests. */ rpf.LoaderDialog.prototype.getTestNames = function() { return this.testNames_; }; /** * Gets the current project object. * @return {Object} The project object. */ rpf.LoaderDialog.prototype.getCurrentProject = function() { return this.curProject_; };
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains the dialog for exporting a project. When * the user enters a project, its tests and details are loaded from the server * and displayed in the dialog. If the user makes changes to the details and * wishes to save those changes the save button must be pressed. It does not * automatically save user changes as they are made. * * The main functionality of this dialog is the ability to export the project * as Java WebDriver code. It does this by translating the loaded project * information through the bite.webdriver and then sends the resulting output * files to the server. The output files are then zipped, stored on the * server, and then downloaded to the user's machine. * * The script button follows the same process as the export button, but * produces a command line script created by RPF for the exported project. The * script will unzip the exported project and move it to the correct location * within the client. * * @author jasonstredwick@google.com (Jason Stredwick) */ goog.provide('rpf.ExportDialog'); goog.require('bite.closure.Helper'); goog.require('bite.common.mvc.helper'); goog.require('bite.webdriver'); goog.require('goog.dom'); goog.require('goog.events'); goog.require('goog.events.EventHandler'); goog.require('goog.events.EventType'); goog.require('goog.events.KeyCodes'); goog.require('goog.format.JsonPrettyPrinter'); goog.require('goog.json'); goog.require('goog.ui.CustomButton'); goog.require('goog.ui.Dialog'); goog.require('goog.ui.TabBar'); goog.require('rpf.Console.Messenger'); goog.require('rpf.DataModel'); goog.require('rpf.StatusLogger'); goog.require('rpf.soy.Dialog'); /** * Defines an export dialog used by RPF to export tests and projects to the * local machine as a zip file. Each zip file will contain the translation * of the information in the selected format. * @param {function(Bite.Constants.UiCmds, Object, Event, function(Object)=)} * onUiEvents The function to handle the specific event. * @param {function()} reloadProject The method to reload the project. * @param {rpf.Console.Messenger} messenger The messenger instance. * @constructor */ rpf.ExportDialog = function(onUiEvents, reloadProject, messenger) { /** * The project data loaded from the server. * @type {Object} * @private */ this.data_ = null; /** * The dialog. * @type {goog.ui.Dialog} * @private */ this.dialog_ = null; /** * Contains key elements within the dialog. * @type {!Object.<string, !Element>} * @private */ this.elements_ = {}; /** * Manages events that are constant through every state. * @type {goog.events.EventHandler} * @private */ this.handlersDynamic_ = null; /** * Manages a set of events that will change from state to state. * @type {goog.events.EventHandler} * @private */ this.handlersStatic_ = null; /** * Whether or not the dialog is ready for use. * @type {boolean} * @private */ this.ready_ = false; /** * The project name. * @type {string} * @private */ this.projectName_ = ''; /** * The location. * @type {string} * @private */ this.location_ = ''; /** * The test ids. * @type {!Array.<string>} * @private */ this.ids_ = []; /** * The method to reload the current project. * @type {function()} * @private */ this.reloadProject_ = reloadProject; /** * The messenger. * @type {rpf.Console.Messenger} * @private */ this.messenger_ = messenger; /** * The function to handle the specific event. * @type {function(Bite.Constants.UiCmds, Object, Event, function(Object)=)} * @private */ this.onUiEvents_ = onUiEvents; }; /** * Ids for important elements. * @enum {string} * @private */ rpf.ExportDialog.Id_ = { ADD: 'export-add-class', EXPORT: 'export-button-export', INTERVAL: 'export-java-interval', JAVA_PACKAGE_PATH: 'export-java-package-path', JAVA_PACKAGE_IMPORT: 'import-java-package-path', IMPORT: 'export-button-import', PAGE_TABLE_BODY: 'export-page-table-body', ROOT: 'export-root', SAVE: 'export-button-save', TEST_DATA: 'export-test-data' }; /** * Destroys the export dialog making it unusable. */ rpf.ExportDialog.prototype.destroy = function() { // Clean up listeners this.handlersDynamic_ && this.handlersDynamic_.removeAll(); this.handlersStatic_ && this.handlersStatic_.removeAll(); // Remove the content generated by this object from the dialog object's html. if (rpf.ExportDialog.Id_.ROOT in this.elements_) { goog.dom.removeNode(this.elements_[rpf.ExportDialog.Id_.ROOT]); } // Remove references to owned objects. this.data_ = null; this.dialog_ = null; this.elements_ = {}; this.handlersDynamic_ = null; this.handlersStatic_ = null; this.ready_ = false; }; /** * Initialize the export dialog. */ rpf.ExportDialog.prototype.init = function() { if (this.isReady()) { return; } try { this.initContent_(); this.initComponents_(); this.initStaticHandlers_(); } catch (error) { this.destroy(); console.error('ERROR (rpf.ExportDialog.init): Failed to initialize. ' + 'Exception: ' + error); return; } this.ready_ = true; }; /** * Create/Setup the major components of the object. These components help * manage the dialog. This function is intended to only be called by init. * @private */ rpf.ExportDialog.prototype.initComponents_ = function() { this.handlersDynamic_ = new goog.events.EventHandler(); this.handlersStatic_ = new goog.events.EventHandler(); var rootElement = this.elements_[rpf.ExportDialog.Id_.ROOT]; this.dialog_ = new goog.ui.Dialog(); this.dialog_.getContentElement().appendChild(rootElement); this.dialog_.setTitle('Project details'); this.dialog_.setButtonSet(null); this.dialog_.setVisible(false); var topTab = new goog.ui.TabBar(); goog.events.listen(topTab, goog.ui.Component.EventType.SELECT, goog.bind(this.onTabSelected_, this)); topTab.decorate(goog.dom.getElement('project-details-tab')); this.renderButtons_(); }; /** * Renders the buttons. * @private */ rpf.ExportDialog.prototype.renderButtons_ = function() { var deleteButton = new goog.ui.CustomButton('Delete'); goog.events.listen( deleteButton, goog.ui.Component.EventType.ACTION, goog.bind(this.onDeleteTests_, this)); deleteButton.render(goog.dom.getElement('delete-tests-button')); var saveButton = new goog.ui.CustomButton('Save'); goog.events.listen( saveButton, goog.ui.Component.EventType.ACTION, goog.bind(this.handleSave_, this)); saveButton.render(this.elements_[rpf.ExportDialog.Id_.SAVE]); var importButton = new goog.ui.CustomButton('Import'); goog.events.listen( importButton, goog.ui.Component.EventType.ACTION, goog.bind(this.handleImport_, this)); importButton.render(this.elements_[rpf.ExportDialog.Id_.IMPORT]); var exportButton = new goog.ui.CustomButton('Export'); goog.events.listen( exportButton, goog.ui.Component.EventType.ACTION, goog.bind(this.handleExport_, this)); exportButton.render(this.elements_[rpf.ExportDialog.Id_.EXPORT]); }; /** * On removing the selected tests. * @private */ rpf.ExportDialog.prototype.onDeleteTests_ = function() { var selectedTestNames = []; var selectedTestIds = []; var location = this.location_; var selector = goog.dom.getElement('project-details-tests-selector'); for (var i = 0; i < selector.options.length; ++i) { if (selector.options[i].selected) { selectedTestNames.push(selector.options[i].value); if (this.ids_ && this.ids_[i]) { selectedTestIds.push(this.ids_[i]); } } } if (selectedTestNames.length > 0) { if (location == rpf.LoaderDialog.Locations.LOCAL) { this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.DELETE_TEST_LOCAL, 'params': {'project': this.projectName_, 'testNames': selectedTestNames}}, this.reloadProject_); } else { this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.DELETE_TEST_ON_WTF, 'params': {'jsonIds': selectedTestIds}}, this.reloadProject_); } } }; /** * Render the content elements for the dialog using soy then store references * to specific elements. Will throw an exception in string form upon error. * This function is intended to only be called by init. * @private */ rpf.ExportDialog.prototype.initContent_ = function() { var helper = bite.common.mvc.helper; var content = helper.renderModel(rpf.soy.Dialog.exportContent); if (!content) { throw 'No content was rendered.'; } var key = ''; // Initialize to null the elements that are always present in the dialog. // Don't include the root element because the search looks within that // element and will not locate itself. var elements = {}; for (key in rpf.ExportDialog.Id_) { var id = rpf.ExportDialog.Id_[key]; elements[id] = null; } // Load all relevant elements. if (!helper.bulkGetElementById(elements, content)) { var keys = []; for (key in elements) { if (!elements[key]) { keys.push(key); } } throw 'Failed to create elements: ' + keys.join(', '); } // Store relevant Element references for quick lookup later. this.elements_ = elements; }; /** * Handles a tab selected event. * @param {Object} e The event object. * @private */ rpf.ExportDialog.prototype.onTabSelected_ = function(e) { var tabSelected = e.target; var id = tabSelected.getContentElement().id; var contentDiv = goog.dom.getElement('project-details-content'); var tabs = contentDiv.querySelectorAll('.project-details-content-tab'); bite.closure.Helper.setElementsVisibility(/** @type {Array} */ (tabs), false); var selectedTab = goog.dom.getElement(id + '-content'); bite.closure.Helper.setElementsVisibility([selectedTab], true); }; /** * Setup handlers for the dialog. This function is intended to only be called * by init. * @private */ rpf.ExportDialog.prototype.initStaticHandlers_ = function() { // State changing button handlers var element = this.elements_[rpf.ExportDialog.Id_.ADD]; this.handlersStatic_.listen(element, goog.events.EventType.CLICK, goog.bind(this.handleAdd_, this)); }; /** * Returns whether or not the dialog is ready and usable. * @return {boolean} Is ready. */ rpf.ExportDialog.prototype.isReady = function() { return this.ready_; }; /** * Creates a row for the url/page map table. * @param {string} url The url pattern. * @param {string} name The page's name. * @param {Element} element The table's body element to add to. * @param {boolean=} opt_first Whether or not the new row should be appended as * the first row (if true) or the last row (if false). Defaults to false. * @private */ rpf.ExportDialog.prototype.generateUrlPageMapRow_ = function(url, name, element, opt_first) { var helper = bite.common.mvc.helper; var first = opt_first || false; // Create a new row by creating a table with soy. var table = helper.renderModel(rpf.soy.Dialog.getPageMap, {'url': url, 'name': name}); if (!table) { console.error('ERROR (rpf.ExportDialog.generateUrlPageMapRow_): Failed ' + 'to create table.'); return; } // Retrieve key elements from the table. var row = helper.getElement('export-page-map-row', table); var close = helper.getElement('export-page-map-close', table); if (!row || !close) { console.error('ERROR (rpf.ExportDialog.generateUrlPageMapRow_): New ' + 'table does not contain required elements.'); return; } // Remove the row from the table and add it to the table within the document. goog.dom.removeNode(row); if (first) { goog.dom.insertChildAt(element, row, 0); } else { element.appendChild(row); } // Create a listener for the close button var closeObject = {}; var closeFunc = function() { goog.events.unlistenByKey(closeObject.listenerKey); goog.dom.removeNode(row); // Clear references closeObject = null; row = null; }; try { var key = goog.events.listen(close, goog.events.EventType.CLICK, closeFunc); if (!key) { throw 'Failed to create listener; returned null.'; } closeObject.listenerKey = key; } catch (error) { console.error('ERROR (rpf.ExportDialog.generateUrlPageMapRow_): Failed ' + 'to create listener for close button.'); return; } }; /** * Loops over the url/page map elements and extracts a url/page map. * @return {!Object} The current url/page map. * @private */ rpf.ExportDialog.prototype.getUrlPageMap_ = function() { var urlPageMap = {}; var rows = this.elements_[rpf.ExportDialog.Id_.PAGE_TABLE_BODY].rows; for (var i = 0, len = rows.length; i < len; ++i) { var children = rows[i].children; var url = children[0].children[0].value; var pageName = children[1].children[0].value; if (!url || !pageName) { continue; } urlPageMap[url] = pageName; } return urlPageMap; }; /** * Opens a page and downloads the zip file. * @param {Object} response The response object. * @private */ rpf.ExportDialog.prototype.getZip_ = function(response) { var url = response['url']; goog.global.window.open(url); }; /** * Handles the pressing of the plus button that adds a new url/page mapping * to the table of mappings. The new mapping begins empty and the user can * add relevant information. * @private */ rpf.ExportDialog.prototype.handleAdd_ = function() { var urlPageMapElement = this.elements_[rpf.ExportDialog.Id_.PAGE_TABLE_BODY]; this.generateUrlPageMapRow_('', '', urlPageMapElement, true); }; /** * Exports the generated Java files by downloading a zip. * @param {Object} data The consolidated data. * @private */ rpf.ExportDialog.prototype.exportAsJavaFilesZip_ = function(data) { var dataModel = new rpf.DataModel(); var processedData = dataModel.convertDataToRaw(data || {}); var pages = bite.webdriver.getWebdriverCode(processedData); var files = {}; for (var pageName in pages) { var filename = pageName + '.java'; var page = pages[pageName]; files[filename] = page; } this.downloadZip_(files); }; /** * Exports the generated data model by downloading a zip. * @param {string} dataFile The data model file content. * @private */ rpf.ExportDialog.prototype.exportAsDataModelZip_ = function(dataFile) { var files = {}; files['data.rpf'] = dataFile; this.downloadZip_(files); }; /** * Sends the files object to server to download a zip. * @param {Object.<string, string>} files It contains the file name and the * corresponding file content. * @private */ rpf.ExportDialog.prototype.downloadZip_ = function(files) { var command = { 'command': Bite.Constants.CONSOLE_CMDS.SAVE_ZIP, 'params': {'files': files} }; var messenger = rpf.Console.Messenger.getInstance(); messenger.sendMessage(command, goog.bind(this.getZip_, this)); }; /** * Handles the clicking of the import button. By default, it will send a ping * to local server and try to import the project defined in data.rpf, and * then save the project to localStorage for further manipulation. * @private */ rpf.ExportDialog.prototype.handleImport_ = function() { var ids = rpf.ExportDialog.Id_; var command = { 'command': Bite.Constants.CONSOLE_CMDS.LOAD_PROJECT_FROM_LOCAL_SERVER, 'params': {'path': this.elements_[ids.JAVA_PACKAGE_IMPORT].value} }; var messenger = rpf.Console.Messenger.getInstance(); messenger.sendMessage(command, goog.bind(this.onImportCallback_, this)); var statusLogger = rpf.StatusLogger.getInstance(); statusLogger.setStatus('Importing the project from your client...'); }; /** * Handles the clicking of the import button. By default, it will send a ping * to local server and try to import the project defined in data.rpf, and * then save the project to localStorage for further manipulation. * @private */ rpf.ExportDialog.prototype.onImportCallback_ = function(response) { // Updates the status for saving the project locally. var statusLogger = rpf.StatusLogger.getInstance(); statusLogger.setStatusCallback(response); // If the project was successfully loaded, load it in the console. if (response['project']) { this.onUiEvents_(Bite.Constants.UiCmds.AUTOMATE_DIALOG_LOAD_PROJECT, {'isWeb': false, 'project': response['project']}, /** @type {Event} */ ({})); } }; /** * Handles the clicking of the export button. The clicked will pass the * necessary data to the translation component. While exporting the * project the dialog will become non-responsive except for the close button on * the dialog. There is no stopping the translation/download process once * started. * @private */ rpf.ExportDialog.prototype.handleExport_ = function() { var name = this.projectName_; if (!name) { rpf.StatusLogger.getInstance().setStatus( 'Please load a project first.', 'red'); return; } var dataModel = new rpf.DataModel(); var result = dataModel.consolidateData( {'name': this.projectName_, 'tests': this.data_['tests'], 'project_details': this.data_['project_details']}); var data = result['data']; var jsFiles = result['jsFiles']; var printer = new goog.format.JsonPrettyPrinter(null); var dataFile = printer.format(data); var requestUrl = rpf.MiscHelper.getUrl('http://localhost:7171', '', {}); var pageMap = this.elements_[rpf.ExportDialog.Id_.JAVA_PACKAGE_PATH].value; var parameters = goog.Uri.QueryData.createFromMap( {'command': 'replaceDatafile', 'datafilePath': pageMap.split('.').join('/'), 'fileName': 'data.rpf', 'jsFiles': jsFiles, 'content': dataFile}).toString(); goog.net.XhrIo.send(requestUrl, goog.bind(function(e) { var xhr = e.target; if (xhr.isSuccess()) { rpf.StatusLogger.getInstance().setStatus(xhr.getResponseText()); } else { // If it fails, we assume the local server is not ready, so we will // send files to the server and then await its response to pull the zip // down to the local machine. var msg = xhr.getResponseText() || 'Local server is not ready...'; rpf.StatusLogger.getInstance().setStatus(msg, 'red'); this.exportAsDataModelZip_(dataFile); } }, this), 'POST', parameters); }; /** * Handles the clicking of the save button. When pressed the current project * details will be formed into an object and sent to the server to be saved. * @private */ rpf.ExportDialog.prototype.handleSave_ = function() { var name = this.projectName_; if (!name) { rpf.StatusLogger.getInstance().setStatus( 'Please load a project first.', 'red'); return; } rpf.StatusLogger.getInstance().setStatus(rpf.StatusLogger.SAVING, '#777'); // Disable dialog elements for (var key in rpf.ExportDialog.Id_) { var id = rpf.ExportDialog.Id_[key]; var element = this.elements_[id]; element.setAttribute('disabled', 'disabled'); } var urlPageMap = this.getUrlPageMap_(); var ids = rpf.ExportDialog.Id_; var wdPage = this.elements_[ids.JAVA_PACKAGE_PATH].value || ''; var interval = this.elements_[ids.INTERVAL].value || ''; var params = {'interval': interval, 'waitVisible': interval ? false : true}; var details = { 'page_map': goog.json.serialize(urlPageMap), 'params': goog.json.serialize(params), 'java_package_path': wdPage }; var data = { 'command': '', 'params': { 'name': name, 'data': goog.json.serialize(details) } }; var location = this.getStorageLocation_(); if ('web' == location) { data['command'] = Bite.Constants.CONSOLE_CMDS.SAVE_PROJECT; } else { data['command'] = Bite.Constants.CONSOLE_CMDS.SAVE_PROJECT_METADATA_LOCALLY; } rpf.Console.Messenger.getInstance().sendMessage(data, goog.bind(this.handleSaveComplete_, this, name)); }; /** * Handles the response from the server after a request to save the project * details. * @param {string} name The name of the project that is being saved. * @param {Object} responseObj The object returned from the request. * @private */ rpf.ExportDialog.prototype.handleSaveComplete_ = function(name, responseObj) { // Enable dialog elements for (var key in rpf.ExportDialog.Id_) { var id = rpf.ExportDialog.Id_[key]; var element = this.elements_[id]; if (element.hasAttribute('disabled')) { element.removeAttribute('disabled'); } } // Process response if (!responseObj || !('success' in responseObj) || !responseObj['success']) { rpf.StatusLogger.getInstance().setStatus(rpf.StatusLogger.SAVE_FAILED, 'red'); } else { rpf.StatusLogger.getInstance().setStatus(rpf.StatusLogger.SAVE_SUCCESS, 'green'); } }; /** * Clears the project info dialog UI. * @private */ rpf.ExportDialog.prototype.clear_ = function() { //Clear major elements this.elements_[rpf.ExportDialog.Id_.TEST_DATA].innerHTML = ''; this.elements_[rpf.ExportDialog.Id_.PAGE_TABLE_BODY].innerHTML = ''; this.elements_[rpf.ExportDialog.Id_.JAVA_PACKAGE_PATH].value = ''; }; /** * Handles the response from the server after a request to load the project * details and tests. * @param {string} name The name of the project that is being saved. * @param {function()} callback The callback function. * @param {Object} responseObj The object returned from the request. */ rpf.ExportDialog.prototype.requestDataComplete = function( name, callback, responseObj) { var statusLogger = rpf.StatusLogger.getInstance(); this.clear_(); // Enable dialog elements for (var key in rpf.ExportDialog.Id_) { var id = rpf.ExportDialog.Id_[key]; var element = this.elements_[id]; if (element.hasAttribute('disabled')) { element.removeAttribute('disabled'); } } // Process response // Check response data for appropriate major components; project_details and // tests. this.data_ = 'jsonObj' in responseObj ? responseObj['jsonObj'] : null; // If an error occurs during communication then the object will have an // error key added to the response. if (!this.data_ || 'error' in this.data_) { this.data_ = null; statusLogger.setStatus(rpf.StatusLogger.PROJECT_NOT_FOUND, 'red'); return; } var details = 'project_details' in this.data_ ? this.data_['project_details'] : null; if (!details) { this.data_ = null; statusLogger.setStatus(rpf.StatusLogger.PROJECT_MISSING_DETAILS, 'red'); return; } if (!('page_map' in details && 'java_package_path' in details)) { this.data_ = null; statusLogger.setStatus(rpf.StatusLogger.PROJECT_MISSING_DETAILS, 'red'); return; } try { var typeOfPageMap = typeof details['page_map']; if ('object' == typeOfPageMap) { details['page_map'] = details['page_map']; } else if ('string' == typeOfPageMap) { details['page_map'] = /** @type {!Object} */ (goog.json.parse(details['page_map'])); } else { statusLogger.setStatus('Incorrect page map argument.', 'red'); throw new Error(); } // Update the url/page map for all project data. When generating the // webdriver code, the reference to the url/page map is updated. Thus // the generated code is thrown away but the mapping is updated. bite.webdriver.getWebdriverCode(this.data_); } catch (error) { this.data_ = null; statusLogger.setStatus('Parse json failed.'); console.error('ERROR (rpf.ExportDialog.requestDataComplete_): Failed to ' + 'parse json for url/page map: ' + error); return; } var tests = 'tests' in this.data_ ? this.data_['tests'] : null; if (!tests) { this.data_ = null; statusLogger.setStatus(rpf.StatusLogger.PROJECT_NO_TESTS, 'red'); return; } // Get list of test names and update appropriate dialog element with data. var names = []; var ids = []; goog.array.sortObjectsByKey(tests, 'test_name'); for (var i = 0; i < tests.length; ++i) { names.push(tests[i]['test_name']); var temp = tests[i]['id']; if (temp) { ids.push(temp); } } this.ids_ = ids; var testElement = this.elements_[rpf.ExportDialog.Id_.TEST_DATA]; bite.common.mvc.helper.renderModelFor(testElement, rpf.soy.Dialog.getTests, {'tests': names}); // Set page/url mappings var urlPageMap = details['page_map']; var urls = []; for (var key in urlPageMap) { urls.push(key); } urls = urls.sort().reverse(); var urlPageMapElement = this.elements_[rpf.ExportDialog.Id_.PAGE_TABLE_BODY]; for (var i = 0, len = urls.length; i < len; ++i) { var url = urls[i]; var pageName = urlPageMap[url]; this.generateUrlPageMapRow_(url, pageName, urlPageMapElement); } // Set webdriver configuration var javaPackagePath = this.elements_[rpf.ExportDialog.Id_.JAVA_PACKAGE_PATH]; javaPackagePath.value = details['java_package_path']; javaPackagePath = this.elements_[rpf.ExportDialog.Id_.JAVA_PACKAGE_IMPORT]; javaPackagePath.value= details['java_package_path']; if (details['params']) { var codeParams = goog.json.parse(details['params']); var intervalInput = this.elements_[rpf.ExportDialog.Id_.INTERVAL]; intervalInput.value = codeParams['interval'] ? codeParams['interval'] : ''; } this.setProjectName_(details['name']); var messenger = rpf.Console.Messenger.getInstance(); messenger.sendStatusMessage( Bite.Constants.COMPLETED_EVENT_TYPES.PROJECT_LOADED_IN_EXPORT); callback(); }; /** * Sets the visibility of the export dialog. * @param {boolean} display Whether or not to show the dialog. */ rpf.ExportDialog.prototype.setVisible = function(display) { if (this.isReady()) { this.dialog_.setVisible(display); } }; /** * Sets the project name. * @param {string} projectName The project name. * @private */ rpf.ExportDialog.prototype.setProjectName_ = function(projectName) { this.projectName_ = projectName; }; /** * Sets the location. * @param {string} location The location. */ rpf.ExportDialog.prototype.setLocation = function(location) { this.location_ = location; }; /** * Gets the storage location. * @return {string} The storage location. * @private */ rpf.ExportDialog.prototype.getStorageLocation_ = function() { return this.location_; };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains the webdriver code generator. * * @author phu@google.com (Po Hu) */ goog.provide('bite.webdriver'); goog.require('bite.base.Helper'); goog.require('common.client.ElementDescriptor'); goog.require('goog.string'); goog.require('rpf.CodeGenerator'); /** * Gets the WebDriver code. This is the entry function of the file, which * takes in a group of test information, and generate pages and tests in * WebDriver/Java format. * * The data is in the format of: * {project_details: {name: string, * page_map: Object, * java_package_path: string}, * tests: [{id: string, test: string, test_name: string} ...], * userId: string} * * The generated files are: * 1. BasePage, which contains common properties and methods. * 2. Test, which contains all of the unit tests. * 3. A group of Page files, each of which contains the locator/action/module * info belonging to it. Take a look at the * bite.webdriver.getPageClassHeader_ which shows the structure of a page. * * The parameters that could control the generated Webdriver code: * interval: The interval between each generated lines. * waitVisible: Whether needs to wait until the element is visible. * * @param {!Object} data The original projec/test data. * @return {Object} Contains code. */ bite.webdriver.getWebdriverCode = function(data) { var wdData = bite.webdriver.convertProjectData_(data); bite.webdriver.author_ = data['userId']; bite.webdriver.packageName_ = wdData.packageNames.source; var pages = bite.webdriver.generatePages_(wdData.codeArr, wdData.infoMap, wdData.startUrlArr, wdData.urlPageMap, wdData.testNameArr, wdData.datafileArr); pages['BasePage'] = bite.webdriver.generateBasePage_( data['project_details']['name']); pages['CustomException'] = bite.webdriver.generateExceptionFile_(); return pages; }; /** * Converts a project and associated tests into an object with the data * formatted for WebDriver. * * @param {!Object} data The original projec/test data. * @return {!Object} WebDriver version of the data. * @private */ bite.webdriver.convertProjectData_ = function(data) { var details = data['project_details']; var tests = data['tests']; var codeArr = []; var datafileArr = []; var startUrlArr = []; var testNameArr = []; var infoMapArr = []; var infoMap = {}; for (var i = 0, len = tests.length; i < len; ++i) { if (!tests[i]['test']) { continue; } var test = bite.base.Helper.getTestObject(tests[i]['test']); codeArr.push(test['script']); startUrlArr.push(test['url']); testNameArr.push(test['name']); var result = bite.console.Helper.trimInfoMap(test['datafile']); datafileArr.push(result['datafile']); infoMapArr.push(result['infoMap']); } bite.webdriver.codeParams_ = details['params'] ? goog.json.parse(details['params']) || {} : {}; return { codeArr: codeArr, datafileArr: datafileArr, infoMap: bite.console.Helper.mergeInfoMaps(infoMapArr), packageNames: { source: details['java_package_path'] }, startUrlArr: startUrlArr, testNameArr: testNameArr, urlPageMap: details['page_map'] }; }; /** * Gets the page class object, which has the following format: * {pageName: {'copyright': string, * 'imports': string, * 'classSig': string, * 'properties': [var declaration string], * 'rest': string, * 'selectors': {xpath/selector string: true}, * 'modules': {module name: * {'methodNames': [{'className': the class the method belongs, * 'xpathName': the xpath variable name, * 'action': the action, * // data input could be a string or an object * // The Object is for verifying different attributes in a command. * 'data': [data input]}], * 'isModule': boolean, * 'startUrl': string}}}, * ... * } * @param {string} pageName The page name. * @return {Object} The code of page class object. * @private */ bite.webdriver.getPageClassHeader_ = function(pageName) { var copyright = bite.webdriver.generateCopyrightAndPackage_(); var imports = bite.webdriver.generatePageImports_(); var classDoc = bite.webdriver.generateClassDoc_(pageName); var classSig = bite.webdriver.generateClass_(pageName, 'BasePage'); var logger = bite.webdriver.generateLogger_(pageName, 2); var constructor = bite.webdriver.generateConstructor_(2, pageName); constructor += bite.webdriver.generateCommands_(4, ['super(driver);']); constructor += '\n' + bite.webdriver.generateClosing_(2); return {'copyright': copyright, 'imports': imports, // Class signature. 'classSig': [classDoc, classSig, logger].join('\n'), // A list of selector/xpath variables to declare. 'properties': [], // The page string after constructor and including it. 'rest': constructor, // A map to make sure no dup selector/xpath exists. 'selectors': {}, // Key is module name and value is a tuple of // original name and real name. 'modules': {}}; }; /** * The package name. * @type {string} * @private */ bite.webdriver.packageName_ = 'testing.chronos.bite.webdriver'; /** * The package name of tests. * @type {string} * @private */ bite.webdriver.packageNameTest_ = ''; /** * The code generation parameters. * @type {!Object} * @private */ bite.webdriver.codeParams_ = {}; /** * The page index. * @type {number} * @private */ bite.webdriver.pageIndex_ = 0; /** * The hashmap variable index in the generated test. * @type {number} * @private */ bite.webdriver.variableIndex_ = 0; /** * The author. * @type {string} * @private */ bite.webdriver.author_ = ''; /** * The supported actions. * @type {Array} * @private */ bite.webdriver.supportedActions_ = [ rpf.CodeGenerator.RecordActions.CLICK, rpf.CodeGenerator.RecordActions.ENTER, rpf.CodeGenerator.RecordActions.TYPE, rpf.CodeGenerator.RecordActions.MOVE, rpf.CodeGenerator.RecordActions.CHANGE, rpf.CodeGenerator.RecordActions.VERIFY, rpf.CodeGenerator.RecordActions.VERIFYNOT, rpf.CodeGenerator.RecordActions.SUBMIT, rpf.CodeGenerator.RecordActions.DRAG, rpf.CodeGenerator.PlaybackActions.SELECT ]; /** * Escapes all of the double quotes. * @param {string} str The given string. * @return {string} The string with double quotes escaped. * @private */ bite.webdriver.escapeDoubleQuotes_ = function(str) { return str.replace(/\"/g, '\\\"'); }; /** * Generates a WebDriver command to navigate to an url. * @param {string} url The start url. * @return {string} The WebDriver navigation command. * @private */ bite.webdriver.generateNavigation_ = function(url) { return 'driver.get("' + bite.webdriver.escapeDoubleQuotes_(url) + '");'; }; /** * Generates the command to instantiate a wait instance. * @return {string} The command in webdriver format. * @private */ bite.webdriver.generateWaitInstance_ = function() { return 'WebDriverWait wait = new WebDriverWait(driver, 6);'; }; /** * Generates the Java method waitAndGetElement. * @param {number} num The number of spaces. * @return {string} The WebDriver waitAndGetElement command. * @private */ bite.webdriver.generateWaitAndGetElement_ = function(num) { return bite.webdriver.addIndentations(num, [ '/**', ' * Waits until the element is ready then returns it.', ' */', 'public Function<WebDriver, WebElement> waitAndGetElement' + '(final By locator) {', ' return new Function<WebDriver, WebElement>() {', ' public WebElement apply(WebDriver driver) {', ' return driver.findElement(locator);', ' }', ' };', '}']).join('\n'); }; /** * Generates the Java copyright and package info. * @param {string=} opt_package The package name. * @return {string} The generated lines. * @private */ bite.webdriver.generateCopyrightAndPackage_ = function(opt_package) { var packageName = opt_package || bite.webdriver.packageName_; return ['// Copyright 2011 Google Inc. All Rights Reserved.', '', 'package ' + packageName + ';', ''].join('\n'); }; /** * Generates the Java class doc. * @param {string} page The page name. * @param {string=} opt_desc The description. * @return {string} The generated lines. * @private */ bite.webdriver.generateClassDoc_ = function(page, opt_desc) { var desc = opt_desc || ('The ' + page + ' class which contains its locators and actions.'); var authorLine = '@author ' + bite.webdriver.author_; var docs = bite.webdriver.generateJavaDoc_([desc, '', authorLine]); return docs.join('\n'); }; /** * Generates the Java doc string. * @param {Array} lines The doc string content array. * @return {Array} The generated lines. * @private */ bite.webdriver.generateJavaDoc_ = function(lines) { var javaDoc = ['', '/**']; for (var i = 0, len = lines.length; i < len; ++i) { javaDoc.push(' * ' + lines[i]); } javaDoc.push(' */'); return javaDoc; }; /** * Generates the Java imports for base page. * @return {string} The generated lines. * @private */ bite.webdriver.generateImports_ = function() { return [ 'import com.google.common.base.Function;', 'import com.google.common.time.DefaultSleeper;', 'import com.google.common.time.Sleeper;', 'import com.google.testing.webdriver.support.ui.ExpectedConditions;', 'import org.openqa.selenium.By;', 'import org.openqa.selenium.JavascriptExecutor;', 'import org.openqa.selenium.Keys;', 'import org.openqa.selenium.WebDriver;', 'import org.openqa.selenium.WebElement;', 'import org.openqa.selenium.interactions.Actions;', 'import org.openqa.selenium.support.ui.WebDriverWait;', 'import java.util.HashMap;', 'import java.util.List;', 'import java.util.concurrent.TimeUnit;', 'import java.util.logging.Level;', 'import java.util.logging.Logger;' ].join('\n'); }; /** * Generates the Java imports for page classes. * @return {string} The generated lines. * @private */ bite.webdriver.generatePageImports_ = function() { return [ 'import org.openqa.selenium.WebDriver;', 'import java.util.logging.Level;', 'import java.util.logging.Logger;', 'import java.util.HashMap;' ].join('\n'); }; /** * Generates the Java class. * @param {string} name The name string. * @param {string=} opt_extends The optional extends part. * @return {string} The generated lines. * @private */ bite.webdriver.generateClass_ = function(name, opt_extends) { var extendsPart = opt_extends ? (' extends ' + opt_extends) : ''; return 'public class ' + name + extendsPart + ' {'; }; /** * Add indents for lines. * @param {number} num The number of indentations. * @param {Array} lines The given array of lines. * @return {Array} The generated lines. * @export */ bite.webdriver.addIndentations = function(num, lines) { var newLines = []; for (var i = 0, len = lines.length; i < len; ++i) { newLines.push(bite.base.Helper.spaces(num) + lines[i]); } return newLines; }; /** * Generates the class variables. * @param {number} num The number of indentations. * @return {string} The generated lines. * @private */ bite.webdriver.generateBaseClassVariables_ = function(num) { return bite.webdriver.addIndentations(num, [ 'private static final Logger logger =' + ' Logger.getLogger(BasePage.class.getName());', 'protected final WebDriver driver;', 'protected final WebDriverWait wait;', '' ]).join('\n'); }; /** * Generates commands. * @param {number} num The number of indentations. * @param {Array} cmdArr The array of commands. * @return {string} The generated lines. * @private */ bite.webdriver.generateCommands_ = function(num, cmdArr) { return bite.webdriver.addIndentations(num, cmdArr).join('\n'); }; /** * Generates the constructor. * @param {number} num The number of indentations. * @param {string} name The constructor name. * @return {string} The generated lines. * @private */ bite.webdriver.generateConstructor_ = function(num, name) { return [bite.base.Helper.spaces(num) + 'public ' + name + '(WebDriver driver) {', ''].join('\n'); }; /** * Adds the ending }. * @param {number} num The number of spaces. * @return {string} The generated lines. * @private */ bite.webdriver.generateClosing_ = function(num) { return [bite.base.Helper.spaces(num) + '}', ''].join('\n'); }; /** * Generates a WebDriver command to create a WebElement. * @param {string} selector The css selector string. * @param {string} action The action string. * @return {string} The WebDriver command. * @private */ bite.webdriver.generateWebElementBySelector_ = function(selector, action) { if (action != 'verifyNot') { if (bite.webdriver.codeParams_['waitVisible'] == undefined || bite.webdriver.codeParams_['waitVisible']) { return ['WebElement element = wait.until(', ' ExpectedConditions.visibilityOfElementLocated(' + 'By.xpath(' + selector + ')));'].join('\n'); } else { return ['WebElement element = wait.until(', ' waitAndGetElement(By.xpath(' + selector + ')));'].join('\n'); } } return ['Boolean isThrow = true;', ' try {', ' WebElement element = wait.until(', ' waitAndGetElement(By.xpath(' + selector + ')));', ' } catch (Exception e) {', ' isThrow = false;', ' }', ' if (isThrow) {', ' throw new CustomException("Element should not exist.");', ' }'].join('\n'); }; /** * Generates a WebDriver command. * @param {string} action The action string. * @return {Array} The generated commands. * @private */ bite.webdriver.generateWebdriverCmd_ = function(action) { switch (action) { case rpf.CodeGenerator.RecordActions.CLICK: return ['element.click();']; case rpf.CodeGenerator.RecordActions.ENTER: return ['element.sendKeys(Keys.ENTER);']; case rpf.CodeGenerator.RecordActions.TYPE: return ['element.clear();', 'element.sendKeys(data);']; case rpf.CodeGenerator.RecordActions.MOVE: return ['Actions moveAction = new Actions(this.driver);', 'moveAction.moveToElement(element).perform();']; case rpf.CodeGenerator.RecordActions.CHANGE: return ['element.clear();', 'element.sendKeys(data);']; case rpf.CodeGenerator.RecordActions.VERIFY: return ['verifyElement(element, data);']; case rpf.CodeGenerator.RecordActions.SUBMIT: return ['element.submit();']; case rpf.CodeGenerator.PlaybackActions.SELECT: return ['selectOption(element, data);']; case rpf.CodeGenerator.RecordActions.DRAG: return ['']; } return ['']; }; /** * Generates the exception file. * @return {string} The generated lines. * @private */ bite.webdriver.generateExceptionFile_ = function() { var header = bite.webdriver.generateCopyrightAndPackage_(); var classDoc = bite.webdriver.generateClassDoc_('', 'The exception class.'); var classSig = bite.webdriver.generateClass_( 'CustomException', 'RuntimeException'); var constructor = bite.webdriver.addIndentations(2, ['public CustomException(String message) {', ' super(message);', '}']).join('\n'); return [header, '', classDoc, classSig, constructor, '}'].join('\n'); }; /** * Generates the base page code. * @param {string} project The project name. * @return {string} The generated lines. * @private */ bite.webdriver.generateBasePage_ = function(project) { var header = bite.webdriver.generateCopyrightAndPackage_(); var imports = bite.webdriver.generateImports_(); var classDoc = bite.webdriver.generateClassDoc_('', 'The base class.'); var classSig = bite.webdriver.generateClass_('BasePage'); var classProperties = bite.webdriver.generateBaseClassVariables_(2); var constructor = bite.webdriver.generateConstructor_(2, 'BasePage'); constructor += bite.webdriver.generateCommands_(4, ['this.driver = driver;', 'wait = new WebDriverWait(driver, 6);']); constructor += ['', bite.webdriver.generateClosing_(2)].join('\n'); var waitElementFunc = bite.webdriver.generateWaitAndGetElement_(2); var selectOption = bite.webdriver.addIndentations(2, [ '/**', ' * Selects a given option which equals to the given value.', ' */', 'private void selectOption(WebElement elem, String value) {', ' List<WebElement> options = elem.findElements(By.tagName("option"));', ' for (WebElement option : options) {', ' if (value.equals(option.getAttribute("value"))) {', ' option.click();', ' break;', ' }', ' }', '}']).join('\n'); var sleep = bite.webdriver.addIndentations(2, [ '/**', ' * Sleeps for the given time.', ' */', 'public void sleep(Integer time) {', ' try {', ' Sleeper sleeper = new DefaultSleeper();', ' sleeper.sleep(time, TimeUnit.MILLISECONDS);', ' } catch (Exception e) {', ' throw new CustomException("Sleep error:" + e.toString());', ' }', '}']).join('\n'); var debugLog = bite.webdriver.addIndentations(2, [ '/**', ' * Logs the debug info, which will be used to locate the failed step.', ' */', 'public void logDebugInfo(String stepId) {', ' StackTraceElement[] stacktrace =', ' Thread.currentThread().getStackTrace();', ' StackTraceElement caller = stacktrace[3];', ' logger.log(Level.WARNING, "The RPF debugging info is: " +', ' "python localserver.py " +', ' "--url=\\\"http://localhost:7171/request?" +', ' "testName=" + caller.getMethodName() + "&" +', ' "project=' + project + '&" +', ' "stepId=" + stepId + "&" +', ' "path=' + escape(bite.webdriver.packageName_) + '\\\"");', '}' ]).join('\n'); var verify = bite.webdriver.addIndentations(2, [ '/**', ' * Verifies the element with the given attributes map.', ' */', 'public void verifyElement(WebElement elem,' + ' HashMap<String, String> data) {', ' for (String key : data.keySet()) {', ' String value = data.get(key);', ' if (key == "elementText") {', ' if (!elem.getText().equals(value)) {', ' throw new CustomException("Can not match the text. Expected: " +', ' value + ", Actual: " + elem.getText());', ' }', ' } else if (key == "checked") {', ' Boolean isChecked = Boolean.parseBoolean(value);', ' if (elem.isSelected() != isChecked) {', ' throw new CustomException("Element checked issue.");', ' }', ' } else if (key == "disabled") {', ' Boolean isEnabled = !Boolean.parseBoolean(value);', ' if (elem.isEnabled() != isEnabled) {', ' throw new CustomException("Element disabled issue.");', ' }', ' } else if (key == "selectedIndex") {', ' By byTag = By.tagName("option");', ' List<WebElement> options = elem.findElements(byTag);', ' String selectedIndex = value;', ' WebElement option = options.get(Integer.parseInt(selectedIndex));', ' if (!option.isSelected()) {', ' throw new CustomException("Element selected issue.");', ' }', ' } else if (key == "href") {', ' String actual = elem.getAttribute(key);', ' if (!actual.equals(value) && !actual.matches(value + "/")) {', ' throw new CustomException("Can not match the attribute " + key);', ' }', ' } else if (elem.getAttribute(key) != null) {', ' if (!elem.getAttribute(key).equals(value)) {', ' throw new CustomException("Can not match the attribute " + key);', ' }', ' }', ' }', '}']).join('\n'); var executeJavascript = bite.webdriver.addIndentations(2, [ '/**', ' * Executes the custom JS function.', ' */', 'public void executeJavascript(String code) {', ' ((JavascriptExecutor) driver).executeScript(code);', '}']).join('\n'); var actions = ''; for (var i = 0, len = bite.webdriver.supportedActions_.length; i < len; ++i) { actions += bite.webdriver.getActionMethod_( bite.webdriver.supportedActions_[i]); } var classEnd = bite.webdriver.generateClosing_(0); return [header, '', imports, '', classDoc, classSig, classProperties, constructor, '', waitElementFunc, '', selectOption, '', sleep, '', debugLog, '', verify, '', executeJavascript, '', actions, '', classEnd].join('\n'); }; /** * Generates the logger instance. * @param {string} page The page name. * @param {number} num The space number. * @return {string} The generated lines. * @private */ bite.webdriver.generateLogger_ = function(page, num) { return bite.webdriver.addIndentations(num, ['private static final Logger logger =', ' Logger.getLogger(' + page + '.class.getName());']).join('\n'); }; /** * Changes the step name to be the selector name * @param {string} stepName The step name. * @return {string} The selector name. * @private */ bite.webdriver.getSelectorName_ = function(stepName) { // In the auto generated step id, there will be "-" in it. // So in this case, it means users have renamed it. var index = stepName.indexOf('-'); if (index == -1) { return stepName; } // Remove the action prefix var temp = stepName.substr(index + 1, stepName.length); temp = temp.toLowerCase(); temp = goog.string.toCamelCase(temp); return temp.replace(/-/g, '').toUpperCase(); }; /** * Generates the selector declaration. * @param {string} name The name of the selector. * @param {string} value The value of the selector. * @param {number} num The space number. * @return {string} The generated lines. * @private */ bite.webdriver.generateSelectorVar_ = function(name, value, num) { return bite.webdriver.addIndentations(num, ['public static final String ' + name + ' =', ' "' + bite.webdriver.escapeDoubleQuotes_(value) + '";']).join('\n'); }; /** * Constructs the page class strings. * @param {Object} pages The pages object. * @return {Object} The page strings. * @private */ bite.webdriver.constructPageStrings_ = function(pages) { var pageStrs = {}; for (var page in pages) { var imports = [pages[page]['imports'], ''].join('\n'); var properties = bite.webdriver.addIndentations( 2, pages[page]['properties']).join('\n'); pageStrs[page] = [pages[page]['copyright'], imports, pages[page]['classSig'], properties, '', pages[page]['rest'], '}', ''].join('\n'); } return pageStrs; }; /** * Gets the page name if the pattern matches the url as a substring. * @param {Object} urlPageMap The url page map. * @param {string} url The url string. * @param {Object} pages The object contains all of the pages information. * @return {string} The new page name. * @private */ bite.webdriver.getPageName_ = function(urlPageMap, url, pages) { // Loop through all url patterns in the url/page map. If the pattern is a // substring of the url then return the corresponding name for the pattern. for (var reg in urlPageMap) { if (url.indexOf(reg) != -1) { return urlPageMap[reg]; } } // Construct a new name from the url's domain and path and add it to the // url/page map. var uri = new goog.Uri(url); var domain = uri.getDomain(); var path = uri.getPath(); var domainPath = domain + path; var pageName = bite.webdriver.getPageNameBasedOnUrl_(domain, path); pages[pageName] = bite.webdriver.getPageClassHeader_(pageName); urlPageMap[domainPath] = pageName; return pageName; }; /** * Gets the page name based on domain name. * @param {string} domain The domain string. * @param {string} path The path string. * @return {string} The page name. * @private */ bite.webdriver.getPageNameBasedOnUrl_ = function(domain, path) { var domainParts = domain.split('.'); var pathParts = path.split('/'); var temp = 'Page'; if (domainParts[0] != 'www') { temp += bite.webdriver.captitalizeFirstLetter_(domainParts[0], 20); } temp += bite.webdriver.captitalizeFirstLetter_(domainParts[1], 20); if (pathParts[0]) { temp += bite.webdriver.captitalizeFirstLetter_(pathParts[0], 20); } return temp + bite.webdriver.pageIndex_++; }; /** * Gets the first letter capitalized string if the length is proper. * @param {string} str The given raw string. * @param {number} limit The max length of the string. * @return {string} The result. * @private */ bite.webdriver.captitalizeFirstLetter_ = function(str, limit) { str = str.replace(/\W+/g, ''); if (!str || str.length > limit) { return ''; } return str.charAt(0).toUpperCase() + str.slice(1); }; /** * Quotes the given string. * @param {string=} opt_str The given raw string. * @return {string} The string with quotes. * @private */ bite.webdriver.quote_ = function(opt_str) { if (!goog.isDef(opt_str)) { return ''; } return '"' + bite.webdriver.escapeDoubleQuotes_(unescape(opt_str)) + '"'; }; /** * Gets the data argument. * @param {string} action The action string. * @return {string} The data argument string. * @private */ bite.webdriver.getDataArg_ = function(action) { if (action == rpf.CodeGenerator.RecordActions.TYPE || action == rpf.CodeGenerator.RecordActions.CHANGE || action == rpf.CodeGenerator.PlaybackActions.SELECT) { return 'String data'; } else if (action == rpf.CodeGenerator.RecordActions.VERIFY) { return 'HashMap<String, String> data'; } return ''; }; /** * Generates an action method. * @param {string} action The action string. * @private */ bite.webdriver.getActionMethod_ = function(action) { // The following code adds javadoc, method signature, log, and action. var wdCode = bite.webdriver.generateJavaDoc_( ['Performs a ' + action + ' on an element.']); var args = ['String xpath']; var actionArg = bite.webdriver.getDataArg_(action); if (actionArg) { args.push(actionArg); } var argStr = args.join(', '); wdCode.push('public void ' + action + '(' + argStr + ') {'); var tempArr = ['logger.log(Level.INFO, "Performed a ' + action + ' action on the element with xpath: " + xpath);']; if (bite.webdriver.codeParams_['interval']) { tempArr.push('sleep(' + bite.webdriver.codeParams_['interval'] + ');'); } tempArr = tempArr.concat(bite.webdriver.generateWebElementBySelector_( 'xpath', action)); tempArr = tempArr.concat( bite.webdriver.generateWebdriverCmd_(action)); tempArr = bite.webdriver.addIndentations(2, tempArr); wdCode = wdCode.concat(tempArr); wdCode.push('}'); wdCode.push(''); return bite.webdriver.addIndentations(2, wdCode).join('\n'); }; /** * Gets the page name from a line. * @param {string} line The current line of code. * @param {Object} urlPageMap The mapping from an url to a page. * @param {Object} pages The object contains all of the pages information. * @return {Object} The url and page name. * @private */ bite.webdriver.getPageInfoFromLine_ = function(line, urlPageMap, pages) { var url = rpf.CodeGenerator.getUrlInRedirectCmd(line); return {'url': url, 'pageName': bite.webdriver.getPageName_(urlPageMap, url, pages)}; }; /** * Gets the correct selectorMap reference. * @param {string} curPageName The current page name. * @param {Object} pages The page objects. * @return {Object} The current selectorMap object. * @private */ bite.webdriver.getSelectorMap_ = function(curPageName, pages) { return pages[curPageName]['selectors']; }; /** * Generates the module method. * @param {Array} moduleSteps The module step object. * @param {string} curPageName The returning page name. * @param {string} moduleName The module name. * @param {number} num The number of spaces. * @param {string} startUrl The start url. * @param {Object} page The page object. * @return {string} The generated code. * @private */ bite.webdriver.generateModuleMethod_ = function( moduleSteps, curPageName, moduleName, num, startUrl, page) { // Adds the javadoc. var wdCode = bite.webdriver.generateJavaDoc_( ['Performs a sequence of actions for ' + moduleName + '.']); // Adds the log. var tempArr = ['logger.log(Level.INFO, "' + moduleName + ' started.");']; // Adds the chained steps. var stepsChain = []; var allArgs = []; var index = 0; for (var i = 0, len = moduleSteps.length; i < len; ++i) { var prefix = 'this.'; var data = moduleSteps[i]['data']; // This is used to show the arguments in each step call. var tempArg = []; // This is used to show the arguments in module signature. var tempArg2 = []; // Prepares the args strings for both in the signature and in each // individual step call. for (var k = 0, lenK = data.length; k < lenK; ++k) { if (data[k]) { var varId = 'data' + index++; tempArg.push(varId); var argType = 'String'; if (typeof(data[k]) == 'object') { argType = 'HashMap<String, String>'; } // The format is like HashMap data1 tempArg2.push(argType + ' ' + varId); } } var tempArgStr = tempArg.join(', '); if (tempArgStr) { // Format: HashMap data0, String data1, ... allArgs.push(tempArg2.join(', ')); } if (moduleSteps[i]['className'] && moduleSteps[i]['xpathName']) { var xpathName = moduleSteps[i]['className'] + '.' + moduleSteps[i]['xpathName']; if (tempArgStr) { tempArgStr = [xpathName, tempArgStr].join(', '); } else { tempArgStr = xpathName; } } stepsChain.push(prefix + moduleSteps[i]['action'] + '(' + tempArgStr + ');'); } tempArr = tempArr.concat(stepsChain); //Adds the method signature. wdCode.push('public void ' + moduleName + '(' + allArgs.join(', ') + ') {'); wdCode = wdCode.concat( bite.webdriver.addIndentations(2, tempArr)); wdCode.push('}'); wdCode.push(''); return bite.webdriver.addIndentations(num, wdCode).join('\n'); }; /** * Generates the test page code. * @param {Object} pages The page objects. * @return {string} The generated lines. * @private */ bite.webdriver.generateBiteTest_ = function(pages) { var copyright = bite.webdriver.generateCopyrightAndPackage_( bite.webdriver.packageNameTest_); var imports = ['import com.google.common.base.Charsets;', 'import com.google.common.io.Files;', 'import com.google.testing.util.Tag;', 'import com.google.testing.util.TestUtil;', 'import junit.framework.TestCase;', 'import org.openqa.selenium.WebDriver;', 'import org.openqa.selenium.remote.DesiredCapabilities;', 'import org.openqa.selenium.remote.RemoteWebDriver;', 'import java.io.*;', 'import java.net.URL;', 'import java.util.HashMap;', 'import java.util.logging.Level;', 'import java.util.logging.Logger;', '']; imports = imports.join('\n'); var classDoc = bite.webdriver.generateClassDoc_('', 'The test file.'); var classSig = bite.webdriver.generateClass_('Tests', 'TestCase'); var logger = bite.webdriver.generateLogger_('Tests', 2); var driver = ' protected WebDriver driver;'; var jsStr = ' String jsStr;'; var getJsStr = [ 'public String getJsAsString() {', ' String location = TestUtil.getSrcDir() + "//java/' + bite.webdriver.packageName_.split('.').join('/') + '/generated_js";', ' File folder = new File(location);', ' File[] listOfFiles = folder.listFiles();', ' String jsStr = "";', ' if (listOfFiles == null) {', ' return jsStr;', ' }', ' for (int i = 0; i < listOfFiles.length; ++i) {', ' File currentFile = listOfFiles[i];', ' if (currentFile.isFile()) {', ' if (currentFile.getName().indexOf(".js") != -1) {', ' try {', ' jsStr += Files.toString(currentFile, Charsets.UTF_8);', ' } catch (IOException e) {', ' logger.log(Level.INFO, "Can not load the JS file.");', ' }', ' }', ' }', ' }', // The following JS function is from actionshelper.js, which is used to // run the generated JS command. ' jsStr += ("BiteRpfAction = {}; BiteRpfAction.call = function() {" +', ' " var func = null;" +', ' " var async = false;" +', ' " var args = [];" +', ' " var firstIndex = 1;" +', ' " if (typeof arguments[0] == \'boolean\') {" +', ' " if (typeof arguments[1] != \'function\' ||" +', ' " typeof arguments[2] != \'function\') {" +', ' " throw new Error(\'The command is malformatted.\');}" +', ' " async = arguments[0];args.push(arguments[1]);" +', ' " func = arguments[2];firstIndex = 3;}else{" +', ' " func = arguments[0];}" +', ' " for (var i = firstIndex; i < arguments.length; ++i) {" +', ' " args.push(arguments[i]);}func.apply(null, args);};");', // This method is defined in RPF to indicate aync call ends. ' jsStr += "var sendResultToBackground = function() {};";', ' return jsStr;', '}', '', 'public String getCurrentJsCommand(String cmd) {', ' return jsStr + cmd;', '}']; getJsStr = bite.webdriver.addIndentations(2, getJsStr).join('\n'); var testMethods = [ '@Override', 'public void setUp() throws Exception {', ' super.setUp();', ' driver = new RemoteWebDriver(new URL("http://127.0.0.1:9515"),', ' DesiredCapabilities.chrome());', ' jsStr = getJsAsString();', '}', '', '@Override', 'public void tearDown() throws Exception {', ' driver.quit();', ' super.tearDown();', '}', '']; testMethods = [bite.webdriver.addIndentations(2, testMethods).join('\n')]; for (var page in pages) { for (var module in pages[page]['modules']) { var startUrl = pages[page]['modules'][module]['startUrl']; // Ensure the module name starts with 'test' so it will be picked up by // webdriver. var moduleName = module; if (!goog.string.startsWith(moduleName, 'test')) { moduleName = 'test' + moduleName; } testMethods = testMethods.concat( [' @Tag("SmokeTest")', ' public void ' + moduleName + '() {', ' try {', ' ' + bite.webdriver.generateNavigation_(startUrl), ' ' + page + ' page = new ' + page + '(driver);', bite.webdriver.getTestMethod_( pages[page]['modules'][module], module), ' } catch (CustomException e) {', ' e.printStackTrace();', ' fail(e.getMessage());', ' }', ' }', '']); } } testMethods = testMethods.join('\n'); return [copyright, imports, classDoc, classSig, logger, driver, jsStr, '', getJsStr, '', testMethods, '}', ''].join('\n'); }; /** * Generates the test methods. * @param {Object} module The module object. * @param {string} moduleName The module name. * @return {string} The generated lines. * @private */ bite.webdriver.getTestMethod_ = function(module, moduleName) { // Iterates each module in each page, and adds it as a test method. // The format depends on whether it is a module. var methodNames = module['methodNames']; var isModule = module['isModule']; var argStr = ''; var argArr = []; var methodArr = []; var declarationArr = []; bite.webdriver.variableIndex_ = 0; for (var i = 0, len = methodNames.length; i < len; ++i) { var prefix = 'page'; var method = methodNames[i]; var xpathName = ''; if (method['className'] && method['xpathName']) { xpathName = method['className'] + '.' + method['xpathName']; } var methodInfo = {'action': method['action'], 'xpath': xpathName}; bite.webdriver.pushDataInput_( method['data'], argArr, methodArr, prefix, methodInfo, declarationArr); } if (isModule) { // Format: HashMap data0 = new HashMap(); // page.moduleName(data0); declarationArr = bite.webdriver.addIndentations(6, declarationArr); declarationArr.push(' page.' + moduleName + '(' + argArr.join(', ') + ');'); return declarationArr.join('\n'); } // Format: HashMap data0 = new HashMap(); // page.methodName1(data0) // .methodName2(); declarationArr = declarationArr.concat(methodArr); return bite.webdriver.addIndentations(6, declarationArr).join('\n'); }; /** * Pushes the data input info in the given arrays. * @param {Array} dataArr The data array. * @param {Array} argArr An array of arguments. * @param {Array} methodArr An array of method calls. * @param {string} prefix The prefix of the method call. * @param {Object} methodInfo The method related info. * @param {Array} declarationArr The array of hashmap declarations. * @private */ bite.webdriver.pushDataInput_ = function( dataArr, argArr, methodArr, prefix, methodInfo, declarationArr) { var data = dataArr[0]; if (typeof(data) == 'object') { var curVarName = 'data' + bite.webdriver.variableIndex_++; declarationArr.push( 'HashMap<String, String> ' + curVarName + ' = new HashMap<String, String>();'); for (var name in data) { var tempData = data[name] ? data[name] : '""'; declarationArr.push( curVarName + '.put("' + name + '", ' + tempData + ');'); } data = curVarName; } if (data) { // This array has the arguments to call a module. // ex. ['arg1'] argArr.push(data); } if (methodInfo['xpath']) { if (data) { // In the format of page.action(Page1.xpath1, "user inputs") data = [methodInfo['xpath'], data].join(', '); } else { // In the format of page.action(Page1.xpath1) data = methodInfo['xpath']; } } // This array has the individual action method calls. // ex. ['.method1("arg1")'] methodArr.push(prefix + '.' + methodInfo['action'] + '(' + data + ');'); }; /** * Checks if the given code is a module. * @param {string} code The code string. * @return {boolean} Whether the given code is a module. * @private */ bite.webdriver.isModule_ = function(code) { return code.indexOf('@type module') != -1 || code.indexOf('@type Module') != -1; }; /** * Checks if the given class name belongs to the urlPageMap. * @param {string} className The class name. * @param {Object} urlPageMap The url and page mapper. * @return {boolean} Whether the given class name is valid. * @private */ bite.webdriver.containClass_ = function(className, urlPageMap) { for (var item in urlPageMap) { if (urlPageMap[item] == className) { return true; } } return false; }; /** * Gets the line content of the last redirection before the next command. * @param {Array} lines The lines of the test. * @param {number} curIndex The current line index. * @param {Object} infoMap The info map. * @param {Object} urlPageMap The url and page name mapper. * @return {Object} The redirection content and the next cmd's class name. * @private */ bite.webdriver.getLastRedirection_ = function( lines, curIndex, infoMap, urlPageMap) { var len = lines.length; var lastRedirectionIndex = 0; while (curIndex < len) { var line = lines[curIndex]; var curId = bite.base.Helper.getStepId(line); // Returns the redirection index if the current line is a command. if (curId) { var pageName = infoMap['steps'][curId]['pageName']; var className = ''; if (bite.webdriver.containClass_(pageName, urlPageMap)) { className = pageName; } return {'redirection': lastRedirectionIndex ? lines[lastRedirectionIndex] : '', 'className': className}; } if (line.indexOf(rpf.CodeGenerator.PlaybackActions.REDIRECT_TO) == 0) { lastRedirectionIndex = curIndex; } ++curIndex; } return {'redirection': lastRedirectionIndex ? lines[lastRedirectionIndex] : ''}; }; /** * Goes through the test script and collect relevant info. * @param {Array} lines The lines of a test script. * @param {Object} infoMap This map contains steps and elements info of project. * @param {string} curPageName The current page class name. * @param {string} curUrl The current test's start url. * @param {Object} urlPageMap The url pattern and page class name mapper. * @param {number} selectorIndex The selector index counter. * @param {Object} selectorMap A mppater for whether the given selector exists. * @param {Object} pages The page object containing info to construct the class. * @param {Array} moduleSteps The steps of a module. * @return {Object} The updated selector index, page name and url. * @private */ bite.webdriver.parseTestLines_ = function( lines, infoMap, curPageName, curUrl, urlPageMap, selectorIndex, selectorMap, pages, moduleSteps) { var playbackActions = rpf.CodeGenerator.PlaybackActions; var page = null; var pageName = ''; var defaultPageName = curPageName; for (var i = 0, len = lines.length; i < len; ++i) { var line = lines[i]; var results = bite.webdriver.getLastRedirection_( lines, i + 1, infoMap, urlPageMap); var nextRedirect = results['redirection']; var nextCmdClassName = results['className']; // Gets the id from a given line. var curId = bite.base.Helper.getStepId(line); if (curId) { var stepInfo = infoMap['steps'][curId]; var realAction = line.split('(')[0]; // TODO(phu): We should always use the real action. if (realAction == 'verifyNot') { stepInfo['action'] = realAction; } // Sets the curPageName. // If the step is associated with a Class name, then use it. // Otherwise, uses the given class name which is probably based on URL. if (stepInfo['pageName'] && bite.webdriver.containClass_(stepInfo['pageName'], urlPageMap)) { curPageName = stepInfo['pageName']; } else { stepInfo['pageName'] = defaultPageName; curPageName = defaultPageName; } selectorMap = bite.webdriver.getSelectorMap_(curPageName, pages); stepInfo['url'] = curUrl; var elemInfo = infoMap['elems'][stepInfo['elemId']]; var curStep = curId; // This peeps ahead to observe if the current action will result in // a url redirection, and then set the return page correctly. if (!nextCmdClassName && nextRedirect) { page = bite.webdriver.getPageInfoFromLine_( nextRedirect, urlPageMap, pages); nextCmdClassName = page['pageName']; } var selector = elemInfo['xpaths'][0]; var selectorKey = selector.replace(/\W+/g, ''); // Only adds the selector declaration if it doesn't exist yet. if (!selectorMap[selectorKey]) { selectorIndex++; selectorMap[selectorKey] = bite.webdriver.getSelectorName_( stepInfo['stepName']); pages[curPageName]['properties'].push( bite.webdriver.generateSelectorVar_( selectorMap[selectorKey], selector, 0)); } moduleSteps.push( {'className': curPageName, 'xpathName': selectorMap[selectorKey], 'action': stepInfo['action'], 'data': [bite.webdriver.getDataValue_(stepInfo, elemInfo)]}); } else if (line.indexOf(rpf.CodeGenerator.PlaybackActions.CALL) == 0) { var command = 'getCurrentJsCommand("BiteRpfAction.' + line + '")'; // TODO(phu): Add executeAsyncScript method. moduleSteps.push({ 'action': 'executeJavascript', 'data': [command]}); } else if (line.indexOf(playbackActions.REDIRECT_TO) == 0) { page = bite.webdriver.getPageInfoFromLine_(line, urlPageMap, pages); // When enters a new page, the relavent info should be reset. if (typeof page == 'object') { if (page['pageName'] != curPageName) { defaultPageName = page['pageName']; curPageName = defaultPageName; curUrl = page['url']; selectorMap = bite.webdriver.getSelectorMap_(curPageName, pages); } } } } return {'selectorIndex': selectorIndex, 'curPageName': curPageName, 'curUrl': curUrl}; }; /** * Gets the data value. * @param {Object} stepInfo The step related info object. * @param {Object} elemInfo The element related info object. * @return {Object|string} Either a string or an object as the data input. * @private */ bite.webdriver.getDataValue_ = function(stepInfo, elemInfo) { var verificationMap = {}; if (stepInfo['action'] == rpf.CodeGenerator.RecordActions.VERIFY) { return common.client.ElementDescriptor.getAttrsToVerify( elemInfo['descriptor'], bite.webdriver.quote_); } return bite.webdriver.quote_(bite.base.Helper.dataFile[stepInfo['varName']]); }; /** * Inits the pages that are defined in urlPageMap. * @param {Object} urlPageMap The url and page mapper. * @param {Object} pages The pages object that contains all of the pages info. * @private */ bite.webdriver.initExistingPages_ = function(urlPageMap, pages) { for (var urlPattern in urlPageMap) { pages[urlPageMap[urlPattern]] = bite.webdriver.getPageClassHeader_(urlPageMap[urlPattern]); } }; /** * Generates the pages code. * @param {Array} codeArr The rpf test code string array. * @param {Object} infoMap This map contains steps and elements info of project. * @param {Array} startUrlArr The start url array for each rpf test. * @param {!Object} urlPageMap A map of urls to page name. * @param {Array} testNameArr The rpf test name array. * @param {Array} datafileArr The data file array. * @return {Object} The generated pages. * @private */ bite.webdriver.generatePages_ = function( codeArr, infoMap, startUrlArr, urlPageMap, testNameArr, datafileArr) { var pages = {}; var selectorMap = {}; var selectorIndex = 0; var curId = ''; var curStep = ''; bite.webdriver.pageIndex_ = 0; bite.webdriver.initExistingPages_(urlPageMap, pages); // This loops through all of the rpf tests and collect info. for (var j = 0; j < codeArr.length; ++j) { var code = codeArr[j]; var startUrl = startUrlArr[j]; var moduleName = testNameArr[j]; var datafile = datafileArr[j]; var isModule = bite.webdriver.isModule_(code); var lines = code.split('\n'); // Gets the current page name based on the url pattern. var curPageName = bite.webdriver.getPageName_(urlPageMap, startUrl, pages); // Get the first cmd's class name if any. var resultPair = bite.webdriver.getLastRedirection_( lines, 0, infoMap, urlPageMap); if (resultPair['className']) { curPageName = resultPair['className']; } pages[curPageName]['modules'][moduleName] = { 'methodNames': [], 'isModule': isModule, 'startUrl': startUrl }; var moduleStartPage = curPageName; var moduleSteps = pages[curPageName]['modules'][moduleName]['methodNames']; // This makes sure one selector only appears once in a page class. selectorMap = bite.webdriver.getSelectorMap_(curPageName, pages); var curUrl = startUrl; // Evals the datafile to get data. bite.base.Helper.evalDatafile(datafile); // Loops through the test script and collect info. var results = bite.webdriver.parseTestLines_( lines, infoMap, curPageName, curUrl, urlPageMap, selectorIndex, selectorMap, pages, moduleSteps); curUrl = results['curUrl']; curPageName = results['curPageName']; selectorIndex = results['selectorIndex']; if (isModule) { // This adds a module to the page class as a method. pages[moduleStartPage]['rest'] += bite.webdriver.generateModuleMethod_( moduleSteps, curPageName, moduleName, 2, startUrl, pages[moduleStartPage]); } } var testPage = bite.webdriver.generateBiteTest_(pages); pages = bite.webdriver.constructPageStrings_(pages); pages['Tests'] = testPage; return pages; };
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Unit tests for getactioninfo. * * @author phu@google.com (Po Hu) */ goog.require('common.client.ElementDescriptor'); goog.require('goog.testing.MockControl'); goog.require('goog.testing.PropertyReplacer'); goog.require('rpf.ContentScript.RecordHelper'); var stubs_ = new goog.testing.PropertyReplacer(); var mockControl_ = null; var chrome = {}; function setUp() { mockControl_ = new goog.testing.MockControl(); chrome.extension = {}; stubs_.set(goog.global, 'chrome', chrome); } function tearDown() { mockControl_.$tearDown(); mockControl_ = null; stubs_.reset(); }
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains the Rhino helper which is used to * generate java files on user's client. * * @author phu@google.com (Po Hu) * @author jasonstredwick@google.com (Jason Stredwick) */ goog.require('bite.webdriver'); goog.require('goog.json'); goog.require('rpf.DataModel'); goog.require('rpf.MiscHelper'); /** * Runs the Rhino commands to generate the WebDriver code. * @param {string} inputFilename The file containing the JavaScript code to * translate into WebDriver Jave code. */ function runRhino(inputFilename) { var contents = ''; try { contents = readFile(inputFilename); if (!contents) { throw 'File missing or no content.'; } } catch (error) { print('ERROR: Failed to read specified file (' + inputFilename + '): ' + error); return; } var data = {}; try { data = goog.json.parse(contents) || {}; } catch (error) { print('ERROR: Failed to parse input file into object from JSON.'); return; } var output = generateContents(data); importPackage(java.io); for (var filename in output) { var writer = new OutputStreamWriter( new FileOutputStream(filename), 'UTF-8'); writer.write(output[filename]); writer.close(); } } /** * Creates the generated WebDriver Java files for the given project data. * @param {!Object} data The object containing information about the project * such as project details, tests, etc. * @return {!Object} A mapping of filenames to file content strings; one for * each generated file. Returns null if there is no output. */ function generateContents(data) { if (!data) { return {}; } var dataModel = new rpf.DataModel(); var processedData = dataModel.convertDataToRaw(data); var pages = bite.webdriver.getWebdriverCode(processedData); var files = {}; for (var pageName in pages) { var filename = pageName + '.java'; var page = pages[pageName]; files[filename] = page; } return files; } runRhino(inputFilename); quit();
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Unit tests for events manager. * * @author phu@google.com (Po Hu) */ goog.require('goog.testing.MockControl'); goog.require('goog.testing.PropertyReplacer'); goog.require('rpf.EventsManager'); var stubs_ = new goog.testing.PropertyReplacer(); var mockControl_ = null; var chrome = {}; var playbackMgr = {}; var recordMgr = {}; var mockLocalStorage = null; function setUp() { mockControl_ = new goog.testing.MockControl(); chrome.extension = {}; chrome.extension.onRequest = {}; chrome.extension.onRequest.addListener = function(f) {}; chrome.tabs = {}; chrome.tabs.onUpdated = {}; chrome.tabs.onUpdated.addListener = function(f) {}; stubs_.set(goog.global, 'chrome', chrome); mockLocalStorage = {getItem: function() { return 'http://hud.test'; }, setItem: function(unused_var) {}}; stubs_.set(goog.global, 'localStorage', mockLocalStorage); } function tearDown() { mockControl_.$tearDown(); mockControl_ = null; stubs_.reset(); } function testCallBackTabUpdated() { var changeInfo = {'status': rpf.EventsManager.TabStatus_.LOADING}; playbackMgr.getPlaybackTabId = function() { return 1; }; playbackMgr.getCurrentStep = function() {return 1; }; recordMgr.getTestTabId = function() { return 1; }; var eventsMgr = new rpf.EventsManager(playbackMgr, recordMgr); mockControl_.$replayAll(); eventsMgr.callBackTabUpdated_(1, changeInfo); mockControl_.$verifyAll(); } function testCallBackOnRequest() { var request = {}; var sender = {}; var sendResponse = {}; request['command'] = rpf.EventsManager.CmdTypes_.CMD_DONE; request['result'] = ''; request['index'] = 1; request['bodyHtml'] = 'a'; playbackMgr.getCurrentStep = function() {return 1; }; recordMgr.getTestTabId = function() { return 1;}; var eventsMgr = new rpf.EventsManager(playbackMgr, recordMgr); mockControl_.$replayAll(); eventsMgr.callBackOnRequest(request, sender, sendResponse); mockControl_.$verifyAll(); } function testExecuteMultipleScripts() { var mockExecuteScript_ = mockControl_.createFunctionMock('executeScript'); mockExecuteScript_(1, {file: 'a', allFrames: true}, goog.testing.mockmatchers.isFunction).$returns(''); chrome.tabs.executeScript = mockExecuteScript_; var eventsMgr = new rpf.EventsManager(playbackMgr, recordMgr); mockControl_.$replayAll(); var result = eventsMgr.executeMultipleScripts( ['a'], 0, true, 1, null); mockControl_.$verifyAll(); }
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Author: michaelwill@google.com (Michael Williamson) goog.require('Bite.Constants'); goog.require('bite.Popup'); goog.require('goog.json'); goog.require('goog.net.XhrIo'); goog.require('goog.testing.MockControl'); goog.require('goog.testing.PropertyReplacer'); goog.require('goog.testing.asserts'); goog.require('goog.testing.mockmatchers'); goog.require('goog.testing.net.XhrIo'); goog.require('goog.testing.recordFunction'); goog.require('rpf.CodeGenerator'); goog.require('rpf.ConsoleLogger'); goog.require('rpf.EventsManager'); goog.require('rpf.PlayBackManager'); goog.require('rpf.RecordManager'); goog.require('rpf.Rpf'); goog.require('rpf.SaveLoadManager'); goog.require('rpf.ScriptManager'); goog.require('rpf.WorkerManager'); var stubs_ = new goog.testing.PropertyReplacer(); var mockLocalStorage = null; function setUp() { initChrome(); this.mocks = new goog.testing.MockControl(); this.stubs = new goog.testing.PropertyReplacer(); console.error = function(error) {}; mockLocalStorage = {getItem: function() { return 'http://hud.test'; }, setItem: function(unused_var) {}}; stubs_.set(goog.global, 'localStorage', mockLocalStorage); } function tearDown() { this.stubs.reset(); this.mocks.$tearDown(); rpf.Rpf.instance_ = null; } function setupRpf() { this.mockWorkerMgr = this.mocks.createStrictMock(rpf.WorkerManager); this.mockWorkerMgrCtor = this.mocks.createConstructorMock( rpf, 'WorkerManager'); this.mockWorkerMgrCtor( goog.testing.mockmatchers.isObject, goog.testing.mockmatchers.isObject, goog.testing.mockmatchers.isObject, goog.testing.mockmatchers.isFunction, goog.testing.mockmatchers.isFunction).$returns(this.mockWorkerMgr); chrome.tabs.onUpdated = {}; chrome.tabs.onRemoved = {}; chrome.tabs.onUpdated.addListener = goog.testing.recordFunction(); chrome.tabs.onUpdated.removeListener = goog.testing.recordFunction(); chrome.tabs.onRemoved.addListener = goog.testing.recordFunction(); chrome.tabs.onRemoved.removeListener = goog.testing.recordFunction(); chrome.windows = {}; chrome.windows.update = goog.testing.recordFunction(); chrome.windows.onRemoved = {}; chrome.windows.onRemoved.addListener = goog.testing.recordFunction(); chrome.windows.onRemoved.removeListener = goog.testing.recordFunction(); } function testRpf() { setupRpf(); this.mocks.$replayAll(); var rpfInstance = rpf.Rpf.getInstance(); this.mocks.$verifyAll(); } function testCreateWindow() { setupRpf(); var createRpfWindowFunc = goog.testing.recordFunction(); rpf.Rpf.prototype.createRpfWindow_ = createRpfWindowFunc; this.mocks.$replayAll(); var rpfInstance = rpf.Rpf.getInstance(); rpfInstance.createWindow(); this.mocks.$verifyAll(); assertEquals(1, createRpfWindowFunc.getCallCount()); } function testCreateWindow_alreadyCreated() { setupRpf(); var createRpfWindowFunc = goog.testing.recordFunction(); rpf.Rpf.prototype.createRpfWindow_ = createRpfWindowFunc; var focusFunc = goog.testing.recordFunction(); rpf.Rpf.prototype.focusRpf = focusFunc; this.mocks.$replayAll(); var rpfInstance = rpf.Rpf.getInstance(); rpfInstance.setWindowId(56); rpfInstance.createWindow(); this.mocks.$verifyAll(); assertEquals(0, createRpfWindowFunc.getCallCount()); assertEquals(1, focusFunc.getCallCount()); } function testCreateWindow_forceRefresh() { setupRpf(); var createRpfWindowFunc = goog.testing.recordFunction(); rpf.Rpf.prototype.createRpfWindow_ = createRpfWindowFunc; var focusFunc = goog.testing.recordFunction(); rpf.Rpf.prototype.focusRpf = focusFunc; this.mocks.$replayAll(); var rpfInstance = rpf.Rpf.getInstance(); rpfInstance.setWindowId(56); rpfInstance.createWindow(true); this.mocks.$verifyAll(); assertEquals(1, createRpfWindowFunc.getCallCount()); assertEquals(0, focusFunc.getCallCount()); } function testRemoveWindow() { setupRpf(); var removeWindowFunc = goog.testing.recordFunction(); rpf.MiscHelper.removeWindowById = removeWindowFunc; this.mocks.$replayAll(); var rpfInstance = rpf.Rpf.getInstance(); rpfInstance.setWindowId(56); rpfInstance.removeWindow(); this.mocks.$verifyAll(); assertEquals(1, removeWindowFunc.getCallCount()); var args = removeWindowFunc.getLastCall().getArguments(); assertEquals(56, args[0]); } function testRemoveWindow_preexistingWindow() { setupRpf(); var removeWindowFunc = goog.testing.recordFunction(); rpf.MiscHelper.removeWindowById = removeWindowFunc; this.mocks.$replayAll(); var rpfInstance = rpf.Rpf.getInstance(); rpfInstance.setWindowId(-1); rpfInstance.removeWindow(); this.mocks.$verifyAll(); assertEquals(0, removeWindowFunc.getCallCount()); } function testWindowDestroyed_differentWindow() { setupRpf(); this.mocks.$replayAll(); var rpfInstance = rpf.Rpf.getInstance(); rpfInstance.setWindowId(55); rpfInstance.windowDestroyed_(50); this.mocks.$verifyAll(); assertEquals(55, rpfInstance.getWindowId()); } function testWindowDestroyed() { setupRpf(); chrome.tabs.onRemoved = {}; chrome.tabs.onRemoved.removeListener = goog.testing.recordFunction(); chrome.tabs.onUpdated = {}; chrome.tabs.onUpdated.removeListener = goog.testing.recordFunction(); this.mocks.$replayAll(); var rpfInstance = rpf.Rpf.getInstance(); rpfInstance.setWindowId(55); rpfInstance.windowDestroyed_(55); this.mocks.$verifyAll(); assertEquals(-1, rpfInstance.getWindowId()); } function testWindowCreated() { setupRpf(); this.mocks.$replayAll(); var rpfInstance = rpf.Rpf.getInstance(); var result = rpfInstance.windowCreated(); assertFalse(result); this.mocks.$verifyAll(); } function testWindowCreated_preexistingWindow() { setupRpf(); this.mocks.$replayAll(); var rpfInstance = rpf.Rpf.getInstance(); rpfInstance.setWindowId(1); var result = rpfInstance.windowCreated(); assertTrue(result); this.mocks.$verifyAll(); }
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Unit tests for play back manager. * * @author phu@google.com (Po Hu) */ goog.require('goog.testing.MockControl'); goog.require('goog.testing.PropertyReplacer'); goog.require('rpf.PlayBackManager'); goog.require('rpf.Rpf'); var stubs_ = new goog.testing.PropertyReplacer(); var mockControl_ = null; var chrome = {}; var getConsoleWindowId = {}; var rpfInstance = null; function setUp() { mockControl_ = new goog.testing.MockControl(); rpfInstance = mockControl_.createStrictMock(rpf.Rpf); chrome.extension = {}; chrome.tabs = {}; stubs_.set(goog.global, 'chrome', chrome); } function tearDown() { mockControl_.$tearDown(); mockControl_ = null; stubs_.reset(); } function testGetAllStepsFromScript() { var scriptStr = 'a\nb\n\n'; var playbackMgr = new rpf.PlayBackManager(rpfInstance); var result = playbackMgr.getAllStepsFromScript(scriptStr); assertEquals(4, result.length); assertEquals('a', result[0]); assertEquals('b', result[1]); } function testCreatePlayBackScript() { var script = 'a*a'; var datafile = 'b*b'; var playbackMgr = new rpf.PlayBackManager(); var result = playbackMgr.createPlayBackScript(datafile); assertNotEquals(-1, result.indexOf(datafile)); } function testWaitForElementReadyAndExecCmds() { var isLoadingReadyForPlayback_ = function() {return true;} mockControl_.$replayAll(); var playbackMgr = new rpf.PlayBackManager({}, isLoadingReadyForPlayback_); assertEquals('', playbackMgr.getCurrentCmd()); playbackMgr.scripts_ = ['run(']; playbackMgr.setCurrentStep(0); playbackMgr.waitForElementReadyAndExecCmds(); mockControl_.$verifyAll(); }
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains the console manager. * TODO(phu): Add potential garbage collection methods for the UI elements. * * @author phu@google.com (Po Hu) */ goog.provide('rpf.ConsoleManager'); goog.provide('rpf.ConsoleManager.ModeInfo'); goog.require('Bite.Constants'); goog.require('bite.base.Helper'); goog.require('bite.closure.Helper'); goog.require('bite.client.Templates.rpfConsole'); goog.require('bite.console.Helper'); goog.require('bite.locators.Updater'); goog.require('goog.array'); goog.require('goog.dom'); goog.require('goog.dom.ViewportSizeMonitor'); goog.require('goog.events'); goog.require('goog.events.EventHandler'); goog.require('goog.positioning.AnchoredViewportPosition'); goog.require('goog.positioning.ClientPosition'); goog.require('goog.positioning.Corner'); goog.require('goog.string'); goog.require('goog.style'); goog.require('goog.ui.LabelInput'); goog.require('goog.ui.MenuItem'); goog.require('goog.ui.Option'); goog.require('goog.ui.Toolbar'); goog.require('goog.ui.ToolbarButton'); goog.require('goog.ui.ToolbarSelect'); goog.require('goog.ui.ToolbarSeparator'); goog.require('rpf.CodeGenerator'); goog.require('rpf.ConsoleLogger'); goog.require('rpf.DetailsDialog'); goog.require('rpf.EditorManager'); goog.require('rpf.ExportDialog'); goog.require('rpf.InfoDialog'); goog.require('rpf.LoaderDialog'); goog.require('rpf.MiscHelper'); goog.require('rpf.NotesDialog'); goog.require('rpf.PlayDialog'); goog.require('rpf.QuickCmdDialog'); goog.require('rpf.SaveDialog'); goog.require('rpf.ScreenShotDialog'); goog.require('rpf.SettingDialog'); goog.require('rpf.StatusLogger'); goog.require('rpf.Tests'); goog.require('rpf.ValidateDialog'); goog.require('rpf.soy.Dialog'); /** * A class for handling console related functions. * @constructor * @export */ rpf.ConsoleManager = function() { /** * The messenger. * @type {rpf.Console.Messenger} * @private */ this.messenger_ = rpf.Console.Messenger.getInstance(); /** * The locator updater. * @type {bite.locators.Updater} * @private */ this.locatorUpdater_ = null; /** * The screenshot dialog. * @type {rpf.ScreenShotDialog} * @private */ this.screenshotDialog_ = new rpf.ScreenShotDialog(); /** * The recorded script. * @type {string} * @private */ this.recordedScript_ = ''; /** * The status logger. * @type {rpf.StatusLogger} * @private */ this.statusLogger_ = rpf.StatusLogger.getInstance(); /** * The project info object, which for now includes an array of json test info, * and will include more project specific info like url/PageName mapper and * package name, etc. later. * @type {Object} * @private */ this.projectInfo_ = new rpf.Tests(); /** * The info map. * @type {Object} * @private */ this.infoMap_ = {}; /** * The user id. * @type {string} * @private */ this.userId_ = ''; /** * What additional information should be shown about the project. This * info will be shown below the toolbar. * @type {Bite.Constants.RpfConsoleInfoType} * @private */ this.moreInfoState_ = Bite.Constants.RpfConsoleInfoType.NONE; /** * Manages the updating all similar elements. * @type {goog.events.EventHandler} * @private */ this.updateAllHandler_ = new goog.events.EventHandler(); /** * Manages resizes of the window. * @type {goog.dom.ViewportSizeMonitor} * @private */ this.viewportSizeMonitor_ = new goog.dom.ViewportSizeMonitor(); /** * Project names in web. * @type {Array.<string>} * @private */ this.projectNames_ = []; /** * The script before adding/modifying. * @type {string} * @private */ this.initialScript_ = ''; this.init_(); }; goog.addSingletonGetter(rpf.ConsoleManager); /** * Sets the initial script. * @private */ rpf.ConsoleManager.prototype.saveScript_ = function() { this.initialScript_ = this.editorMngr_.getOriginalCode(); }; /** * Gets the initial script. * @return {string} The script. */ rpf.ConsoleManager.prototype.getScript = function() { return this.initialScript_; }; /** * Checks whether the script needs to be saved. * @return {boolean} Whether the script needs to be saved. * @private */ rpf.ConsoleManager.prototype.needSave_ = function() { var codeInEditor = this.editorMngr_.getOriginalCode(); return codeInEditor != this.initialScript_; }; /** * Inits the console manager's UI. * @private */ rpf.ConsoleManager.prototype.init_ = function() { this.initUI_(); var toolbar = new goog.ui.Toolbar(); this.setButton(rpf.ConsoleManager.Buttons.ADD_TEST, 'Add a new script', toolbar, Bite.Constants.UiCmds.ADD_NEW_TEST); this.setButton(rpf.ConsoleManager.Buttons.LOAD, 'Toggle Project/Script panel', toolbar, Bite.Constants.UiCmds.LOAD_CMDS); this.setButton(rpf.ConsoleManager.Buttons.SAVE, 'Save your script', toolbar, Bite.Constants.UiCmds.SHOW_SAVE_DIALOG); this.setButton(rpf.ConsoleManager.Buttons.EXPORT, 'Project details', toolbar, Bite.Constants.UiCmds.SHOW_EXPORT); toolbar.addChild(new goog.ui.ToolbarSeparator(), true); this.setButton(rpf.ConsoleManager.Buttons.PLAY, 'Run your script', toolbar, Bite.Constants.UiCmds.SHOW_PLAYBACK_RUNTIME); this.setButton(rpf.ConsoleManager.Buttons.RECORD, 'Record your interaction', toolbar, Bite.Constants.UiCmds.START_RECORDING); this.setButton(rpf.ConsoleManager.Buttons.STOP, 'Stop recording', toolbar, Bite.Constants.UiCmds.STOP_RECORDING); toolbar.addChild(new goog.ui.ToolbarSeparator(), true); this.setButton(rpf.ConsoleManager.Buttons.NOTES, 'Show custom Javascript functions', toolbar, Bite.Constants.UiCmds.SHOW_NOTES); this.setButton(rpf.ConsoleManager.Buttons.INFO, 'Show the logs', toolbar, Bite.Constants.UiCmds.SHOW_INFO); this.setButton(rpf.ConsoleManager.Buttons.SCREEN, 'View the captured screenshots', toolbar, Bite.Constants.UiCmds.SHOW_SCREENSHOT); this.setButton(rpf.ConsoleManager.Buttons.ADD_CMD, 'Show the quick command dialog', toolbar, Bite.Constants.UiCmds.SHOW_QUICK_CMDS); this.setButton(rpf.ConsoleManager.Buttons.WORKER, 'Switch to worker mode', toolbar, Bite.Constants.UiCmds.START_WORKER_MODE); this.setButton(rpf.ConsoleManager.Buttons.SETTING, 'Show the settings dialog', toolbar, Bite.Constants.UiCmds.SHOW_SETTING); toolbar.addChild(new goog.ui.ToolbarSeparator(), true); this.setButton(rpf.ConsoleManager.Buttons.CONTENT_MAP, 'Show the content map', toolbar, Bite.Constants.UiCmds.TOGGLE_CONTENT_MAP); toolbar.addChild(new goog.ui.ToolbarSeparator(), true); this.setButton(rpf.ConsoleManager.Buttons.REFRESH, 'Refresh the rpf console', toolbar, Bite.Constants.UiCmds.ON_CONSOLE_REFRESH); // Allow the content map and project info buttons to have a 'selected' state. this.btns_[rpf.ConsoleManager.Buttons.CONTENT_MAP].setSupportedState( goog.ui.Component.State.SELECTED, true) this.btns_[rpf.ConsoleManager.Buttons.LOAD].setSupportedState( goog.ui.Component.State.SELECTED, true) this.modeSelector_ = this.getModeSelector_(); toolbar.render(goog.dom.getElement('console_toolbar')); this.changeMode(Bite.Constants.ConsoleModes.IDLE); this.checkLocationAndSetProjects_(); goog.events.listen( window, 'keydown', goog.bind(this.onUiEvents, this, Bite.Constants.UiCmds.ON_KEY_DOWN, {})); goog.events.listen( window, 'keyup', goog.bind(this.onUiEvents, this, Bite.Constants.UiCmds.ON_KEY_UP, {})); goog.events.listen( goog.dom.getElement('location-local'), 'click', goog.bind(this.checkLocationAndSetProjects_, this)); goog.events.listen( goog.dom.getElement('location-web'), 'click', goog.bind(this.checkLocationAndSetProjects_, this)); goog.global.window.focus(); chrome.extension.onRequest.addListener( goog.bind(this.makeConsoleCall, this)); this.viewportSizeMonitor_.addEventListener(goog.events.EventType.RESIZE, goog.bind(this.onResize_, this)); this.switchInfoPanel_(Bite.Constants.RpfConsoleInfoType.NONE); }; /** * Checks the location and set the project names. * @private */ rpf.ConsoleManager.prototype.checkLocationAndSetProjects_ = function() { var location = this.loaderDialog_.getStorageLocation(); var command = location == rpf.LoaderDialog.Locations.WEB ? Bite.Constants.CONSOLE_CMDS.GET_PROJECT_NAMES_FROM_WEB : Bite.Constants.CONSOLE_CMDS.GET_PROJECT_NAMES_FROM_LOCAL; this.messenger_.sendMessage( {'command': command, 'params': {}}, goog.bind(this.setProjectNames_, this)); }; /** * Set local project names and requests for web project names. * @param {Object} response The response object. * @private */ rpf.ConsoleManager.prototype.setProjectNames_ = function(response) { this.projectNames_ = response['names']; this.resetProjectNames_(this.projectNames_); }; /** * Resets the project names. * @param {Array} names The project names. * @private */ rpf.ConsoleManager.prototype.resetProjectNames_ = function(names) { bite.closure.Helper.removeItemsFromSelector(this.projectSelector_); bite.closure.Helper.addItemsToSelector(this.projectSelector_, names); this.addCustomMethods_(this.projectSelector_); }; /** * Initializes Console Manager's UI parameters. * @private */ rpf.ConsoleManager.prototype.initUI_ = function() { /** * Whether or not is recording. * @type {boolean} * @private */ this.isRecording_ = false; /** * Whether or not is playing back. * @type {boolean} * @private */ this.isPlaying_ = false; /** * The current mode. * @type {Bite.Constants.ConsoleModes} * @private */ this.mode_ = Bite.Constants.ConsoleModes.IDLE; /** * The buttons displayed on console UI. * @type {Object} * @private */ this.btns_ = {}; /** * The modeInfo static object. * @type {rpf.ConsoleManager.ModeInfo} * @private */ this.modeInfo_ = new rpf.ConsoleManager.ModeInfo(); /** * The line number that should be highlighted. * @type {number} * @private */ this.lineHighlighted_ = -1; /** * The mode selector. * @type {Object} * @private */ this.modeSelector_ = null; /** * The current view mode. * @type {Bite.Constants.ViewModes} * @private */ this.viewMode_ = Bite.Constants.ViewModes.CODE; /** * The line to be inserted. * @type {number} * @private */ this.lineToInsert_ = -1; /** * The editor manager. * @type {rpf.EditorManager} * @private */ this.editorMngr_ = new rpf.EditorManager( Bite.Constants.RpfConsoleId.SCRIPTS_CONTAINER, goog.bind(this.fetchDataFromBackground_, this), goog.bind(this.getViewMode, this), goog.bind(this.getInfoMap, this)); goog.events.listen(this.editorMngr_.getContainer(), goog.events.EventType.DBLCLICK, goog.bind(this.popupDetailedInfo_, this)); /** * The notes dialog. * @type {rpf.NotesDialog} * @private */ this.notesDialog_ = new rpf.NotesDialog( this.messenger_, goog.bind(this.onUiEvents, this)); /** * The export dialog. * @type {rpf.ExportDialog} * @private */ this.exportDialog_ = new rpf.ExportDialog( goog.bind(this.onUiEvents, this), goog.bind(this.changeProject_, this), this.messenger_); this.exportDialog_.init(); /** * The quick commands dialog. * @type {rpf.QuickCmdDialog} * @private */ this.quickDialog_ = new rpf.QuickCmdDialog( goog.bind(this.onUiEvents, this)); /** * The loader dialog. * @type {rpf.LoaderDialog} * @private */ this.loaderDialog_ = new rpf.LoaderDialog( this.messenger_, goog.bind(this.onUiEvents, this)); /** * The validation dialog. * @type {rpf.ValidateDialog} * @private */ this.validationDialog_ = new rpf.ValidateDialog( this.messenger_, goog.bind(this.onUiEvents, this)); /** * The details dialog. * @type {rpf.DetailsDialog} * @private */ this.detailsDialog_ = new rpf.DetailsDialog( this.messenger_, goog.bind(this.onUiEvents, this), this.editorMngr_, this.screenshotDialog_); /** * The playback dialog. * @type {rpf.PlayDialog} * @private */ this.playbackRuntimeDialog_ = new rpf.PlayDialog( this.messenger_, goog.bind(this.onUiEvents, this)); /** * The setting dialog. * @type {rpf.SettingDialog} * @private */ this.settingDialog_ = new rpf.SettingDialog(goog.bind(this.onUiEvents, this)); /** * The info dialog. * @type {rpf.InfoDialog} * @private */ this.infoDialog_ = new rpf.InfoDialog(); /** * The input dialog. * @type {goog.ui.Dialog} * @private */ this.inputDialog_ = new goog.ui.Dialog(); /** * The project selector. * @type {goog.ui.ComboBox} * @private */ this.projectSelector_ = null; /** * The script selector. * @type {goog.ui.ComboBox} * @private */ this.scriptSelector_ = null; /** * The last script name typed in. * @type {string} * @private */ this.lastScriptName_ = ''; this.boundOnScriptNameChange_ = goog.bind(this.onScriptChangeHandler_, this); this.setupProjectInfoUi_(); }; /** * Inits the info dialog. * @param {string} title The title of the dialog. * @param {Element} element The component element to be rendered in the dialog. * @private */ rpf.ConsoleManager.prototype.openInputDialog_ = function(title, element) { var contentElement = this.inputDialog_.getContentElement(); contentElement.innerHTML = ''; contentElement.appendChild(element); this.inputDialog_.setTitle(title); this.inputDialog_.setButtonSet(null); this.inputDialog_.setVisible(true); }; /** * Sets up the project info related UI in the main RPF console. * @private */ rpf.ConsoleManager.prototype.setupProjectInfoUi_ = function() { this.projectSelector_ = this.createSelector_( [], 'rpf-current-project', 'Enter a project name', goog.bind(this.onProjectChangeHandler_, this)); this.scriptSelector_ = this.createSelector_( [], 'testName', 'Enter a script name', this.boundOnScriptNameChange_); var urlInputCtrl = new goog.ui.LabelInput('Script start URL'); var startUrlDiv = goog.dom.getElement('startUrlDiv'); urlInputCtrl.render(startUrlDiv); var urlInput = startUrlDiv.querySelector('.label-input-label'); urlInput.setAttribute('id', 'startUrl'); goog.style.setStyle(urlInput, {'width': '100%'}); }; /** * Adds the custom methods in the popup menu. * @param {goog.ui.ComboBox} selector The combo box selector. * @private */ rpf.ConsoleManager.prototype.addCustomMethods_ = function(selector) { var menuItem = new goog.ui.MenuItem('New Name'); selector.addItemAt(menuItem, 0); var contentElem = menuItem.getContentElement(); goog.style.setStyle(contentElem, {'color': '#D14836'}); var menuSeparator = new goog.ui.MenuSeparator(); var menu = selector.getMenu(); menu.addChildAt(menuSeparator, 1, true); }; /** * Loads the tests in the selector. * @param {Function} callback The callback function. * @param {boolean} clearTest Whether clears the test name field. * @param {boolean} displayMessage Whether displays the message. * @param {Array.<string>} names The script names. * @param {Object=} opt_response The response object. * @private */ rpf.ConsoleManager.prototype.loadTestsInSelector_ = function( callback, clearTest, displayMessage, names, opt_response) { bite.closure.Helper.removeItemsFromSelector(this.scriptSelector_); bite.closure.Helper.addItemsToSelector(this.scriptSelector_, names); this.addCustomMethods_(this.scriptSelector_); if (clearTest) { this.scriptSelector_.setValue(''); } if (opt_response && opt_response['success']) { if (displayMessage) { this.statusLogger_.setStatus(rpf.StatusLogger.LOAD_TEST_SUCCESS, 'green'); } this.exportDialog_.requestDataComplete( this.getProjectName_(), goog.nullFunction, {'jsonObj': this.loaderDialog_.getCurrentProject()}); this.exportDialog_.setLocation(this.loaderDialog_.getStorageLocation()); this.messenger_.sendStatusMessage( Bite.Constants.COMPLETED_EVENT_TYPES.PROJECT_LOADED); callback(); } else { if (displayMessage) { this.statusLogger_.setStatus(rpf.StatusLogger.LOAD_TEST_FAILED, 'red'); } } }; /** * Changes the project.. * @param {boolean=} opt_noCheck Whether it should check for project exists. * @param {Function=} opt_callback The callback function. * @private */ rpf.ConsoleManager.prototype.changeProject_ = function( opt_noCheck, opt_callback) { var noCheck = opt_noCheck || false; var callback = opt_callback || goog.nullFunction; var currentProject = this.getProjectName_(); var onEnterNewName = goog.bind(this.onEnterNewProjectName_, this); var setName = goog.bind(this.setProjectName_, this); var params = {'onEnterNewName': onEnterNewName, 'setName': setName}; if (this.checkForCustomMethods_(currentProject, params)) { return; } if (noCheck || (currentProject && goog.array.contains(this.projectNames_, currentProject))) { this.statusLogger_.setStatus(rpf.StatusLogger.LOAD_TEST, '#777'); this.loaderDialog_.loadProject( currentProject, goog.bind(this.loadTestsInSelector_, this, callback, true, true)); } }; /** * On project name change handler. * @param {Event} e The change event. * @private */ rpf.ConsoleManager.prototype.onProjectChangeHandler_ = function(e) { this.changeProject_(); }; /** * On a new script name has been entered. * @param {Event} e The change event. * @private */ rpf.ConsoleManager.prototype.onEnterNewScriptName_ = function(e) { var newName = goog.dom.getElement('new-name-input').value; if (!newName || goog.array.contains(this.loaderDialog_.getTestNames(), newName)) { this.statusLogger_.setStatus('Please enter a valid script name', 'red'); return; } this.setScriptName_(newName); this.inputDialog_.setVisible(false); }; /** * On a new project name has been entered. * @param {Event} e The change event. * @private */ rpf.ConsoleManager.prototype.onEnterNewProjectName_ = function(e) { var newName = goog.dom.getElement('new-name-input').value; if (!newName || goog.array.contains(this.projectNames_, newName)) { this.statusLogger_.setStatus('Please enter a valid project name', 'red'); return; } this.setProjectName_(newName); this.inputDialog_.setVisible(false); }; /** * On the cancel button is clicked. * @param {Event} e The change event. * @private */ rpf.ConsoleManager.prototype.onCancelNewScriptName_ = function(e) { this.inputDialog_.setVisible(false); }; /** * Checks for the custom methods. * @param {string} name The option name. * @param {Object} params The parameter map. * @return {boolean} Whether the given name is a custom method. * @private */ rpf.ConsoleManager.prototype.checkForCustomMethods_ = function( name, params) { switch (name) { case rpf.ConsoleManager.CustomMethods.ADD_NEW: var setNameMethod = params['setName']; setNameMethod(''); var content = soy.renderAsElement( rpf.soy.Dialog.getNewNameUi, {}); this.openInputDialog_('New', content); goog.events.listen( goog.dom.getElement('new-name-submit'), goog.events.EventType.CLICK, params['onEnterNewName']); goog.events.listen( goog.dom.getElement('new-name-cancel'), goog.events.EventType.CLICK, goog.bind(this.onCancelNewScriptName_, this)); return true; } return false; }; /** * On script name change handler. * @private */ rpf.ConsoleManager.prototype.onScriptChangeHandler_ = function() { var lastName = this.lastScriptName_; var currentScript = this.scriptSelector_.getValue(); this.lastScriptName_ = currentScript; var onEnterNewName = goog.bind(this.onEnterNewScriptName_, this); var setName = goog.bind(this.setScriptName_, this); var params = {'onEnterNewName': onEnterNewName, 'setName': setName}; if (this.checkForCustomMethods_(currentScript, params)) { return; } var id = this.loaderDialog_.getIdByName(currentScript); if (goog.array.contains(this.loaderDialog_.getTestNames(), currentScript)) { if (this.needSave_()) { this.promptSaveDialog_(lastName); } else { this.loadTest_(); } } }; /** * Prompt the user whether to save the script first. * @param {string} lastName The last script name. * @private */ rpf.ConsoleManager.prototype.promptSaveDialog_ = function(lastName) { var content = soy.renderAsElement( rpf.soy.Dialog.getSaveScriptConfirmUi, {}); this.openInputDialog_('Confirm', content); goog.events.listen( goog.dom.getElement('save-script-submit'), goog.events.EventType.CLICK, goog.bind(this.onContinueLoad_, this)); goog.events.listen( goog.dom.getElement('save-script-cancel'), goog.events.EventType.CLICK, goog.bind(this.rollbackScriptName_, this, lastName)); }; /** * Rolls back to the previously saved name. * @param {string} lastName The last name. * @private */ rpf.ConsoleManager.prototype.rollbackScriptName_ = function(lastName) { this.lastScriptName_ = lastName; this.setScriptNameStatic_(lastName); this.inputDialog_.setVisible(false); }; /** * When users choose to continue loading. * @private */ rpf.ConsoleManager.prototype.onContinueLoad_ = function(e) { this.inputDialog_.setVisible(false); this.loadTest_(); }; /** * Loads the test. * @private */ rpf.ConsoleManager.prototype.loadTest_ = function() { if (this.isRecording()) { this.statusLogger_.setStatus( 'During recording, can not load a script.', 'red'); return; } var currentScript = this.scriptSelector_.getValue(); this.statusLogger_.setStatus(rpf.StatusLogger.LOAD_TEST, '#777'); this.loaderDialog_.loadSelectedTest( goog.bind(this.loadTestCallback_, this), this.getProjectName_(), currentScript); }; /** * Creates the project selector for choosing options. * @param {Array} options The options to be showed in selector. * @param {string} id The id of the div where the selector will be rendered. * @param {string} text The default text. * @param {Function} callback The callback function. * @return {goog.ui.ComboBox} The combobox instance. * @private */ rpf.ConsoleManager.prototype.createSelector_ = function( options, id, text, callback) { var selector_ = new goog.ui.ComboBox(); selector_.setUseDropdownArrow(false); selector_.setDefaultText(text); for (var i = 0, len = options.length; i < len; ++i) { var pName = ''; var pId = ''; if (goog.isString(options[i])) { pName = options[i]; pId = options[i]; } else { pName = options[i]['name']; pId = options[i]['id']; } var option = new goog.ui.ComboBoxItem(pName); goog.dom.setProperties(/** @type {Element} */ (option), {'id': pId}); selector_.addItem(option); } var selectorElem = goog.dom.getElement(id); selector_.render(selectorElem); var inputElem = selectorElem.querySelector('.label-input-label'); inputElem.setAttribute('type', 'text'); goog.style.setStyle(inputElem, {'width': '62%'}); var menuElem = selectorElem.querySelector('.goog-menu'); goog.style.setStyle(menuElem, {'max-height': '400px', 'overflow-y': 'auto'}); goog.events.listen( selector_, goog.ui.Component.EventType.CHANGE, callback); return selector_; }; /** * Handles window resizes. * @private */ rpf.ConsoleManager.prototype.onResize_ = function() { var toolbarSize = 34; var infobarSize = 67; var infopanelSize = 163; var curSize = this.viewportSizeMonitor_.getSize(); var container = goog.dom.getElement('scriptsContainer'); if (this.moreInfoState_ == Bite.Constants.RpfConsoleInfoType.NONE) { goog.style.setSize( container, curSize.width, curSize.height - (toolbarSize + infobarSize)); } else { goog.style.setSize( container, curSize.width, curSize.height - (toolbarSize + infobarSize + infopanelSize)); } this.screenshotDialog_.resize(); this.notesDialog_.resize(); this.editorMngr_.resize(); }; /** * Fetches init data from background. * @private */ rpf.ConsoleManager.prototype.fetchDataFromBackground_ = function() { this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.FETCH_DATA_FROM_BACKGROUND, 'params': {}}, goog.bind(this.fetchDataFromBackgroundCallback_, this)); }; /** * Fetches init data from background callback. * @param {Object} response The response object. * @private */ rpf.ConsoleManager.prototype.fetchDataFromBackgroundCallback_ = function( response) { this.userId_ = response['userId']; this.messenger_.sendStatusMessage( Bite.Constants.COMPLETED_EVENT_TYPES.RPF_CONSOLE_OPENED); }; /** * Gets the mode selector control. * @return {goog.ui.ToolbarSelect} The mode selector. * @private */ rpf.ConsoleManager.prototype.getModeSelector_ = function() { var modeMenu = new goog.ui.Menu(); var codeOption = new goog.ui.Option('Code'); var readOption = new goog.ui.Option('Readable'); var bookOption = new goog.ui.Option('Book'); var updaterOption = new goog.ui.Option('Updater'); modeMenu.addChild(codeOption, true); modeMenu.addChild(readOption, true); modeMenu.addChild(bookOption, true); modeMenu.addChild(updaterOption, true); var modeSelector = new goog.ui.ToolbarSelect('Mode', modeMenu); modeSelector.setSelectedIndex(0); goog.events.listen( codeOption, goog.ui.Component.EventType.ACTION, goog.bind(this.selectViewCodeMode_, this)); goog.events.listen( readOption, goog.ui.Component.EventType.ACTION, goog.bind(this.selectViewReadableMode_, this)); goog.events.listen( bookOption, goog.ui.Component.EventType.ACTION, goog.bind(this.selectViewBookMode_, this)); goog.events.listen( updaterOption, goog.ui.Component.EventType.ACTION, goog.bind(this.selectUpdaterMode_, this)); return modeSelector; }; /** * Adds a tooblar button. * @param {rpf.ConsoleManager.Buttons} btn The buttons displayed on console UI. * @param {string} tooltip Tool tip for the toolbar button. * @param {goog.ui.Toolbar} toolbar The toolbar to add buttons on. * @param {Bite.Constants.UiCmds} uiCmd The corresponding message. * @export */ rpf.ConsoleManager.prototype.setButton = function( btn, tooltip, toolbar, uiCmd) { var toolbarItem = new goog.ui.ToolbarButton(goog.dom.getElement(btn)); toolbarItem.setTooltip(tooltip); this.btns_[btn] = toolbarItem; toolbar.addChild(toolbarItem, true); goog.events.listen( toolbarItem.getElement(), goog.events.EventType.CLICK, goog.bind(this.onUiEvents, this, uiCmd, {})); }; /** * Event handler for calls from background world. * @param {Object} request The request object. * @param {MessageSender} sender The sender object. * @param {function(Object)=} opt_callback The callback function. * @export */ rpf.ConsoleManager.prototype.makeConsoleCall = function( request, sender, opt_callback) { this.logInfo('Got this message: ' + request['command']); this.handleMessages_( request['command'], request['params'], opt_callback); }; /** * Handles the events happened on UI. * @param {Bite.Constants.UiCmds} uiCmd The message of the event. * @param {Object} params The params object. * @param {Event} event The event object. * @param {function(Object)=} opt_callback The optional callback function. * @export */ rpf.ConsoleManager.prototype.onUiEvents = function( uiCmd, params, event, opt_callback) { params['event'] = event; this.handleMessages_(uiCmd, params, opt_callback); }; /** * Handles the messages to control the actions on UI. * @param {Bite.Constants.UiCmds} uiCmd The command will be performed on UI. * @param {Object} params The params object. * @param {function(Object)=} opt_callback The optional callback function. * @private */ rpf.ConsoleManager.prototype.handleMessages_ = function( uiCmd, params, opt_callback) { switch (uiCmd) { // For the console helper. case Bite.Constants.UiCmds.GENERATE_CUSTOMIZED_FUNCTION_CALL: var value = ''; this.quickDialog_.writeCmd( rpf.QuickCmdDialog.Commands.FUNCTION, value); break; // For the details dialog. case Bite.Constants.UiCmds.UPDATE_HIGHLIGHT_LINE: this.updateHighlightLine(params['lineNum']); break; case Bite.Constants.UiCmds.ON_PREV_PAGE: this.findPrevCmd(this.detailsDialog_.getCurLineNum()); break; case Bite.Constants.UiCmds.ON_NEXT_PAGE: this.findNextCmd(this.detailsDialog_.getCurLineNum()); break; case Bite.Constants.UiCmds.ON_EDIT_CMD: this.detailsDialog_.onEditCmd(); break; case Bite.Constants.UiCmds.ON_CMD_MOVE_UP: this.detailsDialog_.onCmdMoveUp(); break; case Bite.Constants.UiCmds.ON_CMD_MOVE_DOWN: this.detailsDialog_.onCmdMoveDown(); break; case Bite.Constants.UiCmds.ON_INSERT_ABOVE: this.detailsDialog_.setVisible(false); this.setLineToInsert(this.detailsDialog_.getCurLineNum()); this.startRecording(); break; case Bite.Constants.UiCmds.ON_INSERT_BELOW: this.detailsDialog_.setVisible(false); this.setLineToInsert(this.detailsDialog_.getCurLineNum() + 1); this.startRecording(); break; case Bite.Constants.UiCmds.ON_REMOVE_CUR_LINE: this.detailsDialog_.onRemoveCurLine(); break; // For the playback dialog. case Bite.Constants.UiCmds.AUTOMATE_PLAY_MULTIPLE_TESTS: this.playbackRuntimeDialog_.setVisible(true); this.playbackRuntimeDialog_.automateDialog( params['testInfo'], params['runAll']); this.messenger_.sendStatusMessage( Bite.Constants.COMPLETED_EVENT_TYPES.RUN_PLAYBACK_STARTED); break; case Bite.Constants.UiCmds.UPDATE_COMMENT: this.playbackRuntimeDialog_.updateComment( params['id'], params['comment']); break; case Bite.Constants.UiCmds.UPDATE_ELEMENT_AT_LINE: this.updateElementAtLine_( params['line'], params['cmdMap'], opt_callback || goog.nullFunction); break; case Bite.Constants.UiCmds.SET_PLAYBACK_ALL: this.startPlayback(Bite.Constants.PlayMethods.ALL); this.playbackRuntimeDialog_.setPlaybackAll(); break; case Bite.Constants.UiCmds.SET_PLAYBACK_STEP: this.playbackRuntimeDialog_.setPlaybackStep(); this.startPlayback(Bite.Constants.PlayMethods.STEP); break; case Bite.Constants.UiCmds.SET_PLAYBACK_PAUSE: this.playbackRuntimeDialog_.setPlaybackPause(params['uiOnly']); break; case Bite.Constants.UiCmds.SET_PLAYBACK_STOP: this.playbackRuntimeDialog_.setPlaybackStop(); break; case Bite.Constants.UiCmds.SET_PLAYBACK_STOP_ALL: this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.STOP_GROUP_TESTS, 'params': {}}); this.playbackRuntimeDialog_.setPlaybackStop(); break; case Bite.Constants.UiCmds.SET_FINISHED_TESTS_NUMBER: this.playbackRuntimeDialog_.setFinishedNumber(params['num']); break; case Bite.Constants.UiCmds.DELETE_CMD: var lineNum = this.playbackRuntimeDialog_.deleteCmd(); this.getEditorManager().removeCurrentLine(lineNum - 1); break; case Bite.Constants.UiCmds.FAIL_CMD: this.playbackRuntimeDialog_.failCmd(); break; case Bite.Constants.UiCmds.OVERRIDE_CMD: this.playbackRuntimeDialog_.overrideCmd(); break; case Bite.Constants.UiCmds.UPDATE_CMD: this.playbackRuntimeDialog_.updateCmd(); break; case Bite.Constants.UiCmds.INSERT_CMD: var lineNum = this.playbackRuntimeDialog_.insertCmd(); this.setLineToInsert(lineNum); break; // For the validation dialog. case Bite.Constants.UiCmds.DISPLAY_ALL_ATTRIBUTES: this.validationDialog_.displayAllAttributes(); break; case Bite.Constants.UiCmds.SAVE_TEST: this.saveTest(); break; // For the quick command dialog. case Bite.Constants.UiCmds.UPDATE_INVOKE_SELECT: this.quickDialog_.updateInvokeSelect(params['names'], params['ids']); this.playbackRuntimeDialog_.updateTestSelection( params['names'], params['ids']); break; // For the load dialog. case Bite.Constants.UiCmds.AUTOMATE_DIALOG_LOAD_TEST: this.automateLoadDialog_( params['isWeb'], params['project'], params['test'], goog.nullFunction); break; case Bite.Constants.UiCmds.AUTOMATE_DIALOG_LOAD_PROJECT: this.automateLoadDialog_( params['isWeb'], params['project'], '', goog.nullFunction); break; case Bite.Constants.UiCmds.SET_PROJECT_INFO: this.setProjectInfo( params['name'], params['tests'], params['from'], params['details']); break; // For the main console. case Bite.Constants.UiCmds.SET_CONSOLE_STATUS: this.statusLogger_.setStatus(params['message'], params['color']); break; case Bite.Constants.UiCmds.UPDATE_PLAYBACK_STATUS: this.updatePlaybackStatus(params['text'], params['color']); break; case Bite.Constants.UiCmds.UPDATE_CURRENT_STEP: this.updateCurrentStep(params['curStep']); break; case Bite.Constants.UiCmds.LOAD_TEST_FROM_LOCAL: this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.GET_JSON_LOCALLY, 'params': params}, goog.bind(this.loadTestCallback_, this)); break; case Bite.Constants.UiCmds.LOAD_TEST_FROM_WTF: this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.GET_JSON_FROM_WTF, 'params': params}, goog.bind(this.loadTestCallback_, this)); break; case Bite.Constants.UiCmds.UPDATE_WHEN_ON_FAILED: this.setPlaybackPause(params['uiOnly']); this.playbackRuntimeDialog_.makeChoiceAfterFailure( params['failureReason'], params['failureLog']); this.editorMngr_.addFailedClass(params['currentStep']); break; case Bite.Constants.UiCmds.UPDATE_WHEN_RUN_FINISHED: this.setPlayStatus(false, params['status']); this.updateCurrentStep(-1); this.setPlaybackStop(params['uiOnly']); this.updatePlaybackStatus( 'The current playback has been finished.', 'black'); break; case Bite.Constants.UiCmds.OPEN_VALIDATION_DIALOG: this.validationDialog_.openValidationDialog( params['request']); break; case Bite.Constants.UiCmds.SET_START_URL: this.setStartUrl(params['url']); this.setDocString(params['url']); break; case Bite.Constants.UiCmds.ON_KEY_DOWN: this.onKeyDown_(params['event']); break; case Bite.Constants.UiCmds.ON_KEY_UP: this.onKeyUp_(params['event']); break; case Bite.Constants.UiCmds.ON_CONSOLE_CLOSE: this.onConsoleClose_(); break; case Bite.Constants.UiCmds.ON_CONSOLE_REFRESH: this.onConsoleRefresh_(); break; case Bite.Constants.UiCmds.ON_SHOW_MORE_INFO: this.onShowMoreInfo_(); break; case Bite.Constants.UiCmds.ADD_GENERATED_CMD: this.screenshotDialog_.getScreenshotManager().addGeneratedCmd( params['cmd']); break; case Bite.Constants.UiCmds.ADD_NEW_COMMAND: this.addNewCommand( params['pCmd'], params['dCmd'], params['index'], params['cmdMap']); break; case Bite.Constants.UiCmds.ADD_SCREENSHOT: this.screenshotDialog_.getScreenshotManager().addScreenShot( params['dataUrl'], params['iconUrl']); break; case Bite.Constants.UiCmds.RESET_SCREENSHOTS: this.screenshotDialog_.getScreenshotManager().resetScreenShots( params['screenshots']); break; case Bite.Constants.UiCmds.UPDATE_SCRIPT_INFO: this.updateScriptInfo( params['name'], params['url'], params['script'], params['datafile'], params['userlib'], params['id'], params['projectname']); break; case Bite.Constants.UiCmds.CHANGE_MODE: this.changeMode(params['mode']); break; case Bite.Constants.UiCmds.HIGHLIGHT_LINE: var line = this.projectInfo_.getFailureLineNumber( params['stepId'], params['testName']); if (line >= 0) { this.popDescInfoMap_(line); this.detailsDialog_.onEditCmd(); } break; case Bite.Constants.UiCmds.TOGGLE_CONTENT_MAP: this.handleInfoPanelButton_( Bite.Constants.RpfConsoleInfoType.CONTENT_MAP); break; case Bite.Constants.UiCmds.TOGGLE_PROJECT_INFO: this.handleInfoPanelButton_( Bite.Constants.RpfConsoleInfoType.PROJECT_INFO); break; case Bite.Constants.UiCmds.SHOW_QUICK_CMDS: this.showQuickCmds(); break; case Bite.Constants.UiCmds.SHOW_EXPORT: this.showExportDialog(); break; case Bite.Constants.UiCmds.SHOW_INFO: this.showInfo(); break; case Bite.Constants.UiCmds.LOAD_CMDS: this.loadCmds(); break; case Bite.Constants.UiCmds.SHOW_NOTES: this.showNotes(); break; case Bite.Constants.UiCmds.START_RECORDING: var passChecking = params['passChecking'] || false; this.startRecording(passChecking); break; case Bite.Constants.UiCmds.SHOW_SAVE_DIALOG: this.showSaveDialog(); break; case Bite.Constants.UiCmds.ADD_NEW_TEST: this.addNewTest_(); break; case Bite.Constants.UiCmds.SHOW_SCREENSHOT: this.showScreenshot(); break; case Bite.Constants.UiCmds.SHOW_SETTING: this.showSetting(); break; case Bite.Constants.UiCmds.SHOW_PLAYBACK_RUNTIME: this.showPlaybackRuntime(); break; case Bite.Constants.UiCmds.STOP_RECORDING: this.stopRecording(); break; case Bite.Constants.UiCmds.START_WORKER_MODE: this.startWorkerMode(); break; case Bite.Constants.UiCmds.RECORD_TAB_CLOSED: this.stopRecording(); this.warnRecordTabClosed_(); break; case Bite.Constants.UiCmds.CHECK_TAB_READY: this.checkTabReady_(params['message']); break; case Bite.Constants.UiCmds.CHECK_TAB_READY_TO_UPDATE: this.checkTabReadyToUpdate_(); break; default: break; } }; /** * Enum for image path. * @enum {string} * @export */ rpf.ConsoleManager.Images = { /* TODO(ralphj): Remove the validation image. */ VALIDATION: 'imgs/rpf/validation.png', RECORD_GREY: 'imgs/rpf/record-disabled.png', STOP: 'imgs/rpf/stop.png', VALIDATION_GREY: 'imgs/rpf/validation-disabled.png', RECORD: 'imgs/rpf/record.png', STOP_GREY: 'imgs/rpf/stop-disabled.png', VALIDATION_ON: 'imgs/rpf/validationon.png', WORKER: 'imgs/rpf/workermode.png', WORKER_OFF: 'imgs/rpf/workermodeoff.png' }; /** * Enum for result status. * @enum {string} * @export */ rpf.ConsoleManager.Results = { SUCCESS: 'passed', STOP: 'stop' }; /** * Enum for the custom methods. * @enum {string} */ rpf.ConsoleManager.CustomMethods = { ADD_NEW: 'New Name' }; /** * Enum for buttons. * @enum {string} * @export */ rpf.ConsoleManager.Buttons = { ADD_CMD: 'rpf-addCmd', CONTENT_MAP: 'rpf-content-map-button', EXPORT: 'rpf-export', INFO: 'rpf-info', LOAD: 'rpf-loadTest', NOTES: 'rpf-notes', RECORD: 'rpf-record', REFRESH: 'rpf-refresh', SAVE: 'rpf-saveTest', ADD_TEST: 'rpf-addTest', SCREEN: 'rpf-screenShots', SETTING: 'rpf-setting', PLAY: 'rpf-startPlayback', STOP: 'rpf-stop', WORKER: 'rpf-workerMode' }; /** * Warns the user that the tab under record was closed. * @private */ rpf.ConsoleManager.prototype.warnRecordTabClosed_ = function() { var content = soy.renderAsElement( rpf.soy.Dialog.getRecordTabClosedUi, {}); this.openInputDialog_('Warn', content); }; /** * Automates the load dialog. * @param {boolean} isWeb Whether the location is the web. * @param {string} project The project name. * @param {string} test The test name. * @param {function(Object)} callback The callback function. * @private */ rpf.ConsoleManager.prototype.automateLoadDialog_ = function( isWeb, project, test, callback) { this.switchInfoPanel_(Bite.Constants.RpfConsoleInfoType.PROJECT_INFO); this.setLocation_(isWeb); this.checkLocationAndSetProjects_(); this.setProjectName_(project); if (test) { this.changeProject_( true, goog.bind(this.changeProjectCallback_, this, test)); } else { this.changeProject_(true); } }; /** * Adds a new test. This method will clean up the console except the project. * @private */ rpf.ConsoleManager.prototype.addNewTest_ = function() { this.switchInfoPanel_(Bite.Constants.RpfConsoleInfoType.PROJECT_INFO); this.updateScriptInfo( '', '', '', '', '', '', this.getProjectName_()); this.screenshotDialog_.getScreenshotManager().clear(); this.saveScript_(); this.setStatus('Ready to add new tests.', 'green'); }; /** * Gets the project name from UI. * @return {string} The project name. * @private */ rpf.ConsoleManager.prototype.getProjectName_ = function() { return this.projectSelector_.getValue(); }; /** * The callback function of changing project. * @param {string} test The test name. * @private */ rpf.ConsoleManager.prototype.changeProjectCallback_ = function(test) { this.setScriptName_(test); this.onScriptChangeHandler_(); }; /** * Sets the location where the project is loaded from. * @param {boolean} isWeb Whether the location is the web. * @private */ rpf.ConsoleManager.prototype.setLocation_ = function(isWeb) { goog.dom.getElement('location-local').checked = !isWeb; goog.dom.getElement('location-web').checked = isWeb; }; /** * Sets the script name. * @param {string} script The script name. * @private */ rpf.ConsoleManager.prototype.setScriptName_ = function(script) { this.scriptSelector_.setValue(script); }; /** * Sets the script name without triggering onchange event. * @param {string} script The script name. * @private */ rpf.ConsoleManager.prototype.setScriptNameStatic_ = function(script) { goog.events.unlisten( this.scriptSelector_, goog.ui.Component.EventType.CHANGE, this.boundOnScriptNameChange_); this.scriptSelector_.setValue(script); goog.events.listen( this.scriptSelector_, goog.ui.Component.EventType.CHANGE, this.boundOnScriptNameChange_); }; /** * Sets the project name. * @param {string} projectName The project name. * @private */ rpf.ConsoleManager.prototype.setProjectName_ = function(projectName) { this.projectSelector_.setValue(projectName); }; /** * Updates the element at the given step id. * @param {string} stepId The step id. * @param {Object} cmdMap The command info map. * @param {!Object} originalInfoMap The original script info map. * @return {string} The old xpath. * @private */ rpf.ConsoleManager.prototype.updateElement_ = function( stepId, cmdMap, originalInfoMap) { var elemId = originalInfoMap['steps'][stepId]['elemId']; var elem = originalInfoMap['elems'][elemId]; var oldXpath = elem['xpaths'][0]; if (goog.isDef(cmdMap['selectors'])) { elem['selectors'] = cmdMap['selectors']; } elem['xpaths'] = cmdMap['xpaths']; elem['descriptor'] = cmdMap['descriptor']; if (goog.isDef(cmdMap['iframeInfo'])) { elem['iframeInfo'] = cmdMap['iframeInfo']; } return oldXpath; }; /** * Updates the element at the given step id in a test. * @param {string} testName The test name. * @param {string} stepId The step id. * @param {Object} cmdMap The command info map. * @private */ rpf.ConsoleManager.prototype.updateElementInTest_ = function( testName, stepId, cmdMap) { var originalInfoMap = this.projectInfo_.getInfoMapByTest(testName); this.updateElement_(stepId, cmdMap, originalInfoMap); this.projectInfo_.saveInfoMapToTest(testName, originalInfoMap); }; /** * Updates the element that at the given line with the updated element info * captured from the tab under record. * @param {number} line The line number. * @param {Object} cmdMap The command info map. * @param {function(Function, string)} callback The callback function. * @private */ rpf.ConsoleManager.prototype.updateElementAtLine_ = function( line, cmdMap, callback) { var lineContent = this.editorMngr_.getTextAtLine(line); var stepId = bite.base.Helper.getStepId(lineContent); var oldXpath = this.updateElement_(stepId, cmdMap, this.infoMap_ || {}); var loadFrom = ''; // If the project was loaded from local, we could update all of the // tests and save them back at once. Otherwise, we could only update // steps in the particular test for now. The second case includes // while creating a new test and loads a test from web. if (this.projectInfo_ && this.projectInfo_.getLoadFrom() == rpf.LoaderDialog.Locations.LOCAL) { this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.GET_TEST_NAMES_LOCALLY, 'params': {'project': this.getProjectName_()}}, goog.bind(this.showElementsAfterProjectUpdated_, this, callback, cmdMap, oldXpath)); } else { var data = this.getStepsFromInfoMap_( this.getTestName_(), this.infoMap_, oldXpath); this.showElementsWithSameXpath_( data, rpf.LoaderDialog.Locations.WEB, callback, cmdMap); } }; /** * When the local project is updated, show the steps with the same xpath. * @param {function(Function, string)} callback The callback function. * @param {Object} cmdMap The command info map. * @param {string} oldXpath The old xpath. * @param {Object} response The response object. * @private */ rpf.ConsoleManager.prototype.showElementsAfterProjectUpdated_ = function( callback, cmdMap, oldXpath, response) { this.setProjectInfo( response['name'], response['tests'], rpf.LoaderDialog.Locations.LOCAL, response['details']); var data = this.getStepsWithSameXpath_(oldXpath); this.showElementsWithSameXpath_( data, rpf.LoaderDialog.Locations.LOCAL, callback, cmdMap); }; /** * Shows the steps that are with the same xpath. * @param {Object} data The data of the steps. * @param {string} loadFrom Where the project was loaded from. * @param {function(Function, string)} callback The callback function. * @param {Object} cmdMap The command info map. * @private */ rpf.ConsoleManager.prototype.showElementsWithSameXpath_ = function( data, loadFrom, callback, cmdMap) { if (!data) { return; } var html = element.helper.Templates.locatorsUpdater. showElementsWithSameXpath({'data': data, 'loadFrom': loadFrom}); callback(goog.bind(this.registerEventsOnSameElements_, this, cmdMap), html); }; /** * Registers events on replace and cancel buttons. * @param {Object} newCmdMap The new command's map info. * @param {function()} onCancelHandler The handler to cancel the update. * @private */ rpf.ConsoleManager.prototype.registerEventsOnSameElements_ = function( newCmdMap, onCancelHandler) { this.updateAllHandler_.listen( goog.dom.getElement('replaceAllXpaths'), goog.events.EventType.CLICK, goog.bind(this.handleReplaceButton_, this, newCmdMap, onCancelHandler)); this.updateAllHandler_.listen( goog.dom.getElement('cancelReplaceXpaths'), goog.events.EventType.CLICK, goog.bind(this.handleCancelButton_, this, onCancelHandler)); }; /** * Replace button handler. * @param {Object} newCmdMap The new command map. * @param {function()} onCancelHandler The handler to cancel the update. * @private */ rpf.ConsoleManager.prototype.handleReplaceButton_ = function( newCmdMap, onCancelHandler) { var selectedSteps = goog.dom.getDocument().getElementsByName('selectedSteps'); for (var i = 0, len = selectedSteps.length; i < len; ++i) { if (selectedSteps[i].checked) { var nameAndStep = selectedSteps[i].value.split('___'); if (this.projectInfo_ && this.projectInfo_.getLoadFrom() == rpf.LoaderDialog.Locations.LOCAL) { this.updateElementInTest_(nameAndStep[0], nameAndStep[1], newCmdMap); } else { this.updateElement_(nameAndStep[1], newCmdMap, this.infoMap_ || {}); } } } // In this case, we need to load the project from local first to make sure // it's the latest code before modifing the tests. if (this.projectInfo_ && this.projectInfo_.getLoadFrom() == rpf.LoaderDialog.Locations.LOCAL) { this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.SAVE_PROJECT_LOCALLY, 'params': {'project': {'name': this.getProjectName_(), 'tests': this.projectInfo_.getTests()}}}); } this.handleCancelButton_(onCancelHandler); }; /** * Cancel button handler. * @param {function()} onCancelHandler The handler to cancel the update. * @private */ rpf.ConsoleManager.prototype.handleCancelButton_ = function(onCancelHandler) { onCancelHandler(); this.updateAllHandler_.removeAll(); }; /** * Gets the steps with the same xpath in the current opened project. * @param {string} oldXpath The old xpath. * @return {Array} The array of steps. * @private */ rpf.ConsoleManager.prototype.getStepsWithSameXpath_ = function(oldXpath) { var allSteps = []; var tests = this.projectInfo_.getTests(); for (var i = 0, len = tests.length; i < len; ++i) { var testObj = bite.base.Helper.getTestObject(tests[i]['test']); var result = bite.console.Helper.trimInfoMap(testObj['datafile']); var testName = testObj['name']; var stepsOfTest = this.getStepsFromInfoMap_( testName, result['infoMap'], oldXpath); if (stepsOfTest) { allSteps = allSteps.concat(stepsOfTest); } } if (allSteps.length == 0) { return null; } return allSteps; }; /** * Gets the steps with the same xpath from infoMap. * @param {string} testName The test name. * @param {Object} infoMap The infoMap of the test. * @param {string} oldXpath The old xpath. * @return {Array} The array of steps. * @private */ rpf.ConsoleManager.prototype.getStepsFromInfoMap_ = function( testName, infoMap, oldXpath) { var allSteps = []; var steps = infoMap['steps']; var elems = infoMap['elems']; for (var step in steps) { var elemId = steps[step]['elemId']; var elem = elems[elemId]; if (elem && elem['xpaths'][0] == oldXpath) { allSteps.push({'testName': testName, 'stepName': steps[step]['stepName'], 'elemId': elemId}); } } if (allSteps.length == 0) { return null; } return allSteps; }; /** * @param {string} action The action to be logged in console. * @param {string} label The label string. * @private */ rpf.ConsoleManager.logEvent_ = function(action, label) { chrome.extension.sendRequest({'action': Bite.Constants.HUD_ACTION.LOG_EVENT, 'category': 'ConsoleManager', 'event_action': action, 'label': label}); }; /** * Sets the doc string. * @param {string} url The url. * @export */ rpf.ConsoleManager.prototype.setDocString = function(url) { var domain = new goog.Uri(url).getDomain(); var docString = bite.console.Helper.getDocString(domain, this.userId_); this.editorMngr_.setCode(docString + this.editorMngr_.getCode()); }; /** * @return {boolean} Whether or not is recording. * @export */ rpf.ConsoleManager.prototype.isRecording = function() { return this.isRecording_; }; /** * @return {boolean} Whether or not is playing back. * @export */ rpf.ConsoleManager.prototype.isPlaying = function() { return this.isPlaying_; }; /** * @return {Bite.Constants.ConsoleModes} The current mode. * @export */ rpf.ConsoleManager.prototype.getMode = function() { return this.mode_; }; /** * @return {Object} The buttons displayed on console UI. * @export */ rpf.ConsoleManager.prototype.getButtons = function() { return this.btns_; }; /** * @return {rpf.ConsoleManager.ModeInfo} The modeInfo static object. * @export */ rpf.ConsoleManager.prototype.getModeInfo = function() { return this.modeInfo_; }; /** * @return {number} The line number that should be highlighted. * @export */ rpf.ConsoleManager.prototype.getLineHighlighted = function() { return this.lineHighlighted_; }; /** * @return {Object} The mode selector. * @export */ rpf.ConsoleManager.prototype.getModeSelector = function() { return this.modeSelector_; }; /** * @return {Bite.Constants.ViewModes} The current view mode. * @export */ rpf.ConsoleManager.prototype.getViewMode = function() { return this.viewMode_; }; /** * @return {number} The line to be inserted. * @export */ rpf.ConsoleManager.prototype.getLineToInsert = function() { return this.lineToInsert_; }; /** * @param {number} line The line to be inserted. * @export */ rpf.ConsoleManager.prototype.setLineToInsert = function(line) { this.lineToInsert_ = line; }; /** * @return {rpf.EditorManager} The editor manager. * @export */ rpf.ConsoleManager.prototype.getEditorManager = function() { return this.editorMngr_; }; /** * @return {rpf.ExportDialog} The loader dialog. * @export */ rpf.ConsoleManager.prototype.getExportDialog = function() { return this.exportDialog_; }; /** * @return {rpf.LoaderDialog} The loader dialog. * @export */ rpf.ConsoleManager.prototype.getLoaderDialog = function() { return this.loaderDialog_; }; /** * @return {rpf.ValidateDialog} The validation dialog. * @export */ rpf.ConsoleManager.prototype.getValidationDialog = function() { return this.validationDialog_; }; /** * @return {rpf.NotesDialog} The notes dialog. * @export */ rpf.ConsoleManager.prototype.getNotesDialog = function() { return this.notesDialog_; }; /** * @return {rpf.DetailsDialog} The details dialog. * @export */ rpf.ConsoleManager.prototype.getDetailsDialog = function() { return this.detailsDialog_; }; /** * @return {rpf.PlayDialog} The playback dialog. * @export */ rpf.ConsoleManager.prototype.getPlaybackRuntimeDialog = function() { return this.playbackRuntimeDialog_; }; /** * @return {rpf.ScreenShotDialog} The screenshot dialog. * @export */ rpf.ConsoleManager.prototype.getScreenshotDialog = function() { return this.screenshotDialog_; }; /** * @return {rpf.SettingDialog} The setting dialog. * @export */ rpf.ConsoleManager.prototype.getSettingDialog = function() { return this.settingDialog_; }; /** * @return {rpf.QuickCmdDialog} The quick commands dialog. * @export */ rpf.ConsoleManager.prototype.getQuickDialog = function() { return this.quickDialog_; }; /** * @return {rpf.InfoDialog} The info dialog. * @export */ rpf.ConsoleManager.prototype.getInfoDialog = function() { return this.infoDialog_; }; /** * Pops up the detailed info dialog. * @param {Object} e The event object. * @private */ rpf.ConsoleManager.prototype.popupDetailedInfo_ = function(e) { var currentLineNumber = this.editorMngr_.getCurrentSelection().start['row']; this.popDescInfoMap_(currentLineNumber); }; /** * Get desc info to pop up. * @param {number} lineNum The line number. * @return {boolean} Whether pops up the detail info. * @private */ rpf.ConsoleManager.prototype.popDescInfoMap_ = function(lineNum) { var desc = ''; var translation = ''; var id = ''; var cmd = this.editorMngr_.getOriginalLineAt(lineNum); var xpath = ''; var descObj = this.editorMngr_.checkHasDesc(lineNum); //To support legacy code format. if (descObj) { desc = descObj['desc']; translation = descObj['translation']; id = rpf.MiscHelper.getCmdId(cmd); } else { var elemMap = rpf.MiscHelper.getElemMap( this.editorMngr_.getTextAtLine(lineNum), this.infoMap_); if (elemMap['xpaths']) { // New code format. desc = elemMap['descriptor']; id = bite.base.Helper.getStepId(cmd); xpath = elemMap['xpaths'][0]; } } if (desc) { this.updateHighlightLine(lineNum); this.detailsDialog_.updateInfo( desc, lineNum, translation, id, xpath, this.infoMap_); return true; } else { return false; } }; /** * Finds the next command has descriptor. * @param {number} line The line number. * @export */ rpf.ConsoleManager.prototype.findNextCmd = function(line) { var lineNum = line + 1; var totalNum = this.editorMngr_.getTotalLineCount(); for (var i = lineNum; i <= totalNum; i++) { if (this.popDescInfoMap_(i)) { return; } } }; /** * Finds the previous command which has descriptor. * @param {number} line The line number. * @export */ rpf.ConsoleManager.prototype.findPrevCmd = function(line) { var lineNum = line - 1; if (lineNum < 0) { return; } for (var i = lineNum; i >= 0; i--) { if (this.popDescInfoMap_(i)) { return; } } }; /** * Logs info on console. * @param {string} log Log string. * @param {rpf.ConsoleLogger.LogLevel=} opt_level Log level. * @param {rpf.ConsoleLogger.Color=} opt_color Log color. * @export */ rpf.ConsoleManager.prototype.logInfo = function(log, opt_level, opt_color) { var level = opt_level || rpf.ConsoleLogger.LogLevel.INFO; var color = opt_color || rpf.ConsoleLogger.Color.BLACK; console.log('On console side: ' + log); this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.SAVE_LOG_AND_HTML, 'params': {'log': log, 'level': level, 'color': color}}); this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.GET_LOGS_AS_STRING, 'params': {}}, goog.bind(this.updateLogDialog_, this)); }; /** * Sets the console status. * @param {string} status Status string. * @param {string=} opt_color Status color. * @export */ rpf.ConsoleManager.prototype.setStatus = function(status, opt_color) { var color = opt_color || 'blue'; var statusDiv = '<div style="color:' + color + '">' + status + '</div>'; goog.dom.getElement(Bite.Constants.RpfConsoleId.ELEMENT_STATUS).innerHTML = statusDiv; }; /** * Updates the log dialog. * @param {Object} response The response object. * @private */ rpf.ConsoleManager.prototype.updateLogDialog_ = function(response) { goog.dom.getElement('logs').innerHTML = response['logHtml']; }; /** * Opens the validation dialog. * @param {Object} request The relevant info of an element. * @export */ rpf.ConsoleManager.prototype.openValidationDialog = function(request) { this.validationDialog_.openValidationDialog(request); this.validationDialog_.setVisible(true); }; /** * Updates the playback status. * @param {string} status The status string. * @param {string} color The color code. * @export */ rpf.ConsoleManager.prototype.updatePlaybackStatus = function(status, color) { this.playbackRuntimeDialog_.updatePlaybackStatus(status, color); }; /** * Adds a new created command in the UI. * @param {string} cmd The generated command. * @param {string} data The data string. * @export */ rpf.ConsoleManager.prototype.addNewCreatedCmdInBox = function(cmd, data) { goog.dom.getElement('newCmdBox').value = cmd; this.playbackRuntimeDialog_.tempCmd = cmd; this.playbackRuntimeDialog_.tempData = data; }; /** * Pauses playback. * @param {boolean=} opt_uiOnly Whether to involve the call to * the backend. * @export */ rpf.ConsoleManager.prototype.setPlaybackPause = function(opt_uiOnly) { this.playbackRuntimeDialog_.setPlaybackPause(opt_uiOnly); }; /** * Stops playback. * @param {boolean=} opt_uiOnly Whether to involve the call to * the backend. * @export */ rpf.ConsoleManager.prototype.setPlaybackStop = function(opt_uiOnly) { this.playbackRuntimeDialog_.setPlaybackStop(opt_uiOnly); }; /** * Sets the project info. * @param {string} name The project name. * @param {Array} tests The test array. * @param {string} loadFrom Either from web or local. * @param {Object=} opt_details The optional details of the project. */ rpf.ConsoleManager.prototype.setProjectInfo = function( name, tests, loadFrom, opt_details) { this.projectInfo_.setProjectName(name); this.projectInfo_.setTests(tests); this.projectInfo_.setLoadFrom(loadFrom); this.projectInfo_.setDetails(opt_details); this.updateProjectInfoUi_(); this.updateProjectJsFiles_(opt_details || {}); }; /** * Updates the project JS files. * @param {!Object} details The project details. * @private */ rpf.ConsoleManager.prototype.updateProjectJsFiles_ = function(details) { var file = ''; if (details['js_files'] && typeof(details['js_files']) == 'object') { // Before implementing multiple JS supports, // we use the first JS in the file. if (details['js_files'][0]) { file = details['js_files'][0]['code'] || ''; } } this.notesDialog_.replaceContent(file); }; /** * Updates the editor highlighted line. * @param {number} line Line number. * @export */ rpf.ConsoleManager.prototype.updateHighlightLine = function(line) { this.lineHighlighted_ = line; this.editorMngr_.clearGutterDecoration(); if (line >= 0) { this.editorMngr_.addRunningClass(line); } }; /** * Updates the current step in UI. * @param {number} curStep Current step. * @export */ rpf.ConsoleManager.prototype.updateCurrentStep = function(curStep) { var currentStep = ''; this.editorMngr_.clearGutterDecoration(); if (curStep >= 0) { for (var i = 0; i < curStep; i++) { this.editorMngr_.addPassedClass(i); } this.editorMngr_.addRunningClass(curStep); currentStep = curStep + 1 + ''; } goog.dom.getElement('playbackcurrentstep').value = currentStep; }; /** * Gets the to-be inserted line number. * @return {number} The line to be inserted. * @export */ rpf.ConsoleManager.prototype.getInsertLineNum = function() { if (this.lineToInsert_ != -1) { return this.lineToInsert_; } else { return this.editorMngr_.getTotalLineCount() - 1; } }; /** * Adds a new generated command in console text fields. * @param {string} pCmd The generated puppet command. * @param {string=} opt_dCmd The generated data command (optional). * @param {number=} opt_index Add the commmand at the given line. * @param {Object=} opt_cmdMap The command map. * @export */ rpf.ConsoleManager.prototype.addNewCommand = function( pCmd, opt_dCmd, opt_index, opt_cmdMap) { var dCmd = opt_dCmd || ''; var code = this.editorMngr_.getTempCode(); if (this.viewMode_ == Bite.Constants.ViewModes.CODE) { code = this.editorMngr_.getCode(); } var scnshotId = goog.string.getRandomString(); if (opt_cmdMap) { scnshotId = opt_cmdMap['id']; bite.console.Helper.assignInfoMap(this.infoMap_, opt_cmdMap); } var newCode = ''; if (this.lineToInsert_ != -1) { var allLines = code.split('\n'); allLines.splice(this.lineToInsert_, 0, pCmd); newCode = allLines.join('\n'); this.lineToInsert_ += 1; } else { newCode = code + pCmd + '\n'; } if (opt_index && opt_index == -1) { // TODO(phu): Optimize the way to get screenshots. this.screenshotDialog_.getScreenshotManager().addIndex(scnshotId); } this.addNewData_(dCmd); if (this.viewMode_ == Bite.Constants.ViewModes.CODE) { this.editorMngr_.setCode(newCode); } else { this.editorMngr_.setTempCode(newCode); this.editorMngr_.setReadableCode(); } if (this.isPlaying_) { console.log('Will try to insert the generated line in playback script.'); this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.INSERT_CMDS_WHILE_PLAYBACK, 'params': {'scriptStr': pCmd, 'data': dCmd}}); } }; /** * Adds the new data in datafile. * @param {string=} opt_dCmd The generated data command. * @private */ rpf.ConsoleManager.prototype.addNewData_ = function(opt_dCmd) { if (opt_dCmd) { var curDataValue = this.getDatafile_(); this.setDatafile_(curDataValue + opt_dCmd + '\n'); } }; /** * Shows the notes dialog up. * @export */ rpf.ConsoleManager.prototype.showNotes = function() { rpf.ConsoleManager.logEvent_('Notes', ''); this.notesDialog_.setVisible(true); }; /** * Shows the playback runtime dialog up. * @export */ rpf.ConsoleManager.prototype.showPlaybackRuntime = function() { rpf.ConsoleManager.logEvent_('Play', 'IS_RECORDING: ' + this.isRecording_); if (this.isRecording_) { this.setStatus('Can not playback while recording.', 'red'); throw new Error('Can not play back during recording.'); } this.playbackRuntimeDialog_.setVisible(true); this.messenger_.sendStatusMessage( Bite.Constants.COMPLETED_EVENT_TYPES.PLAYBACK_DIALOG_OPENED); }; /** * Shows the screenshot dialog up. * @export */ rpf.ConsoleManager.prototype.showScreenshot = function() { rpf.ConsoleManager.logEvent_('ShowScreenshot', ''); this.screenshotDialog_.setVisible(true); }; /** * Shows the setting dialog up. * @export */ rpf.ConsoleManager.prototype.showSetting = function() { rpf.ConsoleManager.logEvent_('Setting', ''); this.settingDialog_.setVisible(true); }; /** * Shows the quick commands dialog up. * @export */ rpf.ConsoleManager.prototype.showQuickCmds = function() { rpf.ConsoleManager.logEvent_('AddComds', ''); this.quickDialog_.setVisible(true); }; /** * Shows the info dialog up. * @export */ rpf.ConsoleManager.prototype.showInfo = function() { rpf.ConsoleManager.logEvent_('Info', ''); this.infoDialog_.setVisible(true); }; /** * Shows the save dialog up. * @export */ rpf.ConsoleManager.prototype.showSaveDialog = function() { rpf.ConsoleManager.logEvent_('Save', ''); this.saveTest(); }; /** * Gets the user lib if there is one. * @return {string} User's own lib string. * @export */ rpf.ConsoleManager.prototype.getUserLib = function() { return this.notesDialog_.getUserLib(); }; /** * Opens the project export dialog. */ rpf.ConsoleManager.prototype.showExportDialog = function() { rpf.ConsoleManager.logEvent_('Export', ''); this.exportDialog_.setVisible(true); }; /** * Opens the tests loader dialog. */ rpf.ConsoleManager.prototype.loadCmds = function() { rpf.ConsoleManager.logEvent_('Load', ''); this.handleInfoPanelButton_( Bite.Constants.RpfConsoleInfoType.PROJECT_INFO); }; /** * Gets the script id. * @return {string} The script id. * @private */ rpf.ConsoleManager.prototype.getScriptId_ = function() { var idElement = goog.dom.getElement( Bite.Constants.RpfConsoleId.ELEMENT_TEST_ID); return idElement.getAttribute('title') || ''; }; /** * Sets the script id. * @param {string} id Sets the id. * @private */ rpf.ConsoleManager.prototype.setScriptId_ = function(id) { var idElement = goog.dom.getElement( Bite.Constants.RpfConsoleId.ELEMENT_TEST_ID); idElement.setAttribute('title', id); }; /** * Updates the script related information. * @param {string} name The test name. * @param {string} url The test start URL. * @param {string} script The test content. * @param {string} datafile The test input data. * @param {string} userLib The user's own lib. * @param {string=} opt_id The test id. * @param {string=} opt_projectName The project name. * @export */ rpf.ConsoleManager.prototype.updateScriptInfo = function( name, url, script, datafile, userLib, opt_id, opt_projectName) { var projectName = opt_projectName || ''; this.setTestName_(name); this.setScriptId_(opt_id || ''); this.setStartUrl(url); var result = bite.console.Helper.trimInfoMap(datafile); this.setDatafile_(result['datafile']); this.infoMap_ = result['infoMap']; if (this.viewMode_ == Bite.Constants.ViewModes.CODE) { this.editorMngr_.setCode(script); this.editorMngr_.setTempCode(''); } else if (this.viewMode_ == Bite.Constants.ViewModes.READABLE) { this.editorMngr_.setTempCode(script); this.editorMngr_.setReadableCode(); } this.projectInfo_.setProjectName(projectName); this.messenger_.sendStatusMessage( Bite.Constants.COMPLETED_EVENT_TYPES.FINISHED_LOAD_TEST_IN_CONSOLE); }; /** * Gets the datafile content. * @return {string} The datafile string. * @private */ rpf.ConsoleManager.prototype.getDatafile_ = function() { return goog.dom.getElement(Bite.Constants.RpfConsoleId.DATA_CONTAINER).value; }; /** * Sets the datafile content. * @param {string} value The datafile string. * @private */ rpf.ConsoleManager.prototype.setDatafile_ = function(value) { goog.dom.getElement(Bite.Constants.RpfConsoleId.DATA_CONTAINER).value = value; }; /** * Checks if the current script is runnable. * @return {boolean} Whether or not the script is runnable. * @private */ rpf.ConsoleManager.prototype.checkRunnable_ = function() { var startUrl = this.getStartUrl(); var scripts = this.editorMngr_.getCode(); return goog.string.trim(startUrl) != '' && goog.string.trim(scripts) != ''; }; /** * Playbacks the test in the console. * @param {Bite.Constants.PlayMethods} method Method of playback. * @param {string=} opt_script The script to play. * @export */ rpf.ConsoleManager.prototype.startPlayback = function(method, opt_script) { console.log('rpf.ConsoleManager.prototype.startPlayback'); if (this.isRecording_) { this.setStatus('Can not playback while recording.', 'red'); throw new Error('Can not play back during recording.'); } var testNames = this.playbackRuntimeDialog_.getSelectedTests(); // The current logic is to use the "multiple replay" mode when there // are multiple tests selected, or single test which is the same one // currently loaded in the console. if (testNames.length > 1 || (testNames.length == 1 && testNames[0] != this.getTestName_())) { this.playbackRuntimeDialog_.setFinishedNumber(0); this.playbackRuntimeDialog_.setTotalNumber(testNames.length); this.playbackRuntimeDialog_.setMultipleTestsVisibility(true); this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.RUN_GROUP_TESTS, 'params': {'testNames': testNames, 'tests': this.projectInfo_.getTests(), 'runName': this.getProjectName_(), 'location': this.loaderDialog_.getStorageLocation()}}); return; } if (this.checkRunnable_()) { this.playbackRuntimeDialog_.setMultipleTestsVisibility(false); var scripts = opt_script ? opt_script : this.editorMngr_.getTempCode() || this.editorMngr_.getCode(); var datafile = this.getDatafile_(); var startUrl = goog.string.trim(this.getStartUrl()); var userLib = this.notesDialog_.getUserLibAsRunnable(); this.playbackRuntimeDialog_.clearMatchHtml(); this.setPlayStatus(true); this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.CHECK_PLAYBACK_OPTION_AND_RUN, 'params': {'method': method, 'startUrl': startUrl, 'scripts': scripts, 'infoMap': this.infoMap_, 'datafile': datafile, 'userLib': userLib}}, goog.bind(this.callbackOnStartPlayback_, this)); } else { this.setStatus( 'Please either load or record a script to playback.', 'red'); throw new Error('Error: Necessary fields were not all filled.'); } }; /** * The callback for starting playback. * @param {Object} response The response object. * @private */ rpf.ConsoleManager.prototype.callbackOnStartPlayback_ = function(response) { this.messenger_.sendStatusMessage( Bite.Constants.COMPLETED_EVENT_TYPES.PLAYBACK_STARTED); if (response['isPrepDone']) { this.playbackRuntimeDialog_.switchChoiceSet(false); } }; /** * Checks whether it's ready to enter update mode. * @private */ rpf.ConsoleManager.prototype.checkTabReadyToUpdate_ = function() { var message = {'command': Bite.Constants.CONSOLE_CMDS.ENTER_UPDATER_MODE, 'params': {}}; this.checkTabReady_(message); }; /** * Checks whether it's ready to enter update mode. * @param {Object} messageObj The message body object. * @private */ rpf.ConsoleManager.prototype.checkTabReady_ = function(messageObj) { this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.CHECK_READY_TO_RECORD, 'params': {}}, goog.bind(this.checkReadyCallback_, this, messageObj)); }; /** * Callback after checking the tab under record exists. * @param {Object} messageObj The message body object. * @param {Object} response The response object. * @private */ rpf.ConsoleManager.prototype.checkReadyCallback_ = function( messageObj, response) { if (response['success']) { this.messenger_.sendMessage(messageObj); } else { this.setStatus(response['message'], 'red'); } }; /** * Starts recording user's interactions. * @param {boolean=} opt_pass Whether pass the isPlaying_ checking. * @export */ rpf.ConsoleManager.prototype.startRecording = function(opt_pass) { rpf.ConsoleManager.logEvent_('Record', 'IS_PLAYING: ' + this.isPlaying_); var pass = opt_pass || false; if (this.isPlaying_ && !pass) { this.setStatus('Can not record while playing back a script.', 'red'); throw new Error('Can not record during playing back.'); } this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.CHECK_READY_TO_RECORD, 'params': {}}, goog.bind(this.checkReadyToRecordCallback_, this)); }; /** * Callback after checking the tab under record exists. * @param {Object} response The response object. * @private */ rpf.ConsoleManager.prototype.checkReadyToRecordCallback_ = function(response) { if (response['success']) { var url = goog.string.trim(this.getStartUrl()); if (!url) { this.setStartUrl(response['url']); this.setDocString(response['url']); } this.startRecording_(); } else { this.setStatus(response['message'], 'red'); } }; /** * Starts recording user's interactions. * @private */ rpf.ConsoleManager.prototype.startRecording_ = function() { this.switchInfoPanel_(Bite.Constants.RpfConsoleInfoType.PROJECT_INFO); this.setRecordStatus(true); this.changeMode(Bite.Constants.ConsoleModes.RECORD); var url = goog.string.trim(this.getStartUrl()); this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.START_RECORDING, 'params': {'info': {'pageMap': this.projectInfo_.getPageMap(), 'xpathFinderOn': this.settingDialog_.getUseXpath()}}}); }; /** * Callback for saving the script in the cloud. * @param {Object} response The response object. * @private */ rpf.ConsoleManager.prototype.saveTestCallback_ = function(response) { this.statusLogger_.setStatus(response['message'], response['color']); this.messenger_.sendStatusMessage( Bite.Constants.COMPLETED_EVENT_TYPES.TEST_SAVED); if (response['success']) { this.saveScript_(); // After saving the test, it needs to load the project again to sync up. this.loaderDialog_.loadProject( this.getProjectName_(), goog.bind(this.loadTestsInSelector_, this, goog.nullFunction, false, false)); } }; /** * Callback for loading the script in the cloud. * @param {Object} response The response object. * @private */ rpf.ConsoleManager.prototype.loadTestCallback_ = function(response) { this.statusLogger_.setStatus(response['message'], response['color']); this.changeMode(Bite.Constants.ConsoleModes.VIEW); this.messenger_.sendStatusMessage( Bite.Constants.COMPLETED_EVENT_TYPES.TEST_LOADED); if (response['success']) { var params = response['scriptInfo']; this.updateScriptInfo( params['name'], params['url'], params['script'], params['datafile'], params['userlib'], params['id'], params['projectname']); this.saveScript_(); } }; /** * Removes the redundant data from the ContentMap. * @param {string} datafile The data file. * @param {string} script The script. * @return {string} The new data file. * @private */ rpf.ConsoleManager.prototype.removeDatafileRedundant_ = function( datafile, script) { if (!datafile || !script) { return datafile; } // Assume each line contains only one data input in the following format: // ContentMap["abc"] = "hello"; var dataLines = datafile.split('\n'); for (var i = 0, len = dataLines.length; i < len; ++i) { var result = dataLines[i].match(/ContentMap\[\"(.*)\"\]/); if (!result || !result[1]) { continue; } if (script.indexOf(result[1]) == -1) { delete dataLines[i]; } } return dataLines.join('\n'); }; /** * Removes the redundant data from the infoMap. * @param {Object} infoMap The info map. * @param {string} script The script. * @param {Object} screenshots The screenshots. * @private */ rpf.ConsoleManager.prototype.removeInfoMapRedundant_ = function( infoMap, script, screenshots) { if (!infoMap || !infoMap['steps'] || !infoMap['elems']) { return; } var steps = infoMap['steps']; for (var stepId in steps) { if (script.indexOf(stepId) == -1) { var elemId = steps[stepId]['elemId']; if (infoMap['elems'][elemId]) { delete infoMap['elems'][elemId]; } if (screenshots[stepId]) { delete screenshots[stepId]; } delete steps[stepId]; } } }; /** * Gets the formatted screenshots data. * @return {Object} The screenshots info. * @private */ rpf.ConsoleManager.prototype.getScreenshots_ = function() { var screenshots = {}; var screenshotMgr = this.getScreenshotDialog().getScreenshotManager(); var scrShots = screenshotMgr.getScreenshots(); var scrSteps = screenshotMgr.getCmdIndices(); for (var i = 0; i < scrShots.length; i++) { screenshots[scrSteps[i]] = {}; screenshots[scrSteps[i]]['index'] = scrSteps[i]; screenshots[scrSteps[i]]['data'] = scrShots[i]; } return screenshots; }; /** * Saves the script locally or in the cloud. * @export */ rpf.ConsoleManager.prototype.saveTest = function() { var testName = 'testName'; var startUrl = goog.global.location.href; var scripts = this.recordedScript_; var datafile = 'datafile'; var userLib = 'userLib'; var projectName = 'projectName'; var saveWeb = true; var scriptId = ''; var screenshots = this.getScreenshots_(); testName = this.getTestName_(); saveWeb = goog.dom.getElement('location-web').checked; startUrl = this.getStartUrl(); scripts = this.editorMngr_.getTempCode() || this.getEditorManager().getCode(); datafile = this.getDatafile_(); // remove info map this.removeInfoMapRedundant_(this.infoMap_, scripts, screenshots); // remove data file datafile = this.removeDatafileRedundant_(datafile, scripts); datafile = bite.console.Helper.appendInfoMap(this.infoMap_, datafile); projectName = this.getProjectName_(); userLib = this.getUserLib(); scriptId = this.getScriptId_(); if (!goog.string.trim(testName) || !goog.string.trim(projectName)) { this.setStatus('Please provide both project and script name.', 'red'); this.switchInfoPanel_(Bite.Constants.RpfConsoleInfoType.PROJECT_INFO); return; } try { if (saveWeb) { this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.UPDATE_ON_WEB, 'params': {'testName': testName, 'startUrl': startUrl, 'scripts': scripts, 'datafile': datafile, 'userLib': userLib, 'projectName': projectName, 'screenshots': screenshots, 'scriptId': scriptId}}, goog.bind(this.saveTestCallback_, this)); } else { this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.SAVE_JSON_LOCALLY, 'params': {'testName': testName, 'startUrl': startUrl, 'scripts': scripts, 'datafile': datafile, 'userLib': userLib, 'projectName': projectName}}, goog.bind(this.saveTestCallback_, this)); } // Set status in rpf Console UI. this.statusLogger_.setStatus(rpf.StatusLogger.SAVING, '#777'); } catch (e) { // Set status in rpf Console UI. this.setStatus('Failed saving because: ' + e.toString(), 'red'); throw new Error(e); } }; /** * Sets the recording status. * @param {boolean} recording Whether or not is recording. * @export */ rpf.ConsoleManager.prototype.setRecordStatus = function(recording) { if (recording) { this.statusLogger_.setStatus(rpf.StatusLogger.START_RECORDING); this.isRecording_ = true; } else { this.statusLogger_.setStatus(rpf.StatusLogger.STOP_RECORDING); this.isRecording_ = false; } }; /** * Sets the palyback status. * @param {boolean} playing Whether or not is playing back. * @param {string=} opt_result The result. * @export */ rpf.ConsoleManager.prototype.setPlayStatus = function(playing, opt_result) { var result = opt_result || ''; if (playing) { this.statusLogger_.setStatus(rpf.StatusLogger.START_PLAYBACK); this.isPlaying_ = true; this.changeMode(Bite.Constants.ConsoleModes.PLAY); } else { if (opt_result.indexOf(rpf.ConsoleManager.Results.SUCCESS) != -1) { this.statusLogger_.setStatus(rpf.StatusLogger.PLAYBACK_SUCCESS, 'green'); } else if (opt_result.indexOf(rpf.ConsoleManager.Results.STOP) != -1) { this.statusLogger_.setStatus(rpf.StatusLogger.PLAYBACK_STOPPED, 'brown'); } else { this.statusLogger_.setStatus(rpf.StatusLogger.PLAYBACK_FAILED, 'red'); } this.isPlaying_ = false; if (this.mode_ != Bite.Constants.ConsoleModes.WORKER) { this.changeMode(Bite.Constants.ConsoleModes.VIEW); } } }; /** * Stops recording. * @export */ rpf.ConsoleManager.prototype.stopRecording = function() { rpf.ConsoleManager.logEvent_('Stop', ''); this.setRecordStatus(false); this.changeMode(Bite.Constants.ConsoleModes.VIEW); this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.STOP_RECORDING}); }; /** * Enters worker mode. * @export */ rpf.ConsoleManager.prototype.startWorkerMode = function() { rpf.ConsoleManager.logEvent_('StartWorker', ''); var workerSrc = goog.dom.getElement(rpf.ConsoleManager.Buttons.WORKER).src; if (workerSrc.indexOf('workermodeoff') != -1) { goog.dom.getElement(rpf.ConsoleManager.Buttons.WORKER).src = rpf.ConsoleManager.Images.WORKER; this.stopWorkerMode(); this.changeMode(Bite.Constants.ConsoleModes.VIEW); } else { goog.dom.getElement(rpf.ConsoleManager.Buttons.WORKER).src = rpf.ConsoleManager.Images.WORKER_OFF; this.messenger_.sendMessage( {'command': Bite.Constants.CONTROL_CMDS.START_WORKER_MODE}); this.changeMode(Bite.Constants.ConsoleModes.WORKER); } }; /** * Stops worker mode. * @export */ rpf.ConsoleManager.prototype.stopWorkerMode = function() { this.messenger_.sendMessage( {'command': Bite.Constants.CONTROL_CMDS.STOP_WORKER_MODE}); }; /** * Sets the test start URL. * @param {string} url The test start URL. * @export */ rpf.ConsoleManager.prototype.setStartUrl = function(url) { goog.dom.getElement(Bite.Constants.RpfConsoleId.ELEMENT_START_URL).value = url; }; /** * Gets the test start URL. * @return {string} The start url. * @export */ rpf.ConsoleManager.prototype.getStartUrl = function() { return goog.dom.getElement( Bite.Constants.RpfConsoleId.ELEMENT_START_URL).value; }; /** * Sets the test name. * @param {string} name The test name. * @private */ rpf.ConsoleManager.prototype.setTestName_ = function(name) { this.scriptSelector_.setValue(name); }; /** * Gets the test name. * @return {string} The test name. * @private */ rpf.ConsoleManager.prototype.getTestName_ = function() { return this.scriptSelector_.getValue(); }; /** * A class for handling flux modes info. * @constructor * @export */ rpf.ConsoleManager.ModeInfo = function() { /** * Mode and Buttons. * @type Object */ this.modeAndBtns = {}; this.modeAndBtns[Bite.Constants.ConsoleModes.IDLE] = {'desc': 'Load a script or begin recording to create a new one', 'btns': [rpf.ConsoleManager.Buttons.ADD_TEST, rpf.ConsoleManager.Buttons.LOAD, rpf.ConsoleManager.Buttons.PLAY, rpf.ConsoleManager.Buttons.RECORD, rpf.ConsoleManager.Buttons.EXPORT, rpf.ConsoleManager.Buttons.CONTENT_MAP, rpf.ConsoleManager.Buttons.NOTES, rpf.ConsoleManager.Buttons.SETTING, rpf.ConsoleManager.Buttons.REFRESH]}; this.modeAndBtns[Bite.Constants.ConsoleModes.RECORD] = {'desc': 'Take actions in the browser to record them as javascript', 'btns': [rpf.ConsoleManager.Buttons.STOP, rpf.ConsoleManager.Buttons.CONTENT_MAP, rpf.ConsoleManager.Buttons.NOTES, rpf.ConsoleManager.Buttons.SETTING, rpf.ConsoleManager.Buttons.REFRESH]}; this.modeAndBtns[Bite.Constants.ConsoleModes.PLAY] = {'desc': 'Play back a previously recorded script', 'btns': [rpf.ConsoleManager.Buttons.SETTING, rpf.ConsoleManager.Buttons.CONTENT_MAP, rpf.ConsoleManager.Buttons.NOTES, rpf.ConsoleManager.Buttons.PLAY, rpf.ConsoleManager.Buttons.REFRESH]}; this.modeAndBtns[Bite.Constants.ConsoleModes.DEFINE] = []; this.modeAndBtns[Bite.Constants.ConsoleModes.PAUSE] = []; this.modeAndBtns[Bite.Constants.ConsoleModes.WORKER] = {'desc': 'Serves as a worker, not under your control!', 'btns': [rpf.ConsoleManager.Buttons.SETTING, rpf.ConsoleManager.Buttons.REFRESH]}; this.modeAndBtns[Bite.Constants.ConsoleModes.UPDATER] = {'desc': 'Locator updater mode.', 'btns': [rpf.ConsoleManager.Buttons.REFRESH]}; this.modeAndBtns[Bite.Constants.ConsoleModes.VIEW] = {'desc': 'Review, modify or run a script', 'btns': [rpf.ConsoleManager.Buttons.ADD_TEST, rpf.ConsoleManager.Buttons.LOAD, rpf.ConsoleManager.Buttons.SAVE, rpf.ConsoleManager.Buttons.PLAY, rpf.ConsoleManager.Buttons.SCREEN, rpf.ConsoleManager.Buttons.RECORD, rpf.ConsoleManager.Buttons.EXPORT, rpf.ConsoleManager.Buttons.CONTENT_MAP, rpf.ConsoleManager.Buttons.NOTES, rpf.ConsoleManager.Buttons.SETTING, rpf.ConsoleManager.Buttons.REFRESH]}; }; /** * The callback function when a key down happens. * @param {Object} e The event object. * @private */ rpf.ConsoleManager.prototype.onKeyDown_ = function(e) { switch (e.keyCode) { case goog.events.KeyCodes.ALT: this.keyAlt_ = true; break; case goog.events.KeyCodes.S: if (this.keyAlt_) { if (!this.editorMngr_.getTempCode()) { this.modeSelector_.setSelectedIndex(1); this.selectViewReadableMode_(null); } else { this.modeSelector_.setSelectedIndex(0); this.selectViewCodeMode_(null); } this.keyAlt_ = false; } break; case goog.events.KeyCodes.V: if (this.keyAlt_) { var windowParam = goog.string.buildString( 'alwaysRaised=yes,', 'location=no,', 'resizable=yes,', 'scrollbars=no,', 'status=no,width=600,height=800,', 'left=300,top=100'); window.open( 'visualview.html', 'Visual View', windowParam); this.keyAlt_ = false; } break; } }; /** * The callback function when a key up happens. * @param {Object} e The event object. * @private */ rpf.ConsoleManager.prototype.onKeyUp_ = function(e) { if (e.keyCode == goog.events.KeyCodes.ALT) { this.keyAlt_ = false; } }; /** * Callback function for selecting code mode. * @param {Object} e The onclick event. * @private */ rpf.ConsoleManager.prototype.selectViewCodeMode_ = function(e) { rpf.ConsoleManager.logEvent_( 'SelectViewMode', 'VIEW_MODE: ' + Bite.Constants.ViewModes.CODE); if (this.viewMode_ == Bite.Constants.ViewModes.CODE) { return; } var bookData = goog.dom.getDocument().querySelector('#bookData'); if (bookData) { goog.style.showElement(this.editorMngr_.getContainer(), true); this.editorMngr_.setCode(this.editorMngr_.getTempCode()); bookData.innerHTML = ''; } this.viewMode_ = Bite.Constants.ViewModes.CODE; this.editorMngr_.setCode(this.editorMngr_.getTempCode()); this.editorMngr_.setTempCode(''); }; /** * Gets the infoMap object. * @return {Object} The info map of the script. */ rpf.ConsoleManager.prototype.getInfoMap = function() { return this.infoMap_; }; /** * Callback function for selecting readable mode. * @param {Object} e The onclick event. * @private */ rpf.ConsoleManager.prototype.selectViewReadableMode_ = function(e) { rpf.ConsoleManager.logEvent_( 'SelectViewMode', 'VIEW_MODE: ' + Bite.Constants.ViewModes.READABLE); if (this.viewMode_ == Bite.Constants.ViewModes.READABLE) { return; } this.viewMode_ = Bite.Constants.ViewModes.READABLE; this.editorMngr_.setTempCode(this.editorMngr_.getCode()); this.editorMngr_.setReadableCode(); }; /** * Callback function for selecting book mode. * @param {Object} e The onclick event. * @private */ rpf.ConsoleManager.prototype.selectViewBookMode_ = function(e) { rpf.ConsoleManager.logEvent_( 'SelectViewMode', 'VIEW_MODE: ' + Bite.Constants.ViewModes.BOOK); if (this.viewMode_ == Bite.Constants.ViewModes.BOOK || this.viewMode_ == Bite.Constants.ViewModes.READABLE) { return; } this.editorMngr_.setTempCode(this.editorMngr_.getCode()); this.viewMode_ = Bite.Constants.ViewModes.BOOK; goog.style.showElement(this.editorMngr_.getContainer(), false); var consoleBookData = goog.dom.getDocument().querySelector('#bookData'); var steps = bite.console.Helper.getStepsInfo( this.getScreenshotDialog().getScreenshotManager(), this.infoMap_, this.editorMngr_.getCode()); soy.renderElement( consoleBookData, bite.client.Templates.rpfConsole.showReadable, {'stepsInfo': steps}); bite.console.Helper.registerScreenChangeEvents( steps, goog.bind(this.onScreenChange_, this)); bite.console.Helper.changeScreen(steps[0]['id'], 'stepScreen'); }; /** * Callback function for selecting updater mode. * @param {Object} e The onclick event. * @private */ rpf.ConsoleManager.prototype.selectUpdaterMode_ = function(e) { this.changeMode(Bite.Constants.ConsoleModes.UPDATER); this.viewMode_ = Bite.Constants.ViewModes.UPDATER; goog.style.showElement(this.editorMngr_.getContainer(), false); this.modeSelector_.setVisible(false); this.locatorUpdater_ = new bite.locators.Updater(this.messenger_); this.locatorUpdater_.render(goog.dom.getElement('bookData')); this.checkTabReadyToUpdate_(); }; /** * On screenshot change handler. * @param {Event} e The event object. * @private */ rpf.ConsoleManager.prototype.onScreenChange_ = function(e) { var id = e.target.id; bite.console.Helper.changeScreen(id, 'stepScreen'); }; /** * Displays the mode text on console UI. * @param {Bite.Constants.ConsoleModes} mode The rpf mode. * @export */ rpf.ConsoleManager.prototype.changeMode = function(mode) { this.mode_ = mode; goog.global.document.title = 'RPF - ' + mode; for (var i in rpf.ConsoleManager.Buttons) { this.btns_[rpf.ConsoleManager.Buttons[i]].setVisible(false); } for (var i = 0; i < this.modeInfo_.modeAndBtns[this.mode_]['btns'].length; i++) { this.btns_[this.modeInfo_.modeAndBtns[this.mode_]['btns'][i]]. setVisible(true); } }; /** * Close the current RPF console. * @private */ rpf.ConsoleManager.prototype.onConsoleClose_ = function() { rpf.ConsoleManager.logEvent_('Close', ''); this.messenger_.sendMessage( {'command': Bite.Constants.CONTROL_CMDS.REMOVE_WINDOW}); }; /** * Refresh the current RPF console. * @private */ rpf.ConsoleManager.prototype.onConsoleRefresh_ = function() { rpf.ConsoleManager.logEvent_('Refresh', ''); this.messenger_.sendMessage( {'command': Bite.Constants.CONTROL_CMDS.CREATE_WINDOW, 'params': {'refresh': true}}); }; /** * Show more info in the console. * @private */ rpf.ConsoleManager.prototype.onShowMoreInfo_ = function() { }; /** * Handles button presses from the info panel toggling buttons. * @param {Bite.Constants.RpfConsoleInfoType} type The info state that was * pushed. * @private */ rpf.ConsoleManager.prototype.handleInfoPanelButton_ = function(type) { // If the currently selected button is hit again, hide the info panel. if (this.moreInfoState_ == type) { this.switchInfoPanel_(Bite.Constants.RpfConsoleInfoType.NONE); } else { this.switchInfoPanel_(type); } }; /** * Switches the info panel to the requested state. * @param {Bite.Constants.RpfConsoleInfoType} type The info state to switch to. * @private */ rpf.ConsoleManager.prototype.switchInfoPanel_ = function(type) { this.moreInfoState_ = type; // Shortcut for the ids enum. var ids = Bite.Constants.RpfConsoleId; var contentMap = goog.dom.getElement(ids.CONTENT_MAP_CONTAINER); var projectInfo = goog.dom.getElement(ids.PROJECT_INFO_CONTAINER); switch (type) { case Bite.Constants.RpfConsoleInfoType.NONE: this.btns_[rpf.ConsoleManager.Buttons.CONTENT_MAP].setSelected(false); this.btns_[rpf.ConsoleManager.Buttons.LOAD].setSelected(false); goog.style.showElement(contentMap, false); goog.style.showElement(projectInfo, false); break; case Bite.Constants.RpfConsoleInfoType.PROJECT_INFO: this.btns_[rpf.ConsoleManager.Buttons.CONTENT_MAP].setSelected(false); this.btns_[rpf.ConsoleManager.Buttons.LOAD].setSelected(true); goog.style.showElement(contentMap, false); goog.style.showElement(projectInfo, true); break; case Bite.Constants.RpfConsoleInfoType.CONTENT_MAP: this.btns_[rpf.ConsoleManager.Buttons.CONTENT_MAP].setSelected(true); this.btns_[rpf.ConsoleManager.Buttons.LOAD].setSelected(false); goog.style.showElement(contentMap, true); goog.style.showElement(projectInfo, false); break; } this.onResize_(); }; /** * Updates the UI to reflect the current project info. * @private */ rpf.ConsoleManager.prototype.updateProjectInfoUi_ = function() { this.setProjectNameUi_(this.projectInfo_.getProjectName()); }; /** * Sets the UI to reflect the project name. * @param {string} name The current project name. * @private */ rpf.ConsoleManager.prototype.setProjectNameUi_ = function(name) { var projectNameElement = goog.dom.getElement( Bite.Constants.RpfConsoleId.CURRENT_PROJECT); projectNameElement.value = name; };
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Unit tests for console UI. * * @author phu@google.com (Po Hu) */ goog.require('goog.testing.MockControl'); goog.require('goog.testing.PropertyReplacer'); goog.require('rpf.ConsoleManager'); goog.require('rpf.InfoDialog'); goog.require('rpf.LoaderDialog'); goog.require('rpf.NotesDialog'); goog.require('rpf.PlayDialog'); goog.require('rpf.QuickCmdDialog'); goog.require('rpf.SaveDialog'); goog.require('rpf.SaveLoadManager'); goog.require('rpf.ScreenShotDialog'); goog.require('rpf.SettingDialog'); goog.require('rpf.ValidateDialog'); var stubs_ = new goog.testing.PropertyReplacer(); var mockControl_ = null; var chrome = {}; var CodeMirror = {}; var JSON = {}; var localStorage = {'getItem': function() {}, 'setItem': function() {}}; function setUp() { mockControl_ = new goog.testing.MockControl(); chrome.extension = {}; stubs_.set(goog.global, 'chrome', chrome); } function tearDown() { mockControl_.$tearDown(); mockControl_ = null; stubs_.reset(); } function initStep() { var mockGetBackgroundPage = mockControl_.createFunctionMock('getBackgroundPage'); var mockGetTestNamesLocally_ = mockControl_.createFunctionMock('getTestNamesLocally'); mockGetTestNamesLocally_().$returns('c'); var mockGetAllFromWeb_ = mockControl_.createFunctionMock('getAllFromWeb'); mockGetAllFromWeb_(goog.testing.mockmatchers.isObject, goog.testing.mockmatchers.isString).$returns(); var mockGetJsonFromWTF_ = mockControl_.createFunctionMock('getJsonFromWTF'); mockGetJsonFromWTF_(undefined, 'console').$returns(); mockGetBackgroundPage().$returns( {'logger': {}, 'saveLoadMgr': {'getTestNamesLocally': mockGetTestNamesLocally_, 'getAllFromWeb': mockGetAllFromWeb_, 'getJsonFromWTF': mockGetJsonFromWTF_}}); mockGetBackgroundPage().$returns( {'logger': {}, 'saveLoadMgr': {'getTestNamesLocally': mockGetTestNamesLocally_, 'getAllFromWeb': mockGetAllFromWeb_, 'getJsonFromWTF': mockGetJsonFromWTF_}}); mockGetBackgroundPage().$returns( {'logger': {}, 'saveLoadMgr': {'getTestNamesLocally': mockGetTestNamesLocally_, 'getAllFromWeb': mockGetAllFromWeb_, 'getJsonFromWTF': mockGetJsonFromWTF_}}); return mockGetBackgroundPage; } function testSetVisible() { var mockParse_ = mockControl_.createFunctionMock('parse'); mockParse_('').$returns([]); JSON.parse = mockParse_; var mockCodeMirror_ = mockControl_.createStrictMock(CodeMirror); var mockCodeMirrorCtor_ = mockControl_.createGlobalFunctionMock('CodeMirror'); CodeMirror.replace = mockControl_.createFunctionMock('replace'); CodeMirror.replace(null).$returns('b'); mockCodeMirrorCtor_('b', goog.testing.mockmatchers.isObject). $returns(mockCodeMirror_); var mockGetBackgroundPage = initStep(); chrome.extension.getBackgroundPage = mockGetBackgroundPage; var mockEditor = {'win': {'attachEvent': function() {}}}; var mockGetCode = mockControl_.createFunctionMock('getCode'); mockGetCode().$returns('a'); mockEditor.getCode = mockGetCode; mockControl_.$replayAll(); var validateDialog = new rpf.ConsoleManager(mockEditor); mockControl_.$verifyAll(); } function testStartPlayback() { var mockParse_ = mockControl_.createFunctionMock('parse'); mockParse_('').$returns([]); JSON.parse = mockParse_; var mockCodeMirror_ = mockControl_.createStrictMock(CodeMirror); var mockCodeMirrorCtor_ = mockControl_.createGlobalFunctionMock('CodeMirror'); CodeMirror.replace = mockControl_.createFunctionMock('replace'); CodeMirror.replace(goog.testing.mockmatchers.isObject).$returns('b'); mockCodeMirrorCtor_('b', goog.testing.mockmatchers.isObject). $returns(mockCodeMirror_); var mockCheckRunnable = mockControl_.createMethodMock( rpf.ConsoleManager.prototype, 'checkRunnable_'); mockCheckRunnable().$returns(true); var mockSetPlayStatus = mockControl_.createMethodMock( rpf.ConsoleManager.prototype, 'setPlayStatus'); mockSetPlayStatus(true).$returns(true); var mockEditor = {'win': {'attachEvent': function() {}}}; var mockGetCode = mockControl_.createFunctionMock('getCode'); mockGetCode().$returns('a'); mockEditor.getCode = mockGetCode; var mockGetBackgroundPage = initStep(); mockGetBackgroundPage().$returns( {'playbackMgr': {'preparationDone_': true}}); var mockSetStepMode = mockControl_.createFunctionMock('setStepMode'); mockSetStepMode(false).$returns(true); mockGetBackgroundPage().$returns( {'playbackMgr': {'setStepMode': mockSetStepMode}}); var mockSetUserPauseReady = mockControl_.createFunctionMock('setUserPauseReady'); mockSetUserPauseReady(true).$returns(true); mockGetBackgroundPage().$returns( {'playbackMgr': {'setUserPauseReady': mockSetUserPauseReady}}); chrome.extension.getBackgroundPage = mockGetBackgroundPage; mockControl_.$replayAll(); var console = new rpf.ConsoleManager(mockEditor); console.startPlayback(Bite.Constants.PlayMethods.ALL); mockControl_.$verifyAll(); }
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains the worker mode manager. * * @author phu@google.com (Po Hu) * @suppress {constantProperty} TESTS_EXECUTION_SERVER_ is assigned * a value more than once */ goog.provide('rpf.WorkerManager'); goog.require('Bite.Constants'); goog.require('bite.base.Helper'); goog.require('bite.common.net.xhr.async'); goog.require('bite.options.constants'); goog.require('bite.options.data'); goog.require('goog.Timer'); goog.require('goog.array'); goog.require('goog.events'); goog.require('goog.json'); goog.require('goog.net.XhrIo'); goog.require('goog.userAgent'); goog.require('rpf.MiscHelper'); goog.require('rpf.soy.Dialog'); /** * This class manages running multiple tests by using the given playback * manager instance. The tests could be from multiple sources like * from RPF console, a link, or polling tests from server. * The worker manager will use rpfautomator to execute the test one by one. * @param {rpf.PlayBackManager} playbackMgr The playback manager. * @param {rpf.Automator} automator The rpf automator. * @param {rpf.ConsoleLogger} logger The console logger instance. * @param {function(Object, Object, function(Object))} eventMgrListener * The listener registered in eventsManager. * @param {function(Object, function(*)=)} sendMessageToConsole The * function to send message to console world. * @constructor */ rpf.WorkerManager = function( playbackMgr, automator, logger, eventMgrListener, sendMessageToConsole) { /** * The playback manager. * @type {rpf.PlayBackManager} * @private */ this.playbackMgr_ = playbackMgr; /** * The rpf automator. * @type {rpf.Automator} * @private */ this.automator_ = automator; /** * The console logger. * @type {rpf.ConsoleLogger} * @private */ this.logger_ = logger; /** * The event lisnener registered on event manager. * @type {function(Object, Object, function(Object))} * @private */ this.eventMgrListener_ = eventMgrListener; /** * The function to send message to console world. * @type {function(Object, function(*)=)} * @private */ this.sendMessageToConsole_ = sendMessageToConsole; /** * The test id. * @type {number} * @private */ this.autoRunningTestId_ = 0; /** * The result's unique info string. * @type {string} * @private */ this.newServerUniqueStr_ = ''; /** * If the worker is working. * @type {boolean} * @private */ this.isWorking_ = false; /** * Timer object for periodically polling Executor server. * @type {goog.Timer} * @private */ this.workerTimer_ = new goog.Timer( rpf.WorkerManager.RPF_WORKER_WAITING_INTERVAL_); /** * The test config dictionary. * @type {Object} * @private */ this.testConfig_ = {}; /** * The current run's key string. * @type {string} * @private */ this.currentRunKey_ = ''; /** * The data string. * @type {string} * @private */ this.dataStr_ = ''; /** * Current finished tests number. * @private */ this.finishedTestsNum_ = 0; this.playbackMgr_.setupWorkerCallbacks( goog.bind(this.getAutoRunningTestId, this), goog.bind(this.runNext, this)); }; /** * The worker token. * @type {string} * @export */ rpf.WorkerManager.token = ''; /** * @const The Tests Executor server. * @type {string} * @private */ rpf.WorkerManager.TESTS_EXECUTION_SERVER_ = bite.options.data.get(bite.options.constants.Id.SERVER_CHANNEL); /** * @const The period between two polling. * @type {number} * @private */ rpf.WorkerManager.RPF_WORKER_WAITING_INTERVAL_ = 5000; /** * The handler of suite executor, which will be deprecated soon. * @type {string} * @private */ rpf.WorkerManager.SuiteExecutorRequestsHandlerPath_ = '/requests'; /** * The handler path of new bite server. * @type {string} * @private */ rpf.WorkerManager.BiteServerUpdateResultHandlerPath_ = '/result/update'; /** * The handler path of starting a new run. * @type {string} * @private * @constant */ rpf.WorkerManager.BiteServerStartNewRunHandlerPath_ = '/run/add_realtime_run'; /** * Whether this is pointing to the new server. * @type {boolean} * @private */ rpf.WorkerManager.prototype.isNewServer_ = false; /** * Stops a group of tests. */ rpf.WorkerManager.prototype.stopGroupTests = function() { this.automator_.finish(); this.runFinishCallback_({}); }; /** * Runs a group of tests. * @param {Array} testNames The test names array. * @param {Array} tests The array of tests info. * @param {string} runName The run name. * @param {string=} opt_location Where the tests were loaded from. */ rpf.WorkerManager.prototype.runGroupTests = function( testNames, tests, runName, opt_location) { var location = opt_location || ''; this.finishedTestsNum_ = 0; var testsToRun = []; for (var i = 0, len = tests.length; i < len; ++i) { if (goog.array.contains(testNames, tests[i]['test_name'])) { testsToRun.push(tests[i]); } } if (testsToRun.length < 1) { return; } var stepArr = []; var testInfoArr = []; for (var i = 0, len = testsToRun.length; i < len; ++i) { this.pushTest_(testsToRun[i], stepArr, testInfoArr, location); } // Sends a ping to server and starts the current run. // It will receive the run key which will be used to update the results. this.startRunOnServer_(testInfoArr, runName); // Starts running all of the tests. this.automator_.start( stepArr, goog.bind(this.runFinishCallback_, this)); }; /** * The callback function when the current run is finished. * @param {Object} response The response object. * @private */ rpf.WorkerManager.prototype.runFinishCallback_ = function(response) { var fragment = goog.Uri.QueryData.createFromMap({ 'page': 'run_details', 'runKey': this.currentRunKey_ }); var fragment2 = goog.Uri.QueryData.createFromMap({ 'page': 'set_details', 'suiteName': 'testSuite', 'projectName': 'testProject' }); var resultUrl = rpf.WorkerManager.TESTS_EXECUTION_SERVER_ + '/home#' + fragment; var runsUrl = rpf.WorkerManager.TESTS_EXECUTION_SERVER_ + '/home#' + fragment2; var link = rpf.soy.Dialog.createRunsAndResultsLinks( {'links': {'runsUrl': runsUrl, 'resultUrl': resultUrl}}); // Reset the player if it was disrupted during playing back. if (this.playbackMgr_.isPreparationDone()) { this.playbackMgr_.setPreparationDone(false); } this.automator_.getEventTarget().dispatchEvent( Bite.Constants.COMPLETED_EVENT_TYPES.FINISHED_CURRENT_RUN); // This is to notify the UI with the result link. // TODO(phu): Should display the link in another area. goog.Timer.callOnce(goog.bind(this.sendMessageToConsole_, this, {'command': Bite.Constants.UiCmds.UPDATE_PLAYBACK_STATUS, 'params': {'text': link, 'color': 'green'}}), 1000); }; /** * Gets the user agent string. * @return {string} The user agent string. * @private */ rpf.WorkerManager.prototype.getUserAgent_ = function() { return goog.userAgent.getUserAgentString() || ''; }; /** * Sends the tests info to server and starts a new run. * @param {Array} testInfoArr The tests to be run. * @param {string} runName The run name. * @private */ rpf.WorkerManager.prototype.startRunOnServer_ = function( testInfoArr, runName) { var requestUrl = rpf.WorkerManager.TESTS_EXECUTION_SERVER_ + rpf.WorkerManager.BiteServerStartNewRunHandlerPath_; var parameters = goog.Uri.QueryData.createFromMap({ 'runName': runName, 'projectName': 'testProject', 'suiteName': 'testSuite', 'userAgent': this.getUserAgent_(), 'testInfoList': goog.json.serialize(testInfoArr)}).toString(); goog.net.XhrIo.send(requestUrl, goog.bind(function(e) { var xhr = e.target; if (xhr.isSuccess()) { this.currentRunKey_ = xhr.getResponseText(); } else { alert('error'); } }, this), 'POST', parameters); }; /** * Pushes a test in the array that will be automatically run. * @param {Object.<string, string, string>} test The test object. * @param {Array} stepArr The step array. * @param {Array} testInfoArr The array contains the basic test info. * @param {string} location The location where the tests were from. * @private */ rpf.WorkerManager.prototype.pushTest_ = function( test, stepArr, testInfoArr, location) { var id = test['id']; var testObj = bite.base.Helper.getTestObject(test['test']); var result = bite.console.Helper.trimInfoMap(testObj['datafile']); testInfoArr.push({'id': test['id'] || '', 'name': testObj['name']}); // Assume this is called by console UI for now. // The first step is to load the test in console UI. var temp = this.automator_.getStepObject( Bite.Constants.ListenerDestination.CONSOLE, Bite.Constants.UiCmds.UPDATE_SCRIPT_INFO, {'name': testObj['name'], 'url': testObj['url'], 'script': testObj['script'], 'datafile': testObj['datafile'], 'userlib': testObj['userlib'], 'id': id, 'projectname': testObj['projectname']}, Bite.Constants.COMPLETED_EVENT_TYPES.FINISHED_LOAD_TEST_IN_CONSOLE); stepArr.push(temp); // The second step is to run the test. temp = this.automator_.getStepObject( Bite.Constants.ListenerDestination.EVENT_MANAGER, Bite.Constants.CONSOLE_CMDS.CHECK_PLAYBACK_OPTION_AND_RUN, {'method': Bite.Constants.PlayMethods.ALL, 'startUrl': testObj['url'], 'scripts': testObj['script'], 'infoMap': result['infoMap'], 'datafile': result['datafile'], 'userLib': testObj['userlib'], 'needOverride': false, 'continueOnFailure': true, 'testName': testObj['name'], 'testId': id, 'projectName': testObj['projectname'], 'testLocation': location}, Bite.Constants.COMPLETED_EVENT_TYPES.FINISHED_RUNNING_TEST); stepArr.push(temp); temp = this.automator_.getStepObject( Bite.Constants.ListenerDestination.EVENT_MANAGER, Bite.Constants.CONSOLE_CMDS.UPDATE_TEST_RESULT_ON_SERVER, {}, Bite.Constants.COMPLETED_EVENT_TYPES.FINISHED_UPDATE_TEST_RESULT); stepArr.push(temp); }; /** * Logs info to logger. * @param {string} log Log info. * @param {rpf.ConsoleLogger.LogLevel} opt_level Log level. * @param {rpf.ConsoleLogger.Color} opt_color Log color. * @export */ rpf.WorkerManager.prototype.logInfo = function(log, opt_level, opt_color) { this.logger_.saveLogAndHtml(log, opt_level, opt_color); }; /** * Increases the finished tests number. */ rpf.WorkerManager.prototype.increaseFinishedTestsNum = function() { ++this.finishedTestsNum_; }; /** * Gets the finished tests number. * @return {number} The tests number. */ rpf.WorkerManager.prototype.getFinishedTestsNum = function() { return this.finishedTestsNum_; }; /** * Sets the worker url. * @param {string} url The executor server url. * @export */ rpf.WorkerManager.prototype.setWorkerUrl = function(url) { rpf.WorkerManager.TESTS_EXECUTION_SERVER_ = url; this.isWorking_ = false; }; /** * Sets the worker token. * @param {string} token The token string. * @export */ rpf.WorkerManager.prototype.setWorkerToken = function(token) { rpf.WorkerManager.token = token; }; /** * Starts working in worker mode. * @export */ rpf.WorkerManager.prototype.startWorkerMode = function() { if (this.workerTimer_.enabled) { this.workerTimer_.stop(); } this.workerTimer_ = new goog.Timer( rpf.WorkerManager.RPF_WORKER_WAITING_INTERVAL_); this.isWorking_ = false; this.autoRunningTestId_ = 0; this.workerTimer_.start(); goog.events.listen(this.workerTimer_, goog.Timer.TICK, this.fetchDashboardStatus, false, this); }; /** * Stops worker mode. * @export */ rpf.WorkerManager.prototype.stopWorkerMode = function() { if (this.workerTimer_.enabled) { this.workerTimer_.stop(); } goog.events.unlisten(this.workerTimer_, goog.Timer.TICK, this.fetchDashboardStatus, false, this); }; /** * Updates the Executor server with test results. * @param {number} testId The test id. * @param {Bite.Constants.WorkerResults} result The test result. * @param {string} dataUrl The screenshot data url. * @param {string} failureStr This contains relevant info of the failure. * @export */ rpf.WorkerManager.prototype.updateRunningTestStatus = function( testId, result, dataUrl, failureStr) { var log = failureStr; this.logger_.clearLogs(); var handler = rpf.WorkerManager.BiteServerUpdateResultHandlerPath_; var paramsMap = { 'result': goog.json.serialize({'result': { 'runKey': this.currentRunKey_, 'testName': this.playbackMgr_.getCurrentTestName(), 'testId': this.playbackMgr_.getCurrentTestId()}}), 'status': result, 'screenshot': dataUrl, 'log': log }; var requestUrl = rpf.MiscHelper.getUrl( rpf.WorkerManager.TESTS_EXECUTION_SERVER_, handler, {}); var parameters = goog.Uri.QueryData.createFromMap(paramsMap).toString(); bite.common.net.xhr.async.post( requestUrl, parameters, function(success) { if (success) { console.log('Successfully updated the test result for ' + testId); } }); }; /** * Polls the Executor server and get back the queued job. * @export */ rpf.WorkerManager.prototype.fetchDashboardStatus = function() { if (!this.isWorking_) { this.isWorking_ = true; // Blocks the worker poller. var handler = '/requests'; var parameters = { 'cmd': '3', 'tokens': rpf.WorkerManager.token, 'useragent': navigator.userAgent}; if (this.isNewServer_) { handler = '/result/fetch'; parameters = { 'tokens': rpf.WorkerManager.token }; } var requestUrl = rpf.MiscHelper.getUrl( rpf.WorkerManager.TESTS_EXECUTION_SERVER_, handler, parameters); goog.net.XhrIo.send(requestUrl, goog.bind(this.fetchDashboardStatusCallback_, this)); } }; /** * Callback handler for the fetch dashboard status. * @param {Event} e XhrIo event. * @private */ rpf.WorkerManager.prototype.fetchDashboardStatusCallback_ = function(e) { var xhr = /** @type {goog.net.XhrIo} */ (e.target); if (xhr.isSuccess()) { var resText = xhr.getResponseText(); if (resText == 'null') { this.isWorking_ = false; return; } console.log('Got response from Executor server:' + resText); if (resText && !this.autoRunningTestId_) { var obj = goog.json.parse(resText); if (obj && (typeof obj == 'object') && (obj['key'] || obj['result'])) { var testId = ''; if (!this.isNewServer_) { this.autoRunningTestId_ = obj['key']; this.testConfig_ = goog.json.parse(obj['config']); this.dataStr_ = obj['data_str']; testId = obj['id']; console.log('The data string is:' + this.dataStr_); } else { this.autoRunningTestId_ = obj['result']['id']; this.newServerUniqueStr_ = resText; testId = obj['result']['testId']; } } else { this.isWorking_ = false; } } else { this.isWorking_ = false; console.log('It is still running test id:' + this.autoRunningTestId_); } } else { this.isWorking_ = false; console.log('Failed to poll the tests execution server.' + 'Error status: ' + xhr.getStatus()); } }; /** * Kicks off the playback procedure. * @param {string} url The start url. * @param {string} script The test script. * @param {string} datafile The test datafile. * @param {string} userLib The user's lib. * @export */ rpf.WorkerManager.prototype.kickOffPlayback = function( url, script, datafile, userLib) { var startUrl = this.testConfig_['startUrl'] || this.testConfig_['StartUrl']; if (startUrl) { url = startUrl; } }; /** * Runs the next script after the previous one is done. * @param {Bite.Constants.WorkerResults} * doneResult The result of the previous script. * @param {number} winId The playback window id. * @param {string} dataUrl The img data url string. * @param {string} log The result log. */ rpf.WorkerManager.prototype.runNext = function( doneResult, winId, dataUrl, log) { rpf.MiscHelper.removeWindowById(winId); this.updateRunningTestStatus( this.autoRunningTestId_, doneResult, dataUrl, log); this.autoRunningTestId_ = 0; this.isWorking_ = false; // TODO(phu): Use hanging GET to solve. this.eventMgrListener_( {'command': Bite.Constants.CONSOLE_CMDS.EVENT_COMPLETED, 'params': {'eventType': Bite.Constants.COMPLETED_EVENT_TYPES.FINISHED_UPDATE_TEST_RESULT}}, {}, goog.nullFunction); }; /** * @return {number} The test id. * @export */ rpf.WorkerManager.prototype.getAutoRunningTestId = function() { return this.autoRunningTestId_; };
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains the console messenger. * * @author phu@google.com (Po Hu) */ goog.provide('rpf.Console.Messenger'); goog.require('Bite.Constants'); /** * A class for handling messages to the background world. * @constructor * @export */ rpf.Console.Messenger = function() { }; goog.addSingletonGetter(rpf.Console.Messenger); /** * Sends the message to listener registered in background world. * @param {Object} obj The object to be sent. * @param {function(Object)=} opt_callback The callback function to be called. * @export */ rpf.Console.Messenger.prototype.sendMessage = function(obj, opt_callback) { if (!obj['command']) { console.log('The command parameter is missing.'); return; } var callback = opt_callback || goog.nullFunction; console.log('Is sending command: ' + obj['command']); chrome.extension.sendRequest(obj, callback); }; /** * Sends a message to notify the specified action is completed. * This is useful especially for automating RPF behaviors. * @param {Bite.Constants.COMPLETED_EVENT_TYPES} eventType The event type. */ rpf.Console.Messenger.prototype.sendStatusMessage = function(eventType) { this.sendMessage({ 'command': Bite.Constants.CONSOLE_CMDS.EVENT_COMPLETED, 'params': {'eventType': eventType}}); };
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains RPF's additional info dialog. * It gets popped up when user clicks on the notes button in console. * * @author phu@google.com (Po Hu) */ goog.provide('rpf.NotesDialog'); goog.require('bite.common.net.xhr.async'); goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.events'); goog.require('goog.ui.CustomButton'); goog.require('goog.ui.Dialog'); goog.require('rpf.Console.Messenger'); /** * A class for writing additional test info including project name, * test name, start url, test data and user's own library. * @param {rpf.Console.Messenger} messenger The messenger instance. * @param {function(Bite.Constants.UiCmds, Object, Event)} onUiEvents * The function to handle the specific event. * @constructor * @export */ rpf.NotesDialog = function(messenger, onUiEvents) { /** * The notes dialog. * @type {goog.ui.Dialog} * @private */ this.notesDialog_ = new goog.ui.Dialog(); /** * The editor in notes dialog. * @type {Object} * @private */ this.editor_ = null; /** * The messenger. * @type {rpf.Console.Messenger} * @private */ this.messenger_ = messenger; /** * The function to handle the specific event. * @type {function(Bite.Constants.UiCmds, Object, Event)} * @private */ this.onUiEvents_ = onUiEvents; /** * Inits the notes dialog. */ this.initNotesDialog_(); /** * The editor manager. * @type {rpf.EditorManager} * @private */ this.editorMngr_ = new rpf.EditorManager( 'rpf-console-js-functions', goog.nullFunction, goog.nullFunction, goog.nullFunction); }; /** * Inits the toolbar. * @private */ rpf.NotesDialog.prototype.initToolbar_ = function() { var playBtn = new goog.ui.CustomButton('Play'); goog.events.listen( playBtn, goog.ui.Component.EventType.ACTION, goog.bind(this.playJsFile_, this)); playBtn.render(goog.dom.getElement('rpf-js-play-button')); }; /** * Plays the JS file in the tab under record. * @private */ rpf.NotesDialog.prototype.playJsFile_ = function() { this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.EXECUTE_SCRIPT_IN_RECORD_PAGE, 'params': {'code': this.editorMngr_.getCode(), 'allFrames': false}}); }; /** * Replaces the current JS content. * @param {string} code The JS code. */ rpf.NotesDialog.prototype.replaceContent = function(code) { this.editorMngr_.setCode(code); }; /** * Inits the notes dialog. * @private */ rpf.NotesDialog.prototype.initNotesDialog_ = function() { var dialogElem = this.notesDialog_.getContentElement(); this.notesDialog_.setTitle('Javascript functions'); this.notesDialog_.setButtonSet(null); this.notesDialog_.setVisible(true); this.notesDialog_.setVisible(false); bite.common.mvc.helper.renderModelFor(dialogElem, rpf.soy.Dialog.jsContent); this.initToolbar_(); }; /** * Resizes the window. This is necessary because css overflow does not * play nicely with percentages. */ rpf.NotesDialog.prototype.resize = function() { var dialogTitleHeight = 50; var dialogScreenPercentage = 0.8; var screenHeight = goog.dom.getViewportSize().height; var contentElem = this.notesDialog_.getContentElement(); var newHeight = screenHeight * dialogScreenPercentage - dialogTitleHeight; goog.style.setStyle( contentElem, {'padding': '0', 'height': newHeight}); goog.style.setStyle( goog.dom.getElement('rpf-console-js-functions'), {'width': goog.dom.getViewportSize().width, 'height': screenHeight * dialogScreenPercentage - dialogTitleHeight, 'font-size': '14px'}); this.editorMngr_.resize(); }; /** * Sets the visibility of the notes dialog. * @param {boolean} display Whether to show the dialog. * @export */ rpf.NotesDialog.prototype.setVisible = function(display) { this.notesDialog_.setVisible(display); if (display) { this.resize(); } }; /** * Gets the current user lib in Json format. * @return {string} The current user lib. */ rpf.NotesDialog.prototype.getUserLib = function() { var defaultFiles = [{'name': 'default', 'code': this.editorMngr_.getCode()}]; return goog.json.serialize(defaultFiles); }; /** * Gets the current user lib as a runnable string. * @return {string} The current user lib. */ rpf.NotesDialog.prototype.getUserLibAsRunnable = function() { return this.editorMngr_.getCode(); };
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains the console logger. * * @author phu@google.com (Po Hu) */ goog.provide('rpf.ConsoleLogger'); goog.require('goog.string'); /** * A class for logging info on console. * TODO (phu@google.com): consider integration with closure logger. * @constructor */ rpf.ConsoleLogger = function() { /** * The plain logs. * @type Array */ this.logs = []; /** * The better look logs in html formats. * @type Array */ this.logHtmls = []; }; goog.addSingletonGetter(rpf.ConsoleLogger); /** * Enum for log levels. * @enum {string} * @export */ rpf.ConsoleLogger.LogLevel = { INFO: 'info', WARNING: 'warning', ERROR: 'error', DEBUG: 'debug' }; /** * Enum for the corresponding colors of different log levels. * @enum {string} * @export */ rpf.ConsoleLogger.Color = { BLACK: 'black', YELLOW: 'yellow', RED: 'red', BLUE: 'blue', GREEN: 'green' }; /** * Gets the html of a given log. * @param {rpf.ConsoleLogger.LogLevel} logLevel Refers to saveLogAndHtml. * @param {rpf.ConsoleLogger.Color} logColor Refers to saveLogAndHtml. * @param {string} log Refers to saveLogAndHtml. * @return {string} The log html. * @private */ rpf.ConsoleLogger.prototype.getLogHtml_ = function( logLevel, logColor, log) { var timeStamp = rpf.MiscHelper.getTimeStamp(); return goog.string.buildString( timeStamp, '[', logLevel, ']', ': ', '<div style="font-size:12px;color:', logColor, '">', log, '</div>'); }; /** * Clears up the logs. * @export */ rpf.ConsoleLogger.prototype.clearLogs = function() { this.logs = []; this.logHtmls = []; }; /** * Get the logs as a string. * @return {Object} The response object. * @export */ rpf.ConsoleLogger.prototype.getLogsAsString = function() { var logHtmlStr = ''; for (var i = 0; i < this.logHtmls.length; i++) { logHtmlStr += this.logHtmls[i]; } return {'logHtml': logHtmlStr}; }; /** * Saves logs in both plain text and html formats. * @param {string} log The log string. * @param {rpf.ConsoleLogger.LogLevel} opt_level The level of this log. * @param {rpf.ConsoleLogger.Color} opt_color The color of the log. * @export */ rpf.ConsoleLogger.prototype.saveLogAndHtml = function( log, opt_level, opt_color) { var logLevel = rpf.ConsoleLogger.LogLevel.INFO; var logColor = rpf.ConsoleLogger.Color.BLACK; if (opt_level) { logLevel = opt_level; } if (opt_color) { logColor = opt_color; } this.logs.push(log); this.logHtmls.push(this.getLogHtml_(logLevel, logColor, log)); }; /** * Adds a debug level log. * @param {string} log The log string. * @export */ rpf.ConsoleLogger.prototype.debug = function(log) { this.saveLogAndHtml(log, rpf.ConsoleLogger.LogLevel.DEBUG, rpf.ConsoleLogger.Color.BLACK); }; /** * Adds a info level log. * @param {string} log The log string. * @export */ rpf.ConsoleLogger.prototype.info = function(log) { this.saveLogAndHtml(log, rpf.ConsoleLogger.LogLevel.INFO, rpf.ConsoleLogger.Color.BLACK); }; /** * Adds a warning level log. * @param {string} log The log string. * @export */ rpf.ConsoleLogger.prototype.warning = function(log) { this.saveLogAndHtml(log, rpf.ConsoleLogger.LogLevel.WARNING, rpf.ConsoleLogger.Color.YELLOW); }; /** * Adds a error level log. * @param {string} log The log string. * @export */ rpf.ConsoleLogger.prototype.error = function(log) { this.saveLogAndHtml(log, rpf.ConsoleLogger.LogLevel.ERROR, rpf.ConsoleLogger.Color.RED); };
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains RPF's info dialog. * It gets popped up when user clicks the log info button. * * @author phu@google.com (Po Hu) */ goog.provide('rpf.InfoDialog'); goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.events'); goog.require('goog.ui.Dialog'); /** * A class for showing info dialog for playback logs. * @constructor * @export */ rpf.InfoDialog = function() { /** * The info dialog. * @type {goog.ui.Dialog} * @private */ this.infoDialog_ = new goog.ui.Dialog(); /** * Inits the info dialog. */ this.initInfoDialog_(); }; /** * Sets the visibility of the info dialog. * @param {boolean} display Whether to show the dialog. * @export */ rpf.InfoDialog.prototype.setVisible = function(display) { this.infoDialog_.setVisible(display); }; /** * Inits the info dialog. * @private */ rpf.InfoDialog.prototype.initInfoDialog_ = function() { var dialogElem = this.infoDialog_.getContentElement(); var contentDiv = goog.dom.createDom(goog.dom.TagName.DIV, {'id': 'logs', 'style': 'height: 300px; overflow: scroll;'}); dialogElem.appendChild(contentDiv); this.infoDialog_.setTitle('Logs'); this.infoDialog_.setButtonSet(null); // The dialog seems not initializing before setting it visible. this.infoDialog_.setVisible(true); // Hide the dialog afterwards. this.infoDialog_.setVisible(false); };
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Unit tests for play dialog. * * @author phu@google.com (Po Hu) */ goog.require('goog.testing.MockControl'); goog.require('goog.testing.PropertyReplacer'); goog.require('goog.testing.mockmatchers'); goog.require('rpf.PlayDialog'); var stubs_ = new goog.testing.PropertyReplacer(); var mockControl_ = null; var chrome = {}; var consoleMgr = {}; var mockBackground = null; function setUp() { mockControl_ = new goog.testing.MockControl(); chrome.extension = {}; stubs_.set(goog.global, 'chrome', chrome); } function tearDown() { mockControl_.$tearDown(); mockControl_ = null; stubs_.reset(); } function testSetPlaybackAll() { }
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains the attributes manipulation. * * @author phu@google.com (Po Hu) */ goog.provide('rpf.Attributes'); goog.require('goog.dom'); goog.require('goog.dom.classes'); goog.require('goog.dom.TagName'); goog.require('goog.events'); goog.require('goog.style'); goog.require('goog.ui.CustomButton'); goog.require('goog.ui.Dialog'); goog.require('goog.ui.TabBar'); goog.require('goog.ui.ToggleButton'); goog.require('rpf.Console.Messenger'); /** * A class for attributes manipulation. * @param {rpf.Attributes.UITypes} id The type of this instance. It could be * either a details dialog instance or validation dialog instance. * @param {function(Bite.Constants.UiCmds, Object, Event, Function=)} onUiEvents * The function to handle the specific event. * @constructor * @export */ rpf.Attributes = function(id, onUiEvents) { /** * The element's descriptor which contains the attributes info. * @type {Object} * @private */ this.descriptor_ = null; /** * The callback function when generate the new descriptor. * @type {function()} * @private */ this.generateCmdCallback_ = goog.nullFunction; /** * The id of this instance. * @type {rpf.Attributes.UITypes} * @private */ this.id_ = id; /** * The current line number. * @type {number} * @private */ this.lineNum_ = -1; /** * The current level of descriptor that is selected. */ this.currentLevel_ = 0; /** * The messenger. * @type {rpf.Console.Messenger} * @private */ this.messenger_ = rpf.Console.Messenger.getInstance(); /** * The button to update the current element. * @type {goog.ui.ToggleButton} * @private */ this.updateButton_ = null; /** * The function to handle the specific event. * @type {function(Bite.Constants.UiCmds, Object, Event, Function=)} * @private */ this.onUiEvents_ = onUiEvents; }; /** * Enum for the attributes UI types. * @enum {string} */ rpf.Attributes.UITypes = { DETAILS_DIALOG: 'detailsDialog', VALIDATION_DIALOG: 'validationDialog' }; /** * Creates the attribute tabs. * @param {Object} dialog The dialog object. * @param {Object} descriptor The descriptor object. * @param {string} xpath The xpath of the current element. * @param {function()=} opt_callback The callback function. * @param {number=} opt_lineNum The line number. * @export */ rpf.Attributes.prototype.createAttrTabs = function( dialog, descriptor, xpath, opt_callback, opt_lineNum) { this.descriptor_ = descriptor; this.lineNum_ = opt_lineNum ? opt_lineNum : -1; this.generateCmdCallback_ = opt_callback || goog.nullFunction; var xpathTable = null; var xpathTitle = null; var updateXpathBtn = null; if (xpath) { xpathTitle = goog.dom.createDom(goog.dom.TagName.H3, {'class': 'componentName'}, 'Xpath'); xpathTable = goog.dom.createDom(goog.dom.TagName.TABLE, {'width': '100%', 'style': 'margin-bottom: 10px'}, goog.dom.createDom(goog.dom.TagName.TR, {}, goog.dom.createDom(goog.dom.TagName.TD, {'width': '80%'}, goog.dom.createDom(goog.dom.TagName.INPUT, {'type': 'text', 'style': 'width: 100%', 'id': 'xpath' + this.id_, 'value': xpath})))); var updateAllDiv = goog.dom.createDom(goog.dom.TagName.DIV, {'id': 'updateAllDivInAttribute' + this.id_}); } var tabBar = goog.dom.createDom(goog.dom.TagName.DIV, { 'id': 'top' + this.id_, 'class': 'goog-tab-bar' }); var tabBarTitle = goog.dom.createDom(goog.dom.TagName.H3, {'class': 'componentName'}, 'Attributes'); var clear = goog.dom.createDom(goog.dom.TagName.DIV, { 'class': 'goog-tab-bar-clear' }); var content = goog.dom.createDom(goog.dom.TagName.DIV, { 'class': 'goog-tab-content', 'id': 'top_content' + this.id_ }); var desc = descriptor; var maxLevel = 4; var index = 0; while (desc && index < maxLevel) { tabBar.appendChild(this.addNewTabForAttrs_(desc, index)); index += 1; desc = desc['parentElem']; } if (xpathTable) { dialog.appendChild(xpathTitle); dialog.appendChild(xpathTable); dialog.appendChild(updateAllDiv); } dialog.appendChild(tabBarTitle); dialog.appendChild(tabBar); dialog.appendChild(clear); dialog.appendChild(content); this.getButtonSet_(dialog); var topTab = new goog.ui.TabBar(); goog.events.listen(topTab, goog.ui.Component.EventType.SELECT, goog.bind(this.onTabSelected_, this)); topTab.decorate(goog.dom.getElement('top' + this.id_)); }; /** * Enters the updater mode and awaits the user to update the selected xpath. * @private */ rpf.Attributes.prototype.callbackStartUpdateMode_ = function() { var updateButton = this.updateButton_.getElement(); if (goog.dom.classes.has(updateButton, 'goog-custom-button-checked')) { this.updateButton_.setCaption('Stop'); this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.ENTER_UPDATER_MODE, 'params': {}}); this.onUiEvents_( Bite.Constants.UiCmds.CHECK_TAB_READY_TO_UPDATE, {}, /** @type {Event} */ ({})); this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.SET_ACTION_CALLBACK}, goog.bind(this.callbackOnReceiveAction_, this)); } else { this.setBackUpdateButton_(); } }; /** * Enters the updater mode and awaits the user to update the selected xpath. * @param {boolean=} opt_resetClass Whether to reset the class name. * @private */ rpf.Attributes.prototype.setBackUpdateButton_ = function(opt_resetClass) { this.updateButton_.setCaption('Update'); this.updateButton_.setState(goog.ui.Component.State.CHECKED, false); this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.END_UPDATER_MODE, 'params': {}}); }; /** * Get the xpath input element. * @return {Element} The xpath element. */ rpf.Attributes.prototype.getXpathInput = function() { return goog.dom.getElement('xpath' + this.id_); }; /** * When receives the new xpath, it replaces the old one with the new one. */ rpf.Attributes.prototype.updateElementInfo = function() { if (this.lineNum_ > 0) { var currentCmdMap = {}; currentCmdMap['xpaths'] = [this.getXpathInput().value]; currentCmdMap['descriptor'] = this.descriptor_; this.onUiEvents_( Bite.Constants.UiCmds.UPDATE_ELEMENT_AT_LINE, {'line': this.lineNum_, 'cmdMap': currentCmdMap}, /** @type {Event} */ ({}), goog.bind(this.showUpdateAllUi_, this)); } }; /** * When receives the new xpath, it replaces the old one with the new one. * @param {Object} response The response object. * @private */ rpf.Attributes.prototype.callbackOnReceiveAction_ = function(response) { this.setBackUpdateButton_(true); // Updates the xpath input. goog.dom.getElement('xpath' + this.id_).value = response['cmdMap']['xpaths'][0]; // Updates the descriptor inputs. this.descriptor_ = response['cmdMap']['descriptor']; this.showTabContent_(this.currentLevel_); }; /** * Shows the UI for suggesting the users to update all of the similar steps. * @param {Function} registerEvents The function to register events on * buttons in the UI. * @param {string} html The html string of the UI. * @private */ rpf.Attributes.prototype.showUpdateAllUi_ = function(registerEvents, html) { goog.dom.getElement('updateAllDivInAttribute' + this.id_).innerHTML = html; registerEvents(goog.bind(this.cancelUpdateAllUi_, this)); }; /** * Cancels the current batch updates, but this will not roll back any updates * that are made. * @private */ rpf.Attributes.prototype.cancelUpdateAllUi_ = function() { goog.dom.getElement('updateAllDivInAttribute' + this.id_).innerHTML = ''; }; /** * Gets the attributes buttons set. * @param {Object} dialog The container dialog. * @return {Object} The button set div element. * @private */ rpf.Attributes.prototype.getButtonSet_ = function(dialog) { var buttonSetDiv = goog.dom.createDom(goog.dom.TagName.DIV, { 'id': 'buttonSetDiv' + this.id_, 'style': 'text-align:left;padding-top:5px;' }); var updateButton = new goog.ui.ToggleButton('Update'); updateButton.setTooltip( 'Update the element in the tab under record by right click.'); this.updateButton_ = updateButton; var updateDiv = goog.dom.createDom(goog.dom.TagName.DIV, { 'id': 'updateDiv' + this.id_, 'style': 'display:inline' }); var testButton = new goog.ui.CustomButton('Ping'); testButton.setTooltip( 'Temporarily highlight the found elems in the tab under record.'); var testDiv = goog.dom.createDom(goog.dom.TagName.DIV, { 'id': 'testDiv' + this.id_, 'style': 'display:inline' }); var generateButton = new goog.ui.CustomButton('Save'); generateButton.setTooltip('Generate or update the step.'); var generateDiv = goog.dom.createDom(goog.dom.TagName.DIV, { 'id': 'generateDiv' + this.id_, 'style': 'display:inline' }); buttonSetDiv.appendChild(updateDiv); buttonSetDiv.appendChild(testDiv); buttonSetDiv.appendChild(generateDiv); dialog.appendChild(buttonSetDiv); generateButton.render(goog.dom.getElement('generateDiv' + this.id_)); if (this.id_ == rpf.Attributes.UITypes.DETAILS_DIALOG) { updateButton.render(goog.dom.getElement('updateDiv' + this.id_)); goog.events.listen(updateButton, goog.ui.Component.EventType.ACTION, this.callbackStartUpdateMode_, false, this); testButton.render(goog.dom.getElement('testDiv' + this.id_)); goog.events.listen(testButton, goog.ui.Component.EventType.ACTION, this.testDescriptor_, false, this); } else { goog.style.setStyle(testDiv, 'display', 'none'); } goog.events.listen(generateButton, goog.ui.Component.EventType.ACTION, this.generateDescriptor_, false, this); return buttonSetDiv; }; /** * Generates a the validation command. * @private */ rpf.Attributes.prototype.generateDescriptor_ = function() { this.updateDescriptor_(); this.generateCmdCallback_(); }; /** * Tests a descriptor in the page under record. * @private */ rpf.Attributes.prototype.testDescriptor_ = function() { this.updateDescriptor_(); var message = {'command': Bite.Constants.CONSOLE_CMDS.TEST_DESCRIPTOR, 'params': {'descriptor': this.descriptor_}}; this.onUiEvents_( Bite.Constants.UiCmds.CHECK_TAB_READY, {'message': message}, /** @type {Event} */ ({})); }; /** * Adds a new tab for the element's attributes. * @param {Object} descriptor Descriptor of the element. * @param {number} level Level of ancestor. * @return {Node} The tab object. * @private */ rpf.Attributes.prototype.addNewTabForAttrs_ = function( descriptor, level) { var classValue = 'goog-tab'; var tabName = ''; if (level == 0) { classValue += ' goog-tab-selected'; tabName = 'Recorded element'; } else if (level == 1) { tabName = 'Parent'; } else if (level == 2) { tabName = 'Grandparent'; } else { tabName = level + ' level ancestor'; } var tab = goog.dom.createDom('div', { 'class': classValue, 'id': this.id_ + 'tab_' + level }); goog.dom.setTextContent(tab, tabName); return tab; }; /** * Handles a tab selected event. * @param {Object} e The event object. * @private */ rpf.Attributes.prototype.onTabSelected_ = function(e) { var tabSelected = e.target; var id = tabSelected.getContentElement().id; var parts = id.split('_'); var level = parseInt(parts.pop(), 10); this.currentLevel_ = level; this.showTabContent_(level); }; /** * Show tab content. * @param {number} level The level. * @private */ rpf.Attributes.prototype.showTabContent_ = function(level) { var desc = this.descriptor_; for (var i = 0; i < level; i++) { desc = desc['parentElem']; } this.selectedTabLevelDesc_ = desc; this.selectedTabLevel_ = level; this.showElementAttrs_(desc, level); }; /** * Adds the table header for attributes. * @return {Node} A TR element. * @private */ rpf.Attributes.prototype.addTableHeader_ = function() { /** * <tr> * <td><div></td> * <td><div></td> * <td><div></td> * <td><div></td> * <td><div></td> * </tr> */ var row = goog.dom.createDom(goog.dom.TagName.TR, {}, goog.dom.createDom(goog.dom.TagName.TD, {}, goog.dom.createDom(goog.dom.TagName.DIV, {'class': 'console-attributes-row-div'}, 'Attribute')), goog.dom.createDom(goog.dom.TagName.TD, {}, goog.dom.createDom(goog.dom.TagName.DIV, {'class': 'console-attributes-row-div'}, 'Value')), goog.dom.createDom(goog.dom.TagName.TD, {}, goog.dom.createDom(goog.dom.TagName.DIV, {'class': 'console-attributes-row-div'}, 'Must')), goog.dom.createDom(goog.dom.TagName.TD, {}, goog.dom.createDom(goog.dom.TagName.DIV, {'class': 'console-attributes-row-div'}, 'Optional')), goog.dom.createDom(goog.dom.TagName.TD, {}, goog.dom.createDom(goog.dom.TagName.DIV, {'class': 'console-attributes-row-div'}, 'Ignore'))); return row; }; /** * Shows the element's attributes in UI. * @param {Object} descriptor The descriptor object of an elem. * @param {number} level The level of the elem's ancestor. * @private */ rpf.Attributes.prototype.showElementAttrs_ = function( descriptor, level) { var content = goog.dom.getElement('top_content' + this.id_); goog.dom.removeChildren(content); var table = goog.dom.createDom(goog.dom.TagName.TABLE, { 'id': 'elemAttrs' + this.id_, 'width': '100%' }); var th = this.addTableHeader_(); table.appendChild(th); var row = this.addRowOfAttr_('Tag:', descriptor.tagName, level); table.appendChild(row); row = this.addRowOfAttr_('Text:', descriptor.elementText, level); table.appendChild(row); var disabled = descriptor['disabled']; var checked = descriptor['checked']; var selectedIndex = descriptor['selectedIndex']; if (disabled) { row = this.addRowOfAttr_('Disabled:', disabled, level); } if (checked) { row = this.addRowOfAttr_('Checked:', checked, level); } if (selectedIndex) { row = this.addRowOfAttr_('SelectedIndex:', selectedIndex, level); } table.appendChild(row); for (var key in descriptor.attributes) { row = this.addRowOfAttr_(key + ':', descriptor.attributes[key], level); table.appendChild(row); } content.appendChild(table); }; /** * Adds a row of attribute. * @param {string} name The attribute's name. * @param {null|string|undefined} value The attribute's value. * @param {number} level The level of ancestor. * @return {Node} The row dom element. * @private */ rpf.Attributes.prototype.addRowOfAttr_ = function( name, value, level) { if (value == undefined) { return goog.dom.createDom(goog.dom.TagName.TR, {}, goog.dom.createDom(goog.dom.TagName.TD, {})); } var text = {}; var checked = true; var radioCheckedMust = false; var radioCheckedOptional = false; var radioCheckedIgnore = false; if (typeof(value) != 'string') { if (value['show'] == 'must') { radioCheckedMust = true; } else if (value['show'] == 'optional') { radioCheckedOptional = true; } else { radioCheckedIgnore = true; } value = value['value']; } else { radioCheckedOptional = true; } var radio1 = null; var radio2 = null; var radio3 = null; /** * <tr> * <td><div></td> * <td><input></td> * <td><input></td> * <td><input></td> * <td><input></td> * </tr> */ var row = goog.dom.createDom(goog.dom.TagName.TR, {}, goog.dom.createDom(goog.dom.TagName.TD, {'align': 'center', 'width': '10%', 'style': 'font: 13px verdana;'}, text = goog.dom.createDom(goog.dom.TagName.DIV, {})), goog.dom.createDom(goog.dom.TagName.TD, {'align': 'left', 'width': '30%'}, goog.dom.createDom(goog.dom.TagName.INPUT, { 'id': this.id_ + name + '_' + level, 'type': 'text', 'value': value, 'disabled': !checked})), goog.dom.createDom(goog.dom.TagName.TD, {'width': '20%', 'align': 'center'}, radio1 = goog.dom.createDom(goog.dom.TagName.INPUT, { 'name': this.id_ + 'radio_' + name + '_' + level, 'type': 'radio', 'value': 'must'})), goog.dom.createDom(goog.dom.TagName.TD, {'width': '20%', 'align': 'center'}, radio2 = goog.dom.createDom(goog.dom.TagName.INPUT, { 'name': this.id_ + 'radio_' + name + '_' + level, 'type': 'radio', 'value': 'optional'})), goog.dom.createDom(goog.dom.TagName.TD, {'width': '20%', 'align': 'center'}, radio3 = goog.dom.createDom(goog.dom.TagName.INPUT, { 'name': this.id_ + 'radio_' + name + '_' + level, 'type': 'radio', 'value': 'ignore'}))); radio1.checked = radioCheckedMust; radio2.checked = radioCheckedOptional; radio3.checked = radioCheckedIgnore; goog.events.listen(radio1, goog.events.EventType.CLICK, this.onUpdateAttr_, false, this); goog.events.listen(radio2, goog.events.EventType.CLICK, this.onUpdateAttr_, false, this); goog.events.listen(radio3, goog.events.EventType.CLICK, this.onUpdateAttr_, false, this); goog.dom.setTextContent(text, name); return row; }; /** * Updates the descriptor when user checks on/off an attribute. * @param {Object} e The event object. * @private */ rpf.Attributes.prototype.onUpdateAttr_ = function(e) { this.updateDescriptor_(); }; /** * Updates the descriptor. * @private */ rpf.Attributes.prototype.updateDescriptor_ = function() { var desc = this.selectedTabLevelDesc_; var level = this.selectedTabLevel_; desc.tagName = this.getNewValueObj_('Tag:_' + level); desc.elementText = this.getNewValueObj_('Text:_' + level); if (desc['checked']) { desc['checked'] = this.getNewValueObj_('Checked:_' + level); } if (desc['disabled']) { desc['disabled'] = this.getNewValueObj_('Disabled:_' + level); } if (desc['selectedIndex']) { desc['selectedIndex'] = this.getNewValueObj_('SelectedIndex:_' + level); } for (var key in desc.attributes) { desc.attributes[key] = this.getNewValueObj_(key + ':_' + level); } console.log('The new descriptor is:' + JSON.stringify(desc)); }; /** * Gets the attribute's value and show info. * @param {string} name The attribute's name. * @return {Object} The value and show of the attribute. * @private */ rpf.Attributes.prototype.getNewValueObj_ = function(name) { var value = goog.dom.getElement(this.id_ + name).value; var radios = document.getElementsByName(this.id_ + 'radio_' + name); var show = ''; for (var i = 0; i < radios.length; i++) { if (radios[i].checked) { show = radios[i].value; } } return {'value': value, 'show': show}; };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains the basic helper functions. * * @author phu@google.com (Po Hu) */ goog.provide('bite.base.Helper'); /** * Evals the current datafile. * @param {string} datafile The datafile string. * @export */ bite.base.Helper.evalDatafile = function(datafile) { datafile = 'var ContentMap = {};' + datafile + 'bite.base.Helper.dataFile = ContentMap;'; // TODO(phu): Use goog.json.parse instead of eval. eval(datafile); }; /** * Returns the string without non-word chars. * @param {string|Object.<string, string>} strOrObj The input raw string. * @param {number=} opt_len The optional length of the returned string. * @return {string} The string without non word chars. * @export */ bite.base.Helper.getNonWordRemoved = function(strOrObj, opt_len) { if (!strOrObj) { return ''; } var str = strOrObj; if (typeof(strOrObj) == 'object') { str = strOrObj['value']; } var newStr = str.replace(/\W+/g, ''); var len = newStr.length; var givenLen = opt_len ? opt_len : len; givenLen = givenLen < len ? givenLen : len; return newStr.substring(0, givenLen); }; /** * The global temp datafile object. * @export */ bite.base.Helper.dataFile = {}; /** * Gets the step id from a given cmd. * @param {string} cmd The cmd string. * @return {string} The step id. * @export */ bite.base.Helper.getStepId = function(cmd) { var result = /getElem\(\"(.+)\"\)/i.exec(cmd); return result ? result[1] : ''; }; /** * Gets the test object given the information from server or local. * @param {string|Object} testInfo The test info either an object or json. * @return {Object} The test object. */ bite.base.Helper.getTestObject = function(testInfo) { var testType = typeof testInfo; if (testType == 'string') { testInfo = goog.json.parse(testInfo); } if (testInfo['active']) { testInfo = testInfo['active']; if (typeof testInfo == 'string') { testInfo = goog.json.parse(testInfo); } } return testInfo; }; /** * This is originated from online source, which is used to pretty print xml. * @param {number} len The length of the indentation. * @return {string} The spaces. * @export */ bite.base.Helper.spaces = function(len) { var s = ''; for (var i = 0; i < len; ++i) { s += ' '; } return s; }; /** * This is originated from online source, which is used to pretty print xml. * http://stackoverflow.com/questions/376373/pretty-printing-xml-with-javascript * @param {string} str The raw xml string. * @return {string} The formatted string. * TODO(phu): Rewrite the method if necessary. * @export */ bite.base.Helper.formatXml = function(str) { var xml = ''; // add newlines str = str.replace(/(>)(<)(\/*)/g, '$1\r$2$3'); // add indents var pad = 0; var indent = 0; var node = null; // split the string var strArr = str.split('\r'); // check the various tag states for (var i = 0; i < strArr.length; i++) { indent = 0; node = strArr[i]; if (node.match(/.+<\/\w[^>]*>$/)) { //open and closing in the same line indent = 0; } else if (node.match(/^<\/\w/)) { // closing tag if (pad > 0) { pad -= 1; } } else if (node.match(/^<\w[^>]*[^\/]>.*$/)) { //opening tag indent = 1; } else { indent = 0; } xml += bite.base.Helper.spaces(pad * 4) + node + '\r'; pad += indent; } return xml; };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Tests for the code generator. * * @author ralphj@google.com (Julie Ralph) */ goog.require('rpf.CodeGenerator'); function testUrlMatching() { var commandNoQuotes = 'redirectTo(theUrl)'; var commandQuotes = 'redirectTo("theUrl")'; var changeCommand = 'changeUrl(theUrl)'; var changeCommandQuotes = 'changeUrl("theUrl")'; assertEquals('theUrl', rpf.CodeGenerator.getUrlInRedirectCmd(commandNoQuotes)); assertEquals('theUrl', rpf.CodeGenerator.getUrlInRedirectCmd(commandQuotes)); assertEquals('theUrl', rpf.CodeGenerator.getUrlInRedirectCmd(changeCommand)); assertEquals('theUrl', rpf.CodeGenerator.getUrlInRedirectCmd(changeCommandQuotes)); }
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains RPF's setting dialog. * It gets popped up when user clicks the settings button. * * @author phu@google.com (Po Hu) */ goog.provide('rpf.SettingDialog'); goog.require('bite.common.mvc.helper'); goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.events'); goog.require('goog.ui.Dialog'); goog.require('rpf.Console.Messenger'); goog.require('rpf.MiscHelper'); goog.require('rpf.soy.Dialog'); /** * A class for showing setting dialog. * This dialog shows user options to set playback interval, * or test user's specified script. * @param {function(Bite.Constants.UiCmds, Object, Event)} onUiEvents * The function to handle the specific event. * @constructor * @export */ rpf.SettingDialog = function(onUiEvents) { /** * The setting dialog. * @type Object * @private */ this.settingDialog_ = new goog.ui.Dialog(); /** * The messenger. * @type {rpf.Console.Messenger} * @private */ this.messenger_ = rpf.Console.Messenger.getInstance(); /** * The function to handle the specific event. * @type {function(Bite.Constants.UiCmds, Object, Event)} * @private */ this.onUiEvents_ = onUiEvents; /** * Inits the setting dialog. */ this.initSettingDialog_(); }; /** * Localstorage name for whether takes screenshots. * @type {string} * @private */ rpf.SettingDialog.TAKE_SCREENSHOTS_ = 'takeScreenshots'; /** * Localstorage name for whether uses xpath. * @type {string} * @private */ rpf.SettingDialog.USE_XPATH_ = 'useXpath'; /** * Inits the setting dialog. * @private */ rpf.SettingDialog.prototype.initSettingDialog_ = function() { var dialogElem = this.settingDialog_.getContentElement(); bite.common.mvc.helper.renderModelFor(dialogElem, rpf.soy.Dialog.settingsContent); this.settingDialog_.setTitle('Settings'); this.settingDialog_.setButtonSet(null); this.settingDialog_.setVisible(true); this.settingDialog_.setVisible(false); this.registerListeners_(); this.initTakeScreenshotsCheckbox_(); this.initUseXpath_(); }; /** * Generates the webdriver code directly. * @private */ rpf.SettingDialog.prototype.registerListeners_ = function() { goog.events.listen( goog.dom.getElement('playbackintervalbutton'), 'click', goog.bind(this.setPlaybackInterval_, this)); goog.events.listen( goog.dom.getElement('defaulttimeoutbutton'), 'click', goog.bind(this.setTimeout_, this)); goog.events.listen( goog.dom.getElement('whethertakescreenshot'), 'click', goog.bind(this.setTakeScreenshot_, this)); goog.events.listen( goog.dom.getElement('whetherUseXpath'), 'click', goog.bind(this.setUseXpath_, this)); }; /** * Sets whether take the screenshots while recording. * @private */ rpf.SettingDialog.prototype.initTakeScreenshotsCheckbox_ = function() { var takes = goog.global.localStorage[ rpf.SettingDialog.TAKE_SCREENSHOTS_]; if (!takes || takes == 'true') { goog.dom.getElement('whethertakescreenshot').checked = true; } else { this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.SET_TAKE_SCREENSHOT, 'params': {'isTaken': false}}); } }; /** * Sets whether take the screenshots while recording. * @private */ rpf.SettingDialog.prototype.setTakeScreenshot_ = function() { var checked = goog.dom.getElement('whethertakescreenshot').checked; goog.global.localStorage[ rpf.SettingDialog.TAKE_SCREENSHOTS_] = checked; this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.SET_TAKE_SCREENSHOT, 'params': {'isTaken': checked}}); }; /** * Gets whether to use xpath. * @return {boolean} Whether to use xpath. */ rpf.SettingDialog.prototype.getUseXpath = function() { return goog.dom.getElement('whetherUseXpath').checked; }; /** * Sets whether uses the xpath to replay. * @private */ rpf.SettingDialog.prototype.setUseXpath_ = function() { var checked = goog.dom.getElement('whetherUseXpath').checked; goog.global.localStorage[rpf.SettingDialog.USE_XPATH_] = checked; this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.SET_USE_XPATH, 'params': {'use': checked}}); }; /** * Sets whether uses xpath. * @private */ rpf.SettingDialog.prototype.initUseXpath_ = function() { var use = goog.global.localStorage[rpf.SettingDialog.USE_XPATH_]; if (use && use == 'true') { goog.dom.getElement('whetherUseXpath').checked = true; this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.SET_USE_XPATH, 'params': {'use': true}}); } }; /** * Sets time out. * @private */ rpf.SettingDialog.prototype.setTimeout_ = function() { var time = parseInt(goog.dom.getElement('defaulttimeout').value, 10) * 1000; this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.SET_DEFAULT_TIMEOUT, 'params': {'time': time}}); }; /** * Sets the playback interval in seconds. * @private */ rpf.SettingDialog.prototype.setPlaybackInterval_ = function() { var interval = parseFloat(goog.dom.getElement('playbackinterval').value); this.messenger_.sendMessage( {'command': Bite.Constants.CONSOLE_CMDS.SET_PLAYBACK_INTERVAL, 'params': {'interval': interval}}); }; /** * Sets the visibility of the setting dialog. * @param {boolean} display Whether to show the dialog. * @export */ rpf.SettingDialog.prototype.setVisible = function(display) { this.settingDialog_.setVisible(display); };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains functions for extracting a query selector * for string that can be used to uniquely identify a DOM Element. * * @author jasonstredwick@google.com (Jason Stredwick) */ goog.provide('common.dom.querySelector'); goog.require('goog.dom.TagName'); /** * Finds a selector that uniquely identifies the given DOM Node. * A selector will traverse from the body tag to the given node. Each DOM * Element's portion of the selector is * <node.nodeName>([id=node.id])?(:nth-child([0-9]+))? * and each of the DOM Element's selectors are separated by '>' giving: * selector(>selector)*. * @param {!Node} node The DOM Node requiring identification. * @returns {string} A string containing the selector. */ common.dom.querySelector.getSelector = function(node) { var nodeName = node.nodeName; var id = node.id; var parent = node.parentNode; if (node.nodeName.toLowerCase() == goog.dom.TagName.BODY.toLowerCase()) { return goog.dom.TagName.BODY; } var selector = nodeName + (id ? '[id=' + id + ']' : ''); if (!parent) { return selector; } for (var i = 0; i < parent.childNodes.length; ++i) { var child = parent.childNodes[i]; if (child == node) { selector = selector + ':nth-child(' + (i + 1) + ')'; break; } } var parentSelector = common.dom.querySelector.getSelector(parent); if (parentSelector) { selector = parentSelector + '>' + selector; } return selector; };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains the RPF automator, which is used to * automate RPF actions like opening a new RPF console, loading a specific * test, etc. This will make RPF easy to use like automatically getting * to a RPF status based on the given parameters. Eventually, this will * be used to fully automate RPF. For now, the automator can serve * at most one request at a time, and flush the previous one if a new request * is received. * * @author phu@google.com (Po Hu) */ goog.provide('rpf.Automator'); goog.require('Bite.Constants'); goog.require('goog.events'); goog.require('goog.events.EventTarget'); /** * A class for automating RPF behaviors. * @param {function(Object, function(Object)=)} consoleListener The listener * registered in rpf console. * @param {function(Object, Object, function(Object))} eventMgrListener * The listener registered in eventsManager. * @param {function(Object, Object, function(Object))} rpfListener * The listener registered in rpf.js. * @constructor */ rpf.Automator = function(consoleListener, eventMgrListener, rpfListener) { /** * The steps in queue. Each step contains information of the message name, * and what event type it is expecting as the indication of execution * completes. * @type {!Array.<Object>} * @private */ this.stepArray_ = []; /** * The callback method when the automation is done. * @private */ this.callback_ = goog.nullFunction; /** * The current step index. * @type {number} * @private */ this.currentStepIndex_ = -1; /** * See description for function parameter consoleListener. * @type {function(Object, function(Object)=)} * @private */ this.consoleListener_ = consoleListener; /** * See description for function parameter eventMgrListener. * @type {function(Object, Object, function(Object))} * @private */ this.eventMgrListener_ = eventMgrListener; /** * See description for function parameter rpfListener. * @type {function(Object, Object, function(Object))} * @private */ this.rpfListener_ = rpfListener; /** * The currently expected event type. * @type {Bite.Constants.COMPLETED_EVENT_TYPES} * @private */ this.expectedEventType_ = Bite.Constants.COMPLETED_EVENT_TYPES.DEFAULT; /** * See description for function parameter eventCompleteTarget. * @type {goog.events.EventTarget} * @private */ this.eventTarget_ = new goog.events.EventTarget();; /** * The bound function when the expected event is received. * @type {function()} * @private */ this.boundOnReceiveExpectedEvent_ = goog.bind(this.onReceiveExpectedEvent_, this); }; /** * When the expected finish event is received, it proceeds to execute the * next step. * @private */ rpf.Automator.prototype.onReceiveExpectedEvent_ = function() { goog.events.removeAll(this.eventTarget_); this.executeNextStep_(); }; /** * Returns a step object. * @param {Bite.Constants.ListenerDestination} destination The destination * listener which includes both console and background sides. * @param {string} message The actual message to start an action. * @param {Object} params The parameters to start the action. * @param {Bite.Constants.COMPLETED_EVENT_TYPES} eventType The eventtype that * will be sent out once the action is completed. * @return {Object} The step object. */ rpf.Automator.prototype.getStepObject = function( destination, message, params, eventType) { return {'destination': destination, 'message': message, 'params': params, 'eventType': eventType}; }; /** * Gets the event target. * @return {goog.events.EventTarget} The event target. */ rpf.Automator.prototype.getEventTarget = function() { return this.eventTarget_; }; /** * Starts the new automation run. * @param {Array} stepArray The steps to be run. * @param {function(Object)=} opt_callback The optional callback function. */ rpf.Automator.prototype.start = function(stepArray, opt_callback) { console.log('The automation is started.'); goog.events.removeAll(this.eventTarget_); this.callback_ = opt_callback || goog.nullFunction; this.stepArray_ = stepArray || []; this.currentStepIndex_ = -1; this.expectedEventType_ = Bite.Constants.COMPLETED_EVENT_TYPES.DEFAULT; this.executeNextStep_(); }; /** * Finishes the current automation run. */ rpf.Automator.prototype.finish = function() { goog.events.removeAll(this.eventTarget_); this.eventTarget_.removeEventListener( this.expectedEventType_, this.boundOnReceiveExpectedEvent_); this.stepArray_ = []; this.callback_(); console.log('The automation is finished.'); }; /** * Executes the next step in the step array. * @private */ rpf.Automator.prototype.executeNextStep_ = function() { ++this.currentStepIndex_; var currentStep = this.stepArray_[this.currentStepIndex_]; if (this.currentStepIndex_ >= this.stepArray_.length) { this.finish(); return; } var destination = currentStep['destination']; var message = currentStep['message']; var params = currentStep['params']; this.expectedEventType_ = currentStep['eventType']; console.log('The current message is: ' + message); this.eventTarget_.addEventListener( this.expectedEventType_, this.boundOnReceiveExpectedEvent_); switch (destination) { case Bite.Constants.ListenerDestination.CONSOLE: this.consoleListener_({'command': message, 'params': params}); break; case Bite.Constants.ListenerDestination.EVENT_MANAGER: this.eventMgrListener_({'command': message, 'params': params}, {}, goog.nullFunction); break; case Bite.Constants.ListenerDestination.RPF: this.rpfListener_({'command': message, 'params': params}, {}, goog.nullFunction); break; case Bite.Constants.ListenerDestination.CONTENT: break; } };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Handles client-side filtering of bugs. * * @author jasonstredwick@google.com (Jason Stredwick) */ goog.provide('bite.bugs.filter'); goog.require('bite.options.constants'); /** * Filter bugs based on setting from the Options Page. The filter will mark * bugs as visible or not. * @param {?Object} allBugs All the bugs fetched from the server. * @param {?Object} filters The filters to be applied. */ bite.bugs.filter = function(allBugs, filters) { if (!allBugs || !filters) { return; } for (var i = 0; i < allBugs.length; ++i) { var bugs = allBugs[i][1]; for (var j = 0; j < bugs.length; ++j) { var bug = bugs[j]; bug['visible'] = bite.bugs.isVisible_(bug, filters); } }; }; /** * Apply the filters to the given bug and determine if it should be visible. * @param {!Object} bug The bug to examine. * @param {!Object} filters The filters to apply. * @return {boolean} Whether or not the given bug should be marked visible. * @private */ bite.bugs.isVisible_ = function(bug, filters) { // TODO (jasonstredwick): Once projects are implemented, update this code. // HACK to get projects working immediately, using static ones. var project = bug['project']; var projectFilter = filters[bite.options.constants.Id.BUG_PROJECT]; if (projectFilter != bite.options.constants.ProjectOption.ALL) { if (projectFilter == bite.options.constants.ProjectOption.NOT_TRASH) { if (project == 'trash') { return false; } // If the project filter doesn't match the start of the project // name then return false. This allows multiple components // (which are treated as a separate projects) to be classified under one // filter. For example "geo_other" will match projectFilter "geo". } else if(project.substr(0, projectFilter.length) != projectFilter) { return false; } } var state = bug['state']; var stateFilter = filters[bite.options.constants.Id.BUG_STATE]; if (stateFilter != bite.options.constants.ThreeWayOption.ALL) { if (stateFilter != state) { return false; } } var all = bite.options.constants.ThreeWayOption.ALL; var no = bite.options.constants.ThreeWayOption.NO; var yes = bite.options.constants.ThreeWayOption.YES; var recording = bug['recording_link']; var recordingFilter = filters[bite.options.constants.Id.BUG_RECORDING]; if (recordingFilter != all) { if ((recordingFilter == yes && !recording) || (recordingFilter == no && recording)) { return false; } } var screenshot = bug['screenshot']; var screenshotFilter = filters[bite.options.constants.Id.BUG_SCREENSHOT]; if (screenshotFilter != all) { if ((screenshotFilter == yes && !screenshot) || (screenshotFilter == no && screenshot)) { return false; } } var target = bug['target_element']; var uiBinding = (target && target != 'null') ? target : null; var uiBindingFilter = filters[bite.options.constants.Id.BUG_UI_BINDING]; if (uiBindingFilter != all) { if ((uiBindingFilter == yes && !uiBinding) || (uiBindingFilter == no && uiBinding)) { return false; } } return true; };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Creates a mini popup on the page telling the user the * bug number and allowing the user to change the bug's binding by dragging * the popup. Only one popup can exist on a page at a time. * * @author ralphj@google.com (Julie Ralph) */ goog.provide('bite.client.MiniBugPopup'); goog.require('Bite.Constants'); goog.require('bite.client.BugHelper'); goog.require('bite.client.Templates'); goog.require('common.client.RecordModeManager'); goog.require('goog.dom'); goog.require('goog.math.Coordinate'); goog.require('goog.style'); goog.require('soy'); /** * Creates a mini bug popup on calls to 'initDragBugBinding'. The popup * can be dragged onto a new UI element. The popup itself displays the bug * status and bug number. Upon release it asks the user if they would * like to change the bug binding to the new UI element before destroying * the popup. * @constructor */ bite.client.MiniBugPopup = function() { /** * The mini bug popup being dragged. * @type {Element} * @private */ this.draggedMiniBug_ = null; /** * A dialogue box that allows the user to submit or cancel a change in * a bug's UI binding. */ this.submitCancelPopup_ = null; /** * An array of listener keys for dragging bug popups. * @type {Array.<number>} * @private */ this.dragListenerKeys_ = []; /** * Buffer for the cursor style used by the page under test. This is stored * so that the cursor can be restored after the bug being dragged is * released. * @type {?string} * @private */ this.docCursor_ = null; /** * Manages the record mode for highlighting and selecting the UI element * underneath the dragged mini bug popup. * @type {common.client.RecordModeManager} * @private */ this.recordModeManager_; }; goog.addSingletonGetter(bite.client.MiniBugPopup); /** * The cumulative margin around the text in mini bug popups. * @type {number} * @private */ bite.client.MiniBugPopup.MARGIN_ = 32; /** * The upwards offset that the mini bug popup should have from the cursor. * @type {number} * @private */ bite.client.MiniBugPopup.UP_OFFSET_ = 5; /** * The right offset that the mini bug popup should have from the cursor. * @type {number} * @private */ bite.client.MiniBugPopup.RIGHT_OFFSET_ = 8; /** * Initiates the user dragging a bug binding on the current page. * @param {Object} bugData A dictionary of the bug data for this binding. * @param {Object} e A mouseEvent object from the object being dragged. */ bite.client.MiniBugPopup.prototype.initDragBugBinding = function(bugData, e) { // If the user already has a mini bug or submit cancel popup open, // do not create another. if (!this.draggedMiniBug_ && !this.submitCancelPopup_) { this.toggleAssociateBug_(bugData, e); this.draggedMiniBug_ = this.createBugMiniPopup_( e.clientX + bite.client.MiniBugPopup.UP_OFFSET_, e.clientY + bite.client.MiniBugPopup.RIGHT_OFFSET_, goog.dom.getDocument().body, bugData); this.dragListenerKeys_.push(goog.events.listen( goog.dom.getDocument(), goog.events.EventType.MOUSEMOVE, goog.bind(this.bugBindingDragHandler_, this))); this.dragListenerKeys_.push(goog.events.listen( goog.dom.getDocument(), goog.events.EventType.MOUSEUP, goog.bind(this.toggleAssociateBug_, this, bugData))); this.docCursor_ = goog.dom.getDocument().body.style.cursor; goog.dom.getDocument().body.style.cursor = 'pointer'; // Prevent text from being selected while dragging. e.preventDefault(); } }; /** * Handles a popup being cancelled. * @private */ bite.client.MiniBugPopup.prototype.cancelBugBinding_ = function() { this.removeSubmitCancelPopup_(); }; /** * Removes the Submit/Cancel popup from the page. * @private */ bite.client.MiniBugPopup.prototype.removeSubmitCancelPopup_ = function() { if (this.submitCancelPopup_) { goog.dom.removeNode(this.submitCancelPopup_); this.submitCancelPopup_ = null; } }; /** * Cleans up after the bug binding operations are complete. * @private */ bite.client.MiniBugPopup.prototype.cleanupDragBugBinding_ = function() { goog.dom.removeNode(this.draggedMiniBug_); goog.dom.getDocument().body.style.cursor = /** @type {string} */ ( this.docCursor_); this.docCursor_ = null; this.draggedMiniBug_ = null; this.recordModeManager_.exitRecordingMode(); while (this.dragListenerKeys_.length > 0) { goog.events.unlistenByKey(this.dragListenerKeys_.pop()); } }; /** * The drag handler for moving around the bug binding popup. * @param {Object} e A mouseEvent object from the object being dragged. * @private */ bite.client.MiniBugPopup.prototype.bugBindingDragHandler_ = function(e) { goog.style.setPosition(this.draggedMiniBug_, (e.clientX + bite.client.MiniBugPopup.UP_OFFSET_), (e.clientY + bite.client.MiniBugPopup.RIGHT_OFFSET_)); }; /** * Creates a mini bug popup at the specific coordinates, with the given data. * @param {number} x The x coordinate to draw the mini bug popup. * @param {number} y The y coordinate to draw the mini bug popup. * @param {Node} parent The HTML element to append this popup to. * @param {Object} bugData A dictionary of the bug data for this binding. * @return {Element} The html element of the mini bug popup. * @private */ bite.client.MiniBugPopup.prototype.createBugMiniPopup_ = function( x, y, parent, bugData) { var miniBugIconURL = bite.client.BugHelper.getBugIcon(bugData['state']); var miniBug = soy.renderAsElement( bite.client.Templates.bugMiniPopup, {bugID: bugData['id'], imgURI: miniBugIconURL}); goog.dom.appendChild(parent, miniBug); goog.style.setPosition(miniBug, x, y); // Resize to fit the text within the popup. var miniBugText = miniBug.childNodes[1]; goog.style.setWidth( miniBug, miniBugText.clientWidth + bite.client.MiniBugPopup.MARGIN_); return miniBug; }; /** * Creates a submit/cancel popup at the specific coordinates with the given * data. * @param {Node} parent The HTML element to append this popup to. * @param {string} iconUrl A url to a 16x16 img (will stretch) for this popup. * @param {string} title The title text to put in this popup. * @param {string} content The message contents to put in this content. * @param {goog.math.Coordinate} coord The coordinates to draw the popup * container at. * @param {function(): void} submitCallback Function to call when the * user clicks Submit. * @param {function(): void} cancelCallback Function to call when the * user clicks Cancel. * @private */ bite.client.MiniBugPopup.prototype.createSubmitCancelPopup_ = function( parent, iconUrl, title, content, coord, submitCallback, cancelCallback) { this.submitCancelPopup_ = soy.renderAsElement( bite.client.Templates.submitCancelPopup, {imgURI: iconUrl, title: title, message: content}); goog.style.setPosition(this.submitCancelPopup_, coord); goog.dom.appendChild(parent, this.submitCancelPopup_); goog.events.listenOnce(goog.dom.getElement('confirmSubmit'), goog.events.EventType.CLICK, submitCallback); goog.events.listenOnce(goog.dom.getElement('confirmCancel'), goog.events.EventType.CLICK, cancelCallback); }; /** * Submits a new bug binding to the server. * @param {Object} bugData A dictionary of the bug data for this binding. * @param {string} descriptor The HTML element descriptor to * bind the bug to. * @private */ bite.client.MiniBugPopup.prototype.submitBugBinding_ = function( bugData, descriptor) { chrome.extension.sendRequest( {'action': Bite.Constants.HUD_ACTION.LOG_EVENT, 'category': Bite.Constants.TestConsole.NONE, 'event_action': 'SubmitBugBinding', 'label': 'SUBMIT: Bug ' + bugData['id']}); var requestData = {'action': Bite.Constants.HUD_ACTION.UPDATE_BUG, 'details': {'kind': bugData['kind'], 'id': bugData['id'], 'target_element': descriptor}}; chrome.extension.sendRequest(requestData, goog.bind(this.refreshLocalBugData_, this, goog.bind(this.removeSubmitCancelPopup_, this))); }; /** * Returns true if the element is part of the BITE console. * @param {Element} element The element to check. * @return {boolean} Returns true if the element appear is in the BITE console, * otherwise false. * @private */ bite.client.MiniBugPopup.prototype.isBITEElement_ = function(element) { if (!element) { return false; } if (element == this.draggedMiniBug_ || goog.dom.getAncestorByClass(element, 'bite-container') != null) { // TODO(ralphj): Make sure all BITE elements are in a container // with class bite-container. return true; } return false; }; /** * Toggle the bug association highlighting. * @param {Object} bugData A dictionary of the bug data for this binding. * @param {Object} e A mouseEvent object from the user's cursor. * @private */ bite.client.MiniBugPopup.prototype.toggleAssociateBug_ = function(bugData, e) { if (!this.recordModeManager_) { this.recordModeManager_ = new common.client.RecordModeManager(); } if (this.recordModeManager_.isRecording()) { // If the user hasn't selected an element, or if they drop a bug on a // BITE element, then cancel the attempt. var currElement = this.recordModeManager_.getCurrElement(); if (!currElement || this.isBITEElement_(currElement)) { this.cleanupDragBugBinding_(); this.cancelBugBinding_(); } else { var elementDescriptor = common.client.ElementDescriptor.generateElementDescriptorNAncestors( this.recordModeManager_.getCurrElement(), 3); this.createSubmitCancelPopup_(goog.dom.getDocument().body, bite.client.BugHelper.getBugIcon(bugData['state']), 'Bug ' + bugData['id'], 'Bind to this element?', new goog.math.Coordinate(e.clientX, e.clientY), goog.bind(this.submitBugBinding_, this, bugData, elementDescriptor), goog.bind(this.cancelBugBinding_, this)); this.cleanupDragBugBinding_(); } } else { this.recordModeManager_.enterRecordingMode(function() {return true;}); } }; /** * Refreshes the local bug data with data on the server. * @param {function()=} opt_callback Function to call after requesting * refresh. * @private */ bite.client.MiniBugPopup.prototype.refreshLocalBugData_ = function(opt_callback) { chrome.extension.sendRequest( {action: Bite.Constants.HUD_ACTION.UPDATE_DATA, target_url: goog.global.location.href}); if (opt_callback) { opt_callback(); } };
JavaScript
// Copyright 2010 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Creates a popup on the page giving users details about * a particular bug and ways to interact with it, such as commenting * and changing the status. * * @author bustamante@google.com (Richard Bustamante) */ goog.require('Bite.Constants'); goog.require('bite.client.BugDetailsPopup'); goog.require('bite.client.Templates'); goog.require('goog.Timer'); goog.require('goog.dom'); goog.require('goog.events.EventHandler'); goog.require('goog.style'); goog.require('goog.testing.PropertyReplacer'); var stubs_ = new goog.testing.PropertyReplacer(); // Mock the chrome namespace if it's not defined. if (typeof(chrome) == 'undefined') { var chrome = {}; /** * Mocking the chrome.extension namespace * @export */ chrome.extension = {}; /** * Mocking chrome.extension.getURL and simply returning the relative path. * @param {string} img The relative path of the img to the extension. * @return {string} The relative path that was passed in. * @export */ chrome.extension.getURL = function(img) { return img; }; } var mockIssueTrackerBugData = {key: 98, id: '12345', title: 'Unit Test Issue Tracker Bug', status: 'Testing', state: 'active', priority: 'Top', details_link: 'http://test.asite.com/test', provider: 'issuetracker', project: 'unittest', reported_on: '2010-10-10T20:00:00.123456', author: 'author@bite.com', author_url: 'http://code.google.com/u/author', last_update: '2010-10-20T20:00:00.123456', last_updater: 'test@bite.com', last_updater_url: 'http://code.google.com/' + 'u/test'}; /** * Constructor called at the end of each test case/ * @this The context of the unit test. */ function setUp() { this.popupClient = new bite.client.BugDetailsPopup(); this.mockCaller = new mockCallBack(); } /** * Destructor called at the end of each test case. * @this The context of the unit test. */ function tearDown() { stubs_.reset(); this.popupClient.destroyBugPopup(true); } /** * Creates a fake popup if none exists; * @return {Element} The HTML element of the fake popup. */ function createPopup() { // Don't create duplicates. if (!popupExists()) { var mockBugPopup = goog.dom.createDom( goog.dom.TagName.DIV, {'id': bite.client.BugDetailsPopup.POPUP_CONTAINER_ID, 'innerHTML': 'Test'}); goog.dom.appendChild(goog.global.document.body, mockBugPopup); return mockBugPopup; } } /** * Determines whether the popup exists. * @return {boolean} Returns true if found, otherwise false. */ function popupExists() { if (goog.dom.getElement( bite.client.BugDetailsPopup.POPUP_CONTAINER_ID)) { return true; } return false; } /** * Empty function for mocking calls that don't need to do anything. */ function emptyFunction() { } /** * Mock calls for various functions. * @export */ function mockCallBack() { } /** * @type {string} The last method call. * @export */ mockCallBack.prototype.lastCall = ''; /** * @type {object} A list containing the parameters of the last method call. * @export */ mockCallBack.prototype.lastParameters = null; /** * Resets the mockCallBack members to their default values. * @export */ mockCallBack.prototype.reset = function() { this.lastCall = ''; this.lastParameters = null; }; /** * Mocks goog.Timer.callOnce. * @param {function()} func The function callOnce would normally call. * @param {delay} delay The delay in milliseconds before calling the function. * @param {Object} context The context to call the function in. * @export */ mockCallBack.prototype.callOnce = function(func, delay, context) { this.lastCall = 'callOnce'; this.lastParameters = [func, delay, context]; }; /** * Mocks goog.bind. * @param {function()} func The function goog.bind would normally call. * @param {Object} context The context to call the function in. * @param {Object} arg1 The first argument provided to func. * @param {Object} arg2 The second argument provided to func. * @param {Object} arg3 The third argument provided to func. * @export */ mockCallBack.prototype.bind = function(func, context, arg1, arg2, arg3) { this.lastCall = 'bind'; this.lastParameters = [func, context, arg1, arg2, arg3]; }; /** * Mocks goog.events.listen, stores multiple listens. * @param {Element} element The element to attach a listener to. * @param {String} command The command to listen to. * @param {function()} func The function to call when the event happens. * @export */ mockCallBack.prototype.listen = function(element, command, func) { this.lastCall += 'listen,'; if (!this.lastParameters) { this.lastParameters = [[element, command, func]]; } else { this.lastParameters.push([element, command, func]); } }; /** * Mocks chrome.extension.sendRequest. * @param {Object} queryParams The query parameters for sendRequest. * @param {function()} callback The callback function to run when finished. * @export */ mockCallBack.prototype.sendRequest = function(queryParams, callback) { this.lastCall = 'sendRequest'; this.lastParameters = [queryParams, callback]; }; /** * Verifies a Soy Template is called with all the expected parameters. * @param {Object} expectedValues The expected values in the template call. * @param {Object} actualValues The actual values in the template call. */ function verifyTemplateCallContains(expectedValues, actualValues) { for (prop in expectedValues) { assertEquals('Verifying ' + prop, expectedValues[prop], actualValues[prop]); } } /** * Testing bite.client.BugDetailsPopup.flagBugPopupRemoval * @this The context of the unit test. */ function testFlagBugPopupRemoval() { stubs_.set(goog.Timer, 'callOnce', goog.bind(this.mockCaller.callOnce, this.mockCaller)); // Test flagging the bug popup's removal. this.popupClient.flagBugPopupRemoval(true); assertEquals(popupClient.isFlaggedForRemoval(), true); assertEquals(this.mockCaller.lastCall, 'callOnce'); this.mockCaller.reset(); // Test flagging the bug popup's keep alive. this.popupClient.flagBugPopupRemoval(false); assertEquals(popupClient.isFlaggedForRemoval(), false); assertEquals(this.mockCaller.lastCall, ''); stubs_.reset(); } /** * Testing bite.client.BugDetailsPopup.destroyBugPopup * @this The context of the unit test. */ function testDestroyBugPopup() { // Test the popup isn't destroyed when removeBugPopup_ is false. this.popupClient.setTarget(createPopup()); this.popupClient.setFlaggedForRemoval(false); this.popupClient.setLocked(false); this.popupClient.destroyBugPopup(false); assertEquals('Test popup not destroyed when removeBugPopup_ is false', true, popupExists()); this.popupClient.destroyBugPopup(true); this.popupClient.setTarget(null); // Test the popup is destroyed when removeBugPopup_ is true. this.popupClient.setTarget(createPopup()); this.popupClient.setFlaggedForRemoval(true); this.popupClient.setLocked(false); this.popupClient.destroyBugPopup(false); assertEquals('Test popup is destroyed when removeBugPopup_ is true', false, popupExists()); this.popupClient.destroyBugPopup(true); this.popupClient.setTarget(null); // Test the popup isn't destroyed when the popup is locked. this.popupClient.setTarget(createPopup()); this.popupClient.setFlaggedForRemoval(true); this.popupClient.setLocked(true); this.popupClient.destroyBugPopup(false); assertEquals('Test popup not destroyed when when the popup is locked.', true, popupExists()); this.popupClient.destroyBugPopup(true); this.popupClient.setTarget(null); // Test the popup is is destroyed when the forcing parameter is used. this.popupClient.setTarget(createPopup()); this.popupClient.setFlaggedForRemoval(false); this.popupClient.setLocked(false); this.popupClient.destroyBugPopup(true); assertEquals('Test popup is destroyed when the forcing parameter is true', false, popupExists()); this.popupClient.destroyBugPopup(true); this.popupClient.setTarget(null); // Test the popup is is destroyed forced and the popup is locked. this.popupClient.setTarget(createPopup()); this.popupClient.setFlaggedForRemoval(false); this.popupClient.setLocked(true); this.popupClient.destroyBugPopup(true); assertEquals('Test popup is destroyed when the forcing parameter is true ' + 'and popups are locked', false, popupExists()); this.popupClient.destroyBugPopup(true); this.popupClient.setTarget(null); } /** * Testing bite.client.BugDetailsPopup.createBugPopup * @this The context of the unit test. */ function testCreatBugPopup() { // Ensure the document is large enough, by default it's 8px high. goog.style.setSize(goog.global.document.body, 500, 500); // Verify a bug popup isn't created when bug popups are locked. this.popupClient.setLocked(true); this.popupClient.createBugPopup(10, 10, mockIssueTrackerBugData); assertEquals('Test a bug popup not created when bug popups are locked.', false, popupExists()); this.popupClient.setLocked(false); // Verify a duplicate isn't created, if a popup with the same id exists. var fakeBugPopup = createPopup(); this.popupClient.setTarget(fakeBugPopup); this.popupClient.bugId_ = '12345'; this.popupClient.createBugPopup(10, 10, mockIssueTrackerBugData); goog.dom.removeNode(fakeBugPopup); assertEquals(false, popupExists()); this.popupClient.setTarget(null); // Verify a new popup is created, if the existing one is for a different bug. var fakeBugPopup = createPopup(); this.popupClient.setTarget(fakeBugPopup); this.popupClient.bugId_ = '99999'; this.popupClient.createBugPopup(10, 10, mockIssueTrackerBugData); assertEquals(true, popupExists()); assertEquals('12345', this.popupClient.bugId_); this.popupClient.destroyBugPopup(true); // Verify a popup is created at the desired coordinates. this.popupClient.setLocked(false); assertEquals(false, popupExists()); var popupElement = popupClient.createBugPopup(80, 90, mockIssueTrackerBugData); var popupPosition = goog.style.getPosition(popupElement); assertEquals('Bug Popup element created', true, popupExists()); // Expected x position is the passed in x. assertEquals('Bug Popup has the expected x position', 80, popupPosition.x); // Expected y position is the passed in y. assertEquals('Bug Popup has the expected y position', 90, popupPosition.y); this.popupClient.destroyBugPopup(true); } /** * Testing bite.client.BugDetailsPopup.createElementBugPopup * @this The context of the unit test. */ function testCreateElementBugPopup() { var mockOverlay = goog.dom.createDom(goog.dom.TagName.DIV, {'style': 'position: absolute'}); goog.dom.appendChild(goog.global.document.body, mockOverlay); // Ensure the document is large enough, by default it's 8px high. goog.style.setSize(goog.global.document.body, 500, 500); goog.style.setPosition(mockOverlay, 100, 100); goog.style.setSize(mockOverlay, 75, 25); // Verify a popup is created at the desired coordinates. this.popupClient.setLocked(false); assertEquals(false, popupExists()); var popupElement = popupClient.createElementBugPopup(mockOverlay, mockIssueTrackerBugData); var popupPosition = goog.style.getPosition(popupElement); assertEquals('Bug Popup element created', true, popupExists()); // Expected x position is overlay.x + overlay.width + 3px margin. assertEquals('Bug Popup has the expected x position', 100 + 75 + 3, popupPosition.x); // Expected y position is overlay.y - 2px margin. assertEquals('Bug Popup has the expected y position', 100 - 2, popupPosition.y); this.popupClient.destroyBugPopup(true); } /** * Testing bite.client.BugDetailsPopup.drawBugData_ * @this The context of the unit test. */ function testDrawBugData() { // Verify Issue Tracker bugs are displayed as expected. stubs_.set(bite.client.Templates, 'bugDetailsPopup', goog.bind(verifyTemplateCallContains, this, {'bugID': '12345', 'bugLink': 'http://test.asite.com/test', 'status': 'Testing', 'state': 'active', 'priority': 'Top', 'reportDate': '2010-10-10', 'reportBy': 'author', 'reportByURI': 'http://code.google.com/u/author', 'lastUpdateDate': '2010-10-20', 'lastUpdateBy': 'test', 'lastUpdateByURI': 'http://code.google.com/u/test', 'bugTitle': 'Unit Test Issue Tracker Bug', 'state': 'active'})); this.popupClient.drawBugData_(mockIssueTrackerBugData, goog.global.document.body); } /** * Testing bite.client.BugDetailsPopup.getBugIcon_ * @this The context of the unit test. */ function testGetBugIcon() { assertEquals('Verify active state returns the correct icon.', bite.client.BugDetailsPopup.BugIcons.ACTIVE, this.popupClient.getBugIcon_('active')); assertEquals('Verify resolved state returns the correct icon.', bite.client.BugDetailsPopup.BugIcons.RESOLVED, this.popupClient.getBugIcon_('resolved')); assertEquals('Verify closed state returns the correct icon.', bite.client.BugDetailsPopup.BugIcons.CLOSED, this.popupClient.getBugIcon_('closed')); assertEquals('Verify unknown state returns the correct icon.', bite.client.BugDetailsPopup.BugIcons.UNKNOWN, this.popupClient.getBugIcon_('unknown')); } /** * Testing bite.client.BugDetailsPopup.drawSubmitPopup_ * @this The context of the unit test. */ function testDrawSubmitPopup() { var container = goog.dom.createDom(goog.dom.TagName.DIV); goog.dom.appendChild(goog.global.document.body, container); // Mock out the goog.events.listen for mouse commands stubs_.set(goog.events, 'listen', emptyFunction); // Verify Issue Tracker bugs are handled as expected. stubs_.set(bite.client.Templates, 'bugConfirmChanges', goog.bind(verifyTemplateCallContains, this, {'bugID': '12345', 'bugLink': 'http://test.asite.com/test', 'command': 'activate'})); this.popupClient.drawSubmitPopup('activate', mockIssueTrackerBugData, container); } /** * Testing bite.client.BugDetailsPopup.createBugCommandListeners_ * @this The context of the unit test. */ function testCreateBugCommandListeners() { var mockControl = {}; // Mock out the goog.events.listen for mouse commands stubs_.set(goog.events, 'listen', emptyFunction); stubs_.set(goog, 'bind', goog.bind(this.mockCaller.bind, this.mockCaller)); // Verify the correct actions were included in the bind call, if it // got that far it also ensures the logic found the command control. for (action in bite.client.BugDetailsPopup.BugActions) { var command = bite.client.BugDetailsPopup.BugActions[action]; mockControl = goog.dom.createDom(goog.dom.TagName.DIV, {'id': 'bug-command-' + command}); goog.dom.appendChild(goog.global.document.body, mockControl); this.popupClient.createBugCommandListeners_(mockIssueTrackerBugData); assertEquals('Verifying ' + action, 'bind', this.mockCaller.lastCall); assertEquals(command, this.mockCaller.lastParameters[2]); goog.dom.removeNode(mockControl); } } /** * Testing bite.client.BugDetailsPopup.postBugUpdate_ * @this The context of the unit test. */ function testPostBugUpdate() { var expectedQueryParams = {}; var details = {'kind': 'bugs#bug', 'id': 98, 'comment': 'Unit Test Comment'}; var testComment = goog.dom.createDom(goog.dom.TagName.DIV, {'id': 'bug-popup-comment', 'innerHTML': 'Unit Test Comment'}); goog.dom.appendChild(goog.dom.getDocument().body, testComment); stubs_.set(chrome.extension, 'sendRequest', goog.bind(this.mockCaller.sendRequest, this.mockCaller)); // Mock out the disableSubmitPopup_ here, as that's tested elsewhere. this.popupClient.disableSubmitPopup_ = emptyFunction; this.popupClient.postBugUpdate_(mockIssueTrackerBugData, goog.dom.getDocument().body); expectedQueryParams = {action: Bite.Constants.HUD_ACTION.UPDATE_BUG, details: details}; // Verify the expected call and query parameters were sent. assertEquals('Verify sendRequest was called as expected.', 'sendRequest', this.mockCaller.lastCall); for (param in expectedQueryParams) { assertEquals('Verify the expected ' + param + ' was sent', expectedQueryParams[param], this.mockCaller.lastParameters[0][param]); } assertEquals('Verify a status update wasn\'t sent', undefined, this.mockCaller.lastParameters[0]['status']); details.status = 'Resolved'; var testStatus = goog.dom.createDom(goog.dom.TagName.SELECT, {'id': 'bug-update-status', 'innerHTML': '<OPTION>Resolved</OPTION>'}); goog.dom.appendChild(goog.dom.getDocument().body, testStatus); expectedQueryParams = {action: Bite.Constants.HUD_ACTION.UPDATE_BUG, details: details}; this.popupClient.postBugUpdate_(mockIssueTrackerBugData, goog.dom.getDocument().body); // Verify the expected call and query parameters were sent. assertEquals('Verify sendRequest was called as expected.', 'sendRequest', this.mockCaller.lastCall); for (param in expectedQueryParams) { assertEquals('Verify the expected ' + param + ' was sent', expectedQueryParams[param], this.mockCaller.lastParameters[0][param]); } } /** * Testing bite.client.BugDetailsPopup.disableSubmitPopup_ * @this The context of the unit test. */ function testDisableSubmitPopup() { var testComment = goog.dom.createDom(goog.dom.TagName.DIV, {'id': 'bug-popup-comment'}); goog.dom.appendChild(goog.global.document.body, testComment); var testCancel = goog.dom.createDom(goog.dom.TagName.SPAN, {'id': 'bug-command-cancel'}); goog.dom.appendChild(goog.global.document.body, testCancel); var testSubmit = goog.dom.createDom(goog.dom.TagName.SPAN, {'id': 'bug-command-submit'}); goog.dom.appendChild(goog.global.document.body, testSubmit); var testUpdateStatus = goog.dom.createDom(goog.dom.TagName.SELECT, {'id': 'bug-update-status'}); goog.dom.appendChild(goog.global.document.body, testUpdateStatus); this.popupClient.disableSubmitPopup_(); assertEquals('Verify the comment is grayed out', testComment.style.color, 'rgb(102, 102, 102)'); assertEquals('Verify the comment is no longer editable', testComment.contentEditable, false); assertEquals('Verify the cancel link is grayed out', goog.dom.classes.get(testCancel)[0], 'pseudo-link-disabled'); assertEquals('Verify the submit link is grayed out', goog.dom.classes.get(testSubmit)[0], 'pseudo-link-disabled'); assertEquals('Verify the status drop down is disabled', testUpdateStatus.disabled, true); goog.dom.removeNode(testComment); goog.dom.removeNode(testCancel); goog.dom.removeNode(testSubmit); goog.dom.removeNode(testUpdateStatus); } /** * Testing bite.client.BugDetailsPopup.postBugUpdateHandler_ * @this The context of the unit test. */ function testBugUpdateHandler() { this.popupClient.contentClient_ = {}; this.popupClient.contentClient_.getBugData_ = function(id) { return mockIssueTrackerBugData; } stubs_.set(chrome.extension, 'sendRequest', goog.bind(this.mockCaller.sendRequest, this.mockCaller)); this.popupClient.postBugUpdateHandler_('assigned', mockIssueTrackerBugData, goog.global.document.body, '{}'); assertEquals('Verify sendRequest was called as expected.', 'sendRequest', this.mockCaller.lastCall); } /** * Testing bite.client.BugDetailsPopup.drawConfirmationPopup_ * @this The context of the unit test. */ function testDrawConfirmationPopup() { var container = goog.dom.createDom(goog.dom.TagName.DIV); this.popupClient.contentClient_ = {}; this.popupClient.contentClient_.getBugData_ = function(id) { return mockIssueTrackerBugData; }; var successJson = JSON.parse('{"success": true}'); var errorJson = JSON.parse('{"success": false}'); var accessDeniedJson = JSON.parse('{"success": false, "error": "403, No ' + 'permission to edit issue"}'); // Mock out the goog.events.listen for mouse commands. stubs_.set(goog.events, 'listen', emptyFunction); goog.dom.appendChild(goog.global.document.body, container); stubs_.set(bite.client.Templates, 'bugResultPopup', goog.bind(verifyTemplateCallContains, this, {'bugID': '12345', 'bugLink': 'http://test.asite.com/test', 'resultMessage': 'Your comment has been ' + 'successfully posted.'})); this.popupClient.drawConfirmationPopup_(undefined, mockIssueTrackerBugData, container, successJson); stubs_.set(bite.client.Templates, 'bugResultPopup', goog.bind(verifyTemplateCallContains, this, {'bugID': '12345', 'bugLink': 'http://test.asite.com/test', 'resultMessage': 'This issue has been marked as <b>' + 'assigned</b>'})); this.popupClient.drawConfirmationPopup_('assigned', mockIssueTrackerBugData, container, successJson); stubs_.set(bite.client.Templates, 'bugResultPopup', goog.bind(verifyTemplateCallContains, this, {'bugID': '12345', 'bugLink': 'http://test.asite.com/test', 'resultMessage': 'Unable to submit update'})); this.popupClient.drawConfirmationPopup_('assigned', mockIssueTrackerBugData, container, errorJson); stubs_.set(bite.client.Templates, 'bugResultPopup', goog.bind(verifyTemplateCallContains, this, {'bugID': '12345', 'bugLink': 'http://test.asite.com/test', 'resultMessage': 'Unable to submit update - Access ' + 'Denied<br><span style="color: ' + '#6F6F6F; font-size: 7pt">Please ' + 'contact the appropiate team for ' + 'access to<br>update these issues.' + '</span>'})); this.popupClient.drawConfirmationPopup_('assigned', mockIssueTrackerBugData, container, accessDeniedJson); } /** * Testing bite.client.BugDetailsPopup.createBoundCommandListeners_ * @this The context of the unit test. */ function testCreateBoundCommandListeners() { this.popupClient.eventHandler_.listen = goog.bind(this.mockCaller.listen, this.mockCaller); // Test the case the "Bound" label hasn't been created yet. this.popupClient.createBoundCommandListeners_(mockIssueTrackerBugData, mockPopup); assertEquals('Verify listen was not called as no previous labels existed.', '', this.mockCaller.lastCall); // Test the main case of adding a listener to the "Bound" label. var mockLabel = goog.dom.createDom(goog.dom.TagName.DIV, {'id': 'bug-popup-bound-label'}); var mockPopup = goog.dom.createDom(goog.dom.TagName.DIV, {'id': 'bug-popup-container'}); goog.dom.appendChild(goog.global.document.body, mockLabel); goog.dom.appendChild(goog.global.document.body, mockPopup); var bindMocker = new mockCallBack(); stubs_.set(goog, 'bind', goog.bind(bindMocker.bind, bindMocker)); this.popupClient.createBoundCommandListeners_(mockIssueTrackerBugData, mockPopup); assertEquals('Verify listen was called.', 'listen,', this.mockCaller.lastCall); assertEquals('Verify the correct element was used.', 'bug-popup-bound-label', this.mockCaller.lastParameters[0][0]['id']); assertEquals('Verify the correct command was listened to.', goog.events.EventType.CLICK, this.mockCaller.lastParameters[0][1]); goog.dom.removeNode(mockLabel); goog.dom.removeNode(mockPopup); } /** * Testing bite.client.BugDetailsPopup.showBoundLabelMenu_ * @this The context of the unit test. */ function testShowBoundLabelMenu() { // Mock out the calls for removing bug popups. this.popupClient.contentClient_ = {}; this.popupClient.contentClient_.submitRemoveBugBinding_ = emptyFunction; var mockLabel = goog.dom.createDom(goog.dom.TagName.DIV, {'id': 'bug-popup-bound-label'}); var mockPopup = goog.dom.createDom(goog.dom.TagName.DIV, {'id': 'bug-popup-container'}); goog.dom.appendChild(goog.global.document.body, mockLabel); goog.dom.appendChild(goog.global.document.body, mockPopup); this.popupClient.eventHandler_.listen = goog.bind(this.mockCaller.listen, this.mockCaller); this.popupClient.showBoundLabelMenu_(mockIssueTrackerBugData, mockPopup, mockLabel); // Verify the two listeners were added, for each control. assertEquals('Verify listen was called.', 'listen,listen,', this.mockCaller.lastCall); assertEquals('Verify the correct element was used.', 'bug-popup-bound-menu-remove', this.mockCaller.lastParameters[0][0]['id']); assertEquals('Verify the correct command was listened to.', goog.events.EventType.CLICK, this.mockCaller.lastParameters[0][1]); assertEquals('Verify the correct element was used.', 'bug-popup-bound-menu-cancel', this.mockCaller.lastParameters[1][0]['id']); assertEquals('Verify the correct command was listened to.', goog.events.EventType.CLICK, this.mockCaller.lastParameters[1][1]); goog.dom.removeNode(mockLabel); goog.dom.removeNode(mockPopup); } /** * Testing bite.client.BugDetailsPopup.toProperCase_ * @this The context of the unit test. */ function testStrToProperCase() { assertEquals('Test', this.popupClient.strToProperCase('Test')); assertEquals('Test', this.popupClient.strToProperCase('test')); assertEquals('Test Message', this.popupClient.strToProperCase('test message')); assertEquals('', this.popupClient.strToProperCase('')); }
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview New bug type selector, used to ask the user what type of * bug they will be filing. * @author ralphj@google.com (Julie Ralph) */ goog.provide('bite.client.console.NewBugTypeSelector'); goog.require('Bite.Constants'); goog.require('bite.client.BugTemplate'); goog.require('bite.client.Resizer'); goog.require('bite.client.console.NewBug'); goog.require('bite.client.console.NewBugTypeSelectorTemplate'); goog.require('goog.array'); goog.require('goog.dom'); goog.require('goog.events'); goog.require('goog.math.Size'); goog.require('goog.style'); goog.require('soy'); /** * Creates an instance of the NewBug type selector. * @param {function(string)} templateCallback * The callback function to use, with the selected template as a parameter. * @param {function()} reportBugCallback The callback to continue the bug * reporting proccess. * @param {function()} cancelCallback The callback for when the process * is cancelled. * @constructor */ bite.client.console.NewBugTypeSelector = function(templateCallback, reportBugCallback, cancelCallback) { /** * The function to call with the id of the newly selected template. * @type {function(string)} * @private */ this.templateCallback_ = templateCallback; /** * The callback to call to continue the bug report process. * @type {function()} * @private */ this.reportBugCallback_ = reportBugCallback; /** * The callback to call to cancel the bug type selection. * @type {function()} * @private */ this.cancelCallback_ = cancelCallback; /** * Whether or not the new bug type selector is currently showing an * interface in the viewport. * @type {boolean} * @private */ this.isActive_ = false; /** * Root element for the New Bug Type Selector interface. * @type {?Element} * @private */ this.rootElement_ = null; /** * Extension's root folder URL. * @type {string} * @private */ this.rootFolder_ = chrome.extension.getURL(''); /** * Manages the events for clicks on bug types. * @type {!goog.events.EventHandler} * @private */ this.handler_ = new goog.events.EventHandler(this); /** * Manages dragging the element. * @type {bite.client.Resizer} * @private */ this.dragger_ = null; }; /** * Loads the New Bug Type Selector. * @param {Object.<string, bite.client.BugTemplate>} templates The templates to * choose from. */ bite.client.console.NewBugTypeSelector.prototype.load = function(templates) { if (this.isActive_) { return; } var bugTypes = []; for (var templateId in templates) { bugTypes.push( {bugTemplate: templateId, bugText: templates[templateId]['selectorText'], displayOrder: templates[templateId]['displayOrder']}); } // If there is only one option for the template, use that and exit early. if (bugTypes.length == 1) { this.selectType_(bugTypes[0].bugTemplate); return; } goog.array.sortObjectsByKey(bugTypes, 'displayOrder'); this.rootElement_ = soy.renderAsElement( bite.client.console.NewBugTypeSelectorTemplate.newBugTypeSelector, {rootFolder: this.rootFolder_, bugTypes: bugTypes}); goog.dom.appendChild(goog.dom.getDocument().body, this.rootElement_); var top = goog.dom.getViewportSize().height; var left = goog.dom.getViewportSize().width; // Center the type selector in the viewport. goog.style.setPosition( this.rootElement_, (left - goog.style.getSize(this.rootElement_).width) / 2, (top - goog.style.getSize(this.rootElement_).height) / 2); var headerElement = this.rootElement_.querySelector('.bite-header'); this.dragger_ = new bite.client.Resizer(this.rootElement_, headerElement, true); this.attachHandlers_(bugTypes); this.isActive_ = true; }; /** * Attaches handlers to the UI elements of the NewBug type selector. * @param {Array.<{bugTemplate: string}>} bugTypes The ids * associated with the bug templates. * @private */ bite.client.console.NewBugTypeSelector.prototype.attachHandlers_ = function(bugTypes) { var cancelButton = this.rootElement_.querySelector( '.bite-close-button'); this.handler_.listen(cancelButton, goog.events.EventType.CLICK, goog.bind(this.cancel_, this)); for (var i = 0; i < bugTypes.length; ++i) { var bugTemplate = bugTypes[i].bugTemplate; var bugText = this.rootElement_.querySelector('#' + bugTemplate); this.handler_.listen(bugText, goog.events.EventType.CLICK, goog.bind(this.selectType_, this, bugTemplate)); } }; /** * Sets the template for the newbug and begins the newbug filing process. * @param {string} template The id of the template to use. * @private */ bite.client.console.NewBugTypeSelector.prototype.selectType_ = function(template) { this.templateCallback_(template); this.continueReportBug_(); }; /** * Asks the content script to continue filing a new bug and closes the * type selection console. * @private */ bite.client.console.NewBugTypeSelector.prototype.continueReportBug_ = function() { this.reportBugCallback_(); this.close_(); }; /** * Cancels the type selection. * @private */ bite.client.console.NewBugTypeSelector.prototype.cancel_ = function() { this.cancelCallback_(); this.close_(); }; /** * Closes the new bug type selection console. * @private */ bite.client.console.NewBugTypeSelector.prototype.close_ = function() { goog.dom.removeNode(this.rootElement_); this.handler_.removeAll(); this.rootElement_ = null; this.isActive_ = false; };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Displays an overlay of bugs that have been previously filed * on a page. * * @author ralphj@google.com (Julie Ralph) */ goog.provide('bite.client.BugOverlay'); goog.require('bite.client.BugDetailsPopup'); goog.require('bite.client.BugHelper'); goog.require('bite.client.ElementMapper'); goog.require('bite.client.MiniBugPopup'); goog.require('common.client.ElementDescriptor'); goog.require('goog.events.EventHandler'); /** * Manager for bug overlays. * @constructor */ bite.client.BugOverlay = function() { /** * Whether or not the overlay is visible. * @type {boolean} * @private */ this.bugOverlayOn_ = false; /** * An object that can manage multiple overlapping bug overlay tiles. * @type {!bite.client.ElementMapper} * @private */ this.overlayMap_ = new bite.client.ElementMapper(); /** * The overlay id the mouse is currently hovering over. * @type {?{element: Element, bugLevel: number, bugIndex: number}} * @private */ this.overlay_ = null; /** * The last known overlay list. * @type {Array.<{element: Element, bugLevel: number, bugIndex: number}>} * @private */ this.overlayList_ = null; /** * Manages events on the overlay. * @type {goog.events.EventHandler} * @private */ this.eventHandler_ = new goog.events.EventHandler(); /** * The bugs data. * @type {Object} * @private */ this.bugs_ = null; }; /** * Returns whether or not the bug overlay is visible. * @return {boolean} The visibility of the overlay. */ bite.client.BugOverlay.prototype.bugOverlayOn = function() { return this.bugOverlayOn_; } /** * Renders the bug overlay elements on the current page. */ bite.client.BugOverlay.prototype.render = function() { // Don't display Overlay if the bugs haven't been loaded. if (!this.bugs_) { this.bugOverlayOn_ = false; return; } // Remove any existing overlays to avoid duplicates. Also, clears // the element mapper used to identify overlapping overlays. this.remove(); for (var i = 0; i < this.bugs_.length; i++) { // Note this.bugs_ is a list of bugs found for various urls, for each // member, at index i, this.bugs_[i][0] is the url the bugs are associated // with, while this.bugs_[i][1] is a list of the bug objects. for (var j = 0, bugs = this.bugs_[i][1]; j < bugs.length; ++j) { // Only add an overlay for this bug if it is visible. if (!bugs[j]['visible'] || !bugs[j]['target_element'] || bugs[j]['target_element'] == 'null') { continue; } var parseDesc = common.client.ElementDescriptor.parseElementDescriptor; var targetElement = parseDesc(bugs[j]['target_element']); if (!targetElement) { continue; } var style = 'position: absolute;' + 'opacity: 0.4;' + 'z-index: 50000;' + 'background-color: ' + bite.client.BugHelper.getBugHighlights(bugs[j].state) + ';'; var targetOverlay = goog.dom.createDom(goog.dom.TagName.DIV, { 'id': 'bite-bug-overlay-' + ((i + 1) * (j + 1)), 'class' : 'bite-bug-overlay', 'style' : style }); if (!targetOverlay) { continue; } goog.dom.appendChild(goog.dom.getDocument().body, targetOverlay); // Shape overlay Element. goog.style.setPosition(targetOverlay, goog.style.getPageOffset(targetElement)); goog.style.setSize(targetOverlay, goog.style.getSize(targetElement)); // Add overlay to mapper. this.overlayMap_.add(targetOverlay, { element: targetOverlay, bugLevel: i, bugIndex: j }); // Hookup overlay Element. this.eventHandler_.listen(targetOverlay, goog.events.EventType.MOUSEMOVE, goog.bind(this.overlayMouseMoveHandler_, this)); this.eventHandler_.listen(targetOverlay, goog.events.EventType.MOUSEDOWN, goog.bind(this.overlayMouseDownHandler_, this)); this.eventHandler_.listen(targetOverlay, goog.events.EventType.MOUSEOUT, goog.bind(this.overlayMouseOutHandler_, this)); this.eventHandler_.listen(targetOverlay, goog.events.EventType.CLICK, goog.bind(this.overlayMouseClickHandler_, this)); } } this.bugOverlayOn_ = true; }; /** * Removes the bug overlay elements on the current page. */ bite.client.BugOverlay.prototype.remove = function() { this.overlayMap_.clear(); this.eventHandler_.removeAll(); var currTargets = goog.dom.getDocument().querySelectorAll('div.bite-bug-overlay'); for (var i = 0; i < currTargets.length; ++i) { goog.dom.removeNode(currTargets[i]); } this.bugOverlayOn_ = false; }; /** * Updates the overlay with new data. * @param {Object} bugs The new bug data. */ bite.client.BugOverlay.prototype.updateData = function(bugs) { this.bugs_ = bugs; if (this.bugOverlayOn_) { this.render(); } }; /** * Retrieves the bug overlays the mouse is currently hovering over. * @param {!goog.events.Event} event The event that was recorded. * @return {Array.<!Object>} An array of overlay info. * @private */ bite.client.BugOverlay.prototype.getOverlays_ = function(event) { var win = goog.dom.getWindow(); var x = win.pageXOffset + event.clientX; var y = win.pageYOffset + event.clientY; return this.overlayMap_.find(x, y); }; /** * Retrieves the currently selected overlay's index in the current overlay * list. * @return {number} The index or -1 if not present. * @private */ bite.client.BugOverlay.prototype.getCurrentOverlayPosition_ = function() { if (this.overlay_ && this.overlayList_) { for (var i = 0; i < this.overlayList_.length; ++i) { if (this.overlayList_[i].element.id == this.overlay_.element.id) { return i; } } } return -1; }; /** * Create a bug popup for an overlay element. * @param {Element=} opt_element An optional element that will override the * overlay element being passed to the construction of the bug popup. * @private */ bite.client.BugOverlay.prototype.overlayCreateBugPopup_ = function(opt_element) { var position = this.getCurrentOverlayPosition_(); if (position < 0) { return; } position += 1; // Convert to position order rather than index value. var node = opt_element ? opt_element : this.overlay_.element; node = /** @type {Node} */ (node); var bugLevel = this.overlay_.bugLevel; var bugIndex = this.overlay_.bugIndex; var bugData = this.bugs_[bugLevel][1][bugIndex]; var popup = bite.client.BugDetailsPopup.getInstance().createElementBugPopup( node, bugData, this); if (popup) { var navLeft = goog.dom.getElement('bug-popup-nav-left'); var navRight = goog.dom.getElement('bug-popup-nav-right'); if (navLeft && navRight) { this.eventHandler_.listen(navLeft, goog.events.EventType.CLICK, goog.bind(this.overlayChange_, this, true)); this.eventHandler_.listen(navRight, goog.events.EventType.CLICK, goog.bind(this.overlayChange_, this, false)); } } // Update popup's overlay indicator. var iterationTable = goog.dom.getElement('bug-popup-iterator-table'); var iteration = goog.dom.getElement('bug-popup-iteration'); if (iteration && iterationTable) { if (this.overlayList_.length > 1) { goog.style.setStyle(iterationTable, 'display', 'block'); iteration.innerText = position + ' of ' + this.overlayList_.length; } else { goog.style.setStyle(iterationTable, 'display', 'none'); } } }; /** * Handles an overlay being moused out. * @param {boolean} moveDown Whether or not to process the overlay list down * (or up if false). * @private */ bite.client.BugOverlay.prototype.overlayChange_ = function(moveDown) { var position = this.getCurrentOverlayPosition_(); // If the currently selected overlay is in the current overlay list then // position will be non-negative. if (position >= 0) { // Calculate the next overlay in the list. if (moveDown) { position = position - 1; if (position < 0) { position = this.overlayList_.length - 1; } } else { position = (position + 1) % this.overlayList_.length; } this.overlay_ = this.overlayList_[position]; } else if (this.overlayList_ && this.overlayList_.length > 0) { this.overlay_ = this.overlayList_[0]; } else { return; } // Don't change the popup's position while cycling through overlays // therefore will have to compensate for calculations done in createBugPopup. var bugPopup = goog.dom.getElement(bite.client.BugDetailsPopup.POPUP_CONTAINER_ID); var left = parseInt(bugPopup.style.left, 10) - 3; var top = parseInt(bugPopup.style.top, 10) + 2; var location = { style: { left: left, top: top, width: 0, height: 0 } }; location = /** @type {Element} */ (location); this.overlayCreateBugPopup_(location); }; /** * Handles an overlay being moused out. * @param {!goog.events.Event} event The event fired. * @private */ bite.client.BugOverlay.prototype.overlayMouseClickHandler_ = function(event) { var win = goog.dom.getWindow(); var x = win.pageXOffset + event.clientX; var y = win.pageYOffset + event.clientY; var location = { style: { left: x - 5, top: y - 5, width: 0, height: 0 } }; location = /** @type {Element} */ (location); this.overlayCreateBugPopup_(location); }; /** * Handles an overlay being moused over. * @param {!goog.events.Event} event The event fired. * @private */ bite.client.BugOverlay.prototype.overlayMouseOutHandler_ = function(event) { var overlays = this.getOverlays_(event); if (overlays.length == 0) { // Only completely remove the popup when we are no longer over any // bug overlay elements. bite.client.BugDetailsPopup.getInstance().flagBugPopupRemoval(true); } }; /** * Handles a user clicking down on the overlay. * @param {!goog.events.Event} event The event fired. * @private */ bite.client.BugOverlay.prototype.overlayMouseDownHandler_ = function(event) { if (this.overlay_) { var overlay = this.overlay_; var bugLevel = overlay.bugLevel; var bugIndex = overlay.bugIndex; var bugData = this.bugs_[bugLevel][1][bugIndex]; bite.client.MiniBugPopup.getInstance().initDragBugBinding(bugData, event); } }; /** * Handles the mouse moving over at least one overlay. * @param {!goog.events.Event} event The event fired. * @private */ bite.client.BugOverlay.prototype.overlayMouseMoveHandler_ = function(event) { // Get a list of overlays under the current mouse position. var overlays = this.getOverlays_(event); this.overlayList_ = overlays; var position = this.getCurrentOverlayPosition_(); // If the current overlay is not part of the list set the current overlay to // the first overlay in the list if available. if (position < 0) { if (this.overlayList_.length == 0) { return; } position = 1; this.overlay_ = /** @type {{element: Element, bugLevel: number, bugIndex: number}} */ (this.overlayList_[0]); } this.overlayCreateBugPopup_(); };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * New bug console, used to walk the use through the steps * necessary to log a bug. * * @author ekamenskaya@google.com (Ekaterina Kamenskaya) * @author alexto@google.com (Alexis O. Torres) */ goog.provide('bite.client.console.NewBug'); goog.require('Bite.Constants'); goog.require('bite.client.BugTemplate'); goog.require('bite.client.Container'); goog.require('bite.client.TemplateManager'); goog.require('bite.client.Templates'); goog.require('bite.client.console.NewBugTemplate'); goog.require('bite.console.Helper'); goog.require('common.client.ElementDescriptor'); goog.require('common.client.RecordModeManager'); goog.require('goog.Timer'); goog.require('goog.Uri'); goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.dom.classes'); goog.require('goog.dom.forms'); goog.require('goog.dom.selection'); goog.require('goog.events.EventHandler'); goog.require('goog.string'); goog.require('goog.structs.Map'); goog.require('goog.style'); goog.require('goog.userAgent'); goog.require('goog.userAgent.platform'); goog.require('goog.userAgent.product'); goog.require('soy'); /** * Creates an instance of the NewBug console. * @param {?string} user Email for the current user. * @param {Function=} opt_callback Callback function when New Bug console is * canceled or a new bug is logged. * @constructor */ bite.client.console.NewBug = function(user, opt_callback) { /** * Extension's root folder URL. * @type {string} * @private */ this.rootFolder_ = chrome.extension.getURL(''); /** * Container for the new bug console. * @type {bite.client.Container} * @private */ this.container_ = null; /** * Current user's email. * @type {?string} * @private */ this.user_ = user; /** * Callback function to call when the New Bug console * finishes logging a new bug or is canceled. * @type {function()} * @private */ this.doneCallback_ = opt_callback || goog.nullFunction; /** * Screenshot for when the bug was logged. * @type {?string} * @private */ this.screenshot_ = null; /** * Title text area. * @type {Element} * @private */ this.titleTextArea_ = null; /** * Templates dropdown list. * @type {Element} * @private */ this.templatesList_ = null; /** * The templates to be shown. * @type {!Object.<string, bite.client.BugTemplate>} * @private */ this.templates_ = {}; /** * Screenshot checkbox. * @type {Element} * @private */ this.screenshotCheckbox_ = null; /** * Notes text area. * @type {Element} * @private */ this.notesTextArea_ = null; /** * UI Element description text area. * @type {Element} * @private */ this.uiTextArea_ = null; /** * Recoding script text area. * @type {Element} * @private */ this.recordingTextArea_ = null; /** * The current URL. * @type {string} * @private */ this.url_ = ''; // Set to the current URL from the show() method. /** * Buffer for the link to recorded test. * @type {string} * @private */ this.recordingLink_ = ''; /** * Buffer for the recorded test. * @type {string} * @private */ this.recordingScript_ = ''; /** * Buffer for the recorded test in human readable format. * @type {string} * @private */ this.recordingReadable_ = ''; /** * Buffer for the recording data. * @type {string} * @private */ this.recordingData_ = ''; /** * Buffer for recorded script's info map. * @type {Object} * @private */ this.recordingInfoMap_ = {}; /** * Manager for selecting a new UI element. * @type {common.client.RecordModeManager} * @private */ this.recordModeManger_ = null; /** * Element used as the highlight box. * @type {Element} * @private */ this.pingDiv_ = null; /** * Manages the UI listeners for the new bug console. * @type {!goog.events.EventHandler} * @private */ this.eventHandler_ = new goog.events.EventHandler(this); }; /** * New Bug Form tabs. * @enum {string} * @private */ bite.client.console.NewBug.Tab_ = { RECORDING: 'Recording', OVERVIEW: 'Overview', UI: 'UI' }; /** * Instruments the usage of the NewBug console. * @param {string} action The action to log. * @param {string} label Additional details related to the action to log. * @private */ bite.client.console.NewBug.logEvent_ = function(action, label) { chrome.extension.sendRequest({'action': Bite.Constants.HUD_ACTION.LOG_EVENT, 'category': Bite.Constants.TestConsole.NEWBUG, 'event_action': action, 'label': label}); }; /** * Gets current repro URL. * @return {string} The current repro URL. * @private */ bite.client.console.NewBug.prototype.getCurrentUrl_ = function() { var url = goog.global.location.href; return url; }; /** * Element seleted while logging a new bug or dragging an exising * bug in to the right context. * @type {Element} * @private */ bite.client.console.NewBug.prototype.selectedElement_ = null; /** * Gets the screenshot of this page. * @private */ bite.client.console.NewBug.prototype.getScreenshot_ = function() { chrome.extension.sendRequest( {action: Bite.Constants.HUD_ACTION.GET_SCREENSHOT}, goog.bind(this.getScreenshotCallback_, this)); }; /** * Callback function to call after the current page's screenshot was captured. * @param {string} dataUrl The data URL string. * @private */ bite.client.console.NewBug.prototype.getScreenshotCallback_ = function(dataUrl) { this.container_.show(); var container = goog.dom.getElement('bite-nbg-screenshot'); this.screenshotCheckbox_ = container.querySelector(goog.dom.TagName.INPUT); this.screenshotCheckbox_.checked = true; this.screenshot_ = dataUrl; goog.events.listen(container, goog.events.EventType.CLICK, goog.bind(this.showScreenshotHandler_, this)); }; /** * Shows the captured screenshot data. * @param {Event} event Event data. * @private */ bite.client.console.NewBug.prototype.showScreenshotHandler_ = function(event) { var label = 'SUCCESS'; var text = 'ShowNewBugScreenshot'; if (event.target != this.screenshotCheckbox_) { goog.global.open(this.screenshot_); } else { label = 'NEW_VALUE: ' + this.screenshotCheckbox_.checked; text = 'ToggleNewBugScreenshotCheckbox'; } bite.client.console.NewBug.logEvent_(text, label); }; /** * Allows the user to select a different UI element. * @private */ bite.client.console.NewBug.prototype.replaceElement_ = function() { var replace = this.container_.getRoot().querySelector('#replace'); var replaceText = goog.dom.getFirstElementChild(replace); // RecordModeManager highlights items that the mouse hovers over until one // is clicked, then calls its callback on that element. if (!this.recordModeManager_) { this.recordModeManager_ = new common.client.RecordModeManager(); } if (this.recordModeManager_.isRecording()) { // If the user clicks 'replace' again, cancel the selection process. replaceText.innerHTML = 'replace'; this.recordModeManager_.exitRecordingMode(); this.initializeHighlightBox_(); this.showJson_(); } else { replaceText.innerHTML = 'cancel'; this.showTargetElement_('Select a new UI element'); // Remove the current highlight box. goog.dom.removeNode(this.pingDiv_); this.pingDiv_ = null; this.recordModeManager_.enterRecordingMode( goog.bind(this.replaceSelectedElement_, this)); } }; /** * Replaces the selected UI element. * @param {Element} elem The new element. * @private */ bite.client.console.NewBug.prototype.replaceSelectedElement_ = function(elem) { if (!this.recordModeManager_.isRecording()) { return; } var replace = this.container_.getRoot().querySelector('#replace'); var replaceText = goog.dom.getFirstElementChild(replace); replaceText.innerHTML = 'replace'; this.recordModeManager_.exitRecordingMode(); // Don't select items from the newbug console. var console = goog.dom.getElement('bite-newbug-console'); if (!goog.dom.contains(console, elem)) { this.selectedElement_ = elem; } this.initializeHighlightBox_(); this.showJson_(); }; /** * Initializes the div that highlights the selected element. * @private */ bite.client.console.NewBug.prototype.initializeHighlightBox_ = function() { if (this.selectedElement_) { this.pingDiv_ = goog.dom.createDom(goog.dom.TagName.DIV, { 'id' : 'bite-nbg-highlight-box', 'style' : 'position:absolute;' }); goog.dom.appendChild(goog.global.document.body, this.pingDiv_); this.updateHighlightBoxPosition_(); } }; /** * Updates the position of the highlight box to be that of the currently * selected element. * @private */ bite.client.console.NewBug.prototype.updateHighlightBoxPosition_ = function() { var elem = this.selectedElement_; goog.style.setPosition(this.pingDiv_, goog.style.getPageOffset(elem)); goog.style.setSize(this.pingDiv_, goog.style.getSize(elem)); }; /** * Highlights the selected element briefly. * @private */ bite.client.console.NewBug.prototype.pingElementOn_ = function() { goog.dom.classes.add(this.pingDiv_, 'bite-nbg-emphasis'); goog.Timer.callOnce(goog.bind(this.pingElementOff_, this), 1000); }; /** * Turns off highlighting of the selected element. * @private */ bite.client.console.NewBug.prototype.pingElementOff_ = function() { goog.dom.classes.remove(this.pingDiv_, 'bite-nbg-emphasis'); }; /** * Handles selection changing the templates dropdown. * @private */ bite.client.console.NewBug.prototype.changeTemplateHandler_ = function() { var selectedIndex = this.templatesList_.selectedIndex; var selectedTemplate = this.templatesList_.options[selectedIndex].value; var notes = this.templates_[selectedTemplate].noteText; this.notesTextArea_.value = notes; }; /** * Takes a button Element and styles it as pressed or not pressed * according to the parameter 'pressed'. * @param {Element} button The button to style. * @param {boolean} pressed Whether or not the element should be pressed. * @private */ bite.client.console.NewBug.prototype.stylePressedButton_ = function(button, pressed) { if (pressed) { goog.dom.classes.add(button, 'bite-pressed'); } else { goog.dom.classes.remove(button, 'bite-pressed'); } }; /** * Shows outerHTML of the selected element in the UI tab of New Bug. * @private */ bite.client.console.NewBug.prototype.showOuterHtml_ = function() { var outerHtml = common.client.ElementDescriptor.generateOuterHtml( this.selectedElement_); this.showTargetElement_(outerHtml); var json = this.container_.getRoot().querySelector('#json'); var html = this.container_.getRoot().querySelector('#html'); this.stylePressedButton_(json, false); this.stylePressedButton_(html, true); }; /** * Shows JSON of the selected element in the UI tab of New Bug. * @private */ bite.client.console.NewBug.prototype.showJson_ = function() { var descriptor = common.client.ElementDescriptor.generateElementDescriptorNAncestors( this.selectedElement_, 3); this.showTargetElement_(descriptor); var json = this.container_.getRoot().querySelector('#json'); var html = this.container_.getRoot().querySelector('#html'); this.stylePressedButton_(json, true); this.stylePressedButton_(html, false); }; /** * Public function to clean up the console. */ bite.client.console.NewBug.prototype.cancel = function() { this.cancelHandler_(); }; /** * Cancels the console. * @private */ bite.client.console.NewBug.prototype.cancelHandler_ = function() { this.destroyrootElement_(); this.cleanUp_(); }; /** * Cleans up the listeners for the New Bug Console and calls the doneCallback. * @private */ bite.client.console.NewBug.prototype.cleanUp_ = function() { goog.dom.removeNode(this.pingDiv_); this.pingDiv_ = null; this.eventHandler_.removeAll(); this.doneCallback_(); }; /** * Saves the script to server. * @private */ bite.client.console.NewBug.prototype.saveScriptToServer_ = function() { var datafile = bite.console.Helper.appendInfoMap( this.recordingInfoMap_, this.recordingData_); chrome.extension.sendRequest( {'command': Bite.Constants.CONSOLE_CMDS.UPDATE_ON_WEB, 'params': {'testName': this.titleTextArea_.value, 'startUrl': goog.global.location.href, 'scripts': this.recordingScript_, 'datafile': datafile, 'userLib': '', 'projectName': 'bugs', 'screenshots': '', 'needOverride': ''}}); }; /** * Submits the New Bug Form. The first step is to retrieve the server url. * @private */ bite.client.console.NewBug.prototype.submitHandler_ = function() { // Extract data for the new bug. var selectedIndex = this.templatesList_.selectedIndex; var selectedTemplate = this.templatesList_.options[selectedIndex].value; var title = this.titleTextArea_.value; if (!title) { alert('Title is required'); return; } var details = this.templates_[selectedTemplate]; var project = details.backendProject; var provider = details.backendProvider; var notes = this.notesTextArea_.value || ''; var descriptor = common.client.ElementDescriptor.generateElementDescriptorNAncestors( this.selectedElement_, 3); var label = ''; var screenshot = null; if (this.screenshotCheckbox_.checked) { screenshot = this.screenshot_; label = 'SELECTED'; } else { label = 'NOT_SELECTED'; } bite.client.console.NewBug.logEvent_('SubmitNewBugScreenshot', label); // Construct new bug data and send a post to the server. var data = { 'title': title, 'url': this.url_, 'summary': notes, 'state': 'active', 'provider': provider, 'project': project, 'target_element': descriptor, 'recording_link': this.recordingLink_, 'version': goog.userAgent.VERSION }; if (screenshot) { data['screenshot'] = screenshot; } var requestData = {'action': Bite.Constants.HUD_ACTION.CREATE_BUG, 'details': data}; chrome.extension.sendRequest(requestData, goog.bind(this.onSubmitComplete_, this)); }; /** * Handles the response from the server after filing a new bug. * @param {!{success: boolean, error: string, key: number}} result The object * containing the results of the create new bug request. * @private */ bite.client.console.NewBug.prototype.onSubmitComplete_ = function(result) { // TODO (jason.stredwick): Test out failing to create a bug. // TODO (jason.stredwick): Figure out alternative to alert. Using alert // because it is used elsewhere in this interface. Find a non-blocking // alternative. if (!result['success']) { alert(result['error']); return; } // TODO (jason.stredwick): Remove log after testing of handlers is // complete. console.log('new bug with key: ' + result['key']); // TODO (jason.stredwick): Revisit the opening of the bug in a new window // after filing. Disabled for now. //if (success) { // goog.global.window.open(url); //} // TODO (jason.stredwick): Redo how attachments are specified for bugs and // then how to attach rpf scripts. // Once the bug has been filed, save the auto rpf script. this.saveScriptToServer_(); // Inform the other bug related consoles that they need to update. var action = {action: Bite.Constants.HUD_ACTION.UPDATE_DATA}; chrome.extension.sendRequest(action); // Record success and clean up console. var label = 'SUCCESS: New Bug submitted.'; // 'to project ' + result['project'] + '.'; bite.client.console.NewBug.logEvent_('SubmitNewBug', label); this.destroyrootElement_(); this.cleanUp_(); }; /** * Sets New Bug Form handlers. * @private */ bite.client.console.NewBug.prototype.setConsoleHandlers_ = function() { var cancelLink = goog.dom.getElementByClass('bite-close-button', this.container_.getRoot()); this.eventHandler_.listen(cancelLink, goog.events.EventType.CLICK, goog.bind(this.cancelHandler_, this)); var finishLink = this.container_.getRoot().querySelector('#bite-nbg-submit'); this.eventHandler_.listen(finishLink, goog.events.EventType.CLICK, goog.bind(this.submitHandler_, this)); // Handler for the template list. if (this.templatesList_) { this.eventHandler_.listen(this.templatesList_, goog.events.EventType.CHANGE, goog.bind(this.changeTemplateHandler_, this)); } var recordingTab = this.container_.getRoot().querySelector('td.bite-nbg-recording-tab'); this.eventHandler_.listen(recordingTab, goog.events.EventType.CLICK, goog.bind(this.changeTabHandler_, this, bite.client.console.NewBug.Tab_.RECORDING)); var overviewTab = this.container_.getRoot().querySelector('td.bite-nbg-overview-tab'); this.eventHandler_.listen(overviewTab, goog.events.EventType.CLICK, goog.bind(this.changeTabHandler_, this, bite.client.console.NewBug.Tab_.OVERVIEW)); var uiTab = this.container_.getRoot().querySelector('td.bite-nbg-ui-tab'); this.eventHandler_.listen(uiTab, goog.events.EventType.CLICK, goog.bind(this.changeTabHandler_, this, bite.client.console.NewBug.Tab_.UI)); // Handler for readable recorded script in Recording tab. var readable = this.container_.getRoot().querySelector('#readable'); if (readable) { this.eventHandler_.listen(readable, goog.events.EventType.CLICK, goog.bind(this.showRecordingScriptReadable_, this)) } // Handler for not human readable recorded script in Recording tab. var code = this.container_.getRoot().querySelector('#code'); if (code) { this.eventHandler_.listen(code, goog.events.EventType.CLICK, goog.bind(this.showRecordingScriptCode_, this)); } // Handler for play button in Recording tab. var play = this.container_.getRoot().querySelector('#play'); if (play) { this.eventHandler_.listen(play, goog.events.EventType.CLICK, goog.bind(this.playRecordingScript_, this)); } // Handler for outerHTML representation of target element in UI tab. var html = this.container_.getRoot().querySelector('#html'); if (html) { this.eventHandler_.listen(html, goog.events.EventType.CLICK, goog.bind(this.showOuterHtml_, this)); } // Handler for JSON representation of target element in UI tab. var json = this.container_.getRoot().querySelector('#json'); if (json) { this.eventHandler_.listen(json, goog.events.EventType.CLICK, goog.bind(this.showJson_, this)); } // Handler for replacing the target element in UI tab. var replace = this.container_.getRoot().querySelector('#replace'); if (replace) { this.eventHandler_.listen(replace, goog.events.EventType.CLICK, goog.bind(this.replaceElement_, this)); } // Handler for identifying the target element in UI tab. var ping = this.container_.getRoot().querySelector('#ping'); if (ping) { this.eventHandler_.listen(ping, goog.events.EventType.CLICK, goog.bind(this.pingElementOn_, this)); } }; /** * Destroys console's root element. * @private */ bite.client.console.NewBug.prototype.destroyrootElement_ = function() { this.container_.remove(); this.templatesList_ = null; this.container_ = null; }; /** * Shows the recording script in readable form. * @private */ bite.client.console.NewBug.prototype.showRecordingScriptReadable_ = function() { this.showRecordingScript_(this.recordingReadable_); var codeButton = this.container_.getRoot().querySelector('#code'); var readableButton = this.container_.getRoot().querySelector('#readable'); this.stylePressedButton_(codeButton, false); this.stylePressedButton_(readableButton, true); }; /** * Shows the recording script in code form. * @private */ bite.client.console.NewBug.prototype.showRecordingScriptCode_ = function() { this.showRecordingScript_(this.recordingScript_); var codeButton = this.container_.getRoot().querySelector('#code'); var readableButton = this.container_.getRoot().querySelector('#readable'); this.stylePressedButton_(codeButton, true); this.stylePressedButton_(readableButton, false); }; /** * Shows recorded script in Recording tab of New Bug Form. * @param {?string} script The recorded script. * @private */ bite.client.console.NewBug.prototype.showRecordingScript_ = function(script) { if (!this.recordingScript_) { script = 'No recording has been captured for this page.'; } script = bite.console.Helper.getDocString( goog.global.location.hostname, this.user_ ? this.user_ : 'rpf') + script; this.recordingTextArea_.value = script; }; /** * Plays recorded script from Recording tab in New Bug Form. * @private */ bite.client.console.NewBug.prototype.playRecordingScript_ = function() { if (!this.recordingScript_) { alert('No script recorded'); return; } chrome.extension.sendRequest( {'command': Bite.Constants.CONSOLE_CMDS.CHECK_PLAYBACK_OPTION_AND_RUN, 'params': {'method': Bite.Constants.PlayMethods.ALL, 'startUrl': 'http://maps.google.com', 'scripts': this.recordingScript_, 'datafile': this.recordingData_, 'infoMap': this.recordingInfoMap_, 'preparationDone': false, 'userLib': '', 'needOverride': ''}}); }; /** * Shows outerHTML or JSON descriptor of target element in UI tab of New Bug * Form. * @param {?string} descriptor The outerHTML or JSON descriptor of target * element. * @private */ bite.client.console.NewBug.prototype.showTargetElement_ = function(descriptor) { this.uiTextArea_.value = descriptor; }; /** * Highlights selected tab's title in New Bug Form. * @param {Element} newBugFormTabElmt The tab title element in * New Bug Form (Overview, UI, Recording, etc.). * @param {boolean} selected Whether the corresponding tab is selected. * @private */ bite.client.console.NewBug.prototype.highlightTabTitle_ = function( newBugFormTabElmt, selected) { if (selected) { goog.dom.classes.swap(newBugFormTabElmt, 'bite-navbar-item-inactive', 'bite-navbar-item-active'); } else { goog.dom.classes.swap(newBugFormTabElmt, 'bite-navbar-item-active', 'bite-navbar-item-inactive'); } }; /** * Changes tabs in New Bug Console. * @param {?bite.client.console.NewBug.Tab_} selectedTab The selected tab in * New Bug Form (Overview, Recording, etc.). * @private */ bite.client.console.NewBug.prototype.changeTabHandler_ = function( selectedTab) { var consoleToolbar = this.container_.getRoot().querySelector('div.bite-console-toolbar'); soy.renderElement(consoleToolbar, bite.client.console.NewBugTemplate.getConsoleToolbar, {selectedTab: selectedTab}); // Shows contents of selected tab, and hides contents of other tabs in New // Bug Form. var recordingTabContents = this.container_.getRoot().querySelector('div.bite-nbg-recording-data'); var overviewTabContents = this.container_.getRoot().querySelector('div.bite-nbg-overview-data'); var uiTabContents = this.container_.getRoot().querySelector('div.bite-nbg-ui-data'); var isOverviewTab = selectedTab == bite.client.console.NewBug.Tab_.OVERVIEW; var isUITab = selectedTab == bite.client.console.NewBug.Tab_.UI; var isRecordingTab = selectedTab == bite.client.console.NewBug.Tab_.RECORDING; goog.style.showElement(overviewTabContents, false); goog.style.showElement(uiTabContents, false); goog.style.showElement(recordingTabContents, false); var message = ''; var messageId = ''; if (isOverviewTab) { message = 'Fill out a description of the bug and a title. Explore the ' + 'other tabs for additional options, and click Bug it! when finished.'; messageId = 'newbug-overview-intro'; goog.style.showElement(overviewTabContents, true); } else if (isRecordingTab) { message = 'If automatic recording is turned on, a playback of your ' + 'actions will be displayed here. Visit the BITE settings to turn on ' + 'automatic recording.'; messageId = 'newbug-recording-info'; goog.style.showElement(recordingTabContents, true); this.showRecordingScriptReadable_(); } else if (isUITab) { message = 'Information about the selected UI element is shown here. ' + 'Click replace to choose a new element, or ping to see the current ' + 'one.'; messageId = 'newbug-ui-intro'; goog.style.showElement(uiTabContents, true); this.showJson_(); } this.container_.showInfoMessageOnce(messageId, message); // Highlights selected tab title (in blue), and removes blue selection from // other tab titles in New Bug Form. var recordingTabElmt = this.container_.getRoot().querySelector('td.bite-nbg-recording-tab'); var uiTabElmt = this.container_.getRoot().querySelector('td.bite-nbg-ui-tab'); var overviewTabElmt = this.container_.getRoot().querySelector('td.bite-nbg-overview-tab'); this.highlightTabTitle_(overviewTabElmt, isOverviewTab); this.highlightTabTitle_(uiTabElmt, isUITab); this.highlightTabTitle_(recordingTabElmt, isRecordingTab); this.eventHandler_.removeAll(); this.setConsoleHandlers_(); }; /** * Loads the New Bug console. * @param {Element} selectedElement Element the bug is related to. * @param {string} server The current server url. * @param {!Object.<string, bite.client.BugTemplate>} templates The list of * templates to show. * @param {?string} opt_template The id of the initial template to show. * @param {?string} opt_recordingLink The link to recorded script. * @param {?string} opt_recordingScript The recorded script. * @param {?string} opt_recordingReadable The recorded script in human readable * format. * @param {?string} opt_recordingData The recorded data (e.g. when user types). * @param {Object=} opt_recordingInfoMap The info map for the recordings. */ bite.client.console.NewBug.prototype.show = function( selectedElement, server, templates, opt_template, opt_recordingLink, opt_recordingScript, opt_recordingReadable, opt_recordingData, opt_recordingInfoMap) { this.selectedElement_ = selectedElement; this.initializeHighlightBox_(); var template = opt_template || ''; this.templates_ = templates; this.url_ = this.getCurrentUrl_(); this.container_ = new bite.client.Container(server, 'bite-newbug-console', 'New Bug', 'File a new bug', false, true); var templatesByProject = bite.client.TemplateManager.getTemplatesByProject( this.templates_); this.container_.setContentFromHtml( bite.client.console.NewBugTemplate.newBugConsole( {rootFolder: this.rootFolder_, projects: templatesByProject})); this.titleTextArea_ = this.container_.getRoot().querySelector('#bite-nbg-title'); this.templatesList_ = this.templatesList_ ? this.templatesList_ : this.container_.getRoot().querySelector('#bite-nbg-templates'); this.notesTextArea_ = this.container_.getRoot().querySelector('#bite-nbg-notes'); this.uiTextArea_ = this.container_.getRoot().querySelector('#bite-nbg-ui-text'); this.recordingTextArea_ = this.container_.getRoot().querySelector('#bite-nbg-recording-text'); this.setConsoleHandlers_(); if (!template || template == 'default') { template = 'bite_default_bug'; } this.recordingLink_ = opt_recordingLink || ''; this.recordingScript_ = opt_recordingScript || ''; this.recordingReadable_ = opt_recordingReadable || ''; this.recordingData_ = opt_recordingData || ''; this.recordingInfoMap_ = opt_recordingInfoMap || {}; var newTemplate = this.templatesList_.querySelector( '[value=' + template + ']'); newTemplate.selected = 'true'; this.changeTabHandler_(bite.client.console.NewBug.Tab_.OVERVIEW); this.changeTemplateHandler_(); // Wait for the screen to refresh and show the highlighted element before // taking a screenshot. goog.Timer.callOnce(goog.bind(this.getScreenshot_, this), 10); };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Handles the Bugs console, which displays information about bugs * that have already been filed on the domain being explored. * * @author ralphj@google.com (Julie Ralph) */ goog.provide('bite.client.BugsConsole'); goog.require('bite.client.BugDetailsPopup'); goog.require('bite.client.BugHelper'); goog.require('bite.client.BugOverlay'); goog.require('bite.client.Container'); goog.require('bite.client.MiniBugPopup'); goog.require('bite.client.Templates'); goog.require('goog.dom'); goog.require('goog.events'); goog.require('goog.events.EventHandler'); goog.require('goog.ui.AnimatedZippy'); goog.require('soy'); /** * Creates a bugs console and displays it on the current page. * @param {?string} user The email of the current user. * @param {string} server The current server channel. * @param {bite.client.BugOverlay} overlay The bug overlay manager. * @constructor */ bite.client.BugsConsole = function(user, server, overlay) { /** * The bugs console container. * @type {bite.client.Container} * @private */ this.container_ = null; /** * Manages events on the overlay. * @type {goog.events.EventHandler} * @private */ this.eventHandler_ = new goog.events.EventHandler(); /** * The bug overlay associated with this page. * @type {bite.client.BugOverlay} * @private */ this.bugOverlay_ = overlay; /** * The bugs data. * @type {Object} * @private */ this.bugs_ = null; this.load_(user, server); }; /** * Bug keys used as label indicators. * @enum {string} * @private */ bite.client.BugsConsole.LabelKey_ = { BOUND: 'target_element', RECORDING: 'recording_link' }; /** * The key used by bugs to identify label information. * @type {string} * @private */ bite.client.BugsConsole.LABEL_ID_ = 'labels'; /** * Label data represent valid keys that are interpretted by soy when converting * label information into html. * @enum {string} * @private */ bite.client.BugsConsole.LabelData_ = { BACKGROUND_COLOR: 'bgColor', NAME: 'name' }; /** * Label name. * @enum {string} * @private */ bite.client.BugsConsole.LabelName_ = { BOUND: 'bound', RECORDING: 'recording' }; /** * Returns whether or not the console is currently visible on screen. * @return {boolean} True if the console is visible. */ bite.client.BugsConsole.prototype.isConsoleVisible = function() { if (!this.container_) { return false; } return this.container_.isVisible(); }; /** * Updates the data about bugs, and does necessary updates to * the UI and the overlay if applicable. * @param {Object} bugs The new bugs data to use. * @param {?string} user The user's e-mail. * @param {string} server The server url. */ bite.client.BugsConsole.prototype.updateData = function(bugs, user, server) { this.bugs_ = bugs; if (this.container_) { this.renderBugList_(user, server); } }; /** * Removes the console element from the page. * @return {boolean} Whether the console was removed or not. */ bite.client.BugsConsole.prototype.removeConsole = function() { if (this.container_) { if (this.bugOverlay_) { this.bugOverlay_.remove(); } this.container_.remove(); this.container_ = null; this.eventHandler_.removeAll(); return true; } return false; }; /** * Hides the console element from the page. */ bite.client.BugsConsole.prototype.hideConsole = function() { if (this.bugOverlay_) { this.bugOverlay_.remove(); } if (this.container_) { this.container_.hide(); } }; /** * Shows the console element. */ bite.client.BugsConsole.prototype.showConsole = function() { if (this.container_) { this.container_.show(); } }; /** * Loads the console. * @param {?string} user The user's e-mail. * @param {string} server The server url. * @private */ bite.client.BugsConsole.prototype.load_ = function(user, server) { this.container_ = new bite.client.Container(server, 'bite-bugs-console', 'Bugs', 'Explore existing bugs', true); var rootFolder = chrome.extension.getURL(''); this.container_.setContentFromHtml(bite.client.Templates.bugConsole( {rootFolder: rootFolder})); // Will check the render state and render the bug list if appropriate. this.renderBugList_(user, server); this.setConsoleHandlers_(); }; /** * Renders the bugs in the Bug Console. * @param {?string} user The user's e-mail. * @param {string} server The server url. * @private */ bite.client.BugsConsole.prototype.renderBugList_ = function(user, server) { // Assumes that the console has been loaded. var contentCanvas = this.container_.getRoot().querySelector('#bite-bugs-content-canvas'); // Add a login url if there is no user currently logged in. if (!user) { contentCanvas.innerHTML = '<a href="' + server + '">Please login</a> to view available bugs.</b>'; return; } // Keep the current message if bugs have not yet been loaded. if (!this.bugs_) { return; } // Add a short message if there are no bugs to display. if (this.bugs_.length <= 0) { contentCanvas.innerHTML = '<p style="font-weight: bold">' + 'No known bugs in this page.</p>'; return; } // Results is an array of bugs associated with a specific url. The array // holds Objects of type {url: string, bugs: Array.<Bug Objects>}. var results = []; // allBugs is an array of all the bug objects. The list has no direct ties // to a url like results. var allBugs = []; for (var i = 0; i < this.bugs_.length; ++i) { var bugs = this.bugs_[i][1]; var result = {'url': this.bugs_[i][0], 'bugs': []}; var bugList = result['bugs']; for (var j = 0; j < bugs.length; ++j) { var bug = bugs[j]; if (bug['visible']) { bug.img = bite.client.BugHelper.getBugIcon(bug['state']); bite.client.BugsConsole.applyLabels_(bug); bugList.push(bug); } } goog.array.sort(bugList, bite.client.BugHelper.CompareBugsState); // Extend existing AllBugs array with all additional bugs found. // Equivalent to Python's array.extend method. Array.prototype.push.apply(allBugs, bugList); // Only include the sections if applicable bugs were found. if (result['bugs'].length > 0) { results.push(result); } } contentCanvas.innerHTML = bite.client.Templates.addRows({results: results}); // Once the page has been rendered, determine if any bugs are visible and // give the special "no bugs" message instead of a blank slate. var rows = contentCanvas.querySelectorAll('.bite-bugs-row'); if (!rows.length) { contentCanvas.innerHTML = '<p style="font-weight: bold">' + 'No known bugs in this page.</p>'; return; } var resultContainers = contentCanvas.querySelectorAll( '.bite-bugs-console-result-container'); // Create animated drop downs for the bug lists. for (var i = resultContainers.length - 1; i >= 0; --i) { var curr = resultContainers[i]; var header = goog.dom.getFirstElementChild(curr); var containerBody = goog.dom.getNextElementSibling(header); // Creating an instance of AnimatedZippy on the header and body for each // container causes the Zippy to be attached to the elements. Always // open the first category (when i == 0 is true). var zippy = new goog.ui.AnimatedZippy(header, containerBody, i == 0); } for (var i = rows.length - 1; i >= 0; --i) { this.eventHandler_.listen(rows[i], goog.events.EventType.CLICK, goog.bind(this.handleBugRowClick_, this, allBugs[i])); this.eventHandler_.listen(rows[i], goog.events.EventType.MOUSEDOWN, goog.bind(this.handleBugRowMouseDown_, this, allBugs[i])); } }; /** * Given a bug, adds the appropriate label information to that object. * Currently, it is assumed that no labels will be added from the server and * only those determined by this function will be displayed. A different * approach will be required to reduce duplicates if the assumption proves * false. * @param {Object} bug A reference to the bug to update. * @private */ bite.client.BugsConsole.applyLabels_ = function(bug) { var labels = []; // Add appropriate labels to the bug. for (var labelKey in bite.client.BugsConsole.LabelKey_) { var key = bite.client.BugsConsole.LabelKey_[labelKey]; // Check if each of the desired labels are in the bug. if (bug[key]) { var label = {}; var hasLabel = false; // Handle the specific label. switch (key) { case bite.client.BugsConsole.LabelKey_.BOUND: if (bug[bite.client.BugsConsole.LabelKey_.BOUND] != 'null') { label[bite.client.BugsConsole.LabelData_.NAME] = bite.client.BugsConsole.LabelName_.BOUND; hasLabel = true; } break; case bite.client.BugsConsole.LabelKey_.RECORDING: label[bite.client.BugsConsole.LabelData_.NAME] = bite.client.BugsConsole.LabelName_.RECORDING; hasLabel = true; break; } // Add the newly created label to the list of labels. if (hasLabel) { labels.push(label); } } } // Update the bug with the new list of labels. bug[bite.client.BugsConsole.LABEL_ID_] = labels; }; /** * Handles starting a new bug. * @private */ bite.client.BugsConsole.prototype.startNewBugHandler_ = function() { chrome.extension.sendRequest( {'action': Bite.Constants.HUD_ACTION.START_NEW_BUG}); }; /** * Sets up the handlers for the bugs console. * @private */ bite.client.BugsConsole.prototype.setConsoleHandlers_ = function() { var hideConsole = goog.dom.getElementByClass('bite-close-button', this.container_.getRoot()); if (hideConsole) { this.eventHandler_.listen(hideConsole, goog.events.EventType.CLICK, goog.bind(this.hideConsole, this)); } var newBugButton = goog.dom.getElement('bite-toolbar-button-new-bug'); if (newBugButton) { this.eventHandler_.listen(newBugButton, goog.events.EventType.CLICK, goog.bind(this.startNewBugHandler_, this)); } var overlayBugsButton = goog.dom.getElement('bite-toolbar-button-overlay-bugs'); if (overlayBugsButton) { this.eventHandler_.listen(overlayBugsButton, goog.events.EventType.CLICK, goog.bind(this.toggleBugOverlay_, this)); } }; /** * Handles a mouse down event on a row in the Bugs console. * @param {Object} bugData The corresponding bug data for the row. * @param {Object} e The MouseEvent object from the mousedown. * @private */ bite.client.BugsConsole.prototype.handleBugRowMouseDown_ = function(bugData, e) { bite.client.MiniBugPopup.getInstance().initDragBugBinding(bugData, e); }; /** * Handles a user clicking on a row in the Bugs console. * @param {Object} bugData The corresponding bug data for the row clicked. * @param {Object} e The MouseEvent object from a user clicking. * @private */ bite.client.BugsConsole.prototype.handleBugRowClick_ = function(bugData, e) { var win = goog.dom.getWindow(); bite.client.BugDetailsPopup.getInstance().createBugPopup( win.pageXOffset + e.clientX - 5, win.pageYOffset + e.clientY - 5, bugData, this); }; /** * Toggles the bug overlay mechanism. * @private */ bite.client.BugsConsole.prototype.toggleBugOverlay_ = function() { if (this.bugOverlay_.bugOverlayOn()) { this.bugOverlay_.remove(); } else { this.bugOverlay_.render(); } var label = 'NEW_VISIBILITY: ' + this.bugOverlay_.bugOverlayOn(); chrome.extension.sendRequest( {'action': Bite.Constants.HUD_ACTION.LOG_EVENT, 'category': Bite.Constants.TestConsole.BUGS, 'event_action': 'ToggleBugOverlay', 'label': label}); this.updateBugOverlayUI_(); }; /** * Updates the Bug Overlay UI depending on whether overlay is enabled or not. * @private */ bite.client.BugsConsole.prototype.updateBugOverlayUI_ = function() { var overlayButton = goog.dom.getElement('bite-toolbar-button-overlay-bugs'); if (overlayButton) { if (this.bugOverlay_.bugOverlayOn()) { goog.dom.classes.add(overlayButton, 'bite-pressed'); } else { goog.dom.classes.remove(overlayButton, 'bite-pressed'); } } };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Provides access to Bug Templates used in BITE. * * @author ralphj@google.com (Julie Ralph) */ goog.provide('bite.client.BugTemplate'); goog.provide('bite.client.BugTemplateList'); goog.provide('bite.client.TemplateManager'); goog.require('Bite.Constants'); goog.require('bite.common.net.xhr.async'); goog.require('bite.options.constants'); goog.require('bite.options.data'); goog.require('goog.Uri'); goog.require('goog.json'); goog.require('goog.string'); /** * A template for filing a new bug. The id is assumed to be unique. * Urls will determine which sites the bug is visible for. * * @typedef {{id: string, * name: string, * urls: Array.<string>, * project: string, * backendProject: string, * backendProvider: string, * selectorText: string, * displayOrder: number, * noteText: string}} */ bite.client.BugTemplate; /** * A map of bug templates, keyed by templateId. * @typedef {Object.<string, bite.client.BugTemplate>} */ bite.client.BugTemplateList; /** * A template manager grabs bug templates from the server. * @constructor */ bite.client.TemplateManager = function() { /** * An object holding all possible templates that have been retrieved from * the server, keyed by their template id. * @type {bite.client.BugTemplateList} * @private */ this.templates_ = {}; /** * Whether or not the list of templates has finished loading. * @type {boolean} * @private */ this.loaded_ = false; }; goog.addSingletonGetter(bite.client.TemplateManager); /** * URL path for the get templates API. * @type {string} * @private */ bite.client.TemplateManager.FETCH_TEMPLATE_PATH_ = '/get_templates'; /** * The default bug template. It is used when no other template is provide. * @type {bite.client.BugTemplate} * @private */ bite.client.TemplateManager.DEFAULT_TEMPLATE_ = { id: 'bite_default_bug', name: 'Datastore Default', urls: [], project: 'Datastore Default', backendProject: 'Datastore Default', backendProvider: Bite.Constants.Providers.DATASTORE, selectorText: 'Datastore Default', displayOrder: 0, noteText: 'Describe your problem: ' }; /** * Helper function which converts a BugTemplateList into an array of objects * where each object contains the project name and a list of templates * within in the project. * * @param {bite.client.BugTemplateList} templates The raw templates. * @return {!Array.<{name: string, templates: Array.<bite.client.BugTemplate>}>} */ bite.client.TemplateManager.getTemplatesByProject = function(templates) { var projects = {}; for (var templateId in templates) { var template = templates[templateId]; var projectName = template['project']; if (!projects[projectName]) { projects[projectName] = {'templates': []}; } projects[projectName]['templates'].push(template); } var templatesByProject = []; for (var project in projects) { templatesByProject.push({name: project, templates: projects[project]['templates']}); } return templatesByProject; }; /** * Asks the Template Manager to load templates from the server. This can be * used to pre-load templates and avoid a pause later in the application, or * to force the Template Manager to refresh its cache of templates. */ bite.client.TemplateManager.prototype.forceLoadTemplates = function() { this.loadTemplates_(function() {}); }; /** * Passes a list of all loaded templates to the callback. * @param {function(bite.client.BugTemplateList)} callback A callback. */ bite.client.TemplateManager.prototype.getAllTemplates = function(callback) { if (!this.loaded_) { this.loadTemplates_(callback); } else { callback(this.templates_); } }; /** * Creates an array of all templates relevant to the input URL. * @param {function(bite.client.BugTemplateList)} callback A callback. * @param {string} url The URL to find templates for. */ bite.client.TemplateManager.prototype.getTemplatesForUrl = function(callback, url) { if (!this.loaded_) { this.loadTemplates_(goog.bind(this.getTemplatesForUrlInternal_, this, callback, url)); } else { this.getTemplatesForUrlInternal_(callback, url, this.templates_); } }; /** * Passes a list of all templates relevant to the URL to the callback. * TODO(ralphj): Implement a smarter system of URL matching. * * @param {function(bite.client.BugTemplateList)} callback The callback. * @param {string} url the URL to find templates for. * @param {bite.client.BugTemplateList} templates The bug templates to search * through. * @private */ bite.client.TemplateManager.prototype.getTemplatesForUrlInternal_ = function(callback, url, templates) { var hasTemplate = false; var relevantTemplates = {}; for (var templateId in templates) { var template = templates[templateId]; for (var i = 0; i < template.urls.length; ++i) { var curUrl = template.urls[i]; if (curUrl == 'all' || goog.string.startsWith(url, curUrl)) { relevantTemplates[templateId] = template; hasTemplate = true; } } } // Add default template if no templates are relevant. if (!hasTemplate) { var template = bite.client.TemplateManager.DEFAULT_TEMPLATE_; relevantTemplates[template.id] = template; } callback(relevantTemplates); }; /** * Handles the template data returned by the server. * @param {function(bite.client.BugTemplateList)} callback Function to call * with the loaded templates. * @param {boolean} success Whether or not the request was successful. * @param {Object} data The data received by the request or an error string. * @private */ bite.client.TemplateManager.prototype.loadTemplatesCallback_ = function(callback, success, data) { if (!success) { console.error('Failed to connect to load templates: ' + data); this.useDefaultTemplate_(); } else { // The data is in the form of a list of templates. try { var templates = goog.json.parse(data); if (templates.length < 1) { this.useDefaultTemplate_(); } else { this.templates_ = {}; for (var i = 0; i < templates.length; ++i) { var template = templates[i]; this.templates_[template.id] = template; } } } catch (error) { this.useDefaultTemplate_(); } } this.loaded_ = true; callback(this.templates_); }; /** * Loads all templates from the server. * @param {function(bite.client.BugTemplateList)} callback Function to call * with the loaded templates. * @private */ bite.client.TemplateManager.prototype.loadTemplates_ = function(callback) { var server = bite.options.data.get(bite.options.constants.Id.SERVER_CHANNEL); var url = goog.Uri.parse(server); url.setPath(bite.client.TemplateManager.FETCH_TEMPLATE_PATH_); bite.common.net.xhr.async.get(url.toString(), goog.bind(this.loadTemplatesCallback_, this, callback)); }; /** * Handles the case where there are no templates available. * @private */ bite.client.TemplateManager.prototype.useDefaultTemplate_ = function() { var template = bite.client.TemplateManager.DEFAULT_TEMPLATE_; this.templates_ = {}; this.templates_[template.id] = template; };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Defines kind information related to the Bugs API. * * @author jason.stredwick@gmail.com (Jason Stredwick) */ goog.provide('bugs.kind'); /** * @enum {string} */ bugs.kind.Kind = { BUG: 'bugs#bug', ID: 'bugs#id', URL_BUG_MAP: 'bugs#url-bug-map', URLS: 'bugs#urls' }; /** * @typedef {{kind: bugs.kind.Kind, // BUG * id: number, // Required aftr bug is filed. * title: string, * status: string, * state: string, * url: string, * summary: string, * added: string, * modified: string, * provider: string, * bug_id: string, * author: string, * author_id: string, * reported_on: string, * last_update: string, * last_updater: string, * project: string, * priority: string, * details_link: string, * has_target_element: boolean, * target_element: string, * has_screenshot: boolean, * screenshot: string, * has_recording: boolean, * recording: string}} */ bugs.kind.Bug; /** * @typedef {{kind: bugs.kind.Kind, // ID * id: number}} */ bugs.kind.Id; /** * @typedef {{kind: bugs.kind.Kind, // URL_BUG_MAP * mappings: !Array.<{url: string, bugs: !Array.<bugs.kind.Bug>}>}} */ bugs.kind.UrlBugMap; /** * @typedef {{kind: bugs.kind.Kind, // URLS * urls: !Array.<string>}} */ bugs.kind.Urls; /** * Callback used by create and update handlers. * * Called upon completion of the get request. The object passed to the * callback will return the success of the request. Depending on the success * the object will contain either an error property describing what went wrong * or an object containing the data for the requested bug. * * @typedef{function(!{success: boolean, error: string, bug: bugs.kind.Bug})} */ bugs.kind.callbackReturnBug; /** * Callback used by create and update handlers. * * Called upon completion of the create or update request. The object passed * to the callback will return the success of the request. Depending on the * success the object will contain either an error property describing what * went wrong or a number representing the id of the bug created or updated. * * @typedef{function(!{success: boolean, error: string, id: number})} */ bugs.kind.callbackReturnId; /** * Callback used by the urls handlers. * * Called upon completion of the urls request. The object passed to the * callback will return the success of the request. Depending on the success * the object will contain either an error property describing what went wrong * or an object containing the data for the requested bug. * * @typedef{function(!{success: boolean, error: string, * bugMap: bugs.kind.UrlBugMap})} */ bugs.kind.callbackReturnUrlBugMap;
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Tests for the New Bug Type Selector. * * @author ralphj@google.com (Julie Ralph) */ goog.require('goog.testing.MockControl'); goog.require('goog.testing.PropertyReplacer'); var mocks_ = null; var stubs_ = new goog.testing.PropertyReplacer(); /** * Example single template. */ var singleTemplate = { templateOne: { name: 'templateOne', url: 'http://www.google.com', project: 'project_test', path: 'Projects > Test', backendProject: 'test', backendProvider: Bite.Constants.Providers.ISSUETRACKER, selectorText: 'test', displayOrder: 4, noteText: 'test' } }; /** *Example multiple templates. */ var testTemplates = { templateOne: { name: 'templateOne', url: 'http://www.google.com', project: 'project_test', path: 'Projects > Test', backendProject: 'test', backendProvider: Bite.Constants.Providers.ISSUETRACKER, selectorText: 'test', displayOrder: 1, noteText: 'test' }, templateTwo: { name: 'templateTwo', url: 'http://www.google.com', project: 'project_test_2', path: 'Projects > Test2', backendProject: 'test2', backendProvider: Bite.Constants.Providers.ISSUETRACKER, selectorText: 'test2', displayOrder: 2, noteText: 'test2' } }; /** * Stores the template returned by the New Bug Type Selector when it * exits. * @constructor * @export */ mockCallBack = function() { /** * The template name that was returned. * @type {string} */ this.storedTemplate = null; /** * Whether continue has been called. * @type {boolean} */ this.continueCalled = false; }; /** * Resets storedTemplate back to its default. * @export */ mockCallBack.prototype.reset = function() { this.storedTemplate = null; this.continueCalled = false; }; /** * The actual callback to pass to NewBugTypeSelector. * @param {string} template The template name to store. * @export */ mockCallBack.prototype.templateCallback = function(template) { this.storedTemplate = template; }; /** * The continue bug callback. */ mockCallBack.prototype.continueCallback = function() { this.continueCalled = true; }; function setUp() { initChrome(); mocks_ = new goog.testing.MockControl(); this.mockCaller = new mockCallBack(); this.newBugTypeSelector = new bite.client.console.NewBugTypeSelector( goog.bind(this.mockCaller.templateCallback, this.mockCaller), goog.bind(this.mockCaller.continueCallback, this.mockCaller)); } function tearDown() { stubs_.reset(); mocks_.$tearDown(); this.mockCaller.reset(); } function testLoad() { var fakeRoot = goog.dom.createDom(goog.dom.TagName.DIV, {'id': 'fakeRootElement'}); var fakeElement = goog.dom.createDom(goog.dom.TagName.DIV, {'id': 'fakeElement'}); stubs_.set(soy, 'renderAsElement', function() {return fakeRoot}); fakeRoot.querySelector = function() {return fakeElement;}; var mockListen = mocks_.createFunctionMock('listen'); mockListen(goog.testing.mockmatchers.isObject, goog.testing.mockmatchers.isString, goog.testing.mockmatchers.isFunction).$times(3); stubs_.set(goog.events.EventHandler.prototype, 'listen', mockListen); var mockResizer = mocks_.createStrictMock(bite.client.Resizer); var mockResizerCtor = mocks_.createConstructorMock(bite.client, 'Resizer'); mockResizerCtor(fakeRoot, fakeElement, true).$returns(mockResizer); mocks_.$replayAll(); this.newBugTypeSelector.load(testTemplates); mocks_.$verifyAll(); } function testSingleTemplateExitsEarly() { this.newBugTypeSelector.load(singleTemplate); assertEquals('templateOne', this.mockCaller.storedTemplate); } function testSelectType() { stubs_.set(this.newBugTypeSelector, 'close_', function() {}); this.newBugTypeSelector.selectType_('test1'); assertEquals('test1', this.mockCaller.storedTemplate); this.newBugTypeSelector.selectType_('test2'); assertEquals('test2', this.mockCaller.storedTemplate); assertTrue(this.mockCaller.continueCalled); }
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Defines the client calls to the Bugs API. * * @author jason.stredwick@gmail.com (Jason Stredwick) */ goog.provide('bugs.api'); goog.require('bite.common.net.xhr.async'); goog.require('bite.options.constants'); goog.require('bite.options.data'); goog.require('bugs.kind'); goog.require('goog.Uri.QueryData'); /** * The handlers provided by the Bugs API. * @enum {string} * @private */ bugs.api.Handler_ = { CREATE: 'bugs', // Handler: /bugs GET: 'bugs/', // Handler: /bugs/\d+ UPDATE: 'bugs/', // Handler: /bugs/\d+ URLS: 'bugs/urls' // Handler: /urls }; /** * Create a bug. * Assumption: bug is a valid object. * @param {!bugs.kind.Bug} bug The bug details to used to create the bug. * @param {bugs.kind.callbackReturnId=} opt_callback See details for the * callbackReturnId type. */ bugs.api.create = function(bug, opt_callback) { try { var url = bugs.api.constructUrl_(bugs.api.Handler_.CREATE); bug['kind'] = bugs.kind.Kind.BUG; var data = JSON.stringify(bug); var callback = goog.partial(bugs.api.wrapperForId_, opt_callback); var headers = {'Content-Type': 'application/json'}; bite.common.net.xhr.async.post(url, data, callback, headers); } catch (error) { var msg = 'bugs.api.create failed; ' + error; opt_callback && opt_callback({success: false, error: msg}); } }; /** * Get a bug. * @param {number} id The id of the bug to retrieve. * @param {bugs.kind.callbackReturnBug=} opt_callback See details for the * callbackReturnBug. */ bugs.api.get = function(bug, opt_callback) { try { var url = bugs.api.constructUrl_(bugs.api.Handler_.GET + id); var callback = goog.partial(bugs.api.wrapperForBug_, opt_callback); bite.common.net.xhr.async.get(url, callback); } catch (error) { var msg = 'bugs.api.get failed; ' + error; opt_callback && opt_callback({success: false, error: msg}); } }; /** * Update a bug. * Assumption: bug is a valid object containing a property 'id' with either a * a numeric value or a string convertable into a numeric value. * @param {!bugs.kind.Bug} bug The bug details to update. * @param {bugs.kind.callbackWithId=} opt_callback See details for the * callbackReturnId type. */ bugs.api.update = function(bug, opt_callback) { try { var url = bugs.api.constructUrl_(bugs.api.Handler_.UPDATE + bug['id']); if (!('kind' in bug)) { bug['kind'] = bugs.kind.Kind.BUG; } var data = JSON.stringify(bug); var callback = goog.partial(bugs.api.wrapperForId_, opt_callback); var headers = {'Content-Type': 'application/json'}; bite.common.net.xhr.async.put(url, data, callback, headers); } catch (error) { var msg = 'bugs.api.update failed; ' + error; opt_callback && opt_callback({success: false, error: msg}); } }; /** * Requests a set of bugs by url. * @param {!Array.<string>} target_urls The url to get bugs for. * @param {bugs.kind.callbackReturnUrlBugMap=} opt_callback See details for the * callbackReturnUrlBugMap type. */ bugs.api.urls = function(target_urls, opt_callback) { try{ var url = bugs.api.constructUrl_(bugs.api.Handler_.URLS); var data = JSON.stringify({'kind': bugs.kind.Kind.URLS, 'urls': target_urls}); var callback = goog.partial(bugs.api.wrapperForUrlBugMap_, opt_callback); var headers = {'Content-Type': 'application/json'}; bite.common.net.xhr.async.post(url, data, callback, headers); } catch (error) { var msg = 'bugs.api.urls failed: ' + error; opt_callback && opt_callback({success: false, error: msg}); } }; /** * Constructs the url to the server using the given path. * @param {string} path The path from the server. * @returns {string} The server url including the path to the handler. * @private */ bugs.api.constructUrl_ = function(path) { var url = bite.options.data.get(bite.options.constants.Id.SERVER_CHANNEL); return url + (url[url.length - 1] == '/' ? '' : '/') + path; }; /** * Wraps the user-defined callback to ensure the return of an object with the * proper data and type information. * @param {bugs.kind.callbackReturnBug=} opt_callback See details for the * callbackReturnBug type. * @param {boolean} success Whether or not the request was a success. * @param {string} data The error message or data string returned from server. * @private */ bugs.api.wrapperForBug_ = function(opt_callback, success, data) { try { if (success) { var bug = /** @type {bugs.kind.Bug} */ (JSON.parse(data)); if (!('kind' in bug)) { throw 'Missing kind information'; } else if (bug['kind'] != bugs.kind.Kind.BUG) { throw 'Invalid kind; [kind=' + bug['kind'] + ']'; } opt_callback && opt_callback({success: true, bug: bug}); } else { throw data; // Contains error message from server. } } catch (error) { var msg = 'Invalid bug data received; ' + error; opt_callback && opt_callback({success: false, error: msg}); } }; /** * Wraps the user-defined callback to ensure the return of an object with the * proper data and type information. * @param {bugs.kind.callbackReturnId=} opt_callback See details for the * callbackReturnId type. * @param {boolean} success Whether or not the request was a success. * @param {string} data The error message or data string returned from server. * @private */ bugs.api.wrapperForId_ = function(opt_callback, success, data) { try { if (success) { var id_data = /** @type {bugs.kind.Id} */ (JSON.parse(data)); if (!('kind' in id_data)) { throw 'Missing kind information'; } else if (id_data['kind'] != bugs.kind.Kind.ID) { throw 'Invalid kind; [kind=' + id_data['kind'] + ']'; } var id = /** @type {number} */ (id_data['id']); opt_callback && opt_callback({success: true, id: id}); } else { throw data; // Contains error message from server. } } catch (error) { var msg = 'Invalid id data received; ' + error; opt_callback && opt_callback({success: false, error: msg}); } }; /** * Wraps the user-defined callback to ensure the return of an object with the * proper data and type information. * @param {bugs.kind.callbackReturnUrlBugMap=} opt_callback See details for the * callbackReturnUrlBugMap type. * @param {boolean} success Whether or not the request was a success. * @param {string} data The error message or data string returned from server. * @private */ bugs.api.wrapperForUrlBugMap_ = function(opt_callback, success, data) { try { if (success) { var bugMap = /** @type {bugs.kind.UrlBugMap} */ (JSON.parse(data)); if (!('kind' in bugMap)) { throw 'Missing kind information'; } else if (bugMap['kind'] != bugs.kind.Kind.URL_BUG_MAP) { throw 'Invalid kind; [kind=' + bugMap['kind'] + ']'; } opt_callback && opt_callback({success: true, bugMap: bugMap}); } else { throw data; // Contains error message from server. } } catch (error) { var msg = 'Invalid UrlBugMap data received; ' + error; opt_callback && opt_callback({success: false, error: msg}); } };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Helper functions for dealing with bugs. * * @author ralphj@google.com (Julie Ralph) */ goog.provide('bite.client.BugHelper'); /** * Bug icons URLs enumeration. * @enum {string} */ bite.client.BugHelper.BugIcons = { ACTIVE: chrome.extension.getURL('imgs/bug-active-32.png'), RESOLVED: chrome.extension.getURL('imgs/bug-resolved-32.png'), CLOSED: chrome.extension.getURL('imgs/bug-closed-32.png'), UNKNOWN: chrome.extension.getURL('imgs/bug-unknown-32.png') }; /** * The color to use when highlighting bugs depending on state. * @enum {string} */ bite.client.BugHelper.BugStateColor = { ACTIVE: 'red', RESOLVED: 'yellow', CLOSED: 'green', UNKNOWN: 'blue' }; /** * Bug states. * @enum {string} */ bite.client.BugHelper.BugState = { ACTIVE: 'active', RESOLVED: 'resolved', CLOSED: 'closed', UNKNOWN: 'unknown' }; /** * Compares two bugs for order, using the bug state property. * The state order is considered to be: * active < resolved < closed < unknown. * @param {{state: bite.client.BugHelper.BugState}} a The first bug to be * compared. * @param {{state: bite.client.BugHelper.BugState}} b The second bug to be * compared. * @return {number} -1 if a is before b, 0 if a is the same state as b, * 1 if a is after b. */ bite.client.BugHelper.CompareBugsState = function(a, b) { var aState = a['state']; var bState = b['state']; if (aState == bState) { return 0; } else if (aState == bite.client.BugHelper.BugState.ACTIVE) { return -1; // a should go first. } else if (bState == bite.client.BugHelper.BugState.ACTIVE) { return 1; // b should go first. } else if (aState == bite.client.BugHelper.BugState.RESOLVED) { return -1; } else if (bState == bite.client.BugHelper.BugState.RESOLVED) { return 1; } else if (aState == bite.client.BugHelper.BugState.CLOSED) { return -1; } else { return 1; // At this point aState == UNKOWN and bState == CLOSED. } }; /** * Gets the appropiate bug icon associated with the specified Bug status. * @param {bite.client.BugHelper.BugState} state The state of the bug. * @return {bite.client.BugHelper.BugIcons} An URL to an icon. */ bite.client.BugHelper.getBugIcon = function(state) { switch (state.toLowerCase()) { case bite.client.BugHelper.BugState.ACTIVE: return bite.client.BugHelper.BugIcons.ACTIVE; case bite.client.BugHelper.BugState.RESOLVED: return bite.client.BugHelper.BugIcons.RESOLVED; case bite.client.BugHelper.BugState.CLOSED: return bite.client.BugHelper.BugIcons.CLOSED; } return bite.client.BugHelper.BugIcons.UNKNOWN; }; /** * Gets the appropiate color to highlight a target element with. * @param {string} state The state of the bug, valid values are 'active', * 'resolved', 'closed', and 'unknown'. * @return {bite.client.BugHelper.BugStateColor} The color to highlight. */ bite.client.BugHelper.getBugHighlights = function(state) { switch (state.toLowerCase()) { case bite.client.BugHelper.BugState.ACTIVE: return bite.client.BugHelper.BugStateColor.ACTIVE; case bite.client.BugHelper.BugState.RESOLVED: return bite.client.BugHelper.BugStateColor.RESOLVED; case bite.client.BugHelper.BugState.CLOSED: return bite.client.BugHelper.BugStateColor.CLOSED; } return bite.client.BugHelper.BugStateColor.UNKNOWN; };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Creates a popup on the page giving users details about * a particular bug and ways to interact with it, such as commenting and * changing the status. Only one popup can exist on a page at a time, * and the popup is removed upon the user moving their mouse away. * * @author bustamante@google.com (Richard Bustamante) */ goog.provide('bite.client.BugDetailsPopup'); goog.require('Bite.Constants'); goog.require('bite.client.Templates'); goog.require('goog.Timer'); goog.require('goog.dom'); goog.require('goog.events.EventHandler'); goog.require('goog.style'); /** * Bug Details Popup class constructor. * @constructor * @export */ bite.client.BugDetailsPopup = function() { /** * Handler for popup events. * @type {goog.events.EventHandler} * @private */ this.eventHandler_ = new goog.events.EventHandler(); }; goog.addSingletonGetter(bite.client.BugDetailsPopup); /** * The width of the popup. * @type {number} * @private */ bite.client.BugDetailsPopup.BUG_POPUP_WIDTH_ = 310; /** * The height of the popup. * @type {number} * @private */ bite.client.BugDetailsPopup.BUG_POPUP_HEIGHT_ = 150; /** * The ID of the popup container. * @type {string} * @export */ bite.client.BugDetailsPopup.POPUP_CONTAINER_ID = 'bug-popup-container'; /** * An error string fragment to identify access denied errors. * @type {string} * @private */ bite.client.BugDetailsPopup.ACCESS_DENIED_ERROR_ = '403'; /** * Whether to remove the bug popup. * @type {boolean} * @private */ bite.client.BugDetailsPopup.prototype.removeBugPopup_ = false; /** * Whether to lock the bug popup from being removed. * @type {boolean} * @private */ bite.client.BugDetailsPopup.prototype.lockBugPopup_; /** * The ID of the bug being represented. * @type {string} * @private */ bite.client.BugDetailsPopup.prototype.bugId_ = ''; /** * The popup HTML container. * @type {Element} * @private */ bite.client.BugDetailsPopup.prototype.popup_; /** * The HUD content client of the caller. * * TODO(ralphj): Get rid of this circular dependency. * @type {Object} * @private */ bite.client.BugDetailsPopup.prototype.contentClient_; /** * Enum for bug icon URLs enumeration. * * TODO(ralphj): Use the BugHelper.BugIcons here instead. * @enum {string} * @export */ bite.client.BugDetailsPopup.BugIcons = { ACTIVE: 'imgs/bug-active-32.png', RESOLVED: 'imgs/bug-resolved-32.png', CLOSED: 'imgs/bug-closed-32.png', UNKNOWN: 'imgs/bug-unknown-32.png' }; /** * Enum for actions to take when interacting with Bugs. * @enum {string} * @export */ bite.client.BugDetailsPopup.BugActions = { ACTIVATE: 'activate', RESOLVE: 'resolve', VERIFY: 'verify', NOTABUG: 'notABug', COMMENT: 'comment' }; /** * Converts a string to proper case, captializing the first letter of * each word. * @param {string} string The string to convert to proper casing. * @return {string} The string with proper casing. * @export */ bite.client.BugDetailsPopup.prototype.strToProperCase = function(string) { // Replace the first character of each word with it's toUpperCase equivelant. return string.replace(/\b(.)/g, function(letter) { return letter.toUpperCase(); }); }; /** * Creates a bug popup for the specified element. * @param {Node} element The overlayElement to create a popup next to. * @param {Object} bugData A dictionary containing the bug data. * @param {Object} contentClient The HUD content client of the caller. * @return {?Element} The popup container element or null if not created. * @export */ bite.client.BugDetailsPopup.prototype.createElementBugPopup = function( element, bugData, contentClient) { // Move the popup 2 pixels up to compensate for a visual effect of the // popup having having rounded corners. var popupTop = parseInt(element.style.top, 10) - 2; // Keep the popup within the browser window. popupTop = Math.min(popupTop, goog.global.document.documentElement.clientHeight - bite.client.BugDetailsPopup.BUG_POPUP_HEIGHT_); popupTop = Math.max(popupTop, 0); // Move the popup 3 pixels away from the overlay for aesthetic reasons. var popupLeft = parseInt(element.style.left, 10) + parseInt(element.style.width, 10) + 3; // Keep the popup within the browser window. popupLeft = Math.min(popupLeft, goog.global.document.documentElement.clientWidth - bite.client.BugDetailsPopup.BUG_POPUP_WIDTH_); return this.createBugPopup(popupLeft, popupTop, bugData, contentClient); }; /** * Creates a bug popup at the specified coordinates. If a popup for the same * bug already exists or the popup is locked this function will abort and * return null. * @param {number} left The left position to create the bug popup at. * @param {number} top The top position to create the bug popup at. * @param {Object} bugData A dictionary containing the bug data. * @param {Object} contentClient The HUD content client of the caller. * @return {?Element} The popup container element or null if not created. * @export */ bite.client.BugDetailsPopup.prototype.createBugPopup = function( left, top, bugData, contentClient) { this.contentClient_ = contentClient; // If this function is called in the interim of flagBugPopupRemoval // abort destroying the popup as the user has performed an action to keep // it around. this.removeBugPopup_ = false; // If the popups have been locked, don't create a new one. if (this.lockBugPopup_) { return null; } // If a popup for the same bug already exists, don't create a duplicate, if // it's for a new bug then remove the existing popup and continue. if (this.popup_) { if (this.bugId_ == bugData['id']) { // Update position. goog.style.setPosition(this.popup_, left, top); return null; } else { this.destroyBugPopup(true); } } this.bugId_ = bugData['id']; this.popup_ = goog.dom.createDom(goog.dom.TagName.DIV, {'id': bite.client.BugDetailsPopup.POPUP_CONTAINER_ID, 'class': 'popup-empty-frame', 'style': 'position: absolute'}); goog.style.setPosition(this.popup_, left, top); goog.dom.appendChild(goog.global.document.body, this.popup_); this.drawBugData_(bugData, this.popup_); // Setup listeners to remove/keep the popup on mouse out / in respectively. this.eventHandler_.listen(this.popup_, goog.events.EventType.MOUSEOVER, goog.bind(this.flagBugPopupRemoval, this, false)); this.eventHandler_.listen(this.popup_, goog.events.EventType.MOUSEOUT, goog.bind(this.flagBugPopupRemoval, this, true)); return this.popup_; }; /** * Gets the appropiate bug icon associated with the specified Bug status. * @param {string} state The state of the bug, valid values are 'active', * 'resolved', 'closed', and 'unknown'. * @return {string} A URL to the bug icon. * @private */ bite.client.BugDetailsPopup.prototype.getBugIcon_ = function(state) { var result = null; switch (state.toLowerCase()) { case 'active': result = chrome.extension.getURL( bite.client.BugDetailsPopup.BugIcons.ACTIVE); break; case 'resolved': result = chrome.extension.getURL( bite.client.BugDetailsPopup.BugIcons.RESOLVED); break; case 'closed': result = chrome.extension.getURL( bite.client.BugDetailsPopup.BugIcons.CLOSED); break; case 'unknown': default: result = chrome.extension.getURL( bite.client.BugDetailsPopup.BugIcons.UNKNOWN); break; } return result; }; /** * Draws a popup Element with Bug data. * @param {Object} bugData A dictionary of the Bug data elements. * @param {Node} container The HTML element object of the container. * @private */ bite.client.BugDetailsPopup.prototype.drawBugData_ = function( bugData, container) { this.lockBugPopup_ = false; var iconURL = this.getBugIcon_(bugData['state']); var bugStatus = this.strToProperCase(bugData['status']); // Only use the 'yyyy-mm-dd' part of the date/time strings. var reportByDate = bugData['reported_on'].substring(0, 10); var lastUpdateByDate = bugData['last_update'].substring(0, 10); var reportByUser = bugData['author'].split('@')[0]; var reportByLink = bugData['author_url']; var lastUpdateByUser = bugData['last_updater'].split('@')[0]; var lastUpdateByLink = bugData['last_updater_url']; var bugDataPopup = goog.dom.createDom(goog.dom.TagName.DIV, {'class': 'popup-empty-frame'}); goog.dom.removeChildren(container); bugDataPopup.innerHTML = bite.client.Templates.bugDetailsPopup( {imgURI: iconURL, bugID: bugData['id'], bugLink: bugData['details_link'], status: bugStatus, priority: bugData['priority'], reportDate: reportByDate, reportBy: reportByUser, reportByURI: reportByLink, lastUpdateDate: lastUpdateByDate, lastUpdateBy: lastUpdateByUser, lastUpdateByURI: lastUpdateByLink, bugTitle: bugData['title'], state: bugData['state'], navLeft: chrome.extension.getURL('imgs/nav-left.png'), navRight: chrome.extension.getURL('imgs/nav-right.png')}); goog.dom.appendChild(container, bugDataPopup); this.createBugCommandListeners_(bugData, container); this.createBoundCommandListeners_(bugData, bugDataPopup); }; /** * Adds listeners for the "Bound" label. * @param {Object} bugData A dictionary of the Bug data elements. * @param {Node} bugDataPopup The HTML element object of the bug popup. * @private */ bite.client.BugDetailsPopup.prototype.createBoundCommandListeners_ = function( bugData, bugDataPopup) { var boundLabel = goog.dom.getElement('bug-popup-bound-label'); if (boundLabel) { this.eventHandler_.listen(boundLabel, goog.events.EventType.CLICK, goog.bind(this.showBoundLabelMenu_, this, bugData, bugDataPopup, boundLabel)); } }; /** * Adds listeners for any bug command elements found. * @param {Object} bugData A dictionary of the Bug data elements. * @param {Node} container The HTML element object of the container. * @param {Element} label The HTML element object of the "Bound" label. * @private */ bite.client.BugDetailsPopup.prototype.showBoundLabelMenu_ = function( bugData, container, label) { var boundMenuControl = goog.dom.createDom(goog.dom.TagName.DIV, {'class': 'popup-empty-frame'}); boundMenuControl.innerHTML = bite.client.Templates.boundControlOptions(); goog.dom.appendChild(container, boundMenuControl); // Depending on the length of the Bug ID the bound label can change position. var labelPosition = goog.style.getPosition(label); goog.style.setPosition(boundMenuControl, labelPosition.x + 35, labelPosition.y + 22); this.eventHandler_.listen( goog.dom.getElement('bug-popup-bound-menu-remove'), goog.events.EventType.CLICK, goog.bind(this.submitRemoveBugBinding_, this, bugData, goog.bind(goog.dom.removeNode, this, boundMenuControl))); this.eventHandler_.listen(goog.dom.getElement('bug-popup-bound-menu-cancel'), goog.events.EventType.CLICK, goog.bind(goog.dom.removeNode, this, boundMenuControl)); }; /** * Submits a remove/clear bug binding message to the server. * @param {Object} bugData A dictionary of the bug data for this binding. * @param {function()} callback Callback to call after submitting the * bug binding removal to the server. * @private */ bite.client.BugDetailsPopup.prototype.submitRemoveBugBinding_ = function( bugData, callback) { var requestData = {'action': Bite.Constants.HUD_ACTION.UPDATE_BUG, 'details': {'kind': bugData['kind'], 'id': bugData['id'], 'target_element': ''}}; chrome.extension.sendRequest(requestData, goog.bind(this.refreshLocalBugData_, this, callback)); }; /** * Refreshes the local bug data with data on the server. * @param {function()=} opt_callback Function to call after requesting refresh. * @private */ bite.client.BugDetailsPopup.prototype.refreshLocalBugData_ = function(opt_callback) { chrome.extension.sendRequest( {action: Bite.Constants.HUD_ACTION.UPDATE_DATA, target_url: goog.global.location.href}); if (opt_callback) { opt_callback(); } }; /** * Adds listeners for any bug command elements found. * @param {Object} bugData A dictionary of the Bug data elements. * @param {Node} container The HTML element object of the container. * @private */ bite.client.BugDetailsPopup.prototype.createBugCommandListeners_ = function( bugData, container) { var commandObj = null; for (var command in bite.client.BugDetailsPopup.BugActions) { commandObj = goog.dom.getElement( 'bug-command-' + bite.client.BugDetailsPopup.BugActions[command]); if (commandObj) { this.eventHandler_.listen( commandObj, goog.events.EventType.CLICK, goog.bind(this.drawSubmitPopup, this, bite.client.BugDetailsPopup.BugActions[command], bugData, container)); } } }; /** * Draws a popup for users to tailor/submit a change for a bug. * @param {bite.client.BugDetailsPopup.BugActions} action The action being * taken. * @param {Object} bugData A dictionary of the Bug data elements. * @param {Node} container The container HTML element to draw in. * @export */ bite.client.BugDetailsPopup.prototype.drawSubmitPopup = function( action, bugData, container) { this.lockBugPopup_ = true; goog.dom.removeChildren(container); var bugDataIconURL = this.getBugIcon_(bugData['state']); var bugDataPopup = goog.dom.createDom(goog.dom.TagName.DIV, {'class': 'popup-empty-frame'}); bugDataPopup.innerHTML = bite.client.Templates.bugConfirmChanges( {imgURI: bugDataIconURL, bugID: bugData['id'], bugLink: bugData['details_link'], command: action}); goog.dom.appendChild(container, bugDataPopup); this.eventHandler_.listen(goog.dom.getElement('bug-command-cancel'), goog.events.EventType.CLICK, goog.bind(this.drawBugData_, this, bugData, container)); this.eventHandler_.listen(goog.dom.getElement('bug-command-submit'), goog.events.EventType.CLICK, goog.bind(this.postBugUpdate_, this, bugData, container)); }; /** * Collects information for a bug update and posts it to the back end. * @param {Object} bugData A dictionary of the Bug data elements. * @param {Node} container The HTML element object of the container. * @private */ bite.client.BugDetailsPopup.prototype.postBugUpdate_ = function( bugData, container) { // Disable the appearance of the popup while waiting for a response. this.disableSubmitPopup_(); var details = {'kind': bugData['kind'], 'id': bugData['id']}; var commentElem = goog.dom.getElement('bug-popup-comment'); if (commentElem) { details['comment'] = commentElem.innerHTML; } var statusElem = goog.dom.getElement('bug-update-status'); var status = null; if (statusElem) { status = statusElem.value.toLowerCase(); details['status'] = status; // TODO (jason.stredwick): Move logic to server. if (status == 'resolved' || status == 'fixed') { details['state'] = 'resolved'; } else if (status == 'available' || status == 'assigned' || status == 'untriaged') { details['state'] = 'active'; } else { details['state'] = 'closed'; } } // TODO (jason.stredwick): I notice that the status in the bug data is not // updated here and perhaps not elsewhere. Look into this. var requestData = {'action': Bite.Constants.HUD_ACTION.UPDATE_BUG, 'details': details}; chrome.extension.sendRequest(requestData, goog.bind(this.postBugUpdateHandler_, this, status, bugData, container)); }; /** * Disables the controls users can interact with on the Submit popup. * @private */ bite.client.BugDetailsPopup.prototype.disableSubmitPopup_ = function() { // Gray-out the controls, to make the popup appear disabled. goog.style.setStyle(goog.dom.getElement('bug-popup-comment'), 'color', '#666666'); goog.dom.getElement('bug-popup-comment').contentEditable = false; goog.dom.classes.set(goog.dom.getElement('bug-command-cancel'), 'pseudo-link-disabled'); goog.dom.classes.set(goog.dom.getElement('bug-command-submit'), 'pseudo-link-disabled'); // If the user is just commenting this control won't exist. var updateStatus = goog.dom.getElement('bug-update-status'); if (updateStatus) { updateStatus.disabled = true; } }; /** * Handles the response for updating a bug server side. * @param {?string} status The new status of the bug. * @param {Object} bugData A dictionary of the Bug data elements. * @param {Node} container The container HTML element to draw in. * @param {string} result A JSON with the result of the update. * @private */ bite.client.BugDetailsPopup.prototype.postBugUpdateHandler_ = function( status, bugData, container, result) { chrome.extension.sendRequest( {action: Bite.Constants.HUD_ACTION.UPDATE_DATA, target_url: goog.global.location.href}); this.drawConfirmationPopup_(status, bugData, container, result); }; /** * Draws a popup Element that confirms the update to the bug. * @param {?string} status The new status of the bug, can be undefined if no * status value was updated. * @param {Object} bugData A dictionary of the Bug data elements. * @param {Node} container The container HTML element to draw in. * @param {string} result A JSON with the result. * @private */ bite.client.BugDetailsPopup.prototype.drawConfirmationPopup_ = function( status, bugData, container, result) { var updatedBugData = this.contentClient_.getBugData_(bugData['id']); var resultMsg = ''; this.lockBugPopup_ = false; goog.dom.removeChildren(container); if (result['success'] == true) { if (status == null) { resultMsg = 'Your comment has been successfully posted.'; } else { resultMsg = 'This issue has been marked as <b>' + status + '</b>'; } } else { resultMsg = 'Unable to submit update'; // If there was an error message return to the user, specifically for 403 // errors give the user a user-friendly asking them to contact the team. if (result['error']) { if (result['error'].indexOf( bite.client.BugDetailsPopup.ACCESS_DENIED_ERROR_) > -1) { resultMsg += ' - Access Denied' + '<br><span style="color: #6F6F6F; font-size: 7pt">' + 'Please contact the appropiate team for access to' + '<br>update these issues.</span>'; } else { resultMsg += ' - ' + escape(result['error']); } } } var bugResultIconURL = this.getBugIcon_(updatedBugData['state']); var bugResultPopup = goog.dom.createDom(goog.dom.TagName.DIV, {'class': 'popup-empty-frame'}); bugResultPopup.innerHTML = bite.client.Templates.bugResultPopup( {imgURI: bugResultIconURL, bugID: updatedBugData['id'], bugLink: updatedBugData['details_link'], resultMessage: resultMsg}); goog.dom.appendChild(container, bugResultPopup); this.eventHandler_.listen(goog.dom.getElement('back-to-bug-details'), goog.events.EventType.CLICK, goog.bind(this.drawBugData_, this, updatedBugData, container)); }; /** * Flags the BugPopup for removal or switches the flag to keep it. * @param {boolean} remove Whether to remove (true) or keep (false) the popup. * @export */ bite.client.BugDetailsPopup.prototype.flagBugPopupRemoval = function(remove) { // To prevent an accidental mouse-out, wait 200 milliseconds before // destroying the popup. If the user mouses back in this.removeBugPopup_ // is set to false and the popup won't be destroyed. this.removeBugPopup_ = remove; if (remove == true) { goog.Timer.callOnce(this.destroyBugPopup, 200, this); } }; /** * @param {boolean} locked Whether to lock the bug popup from being removed. * @export */ bite.client.BugDetailsPopup.prototype.setLocked = function(locked) { this.lockBugPopup_ = locked; }; /** * @return {boolean} Whether the popup is flagged for removal. * @export */ bite.client.BugDetailsPopup.prototype.isFlaggedForRemoval = function() { return this.removeBugPopup_; }; /** * @param {boolean} remove Whether the popup is flagged for removal. * @export */ bite.client.BugDetailsPopup.prototype.setFlaggedForRemoval = function(remove) { this.removeBugPopup_ = remove; }; /** * Removes the Bug Popup depending whether it's flagged for removal. * @param {boolean} force Whether to force destroy the popup, ignoring other * flags and parameters. * @export */ bite.client.BugDetailsPopup.prototype.destroyBugPopup = function(force) { // Make sure we still want to remove it when this gets called. if ((this.removeBugPopup_ == true && this.lockBugPopup_ == false) || force) { if (this.popup_) { this.eventHandler_.removeAll(); goog.dom.removeNode(this.popup_); this.popup_ = null; } } }; /** * Sets the new popup element. * @param {Element} elmnt The target popup element. * @export */ bite.client.BugDetailsPopup.prototype.setTarget = function(elmnt) { this.popup_ = elmnt; };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Tests for the BugTemplate and TemplateManager. * * @author ralphj@google.com (Julie Ralph) */ goog.require('Bite.Constants'); goog.require('bite.client.TemplateManager'); goog.require('bite.common.net.xhr.async'); goog.require('goog.json'); goog.require('goog.testing.PropertyReplacer'); var stubs = new goog.testing.PropertyReplacer(); var testTemplates = { 'geo_tiles': {id: 'geo_tiles', urls: ['http://maps.google.com'], project: 'Geo', name: 'Map Tiles', backendProject: 'geo_map_tiles', backendProvider: Bite.Constants.Providers.ISSUETRACKER, selectorText: 'A problem with a map tile', displayOrder: 0, noteText: 'Enter your problem description. TILES' }, 'geo_address': {id: 'geo_address', urls: ['http://maps.google.com'], project: 'Geo', name: 'Address/Business Search', backendProject: 'geo_address_business_search', backendProvider: Bite.Constants.Providers.ISSUETRACKER, selectorText: 'Inaccurate or incorrect search results', displayOrder: 0, noteText: 'Enter your problem description. ADDRESS' }, 'chrome_render': {id: 'chrome_render', urls: [], project: 'Chrome', name: 'Directions', backendProject: 'geo_directions', backendProvider: Bite.Constants.Providers.ISSUETRACKER, selectorText: 'Wrong or missing directions', displayOrder: 0, noteText: 'Enter your problem description. DIRECTIONS' }, 'all_other': {id: 'all_other', urls: [], project: 'Default', name: 'Public Transit', backendProject: 'geo_public_transit', backendProvider: Bite.Constants.Providers.ISSUETRACKER, selectorText: 'An issue with public transit directions', displayOrder: 5, noteText: 'Enter your problem description. TRANSIT' } }; /** * Asserts that the template list passed in has template ids equal to the * list passed in. * @param {Array.<string>} expectedIds A list of expected template ids. * @param {bite.client.BugTemplateList} templates The list of templates. */ var assertTemplateIdsEqual = function(expectedIds, templates) { var i = 0; for (templateid in templates) { assertEquals(expectedIds[i], templateid); ++i; } }; /** * Used to mock bite.common.net.xhr.async.get * @param {string} url The url. * @param {Function} callback The callback. */ var mockXhr = function(url, callback) { callback(true, goog.json.serialize(testTemplates)); }; function setUp() { stubs.set(bite.options.data, 'get', function() {return 'a_string'}); } function tearDown() { stubs.reset(); } /** * Tests the GetTemplatesByProject() static function. * @this The context of the unit test. */ function testGetTemplatesByProject() { var projects = bite.client.TemplateManager.getTemplatesByProject(testTemplates); assertEquals(3, projects.length); assertEquals('Geo', projects[0].name); assertEquals(2, projects[0].templates.length); assertEquals('Chrome', projects[1].name); assertEquals(1, projects[1].templates.length); } /** * Tests the GetTemplates() function. * @this The context of the unit test. */ function testGetTemplates() { templateManager = bite.client.TemplateManager.getInstance(); stubs.set(bite.common.net.xhr.async, 'get', mockXhr); templateManager.getAllTemplates( goog.partial(assertTemplateIdsEqual, ['geo_tiles', 'geo_address, chrome_render, all_other'])); } /** * Tests the GetTemplates() function when there are no templates in the * backend. * @this The context of the unit test. */ function testDefaultTemplate() { templateManager = bite.client.TemplateManager.getInstance(); stubs.set(bite.common.net.xhr.async, 'get', function() {return null;}); templateManager.getAllTemplates(goog.partial(assertTemplateIdsEqual, ['bite_default_bug'])); }
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Tests for New Bug Form which is used to log a bug. * * @author ekamenskaya@google.com (Ekaterina Kamenskaya) */ goog.require('goog.testing.MockControl'); goog.require('goog.testing.PropertyReplacer'); var stubs_ = new goog.testing.PropertyReplacer(); // Mock the chrome namespace if it's not defined. if (typeof(chrome) == 'undefined') { var chrome = {}; /** * Mocking the chrome.extension namespace. * @export */ chrome.extension = {}; /** * Mocking chrome.extension.getURL and simply returning the relative path. * @param {string} img The relative path of the img to the extension. * @return {string} The relative path that was passed in. * @export */ chrome.extension.getURL = function(img) { return img; }; } /** * Mocks bite.client.console.NewBug.TemplateDetails_. */ var TemplateDetails = { 'selectedTemplateFirst': {project: 'test_project_first', path: '{test_trash_first}', backendProject: 'test_trash_first', backendProvider: Bite.Constants.Providers.ISSUETRACKER}, 'selectedTemplateSecond': {project: 'test_project_second', path: '{test_trash_second}', backendProject: 'test_trash_second', backendProvider: Bite.Constants.Providers.ISSUETRACKER} }; /** * Constructor called at the end of each test case/ * @this The context of the unit test. */ function setUp() { this.mockCaller = new mockCallBack(); stubs_.set(chrome.extension, 'sendRequest', goog.bind(this.mockCaller.sendRequest, this.mockCaller)); var user = 'test-bite@google.com'; this.newBugConsole = new bite.client.console.NewBug(user); this.mockCaller.reset(); } /** * Destructor called at the end of each test case. * @this The context of the unit test. */ function tearDown() { this.mockCaller.reset(); stubs_.reset(); } /** * Mocks calls for various functions. * @constructor * @export */ mockCallBack = function() { /** * The last method call. * @type {string} */ this.lastCall = ''; /** * A list containing the parameters of the last method call. * @type {Object} */ this.lastParameters = null; }; /** * Resets the mockCallBack members to their default values. * @export */ mockCallBack.prototype.reset = function() { this.lastCall = ''; this.lastParameters = null; }; /** * Mocks chrome.extension.sendRequest. * @param {Object} queryParams The query parameters for sendRequest. * @param {function()} callback The callback function to run when finished. * @export */ mockCallBack.prototype.sendRequest = function(queryParams, callback) { this.lastCall = 'sendRequest'; this.lastParameters = [queryParams, callback]; }; /** * Mocks querySelector method. * @param {string} selectors The string containing one or more CSS selectors * separated by commas. * @return {Node} The node returned by querySelector. * @export */ mockCallBack.prototype.querySelector = function(selectors) { this.lastCall = 'querySelector'; this.lastParameters = [selectors]; return goog.dom.createDom(goog.dom.TagName.DIV); }; /** * Mocks bite.client.console.NewBug.setConsoleHandlers_. * @export */ mockCallBack.prototype.setConsoleHandlers = function() { this.lastCall = 'setConsoleHandlers'; this.lastParameters = []; }; /** * Mocks bite.client.console.NewBug.changeTemplateHandler_. * @export */ mockCallBack.prototype.changeTemplateHandler = function() { this.lastCall = 'changeTemplateHandler'; this.lastParameters = []; }; /** * Mocks goog.events.listen, stores multiple listens. * @param {Element} element The element to attach a listener to. * @param {String} command The command to listen to. * @param {function()} func The function to call when the event happens. * @export */ mockCallBack.prototype.listen = function(element, command, func) { this.lastCall += 'listen,'; if (!this.lastParameters) { this.lastParameters = [[element, command, func]]; } else { this.lastParameters.push([element, command, func]); } }; /** * Mocks goog.dom.appendChild. * @param {Node} parent The parent element. * @param {Node} child The child element. * @export */ mockCallBack.prototype.appendChild = function(parent, child) { this.lastCall = 'appendChild'; this.lastParameters = [parent, child]; }; /** * Mocks goog.dom.removeChildren. * @param {Node} parent The parent element. * @export */ mockCallBack.prototype.removeChildren = function(parent) { this.lastCall = 'removeChildren'; this.lastParameters = [parent]; }; /** * Mocks submit method. * @export */ mockCallBack.prototype.submit = function() { this.lastCall = 'submit'; this.lastParameters = []; }; /** * Mocks common.client.ElementDescriptor.generateElementDescriptorNAncestors * method. * @param {Element} element The selected element. * @param {number} level The level to generate descriptor. * @return {string} The resulted descriptor. * @export */ mockCallBack.prototype.generateElementDescriptorNAncestors = function(element, level) { this.lastCall = 'generateElementDescriptorNAncestors'; this.lastParameters = [element, level]; return 'descriptor'; }; /** * Testing bite.client.console.NewBug.prototype.getCurrentUrl_. * @this The context of the unit test. */ function testGetCurrentUrl() { assertEquals(goog.global.location.href, this.newBugConsole.getCurrentUrl_()); assertEquals('', this.mockCaller.lastCall); } /** * Testing bite.client.console.NewBug.prototype.show. * @this The context of the unit test. */ function testShow() { var mocks = new goog.testing.MockControl(); var selectedElement = goog.dom.createDom(goog.dom.TagName.DIV); this.newBugConsole.templatesList_ = goog.dom.createDom(goog.dom.TagName.DIV, {'id': 'fakeTemplatesList_'}); this.newBugConsole.templates_ = TemplateDetails; stubs_.set(this.newBugConsole.templatesList_, 'querySelector', goog.bind(this.mockCaller.querySelector, this.mockCaller)); stubs_.set(this.newBugConsole, 'setConsoleHandlers_', goog.bind(this.mockCaller.setConsoleHandlers, this.mockCaller)); stubs_.set(this.newBugConsole, 'changeTemplateHandler_', goog.bind(this.mockCaller.changeTemplateHandler, this.mockCaller)); stubs_.set(goog.dom, 'getElement', goog.bind(this.mockCaller.querySelector, this.mockCaller)); var mockContainer = mocks.createLooseMock(bite.client.Container); var mockContainerConstructor = mocks.createConstructorMock( bite.client, 'Container'); mockContainerConstructor(goog.testing.mockmatchers.ignoreArgument, goog.testing.mockmatchers.ignoreArgument, goog.testing.mockmatchers.ignoreArgument, goog.testing.mockmatchers.ignoreArgument, false, true).$returns(mockContainer); mockContainer.setContentFromHtml( goog.testing.mockmatchers.ignoreArgument).$times(1); mockContainer.showInfoMessageOnce( goog.testing.mockmatchers.isString, goog.testing.mockmatchers.isString).$times(1); mockContainer.getRoot().$anyTimes().$returns(this.mockCaller); mocks.$replayAll(); assertEquals(this.newBugConsole.rootElement_, this.newBugConsole.show(selectedElement)); assertEquals('Verify changeTemplateHandler_ was called', 'changeTemplateHandler', this.mockCaller.lastCall); mocks.$verifyAll(); mocks.$tearDown(); }
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview BITE server messages. * TODO(phu): Will add the strings exposed to users in this file. * * @author phu@google.com (Po Hu) */ goog.provide('bite.server.Messages');
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Unit tests for the overview tab in set's page. * * @author phu@google.com (Po Hu) */ goog.require('bite.server.set.Overview'); goog.require('goog.json'); goog.require('goog.testing.MockControl'); goog.require('goog.testing.PropertyReplacer'); goog.require('goog.testing.asserts'); goog.require('goog.testing.mockmatchers'); var stubs_ = new goog.testing.PropertyReplacer(); var mockControl_ = null; function setUp() { mockControl_ = new goog.testing.MockControl(); } function tearDown() { mockControl_.$tearDown(); mockControl_ = null; stubs_.reset(); } function testSetProperties() { var overview = new bite.server.set.Overview(null); var params = {'description': 'a', 'labels': goog.json.serialize({'labels': ['b']}), 'projectName': 'c'}; overview.setProperties(params); assertEquals(overview.description, 'a'); assertObjectEquals(overview.labels, ['b']); assertEquals(overview.biteProject, 'c'); } function testAddProperties() { var overview = new bite.server.set.Overview(null); var params = {}; overview.biteProject = 'c'; overview.description = 'a'; overview.labels = ['b']; overview.addProperties(params); assertEquals(params['description'], 'a'); assertEquals(params['projectName'], 'c'); assertObjectEquals(params['labels'], goog.json.serialize({'labels': ['b']})); }
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Unit tests for the tests tab in set's page. * * @author phu@google.com (Po Hu) */ goog.require('bite.server.set.Tests'); goog.require('goog.json'); goog.require('goog.testing.MockControl'); goog.require('goog.testing.PropertyReplacer'); goog.require('goog.testing.asserts'); goog.require('goog.testing.mockmatchers'); var stubs_ = new goog.testing.PropertyReplacer(); var mockControl_ = null; function setUp() { mockControl_ = new goog.testing.MockControl(); } function tearDown() { mockControl_.$tearDown(); mockControl_ = null; stubs_.reset(); }
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains the details page's all tab. * * @author phu@google.com (Po Hu) */ goog.provide('bite.server.set.Overview'); goog.require('bite.server.Helper'); goog.require('bite.server.set.Tab'); goog.require('bite.server.templates.details'); goog.require('goog.dom'); goog.require('goog.json'); /** * A class for the set, which is a group of tests. * @param {function():Object} getInfoFunc The function to get the set's info. * @extends {bite.server.set.Tab} * @constructor * @export */ bite.server.set.Overview = function(getInfoFunc) { /** * The function to get the info of selected item. * @type {function():Object} * @private */ this.getInfoFunc_ = getInfoFunc; /** * The set's description. * @type {string} */ this.description = ''; /** * The set's labels. * @type {Array.<string>} */ this.labels = []; /** * The set's project name. * @type {string} */ this.biteProject = 'BITE'; }; goog.inherits(bite.server.set.Overview, bite.server.set.Tab); /** * Inits the setting's overview page. * @param {Element} tabDetailsDiv The tab details div. * @export */ bite.server.set.Overview.prototype.init = function(tabDetailsDiv) { tabDetailsDiv.innerHTML = bite.server.templates.details.showTabOverview({}); this.loadSetting(); }; /** * Saves the previous page settings. This is called when another tab is * selected. * @export */ bite.server.set.Overview.prototype.saveSetting = function() { this.biteProject = goog.dom.getElement('setProject').value; this.description = goog.dom.getElement('setDesc').value; this.labels = bite.server.Helper.splitAndTrim( goog.dom.getElement('setLabels').value, ','); }; /** * Loads the page's settings. This is called when the overview tab is selected. * @export */ bite.server.set.Overview.prototype.loadSetting = function() { goog.dom.getElement('setProject').value = this.biteProject; goog.dom.getElement('setDesc').value = this.description; goog.dom.getElement('setLabels').value = bite.server.Helper.joinToStr( this.labels, ','); }; /** * Sets the default properties. This is called when a set is loaded, and * a map of params will be passed in. * @param {Object} params The parameter map. * @export */ bite.server.set.Overview.prototype.setProperties = function(params) { this.description = params['description']; this.labels = goog.json.parse(params['labels'])['labels']; this.biteProject = params['projectName']; }; /** * Adds the properties to the given map. This is called when a set is saved, * and this function adds parameters to the map to be sent to the server. * @param {Object} params The parameter map. * @export */ bite.server.set.Overview.prototype.addProperties = function(params) { params['projectName'] = this.biteProject; params['description'] = this.description; params['labels'] = goog.json.serialize({'labels': this.labels}); };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Unit tests for the explore page. * * @author phu@google.com (Po Hu) */ goog.require('bite.server.Helper'); goog.require('goog.testing.asserts'); function setUp() { } function tearDown() { } function testGetUrl() { var serverUrl = ''; var requestPath = '/run/get'; var paramMap = {'page': 'set'}; var url = bite.server.Helper.getUrl(serverUrl, requestPath, paramMap); assertEquals('/run/get?page=set', url); } function testGetUrlHash() { var serverUrl = ''; var requestPath = '/run/get'; var paramMap = {'page': 'set'}; var url = bite.server.Helper.getUrlHash(serverUrl, requestPath, paramMap); assertEquals('/run/get#page=set', url); } function testSplitAndTrim() { var str = 'hello, yes, hi '; var delimiter = ','; var results = bite.server.Helper.splitAndTrim(str, delimiter); assertObjectEquals(['hello', 'yes', 'hi'], results); }
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains the details page's runs tab. * * @author phu@google.com (Po Hu) */ goog.provide('bite.server.set.Runs'); goog.require('bite.server.Constants'); goog.require('bite.server.Helper'); goog.require('bite.server.explore.RunTab'); goog.require('bite.server.set.Tab'); goog.require('bite.server.templates.details.SetRuns'); goog.require('goog.Uri'); goog.require('goog.dom'); goog.require('goog.net.XhrIo'); /** * A class for the runs tab in the set page. * @param {function():Object} getInfoFunc The getter for set's info. * @extends {bite.server.set.Tab} * @constructor * @export */ bite.server.set.Runs = function(getInfoFunc) { /** * A function to get the selected item's info. * @type {function():Object} * @private */ this.getInfoFunc_ = getInfoFunc; /** * The instance of bite.server.explore.RunTab. * @type {bite.server.explore.RunTab} * @private */ this.testsExploreRunHelper_ = new bite.server.explore.RunTab( goog.bind(this.getProjectName_, this)); }; goog.inherits(bite.server.set.Runs, bite.server.set.Tab); /** * Inits the setting's overview page. * @param {Element} tabDetailsDiv The tab details div. * @export */ bite.server.set.Runs.prototype.init = function(tabDetailsDiv) { tabDetailsDiv.innerHTML = bite.server.templates.details.SetRuns.showTabRuns( {'data': bite.server.Constants.DETAILS_RUNS_LEFT_NAVIGATION}); var leftNavs = /** @type {Array} */ (goog.dom.getElementsByClass('kd-sidebarlistitem')); bite.server.Helper.addListenersToElems( leftNavs, goog.bind(this.listenFilterRuns, this)); this.filterRuns('all', goog.dom.getElement('all')); }; /** * Gets the project name. * @return {string} The project name. * @private */ bite.server.set.Runs.prototype.getProjectName_ = function() { return this.getInfoFunc_()['projectName']; }; /** * Listens to select a choice to filter the runs. * @param {Object} event The event object. * @export */ bite.server.set.Runs.prototype.listenFilterRuns = function(event) { this.filterRuns(event.currentTarget.id, event.currentTarget); }; /** * Selects a choice to filter the runs. * @param {string} filter The filter choice. * @param {Element} elem The filter element was clicked. * @export */ bite.server.set.Runs.prototype.filterRuns = function(filter, elem) { goog.dom.getElement('main_preview').innerHTML = ''; bite.server.Helper.updateSelectedCss( elem, 'kd-sidebarlistitem', 'kd-sidebarlistitem selected'); var requestUrl = bite.server.Helper.getUrl( '', '/run/same_suite', {}); var parameters = goog.Uri.QueryData.createFromMap( {'suiteKey': this.getInfoFunc_()['suiteKey'], 'suiteName': this.getInfoFunc_()['suiteName'], 'projectName': this.getInfoFunc_()['projectName'], 'filter': filter}).toString(); goog.net.XhrIo.send( requestUrl, goog.bind(this.filterRunsCallback_, this), 'POST', parameters); bite.server.Helper.displayMessage('Loading runs...', 30 * 1000); }; /** * Callback after selecting a choice to filter the runs. * @param {Event} event The event object. * @private */ bite.server.set.Runs.prototype.filterRunsCallback_ = function(event) { var xhr = /** @type {goog.net.XhrIo} */ (event.target); if (xhr.isSuccess()) { var runs_obj = xhr.getResponseJson(); if (runs_obj) { goog.dom.getElement('filteredRuns').innerHTML = bite.server.templates.details.SetRuns.showFilteredRuns(runs_obj); var dataRows = /** @type {Array} */ (goog.dom.getElementsByClass('data-row')); var layoutHelper = bite.server.LayoutHelper.getInstance(); bite.server.Helper.addListenersToElems( dataRows, goog.bind(layoutHelper.selectArtifact, layoutHelper, goog.bind(this.testsExploreRunHelper_.onArtifactSelected, this.testsExploreRunHelper_))); var dataActions = /** @type {Array} */ (goog.dom.getElementsByClass('data-action')); bite.server.Helper.addListenersToElems( dataActions, goog.bind( this.testsExploreRunHelper_.handleUserOperation, this.testsExploreRunHelper_)); } bite.server.Helper.dismissMessage(); } else { throw new Error('Failed to get the runs. Error status: ' + xhr.getStatus()); } };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains the details page's runs tab. * * @author phu@google.com (Po Hu) */ goog.provide('bite.server.set.Settings'); goog.require('bite.server.Helper'); goog.require('bite.server.set.Tab'); goog.require('bite.server.templates.details'); goog.require('goog.dom'); goog.require('goog.json'); goog.require('goog.string'); /** * A class for the settings tab in the Set's page. * @param {function():Object} getInfoFunc The getter for set's info. * @extends {bite.server.set.Tab} * @constructor * @export */ bite.server.set.Settings = function(getInfoFunc) { /** * A function used to get the selected item's info. * @type {function():Object} * @private */ this.getInfoFunc_ = getInfoFunc; /** * The set's token string. * @type {string} * @private */ this.token_ = ''; /** * The set's start url string. * @type {string} * @private */ this.startUrl_ = ''; /** * The set's scheduled running interval. * @type {number} * @private */ this.interval_ = 0; /** * The set's default email from list. * @type {Array} * @private */ this.emailFrom_ = []; /** * The set's default email to list. * @type {Array} * @private */ this.emailTo_ = []; /** * The set's failure threshhold. * @type {number} * @private */ this.failureThresh_ = 0; }; goog.inherits(bite.server.set.Settings, bite.server.set.Tab); /** * Inits the setting's overview page. * @param {Element} tabDetailsDiv The tab details div. * @export */ bite.server.set.Settings.prototype.init = function(tabDetailsDiv) { tabDetailsDiv.innerHTML = bite.server.templates.details.showTabSettings({}); this.loadSetting(); }; /** * Saves the previous page settings. This is called when another tab is * selected. * @export */ bite.server.set.Settings.prototype.saveSetting = function() { this.token_ = goog.dom.getElement('setToken').value; this.startUrl_ = goog.dom.getElement('setReplaceUrl').value; this.interval_ = goog.string.toNumber( goog.dom.getElement('setInterval').value); this.emailFrom_ = bite.server.Helper.splitAndTrim( goog.dom.getElement('setEmailFrom').value, ','); this.emailTo_ = bite.server.Helper.splitAndTrim( goog.dom.getElement('setEmailTo').value, ','); this.failureThresh_ = goog.string.toNumber(goog.dom.getElement('setEmailThreshold').value); }; /** * Loads the page's settings. This is called when the settings tab is selected. * @export */ bite.server.set.Settings.prototype.loadSetting = function() { goog.dom.getElement('setToken').value = this.token_; goog.dom.getElement('setReplaceUrl').value = this.startUrl_; goog.dom.getElement('setInterval').value = this.interval_; goog.dom.getElement('setEmailFrom').value = bite.server.Helper.joinToStr( this.emailFrom_, ','); goog.dom.getElement('setEmailTo').value = bite.server.Helper.joinToStr( this.emailTo_, ','); goog.dom.getElement('setEmailThreshold').value = this.failureThresh_; }; /** * Sets the default properties. This is called when loading a set from server. * @param {Object} params The parameter map. * @export */ bite.server.set.Settings.prototype.setProperties = function(params) { this.token_ = params['token']; this.startUrl_ = params['startUrl']; this.interval_ = params['interval']; this.emailFrom_ = params['emailFrom']; this.emailTo_ = params['emailTo']; this.failureThresh_ = params['failureThresh']; }; /** * Adds the properties to the given map. This is called when it creates * a map of properties to be saved to server. * @param {Object} params The parameter map. * @export */ bite.server.set.Settings.prototype.addProperties = function(params) { // TODO(phu): Use constants or enum for the constants. params['tokens'] = this.token_; params['interval'] = this.interval_; params['startUrl'] = this.startUrl_; params['failureThresh'] = this.failureThresh_; params['emailFrom'] = goog.json.serialize(this.emailFrom_); params['emailTo'] = goog.json.serialize(this.emailTo_); };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains the tab base class, which is the * base class for all the tabs in details page. * * @author phu@google.com (Po Hu) */ goog.provide('bite.server.set.Tab'); /** * A class for set tab functions. * @param {Function} getKeyFunc The getter for set's key. * @constructor * @export */ bite.server.set.Tab = function(getKeyFunc) { this.getKeyFunc = getKeyFunc; }; /** * Saves the previous page settings. * @export */ bite.server.set.Tab.prototype.saveSetting = function() { }; /** * Inits the UI. * @export */ bite.server.set.Tab.prototype.init = function() { }; /** * Sets the default properties. * @param {Object} params The parameter map. * @export */ bite.server.set.Tab.prototype.setProperties = function(params) { }; /** * Adds the properties to the given map. * @param {Object} params The parameter map. * @export */ bite.server.set.Tab.prototype.addProperties = function(params) { };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Unit tests for the url parser script. * * @author phu@google.com (Po Hu) */ goog.require('bite.server.UrlParser'); goog.require('goog.testing.MockControl'); goog.require('goog.testing.PropertyReplacer'); goog.require('goog.testing.asserts'); goog.require('goog.testing.mockmatchers'); var stubs_ = new goog.testing.PropertyReplacer(); var mockControl_ = null; var mockPage = null; var mockPageCtor = null; function setUp() { mockControl_ = new goog.testing.MockControl(); mockPage = mockControl_.createStrictMock(bite.server.Page); mockPageCtor = mockControl_.createConstructorMock(bite.server, 'Page'); mockPageCtor().$returns(mockPage); mockPage.destroy().$returns(); } function tearDown() { mockControl_.$tearDown(); mockControl_ = null; stubs_.reset(); } function testUrlParseViewPage() { var mockView = mockControl_.createStrictMock(bite.server.View); var mockViewCtor = mockControl_.createConstructorMock(bite.server, 'View'); mockViewCtor().$returns(mockView); mockView.init(goog.testing.mockmatchers.isObject).$returns(true); mockControl_.$replayAll(); var urlParser = new bite.server.UrlParser(); urlParser.layoutHelper = bite.server.LayoutHelper.getInstance(); urlParser.parseLayout('page=explore'); assertNotNull(urlParser.setExplorePage); mockControl_.$verifyAll(); } function testUrlParseDetailsPage() { var mockSet = mockControl_.createStrictMock(bite.server.Set); var mockSetCtor = mockControl_.createConstructorMock(bite.server, 'Set'); mockSetCtor().$returns(mockSet); mockSet.init(goog.testing.mockmatchers.isObject).$returns(true); mockControl_.$replayAll(); var urlParser = new bite.server.UrlParser(); urlParser.layoutHelper = bite.server.LayoutHelper.getInstance(); urlParser.parseLayout('page=set_details'); assertNotNull(urlParser.setDetailsPage); mockControl_.$verifyAll(); }
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview BITE server constants. * * @author phu@google.com (Po Hu) */ goog.provide('bite.server.Constants'); /** * The everything tab UI data in explore page. * @type {Object} * @export */ bite.server.Constants.EVERYTHING_DEFAULT_UI_DATA = { 'name': 'all', 'href': '/event/show_all', 'title': 'Everything', 'artifactTitle': 'Recent Activities', 'icon': '/images/artifacts/testing.png', 'description': 'This page shows recent activities', 'data': [], 'filters': [ {'name': 'all', 'title': 'All items', 'href': '/event/show_all', 'selected': true}] }; /** * The Set tab UI data in explore page. * @type {Object} * @export */ bite.server.Constants.SUITES_DEFAULT_UI_DATA = { 'name': 'suites', 'href': '/suite/show_all', 'title': 'Sets', 'icon': '/images/artifacts/testsuite.png', 'description': 'Sets are a collection of tests intended to ' + 'be run under a specific configuration(s).', 'data': [], 'filters': [ {'name': 'all', 'title': 'All items', 'href': '/suite/show_all', 'selected': true}] }; /** * The Runs tab UI data in explore page. * @type {Object} * @export */ bite.server.Constants.RUNS_DEFAULT_UI_DATA = { 'name': 'runs', 'title': 'Runs', 'href': '/run/show_all', 'icon': '/images/artifacts/testrun.png', 'description': 'Runs are an execution of a set of tests. ' + 'Results are stored in the test case manager.', 'filters': [ {'name': 'all', 'title': 'All items', 'href': '/run/show_all?filter=all'}, {'name': 'completed', 'title': 'Completed', 'href': '/run/show_all?filter=completed'}, {'name': 'running', 'title': 'Running', 'href': '/run/show_all?filter=running'}, {'name': 'scheduled', 'title': 'Scheduled', 'href': '/run/show_all?filter=scheduled'}] }; /** * The top navigation data in all pages. * @type {Array} * @export */ bite.server.Constants.TOP_NAV_DEFAULT_DATA = [ ]; /** * The tab id and tab data's map in explore page. * @type {Object} * @export */ bite.server.Constants.NAV_DETAILS_MAP = { 'all': bite.server.Constants.EVERYTHING_DEFAULT_UI_DATA, 'suites': bite.server.Constants.SUITES_DEFAULT_UI_DATA, 'runs': bite.server.Constants.RUNS_DEFAULT_UI_DATA }; /** * The main navigations UI data in explore page. * @type {Array} * @export */ bite.server.Constants.DEFAULT_MAINNAVS_EXPLORE_PAGE = [ {'name': 'all', 'title': 'Everything', 'path': '/event/show_all'}, {'name': 'suites', 'title': 'Sets', 'path': '/suite/show_all'}, {'name': 'runs', 'title': 'Runs', 'path': '/run/show_all'} ]; /** * The main navigations UI data in project explore page. * @type {Array} * @export */ bite.server.Constants.MAINNAVS_PROJECT_EXPLORE_PAGE = [ {'name': 'projects', 'title': 'Projects'} ]; /** * The main navigations UI data in Set's details page. * @type {Array} * @export */ bite.server.Constants.DEFAULT_MAINNAVS_DETAILS_PAGE = [ {'name': 'runs', 'title': 'Runs', 'href': ''} ]; /** * The main navigations UI data in Run's details page. * @type {Array} * @export */ bite.server.Constants.DEFAULT_MAINNAVS_RUN_DETAILS_PAGE = [ {'name': 'results', 'title': 'Results', 'href': ''} ]; /** * The main navigations UI data in Project's details page. * @type {Array} * @export */ bite.server.Constants.DEFAULT_MAINNAVS_PROJECT_DETAILS_PAGE = [ {'name': 'general', 'title': 'General', 'href': ''}, {'name': 'members', 'title': 'Members', 'href': ''}, {'name': 'settings', 'title': 'Settings', 'href': ''} ]; /** * The left navigations UI data in runs tab of Set's details page. * @type {Array} * @export */ bite.server.Constants.DETAILS_RUNS_LEFT_NAVIGATION = [ {'name': 'all', 'title': 'All'}, {'name': 'day1', 'title': 'Past 24 hours'}, {'name': 'day2', 'title': 'Past 2 days'}, {'name': 'day7', 'title': 'Past week'}, {'name': 'running', 'title': 'Running'}, {'name': 'queued', 'title': 'Queued'}, {'name': 'completed', 'title': 'Completed'} ];
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Unit tests for the Run's details page. * * @author phu@google.com (Po Hu) */ goog.require('bite.server.Run'); goog.require('bite.server.run.Overview'); goog.require('goog.dom'); goog.require('goog.json'); goog.require('goog.net.XhrIo'); goog.require('goog.testing.MockControl'); goog.require('goog.testing.PropertyReplacer'); goog.require('goog.testing.asserts'); goog.require('goog.testing.mockmatchers'); goog.require('goog.testing.net.XhrIo'); var stubs_ = new goog.testing.PropertyReplacer(); var mockControl_ = null; function setUp() { mockControl_ = new goog.testing.MockControl(); stubs_.replace(goog.net.XhrIo, 'send', goog.testing.net.XhrIo.send); } function tearDown() { mockControl_.$tearDown(); mockControl_ = null; goog.testing.net.XhrIo.sendInstances_ = []; stubs_.reset(); } function testLoadRunFromServer() { var elem1 = goog.dom.createDom('div', {'id': 'runName', 'value': 'abc'}); goog.dom.appendChild(goog.dom.getDocument().body, elem1); var elem2 = goog.dom.createDom('div', {'id': 'runDesc', 'value': 'abc'}); goog.dom.appendChild(goog.dom.getDocument().body, elem2); var elem3 = goog.dom.createDom('div', {'id': 'interval', 'value': 'abc'}); goog.dom.appendChild(goog.dom.getDocument().body, elem3); var mockGetKeyFunc = mockControl_.createFunctionMock(); mockControl_.$replayAll(); var run = new bite.server.Run(); var runKey = 'abc'; run.selectedTab = new bite.server.run.Overview(mockGetKeyFunc); run.loadRunFromServer(runKey); var sendInstance = goog.testing.net.XhrIo.getSendInstances()[0]; var sentUri = sendInstance.getLastUri(); sendInstance.simulateResponse(200, goog.json.serialize({'runKey': 'ddd'})); assertEquals('/run/load_template', sentUri); assertEquals('ddd', run.runKey_); mockControl_.$verifyAll(); } function testSaveRunToServer() { var run = new bite.server.Run(); run.saveRunToServer(); var sendInstance = goog.testing.net.XhrIo.getSendInstances()[0]; var sentUri = sendInstance.getLastUri(); assertEquals('/run/add_template', sentUri); }
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file is the entry point of the client scripts, which * parses the url and perform accordingly. * * @author phu@google.com (Po Hu) */ goog.provide('bite.server.UrlParser'); goog.require('bite.server.LayoutHelper'); goog.require('bite.server.Page'); goog.require('bite.server.Project'); goog.require('bite.server.ProjectDetails'); goog.require('bite.server.Result'); goog.require('bite.server.Run'); goog.require('bite.server.Set'); goog.require('bite.server.View'); goog.require('goog.Uri'); goog.require('goog.events'); goog.require('goog.string'); /** * A class for initializing layouts. * @constructor * @export */ bite.server.UrlParser = function() { /** * The layout helper object. * @type {bite.server.LayoutHelper} */ this.layoutHelper = null; /** * The selected page object. * @type {bite.server.Page} */ this.selectedPage = new bite.server.Page(); }; goog.addSingletonGetter(bite.server.UrlParser); /** * Inits the layout based on the params. * @export */ bite.server.UrlParser.prototype.init = function() { this.layoutHelper = bite.server.LayoutHelper.getInstance(); this.layoutHelper.init(); this.parseLayout(); goog.events.listen( goog.global.window, goog.events.EventType.HASHCHANGE, goog.bind(this.parseLayout, this, null)); }; /** * Parses and inits the layouts. * @param {string=} opt_fragment The optional fragment. * @export */ bite.server.UrlParser.prototype.parseLayout = function(opt_fragment) { var fragment = opt_fragment || (new goog.Uri(goog.global.window.location.href)).getFragment(); var paramsMap = new goog.Uri.QueryData(fragment); if (paramsMap.containsKey('page')) { this.layoutHelper.clearStatus(); this.selectedPage.destroy(); switch (paramsMap.get('page')) { case 'explore': this.selectedPage = new bite.server.View(); break; case 'set_details': this.selectedPage = new bite.server.Set(); break; case 'run_details': this.selectedPage = new bite.server.Run(); break; case 'project_explore': this.selectedPage = new bite.server.Project(); break; case 'project_details': this.selectedPage = new bite.server.ProjectDetails(); break; case 'result': this.selectedPage = new bite.server.Result(); break; } this.selectedPage.init(paramsMap); } };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains the bite server page's base object. * * @author phu@google.com (Po Hu) */ goog.provide('bite.server.Page'); /** * A base class for bite server's page object. * @constructor * @export */ bite.server.Page = function() { }; /** * Inits the page object. * @param {Object} paramsMap The params map of the url hash. * @export */ bite.server.Page.prototype.init = function(paramsMap) { }; /** * Destroys the page object. * @export */ bite.server.Page.prototype.destroy = function() { };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains the helper functions. * * @author phu@google.com (Po Hu) */ goog.provide('bite.server.Helper'); goog.require('goog.Timer'); goog.require('goog.Uri'); goog.require('goog.dom'); goog.require('goog.events'); goog.require('goog.string'); goog.require('goog.ui.ComboBox'); /** * A class for helper functions. * @constructor * @export */ bite.server.Helper = function() { }; /** * Updates the selected item's css. * @param {Element} elem The element was clicked. * @param {string} normalCss The css for unselected choice. * @param {string} selectedCss The css for selected choice. * @export */ bite.server.Helper.updateSelectedCss = function( elem, normalCss, selectedCss) { var mainNavs = goog.dom.getElementsByClass(normalCss); for (var i = 0, len = mainNavs.length; i < len; i++) { goog.dom.setProperties(mainNavs[i], {'class': normalCss}); } goog.dom.setProperties(elem, {'class': selectedCss}); }; /** * Gets the url string with the given parameters. * @param {string} serverUrl The server url. * @param {string} requestPath The request path of the server. * @param {!Object} paramMap The param map object. * @return {string} the request url. * @export */ bite.server.Helper.getUrl = function( serverUrl, requestPath, paramMap) { var request = goog.Uri.parse(serverUrl); request.setPath(requestPath); var data = goog.Uri.QueryData.createFromMap(paramMap); request.setQueryData(data); return request.toString(); }; /** * Gets the url with hash data by the given parameters. * @param {string} serverUrl The server url. * @param {string} requestPath The request path of the server. * @param {!Object} paramMap The param map object. * @return {string} the request url. * @export */ bite.server.Helper.getUrlHash = function( serverUrl, requestPath, paramMap) { var request = goog.Uri.parse(serverUrl); request.setPath(requestPath); var data = goog.Uri.QueryData.createFromMap(paramMap).toString(); request.setFragment(data, true); return request.toString(); }; /** * Adds listeners to a group of elements. * @param {Array} elems The elements to be added listeners. * @param {Function} callback The callback function. * @export */ bite.server.Helper.addListenersToElems = function( elems, callback) { for (var i = 0, len = elems.length; i < len; i++) { goog.events.listen( elems[i], 'click', callback); } }; /** * Adds listeners to a group of elements. * @param {Array} array The data array. * @param {string} name The sample name. * @param {string} value The sample value. * @param {string} requestedName The requested name. * @return {*} The requested name's value. * @export */ bite.server.Helper.getValueInArray = function( array, name, value, requestedName) { for (var i = 0, len = array.length; i < len; i++) { if (array[i][name] == value) { return array[i][requestedName]; } } return null; }; /** * Draws the chart. * @param {number} passed The passed number. * @param {number} failed The failed number. * @param {number} uncompleted The uncompleted number. * @suppress {missingProperties} google.visualization.DataTable and * google.visualization.ImageBarChart * @export */ bite.server.Helper.drawBarChart = function(passed, failed, uncompleted) { // Create and populate the data table. var data = new google.visualization.DataTable(); data.addColumn('string', 'tests'); data.addColumn('number', 'passed'); data.addColumn('number', 'failed'); data.addColumn('number', 'uncompleted'); data.addRows(1); data.setCell(0, 0, ''); data.setCell(0, 1, passed); data.setCell(0, 2, failed); data.setCell(0, 3, uncompleted); // Create and draw the visualization. new google.visualization.ImageBarChart(goog.dom.getElement('visualization')). draw(data, {'isStacked': true, 'width': 400, 'height': 100, 'colors': ['00FF00', 'FF0000', 'C0C0C0'] }); }; /** * Draws the pie chart. * @param {number} passed The passed number. * @param {number} failed The failed number. * @param {number} uncompleted The uncompleted number. * @suppress {missingProperties} google.visualization.DataTable and * google.visualization.PieChart * @export */ bite.server.Helper.drawPieChart = function(passed, failed, uncompleted) { // Create and populate the data table. var data = new google.visualization.DataTable(); data.addColumn('string', 'Status'); data.addColumn('number', 'Number'); data.addRows(3); data.setValue(0, 0, 'Passed'); data.setValue(0, 1, passed); data.setValue(1, 0, 'Failed'); data.setValue(1, 1, failed); data.setValue(2, 0, 'Uncompleted'); data.setValue(2, 1, uncompleted); // Create and draw the visualization. new google.visualization.PieChart(goog.dom.getElement('visualization')). draw(data, {'width': 200, 'height': 200, 'colors': ['00FF00', 'FF0000', 'C0C0C0'], 'legend': 'none' }); }; /** * Splits a string and trim each elements. * @param {string} str The string to be splited. * @param {string} delimiter Used to split the string. * @return {Array} The result array. */ bite.server.Helper.splitAndTrim = function(str, delimiter) { var result = []; var arr = str.split(delimiter); for (var i = 0, len = arr.length; i < len; i++) { result.push(goog.string.trim(arr[i])); } return result; }; /** * Creates the project selector for choosing options. * @param {Array} options The options to be showed in selector. * @param {string} id The id of the div where the selector will be rendered. * @param {string} text The default text. * @return {goog.ui.ComboBox} The combobox instance. * @export */ bite.server.Helper.createSelector = function(options, id, text) { var projectSelector_ = new goog.ui.ComboBox(); projectSelector_.setUseDropdownArrow(true); projectSelector_.setDefaultText(text); for (var i = 0, len = options.length; i < len; ++i) { var pName = ''; var pId = ''; if (goog.isString(options[i])) { pName = options[i]; pId = options[i]; } else { pName = options[i]['name']; pId = options[i]['id']; } var option = new goog.ui.ComboBoxItem(pName); goog.dom.setProperties(/** @type {Element} */ (option), {'id': pId}); projectSelector_.addItem(option); } projectSelector_.render(goog.dom.getElement(id)); return projectSelector_; }; /** * Joins the list or returns the string directly. * @param {string|Array} strOrArr The given array or string. * @param {string} delimiter The delimiter string. * @return {string} The result string. */ bite.server.Helper.joinToStr = function(strOrArr, delimiter) { return typeof strOrArr == 'string' ? strOrArr : strOrArr.join(delimiter); }; /** * Displays a status message in Google bar, and optionally dismiss it. * @param {string} message The message to be displayed. * @param {number} opt_timeout The optional time out to hide the message. */ bite.server.Helper.displayMessage = function(message, opt_timeout) { goog.dom.getElement('statusMessage').innerHTML = message; bite.server.Helper.updateSelectedCss( goog.dom.getElement('statusMessageDiv'), 'kd-butterbar', 'kd-butterbar shown'); if (opt_timeout) { goog.Timer.callOnce(bite.server.Helper.dismissMessage, opt_timeout); } }; /** * Dismisses the message. */ bite.server.Helper.dismissMessage = function() { bite.server.Helper.updateSelectedCss( goog.dom.getElement('statusMessageDiv'), 'kd-butterbar shown', 'kd-butterbar'); };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains the Set's details page class. * * @author phu@google.com (Po Hu) */ goog.provide('bite.server.Set'); goog.require('bite.server.Constants'); goog.require('bite.server.Helper'); goog.require('bite.server.LayoutHelper'); goog.require('bite.server.Page'); goog.require('bite.server.set.Overview'); goog.require('bite.server.set.Runs'); goog.require('bite.server.set.Settings'); goog.require('bite.server.set.Tab'); goog.require('bite.server.set.Tests'); goog.require('bite.server.templates.details'); goog.require('goog.Uri'); goog.require('goog.Uri.QueryData'); goog.require('goog.dom'); goog.require('goog.events'); goog.require('goog.net.XhrIo'); goog.require('goog.ui.CustomButton'); /** * A class for set functions. * @extends {bite.server.Page} * @constructor * @export */ bite.server.Set = function() { /** * The Set's name. * @type {string} */ this.name = ''; /** * The current Set's key string. * @type {string} */ this.suiteKey = ''; /** * The current project name. * @type {string} * @private */ this.projectName_ = ''; /** * The layout helper object. * @type {bite.server.LayoutHelper} */ this.layoutHelper = null; /** * A function used to get the Set's key string. * @type {function():Object} */ var getSetInfoFunc = goog.bind(this.getSetInfo_, this); /** * The currently selected tab. * @type {bite.server.set.Tab} */ this.selectedTab = new bite.server.set.Tab(getSetInfoFunc); /** * The overview tab. * @type {bite.server.set.Tab} */ this.overviewTab = new bite.server.set.Overview(getSetInfoFunc); /** * The runs tab. * @type {bite.server.set.Runs} */ this.runsTab = new bite.server.set.Runs(getSetInfoFunc); /** * The settings tab. * @type {bite.server.set.Settings} */ this.settingsTab = new bite.server.set.Settings(getSetInfoFunc); /** * The tests tab. * @type {bite.server.set.Tests} */ this.testsTab = new bite.server.set.Tests(getSetInfoFunc); /** * The tab id and instance map. * @type {Object} */ this.tabNameObjMap = { 'overview': this.overviewTab, 'runs': this.runsTab, 'settings': this.settingsTab, 'tests': this.testsTab }; }; goog.inherits(bite.server.Set, bite.server.Page); /** * Inits the setting page. * @param {goog.Uri.QueryData} paramsMap The params map of the url hash. * @export */ bite.server.Set.prototype.init = function(paramsMap) { this.layoutHelper = bite.server.LayoutHelper.getInstance(); var baseHeader = goog.dom.getElement('baseHeader'); var baseView = goog.dom.getElement('baseView'); baseHeader.innerHTML = bite.server.templates.details.showHeader(); baseView.innerHTML = bite.server.templates.details.showBodyArea(); goog.dom.getElement('setName').value = 'Untitled set'; this.parseParams_(paramsMap); this.selectedTab = this.tabNameObjMap['runs']; this.selectedTab.init(goog.dom.getElement('setTabDetailDiv')); }; /** * Gets the set's info. * @return {Object} The set's info. * @private */ bite.server.Set.prototype.getSetInfo_ = function() { return {'suiteKey': this.suiteKey, 'suiteName': this.name, 'projectName': this.projectName_}; }; /** * Parses the given params and performs accordingly. * @param {goog.Uri.QueryData} paramsMap The params map. * @private */ bite.server.Set.prototype.parseParams_ = function(paramsMap) { var projectName = paramsMap.get('projectName'); this.projectName_ = projectName ? /** @type {string} */ (projectName) : ''; var suiteName = paramsMap.get('suiteName'); this.name = suiteName ? /** @type {string} */ (suiteName) : ''; var suiteKey = paramsMap.get('suiteKey'); this.suiteKey = suiteKey ? /** @type {string} */ (suiteKey) : ''; if (this.projectName_ && this.name || this.suiteKey) { this.loadSuiteFromServer(this.projectName_, this.name, this.suiteKey); } }; /** * Renders the save button. * @private */ bite.server.Set.prototype.renderSaveButton_ = function() { var saveButtonDiv = goog.dom.getElement('saveSuiteButton'); var button = new goog.ui.CustomButton('Save'); button.render(saveButtonDiv); var that = this; goog.events.listen( button, goog.ui.Component.EventType.ACTION, function(e) { that.saveSetToServer(); }); }; /** * Renders the "create run" button. * @private */ bite.server.Set.prototype.renderCreateRunButton_ = function() { var createRunButtonDiv = goog.dom.getElement('createRunButtonDiv'); var button = new goog.ui.CustomButton('Create Run'); button.render(createRunButtonDiv); var that = this; goog.events.listen( button, goog.ui.Component.EventType.ACTION, function(e) { goog.global.window.open(bite.server.Helper.getUrlHash( '', '/home', {'page': 'run_details', 'setName': that.name, 'setKey': that.suiteKey})); }); }; /** * Loads the suite info from server. * @param {string} projectName The project name. * @param {string} suiteName The suite name. * @param {string} suiteKey The suite key string. * @export */ bite.server.Set.prototype.loadSuiteFromServer = function( projectName, suiteName, suiteKey) { var requestUrl = bite.server.Helper.getUrl( '', '/suite/load', {}); var parameters = goog.Uri.QueryData.createFromMap( {'suiteKey': suiteKey, 'suiteName': suiteName, 'projectName': projectName}).toString(); var that = this; goog.net.XhrIo.send( requestUrl, function() { if (this.isSuccess()) { var suite = this.getResponseJson(); that.name = suite['suiteName']; that.suiteKey = suite['suiteKey']; that.projectName_ = suite['projectName']; for (var tab in that.tabNameObjMap) { that.tabNameObjMap[tab].setProperties(suite); } that.loadSetting(); } else { throw new Error('Failed to get the Set. Error status: ' + this.getStatus()); } }, 'POST', parameters); }; /** * Saves the set info to server. * @export */ bite.server.Set.prototype.saveSetToServer = function() { this.saveSetting(); var requestUrl = bite.server.Helper.getUrl( '', '/suite/add', {}); var paramsMap = { 'suiteName': this.name, 'configs': '', 'watchdogSetting': '', 'versionUrl': '', 'report': '', 'retryTimes': '', 'defaultTimeout': '', 'deleteDeadline': '' }; for (var tab in this.tabNameObjMap) { this.tabNameObjMap[tab].addProperties(paramsMap); } var parameters = goog.Uri.QueryData.createFromMap(paramsMap).toString(); goog.net.XhrIo.send( requestUrl, function() { if (this.isSuccess()) { } else { throw new Error('Failed to save the set to server. Error status: ' + this.getStatus()); } }, 'POST', parameters); }; /** * Saves the previous page settings. * @export */ bite.server.Set.prototype.saveSetting = function() { this.name = goog.dom.getElement('setName').value; this.selectedTab.saveSetting(); }; /** * Loads the page's settings. * @export */ bite.server.Set.prototype.loadSetting = function() { if (this.name) { goog.dom.getElement('setName').value = this.name; } this.selectedTab.loadSetting(); }; /** * Listens to show the specified set tab. * @param {Object} event The event object. * @export */ bite.server.Set.prototype.listenToShowSetTab = function(event) { this.layoutHelper.handleMainNavChanges(event.target.id); this.showSetTab(event.target); }; /** * Shows the specified set tab. * @param {Element} elem The clicked elem. * @export */ bite.server.Set.prototype.showSetTab = function(elem) { this.selectedTab.saveSetting(); var tabDetailsDiv = goog.dom.getElement('setTabDetailDiv'); var tabTitle = elem.id.substring('mainnav-'.length); this.selectedTab = this.tabNameObjMap[tabTitle]; this.selectedTab.init(tabDetailsDiv); }; /** * Destroys this object. * @export */ bite.server.Set.prototype.destroy = function() { // TODO(phu): Clean up any listeners and other global objects. };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains the run details page's settings tab. * * @author phu@google.com (Po Hu) */ goog.provide('bite.server.run.Settings'); goog.require('bite.server.Helper'); goog.require('bite.server.set.Tab'); goog.require('bite.server.templates.details.RunSettings'); goog.require('goog.dom'); goog.require('goog.json'); goog.require('goog.string'); /** * A class for the settings tab in the Run's page. * @param {function():string} getKeyFunc The getter for set's key. * @extends {bite.server.set.Tab} * @constructor * @export */ bite.server.run.Settings = function(getKeyFunc) { /** * A function used to get the selected item's key string. * @type {function():string} * @private */ this.getKeyFunc_ = getKeyFunc; /** * The run's token string. * @type {string} * @private */ this.token_ = ''; /** * The run's start url string. * @type {string} * @private */ this.startUrl_ = ''; /** * The run's line timeout limit. * @type {number} * @private */ this.lineTimeout_ = 0; /** * The run's test timeout limit. * @type {number} * @private */ this.testTimeout_ = 0; /** * The run's filtered results labels. * @type {Array} * @private */ this.filteredResultLabels_ = []; /** * The run's test dimension labels. * @type {Array} * @private */ this.dimensionLabels_ = []; /** * Whether to save the screenshots. * @type {boolean} * @private */ this.saveScnShots_ = true; }; goog.inherits(bite.server.run.Settings, bite.server.set.Tab); /** * Inits the Run page's settings page. * @param {Element} tabDetailsDiv The tab details div. * @export */ bite.server.run.Settings.prototype.init = function(tabDetailsDiv) { tabDetailsDiv.innerHTML = bite.server.templates.details.RunSettings.showTabSettings({}); this.loadSetting(); }; /** * Saves the previous page settings. This is called when another tab is * selected. * @export */ bite.server.run.Settings.prototype.saveSetting = function() { this.filteredResultLabels_ = bite.server.Helper.splitAndTrim( goog.dom.getElement('runFilteredLabels').value, ','); this.dimensionLabels_ = bite.server.Helper.splitAndTrim( goog.dom.getElement('runDimensionLabels').value, ','); this.token_ = goog.dom.getElement('runWorkerToken').value; this.startUrl_ = goog.dom.getElement('runStartUrl').value; this.lineTimeout_ = goog.dom.getElement('runLineTimeout').value; this.testTimeout_ = goog.dom.getElement('runTestTimeout').value; this.saveScnShots_ = goog.dom.getElement('runSaveScnShots').checked; }; /** * Loads the page's settings. This is called when the settings tab is selected. * @export */ bite.server.run.Settings.prototype.loadSetting = function() { goog.dom.getElement('runFilteredLabels').value = bite.server.Helper.joinToStr(this.filteredResultLabels_, ','); goog.dom.getElement('runDimensionLabels').value = bite.server.Helper.joinToStr(this.dimensionLabels_, ','); goog.dom.getElement('runWorkerToken').value = this.token_; goog.dom.getElement('runStartUrl').value = this.startUrl_; goog.dom.getElement('runLineTimeout').value = this.lineTimeout_; goog.dom.getElement('runTestTimeout').value = this.testTimeout_; goog.dom.getElement('runSaveScnShots').checked = this.saveScnShots_; }; /** * Sets the default properties. This is called when loading a set from server. * @param {Object} params The parameter map. * @export */ bite.server.run.Settings.prototype.setProperties = function(params) { this.filteredResultLabels_ = params['filteredLabels']; this.dimensionLabels_ = params['dimensionLabels']; this.token_ = params['runTokens']; this.startUrl_ = params['runStartUrl']; this.lineTimeout_ = 0; this.testTimeout_ = 0; this.saveScnShots_ = true; }; /** * Adds the properties to the given map. This is called when it creates * a map of properties to be saved to server. * @param {Object} params The parameter map. * @export */ bite.server.run.Settings.prototype.addProperties = function(params) { params['runTokens'] = this.token_; params['runStartUrl'] = this.startUrl_; params['filteredLabels'] = goog.json.serialize(this.filteredResultLabels_); params['dimensionLabels'] = goog.json.serialize(this.dimensionLabels_); params['lineTimeout'] = this.lineTimeout_; params['testTimeout'] = this.testTimeout_; params['saveScnShots'] = this.saveScnShots_; };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains the Project's details page class. * * @author phu@google.com (Po Hu) */ goog.provide('bite.server.ProjectDetails'); goog.require('bite.project.General'); goog.require('bite.project.Member'); goog.require('bite.project.Settings'); goog.require('bite.server.Constants'); goog.require('bite.server.Helper'); goog.require('bite.server.LayoutHelper'); goog.require('bite.server.Page'); goog.require('bite.server.set.Tab'); goog.require('bite.server.templates.details.ProjectPage'); goog.require('goog.Uri'); goog.require('goog.dom'); goog.require('goog.events'); goog.require('goog.net.XhrIo'); goog.require('goog.ui.CustomButton'); /** * A class for Project's details page. * @extends {bite.server.Page} * @constructor * @export */ bite.server.ProjectDetails = function() { goog.base(this); /** * The layout helper object. * @type {bite.server.LayoutHelper} * @private */ this.layoutHelper_ = null; /** * The currently selected tab. * @type {Object} * @private */ this.selectedTab_ = null; /** * The general tab. * @type {bite.project.General} * @private */ this.generalTab_ = bite.project.General.getInstance(); /** * The results tab. * @type {bite.project.Member} * @private */ this.memberTab_ = bite.project.Member.getInstance(); /** * The settings tab. * @type {bite.project.Settings} * @private */ this.settingsTab_ = bite.project.Settings.getInstance(); /** * The tab id and instance map. * @type {Object} * @private */ this.tabNameObjMap_ = { 'general': this.generalTab_, 'members': this.memberTab_, 'settings': this.settingsTab_ }; }; goog.inherits(bite.server.ProjectDetails, bite.server.Page); /** * Inits the setting page. * @param {Object} paramsMap The params map of the url hash. * @export */ bite.server.ProjectDetails.prototype.init = function(paramsMap) { this.layoutHelper_ = bite.server.LayoutHelper.getInstance(); var baseHeader = goog.dom.getElement('baseHeader'); var baseView = goog.dom.getElement('baseView'); baseHeader.innerHTML = bite.server.templates.details.ProjectPage.showHeader(); baseView.innerHTML = bite.server.templates.details.ProjectPage.showBodyArea( {'data': { 'mainNavs': bite.server.Constants.DEFAULT_MAINNAVS_PROJECT_DETAILS_PAGE } }); this.renderSaveButton(); var mainNavs = /** @type {Array} */ (goog.dom.getElementsByClass('mainnav-item')); this.handleShowRunTab_(mainNavs[0]); bite.server.Helper.addListenersToElems( mainNavs, goog.bind(this.listenToShowRunTab_, this)); this.parseParams(paramsMap); }; /** * Parses the given params and perform accordingly. * @param {Object} paramsMap The params map. * @export */ bite.server.ProjectDetails.prototype.parseParams = function(paramsMap) { // var runKey = paramsMap.get('runKey'); // runKey = runKey ? runKey : ''; // var setKey = paramsMap.get('setKey'); // setKey = setKey ? setKey : ''; // var setName = paramsMap.get('setName'); // setName = setName ? setName : ''; // var runTemplateKey = paramsMap.get('runTemplateKey'); // runTemplateKey = runTemplateKey ? runTemplateKey : ''; // this.runKey_ = runKey; // this.setKey_ = setKey; // this.setName_ = setName; // this.runTemplateKey_ = runTemplateKey; // this.showRunTab(goog.dom.getElementsByClass('mainnav-item')[0]); // if (runKey || runTemplateKey) { // this.loadRunFromServer(runKey, runTemplateKey) // } }; /** * Renders the save button. * @export */ bite.server.ProjectDetails.prototype.renderSaveButton = function() { var saveButtonDiv = goog.dom.getElement('saveProjectButton'); var button = new goog.ui.CustomButton('Save'); button.render(saveButtonDiv); var that = this; goog.events.listen(button, goog.ui.Component.EventType.ACTION, function(e) { that.saveProjectToServer(); }); }; /** * Loads the run info from server. * @param {string} runKey The run key string. * @param {string} runTemplateKey The run template key string. * @export */ bite.server.ProjectDetails.prototype.loadProjectFromServer = function( runKey, runTemplateKey) { }; /** * Saves the run info to server. * @export */ bite.server.ProjectDetails.prototype.saveProjectToServer = function() { }; /** * Saves the previous page settings. * @export */ bite.server.ProjectDetails.prototype.saveSetting = function() { }; /** * Loads the page's settings. * @export */ bite.server.ProjectDetails.prototype.loadSetting = function() { }; /** * Listens to show the specified run's tab. * @param {Object} event The event object. * @private */ bite.server.ProjectDetails.prototype.listenToShowRunTab_ = function(event) { this.handleShowRunTab_(event.target); }; /** * Handles show the specified project's tab. * @param {Element} elem The tab's element. * @private */ bite.server.ProjectDetails.prototype.handleShowRunTab_ = function(elem) { this.layoutHelper_.handleMainNavChanges(elem.id); this.showRunTab(elem); }; /** * Shows the specified run's tab. * @param {Element} elem The clicked elem. * @export */ bite.server.ProjectDetails.prototype.showRunTab = function(elem) { var tabDetailsDiv = goog.dom.getElement('setTabDetailDiv'); var tabTitle = elem.id.substring('mainnav-'.length); this.selectedTab_ = this.tabNameObjMap_[tabTitle]; this.selectedTab_.init(); goog.dom.getElement('setTabDetailDiv').innerHTML = ''; goog.dom.appendChild( goog.dom.getElement('setTabDetailDiv'), this.selectedTab_.getView()); }; /** * Destroys this object. * @export */ bite.server.ProjectDetails.prototype.destroy = function() { };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Unit tests for the explore page. * * @author phu@google.com (Po Hu) */ goog.require('bite.server.View'); goog.require('goog.dom'); goog.require('goog.json'); goog.require('goog.net.XhrIo'); goog.require('goog.testing.MockControl'); goog.require('goog.testing.PropertyReplacer'); goog.require('goog.testing.asserts'); goog.require('goog.testing.mockmatchers'); goog.require('goog.testing.net.XhrIo'); var stubs_ = new goog.testing.PropertyReplacer(); var mockControl_ = null; function setUp() { mockControl_ = new goog.testing.MockControl(); stubs_.replace(goog.net.XhrIo, 'send', goog.testing.net.XhrIo.send); } function tearDown() { mockControl_.$tearDown(); mockControl_ = null; goog.testing.net.XhrIo.sendInstances_ = []; stubs_.reset(); }
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains the explore page functions. * * @author phu@google.com (Po Hu) */ goog.provide('bite.server.Project'); goog.require('bite.project.Explore'); goog.require('bite.server.Constants'); goog.require('bite.server.Helper'); goog.require('bite.server.LayoutHelper'); goog.require('bite.server.Page'); goog.require('bite.server.explore.OverviewTab'); goog.require('bite.server.explore.RunTab'); goog.require('bite.server.explore.SetTab'); goog.require('bite.server.explore.Tab'); goog.require('bite.server.templates.explore'); goog.require('goog.Uri'); goog.require('goog.dom'); goog.require('goog.events'); goog.require('goog.net.XhrIo'); goog.require('goog.positioning'); goog.require('goog.ui.MenuItem'); goog.require('goog.ui.PopupMenu'); /** * A class for the server Project page. * @extends {bite.server.Page} * @constructor * @export */ bite.server.Project = function() { goog.base(this); /** * The layout helper object. * @type {bite.server.LayoutHelper} * @private */ this.layoutHelper_ = null; /** * The project tab in project explore page. * @type {bite.project.Explore} * @private */ this.projectTab_ = new bite.project.Explore(); /** * The selected tab in explore page. * @type {bite.server.explore.Tab} * @private */ this.selectedTab_ = new bite.server.explore.Tab(null); /** * The event listener's key. * @type {?number} * @private */ this.createbtnLtnKey_ = 0; }; goog.inherits(bite.server.Project, bite.server.Page); /** * Inits the page. * @param {Object} paramsMap The params map of the url hash. * @export */ bite.server.Project.prototype.init = function(paramsMap) { this.layoutHelper_ = bite.server.LayoutHelper.getInstance(); var baseHeader = goog.dom.getElement('baseHeader'); var baseView = goog.dom.getElement('baseView'); soy.renderElement(baseHeader, bite.server.templates.explore.showHeader); soy.renderElement( baseView, bite.server.templates.explore.showBodyArea, {'data': { 'mainNavs': bite.server.Constants.MAINNAVS_PROJECT_EXPLORE_PAGE}}); var mainNavs = /** @type {Array} */ (goog.dom.getElementsByClass('mainnav-item')); this.layoutHelper_.handleMainNavChanges(mainNavs[0].id); var explore = bite.project.Explore.getInstance(); explore.init(); goog.dom.appendChild(goog.dom.getElement('main_content'), explore.getView()); goog.dom.getElement('createButton').innerHTML = 'New Project'; this.createbtnLtnKey_ = goog.events.listen( goog.dom.getElement('createButton'), 'click', goog.bind(this.createNewProject_, this)); }; /** * Creates a new project. * @private */ bite.server.Project.prototype.createNewProject_ = function() { var paramsBag = {}; paramsBag['page'] = 'project_details'; goog.global.window.open(bite.server.Helper.getUrlHash( '', '/home', paramsBag)); }; /** * Destroys this object. * @export */ bite.server.Project.prototype.destroy = function() { };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains the Run's details page class. * TODO(phu): Move the tab related logic to its parent class. * * @author phu@google.com (Po Hu) */ goog.provide('bite.server.Run'); goog.require('bite.server.Constants'); goog.require('bite.server.LayoutHelper'); goog.require('bite.server.Page'); goog.require('bite.server.Helper'); goog.require('bite.server.run.Overview'); goog.require('bite.server.run.Settings'); goog.require('bite.server.run.Results'); goog.require('bite.server.set.Tab'); goog.require('bite.server.templates.details.RunPage'); goog.require('goog.Uri'); goog.require('goog.dom'); goog.require('goog.events'); goog.require('goog.net.XhrIo'); goog.require('goog.ui.CustomButton'); /** * A class for run's details page. * @extends {bite.server.Page} * @constructor * @export */ bite.server.Run = function() { /** * The current Run's key string. * @type {string} * @private */ this.runKey_ = ''; /** * The current Set's key string. * @type {string} * @private */ this.setKey_ = ''; /** * The current Set's name string. * @type {string} * @private */ this.setName_ = ''; /** * The current Run template's key string. * @type {string} * @private */ this.runTemplateKey_ = ''; /** * The layout helper object. * @type {bite.server.LayoutHelper} */ this.layoutHelper = null; var getRunKeyFunc = goog.bind(this.getRunKey, this); /** * The currently selected tab. * @type {bite.server.set.Tab} */ this.selectedTab = new bite.server.set.Tab(getRunKeyFunc); /** * The overview tab. * @type {bite.server.run.Overview} */ this.overviewTab = new bite.server.run.Overview(getRunKeyFunc); /** * The results tab. * @type {bite.server.run.Results} */ this.resultsTab = new bite.server.run.Results(getRunKeyFunc); /** * The settings tab. * @type {bite.server.run.Settings} */ this.settingsTab = new bite.server.run.Settings(getRunKeyFunc); /** * The tab id and instance map. * @type {Object} */ this.tabNameObjMap = { 'overview': this.overviewTab, 'results': this.resultsTab, 'settings': this.settingsTab }; }; goog.inherits(bite.server.Run, bite.server.Page); /** * Inits the setting page. * @param {Object} paramsMap The params map of the url hash. * @export */ bite.server.Run.prototype.init = function(paramsMap) { this.layoutHelper = bite.server.LayoutHelper.getInstance(); var baseHeader = goog.dom.getElement('baseHeader'); var baseView = goog.dom.getElement('baseView'); baseHeader.innerHTML = bite.server.templates.details.RunPage.showHeader(); baseView.innerHTML = bite.server.templates.details.RunPage.showBodyArea(); this.parseParams(paramsMap); this.selectedTab = this.tabNameObjMap['results']; this.selectedTab.init(goog.dom.getElement('setTabDetailDiv')); }; /** * Gets the set's key. * @export */ bite.server.Run.prototype.getRunKey = function() { return this.runKey_; }; /** * Parses the given params and perform accordingly. * @param {Object} paramsMap The params map. * @export */ bite.server.Run.prototype.parseParams = function(paramsMap) { var runKey = paramsMap.get('runKey') || ''; var setKey = paramsMap.get('setKey') || ''; var setName = paramsMap.get('setName') || ''; var runTemplateKey = paramsMap.get('runTemplateKey') || ''; this.runKey_ = runKey; this.setKey_ = setKey; this.setName_ = setName; this.runTemplateKey_ = runTemplateKey; if (runKey || runTemplateKey) { this.loadRunFromServer(runKey, runTemplateKey) } }; /** * Renders the save button. * @export */ bite.server.Run.prototype.renderSaveButton = function() { var saveButtonDiv = goog.dom.getElement('saveRunButton'); var button = new goog.ui.CustomButton('Save'); button.render(saveButtonDiv); var that = this; goog.events.listen(button, goog.ui.Component.EventType.ACTION, function(e) { that.saveRunToServer(); }); }; /** * Loads the run info from server. * @param {string} runKey The run key string. * @param {string} runTemplateKey The run template key string. * @export */ bite.server.Run.prototype.loadRunFromServer = function( runKey, runTemplateKey) { var requestUrl = bite.server.Helper.getUrl( '', '/run/load_template', {}); var parameters = goog.Uri.QueryData.createFromMap( {'runKey': runKey, 'runTemplateKey': runTemplateKey}).toString(); var that = this; goog.net.XhrIo.send(requestUrl, function() { if (this.isSuccess()) { var run = this.getResponseJson(); that.runKey_ = run['runKey']; that.runTemplateKey_ = run['runTemplateKey']; for (var tab in that.tabNameObjMap) { that.tabNameObjMap[tab].setProperties(run); } that.loadSetting(); } else { throw new Error('Failed to get the Run template: ' + this.getStatus()); } }, 'POST', parameters); }; /** * Saves the run info to server. * @export */ bite.server.Run.prototype.saveRunToServer = function() { this.saveSetting(); var requestUrl = bite.server.Helper.getUrl( '', '/run/add_template', {}); var paramsMap = { 'suiteKey': this.setKey_, 'runTemplateKey': this.runTemplateKey_}; for (var tab in this.tabNameObjMap) { this.tabNameObjMap[tab].addProperties(paramsMap); } var parameters = goog.Uri.QueryData.createFromMap(paramsMap).toString(); goog.net.XhrIo.send(requestUrl, function() { if (this.isSuccess()) { alert(this.getResponseText()); } else { throw new Error('Failed to save the run templates to server: ' + this.getStatus()); } }, 'POST', parameters); }; /** * Saves the previous page settings. * @export */ bite.server.Run.prototype.saveSetting = function() { this.selectedTab.saveSetting(); }; /** * Loads the page's settings. * @export */ bite.server.Run.prototype.loadSetting = function() { this.selectedTab.loadSetting(); }; /** * Listens to show the specified run's tab. * @param {Object} event The event object. * @export */ bite.server.Run.prototype.listenToShowRunTab = function(event) { this.layoutHelper.handleMainNavChanges(event.target.id); this.showRunTab(event.target); }; /** * Shows the specified run's tab. * @param {Element} elem The clicked elem. * @export */ bite.server.Run.prototype.showRunTab = function(elem) { this.selectedTab.saveSetting(); var tabDetailsDiv = goog.dom.getElement('setTabDetailDiv'); var tabTitle = elem.id.substring('mainnav-'.length); this.selectedTab = this.tabNameObjMap[tabTitle]; this.selectedTab.init(tabDetailsDiv); }; /** * Destroys this object. * @export */ bite.server.Run.prototype.destroy = function() { };
JavaScript
// Copyright 2011 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview This file contains the explore page functions. * * @author phu@google.com (Po Hu) */ goog.provide('bite.server.View'); goog.require('bite.server.Constants'); goog.require('bite.server.LayoutHelper'); goog.require('bite.server.Helper'); goog.require('bite.server.Page'); goog.require('bite.server.explore.OverviewTab'); goog.require('bite.server.explore.RunTab'); goog.require('bite.server.explore.SetTab'); goog.require('bite.server.explore.Tab'); goog.require('bite.server.templates.explore'); goog.require('goog.Uri'); goog.require('goog.dom'); goog.require('goog.events'); goog.require('goog.net.XhrIo'); goog.require('goog.positioning'); goog.require('goog.ui.ComboBox'); goog.require('goog.ui.MenuItem'); goog.require('goog.ui.PopupMenu'); /** * A class for view page. * @extends {bite.server.Page} * @constructor * @export */ bite.server.View = function() { bite.server.Page.call(this); /** * The last selected project name. * @type {goog.ui.ComboBox} * @private */ this.projectSelector_ = null; /** * All of the project names. * @type {Array} * @private */ this.projects_ = []; /** * The layout helper object. * @type {bite.server.LayoutHelper} * @private */ this.layoutHelper_ = null; var getProjectName = goog.bind(this.getProjectName, this); /** * The overview tab in explore page. * @type {bite.server.explore.OverviewTab} * @private */ this.overviewTab_ = new bite.server.explore.OverviewTab(getProjectName); /** * The set tab in explore page. * @type {bite.server.explore.SetTab} * @private */ this.setTab_ = new bite.server.explore.SetTab(getProjectName); /** * The run tab in explore page. * @type {bite.server.explore.RunTab} * @private */ this.runTab_ = new bite.server.explore.RunTab(getProjectName); /** * The selected tab in explore page. * @type {bite.server.explore.Tab} * @private */ this.selectedTab_ = new bite.server.explore.Tab(getProjectName); /** * The tab id and instance map. * @type {Object} * @private */ this.tabNameObjMap_ = { 'all': this.overviewTab_, 'suites': this.setTab_, 'runs': this.runTab_ }; }; goog.inherits(bite.server.View, bite.server.Page); /** * Inits the page. * @param {Object} paramsMap The params map of the url hash. * @export */ bite.server.View.prototype.init = function(paramsMap) { this.layoutHelper_ = bite.server.LayoutHelper.getInstance(); var baseHeader = goog.dom.getElement('baseHeader'); var baseView = goog.dom.getElement('baseView'); soy.renderElement(baseHeader, bite.server.templates.explore.showHeader); soy.renderElement( baseView, bite.server.templates.explore.showBodyArea, {'data': { 'mainNavs': bite.server.Constants.DEFAULT_MAINNAVS_EXPLORE_PAGE}}); this.renderProjectSelector_(); var mainNavs = /** @type {Array} */ (goog.dom.getElementsByClass('mainnav-item')); this.handleMainNavChanges_(mainNavs[0].id); this.initCreateMenu(); bite.server.Helper.addListenersToElems( mainNavs, goog.bind(this.listenToHandleMainNavChanges, this)); }; /** * Returns the project name. * @return {string} The project name. * @export */ bite.server.View.prototype.getProjectName = function() { if (this.projectSelector_) { return this.projectSelector_.getValue(); } else { // TODO(phu): This should be done on server side to choose the // user's first project choice. return 'BITE'; } }; /** * Renders the project selector. * @private */ bite.server.View.prototype.renderProjectSelector_ = function() { var requestUrl = bite.server.Helper.getUrl( '', '/project/list', {}); goog.net.XhrIo.send( requestUrl, goog.bind(this.callbackRenderProjectSelector_, this), 'POST'); }; /** * Callback for Rendering the project selector. * @param {Event} e The event object. * @private */ bite.server.View.prototype.callbackRenderProjectSelector_ = function(e) { var xhr = /** @type {goog.net.XhrIo} */ (e.target); if (xhr.isSuccess()) { var projects = /** @type {Array} */ (xhr.getResponseJson()); if (projects) { this.projects_ = projects; this.projectSelector_ = bite.server.Helper.createSelector( projects, 'projectSelector', 'Select a project...'); this.projectSelector_.setValue('BITE'); } } else { throw new Error('Failed to get the projects. Error status: ' + xhr.getStatus()); } }; /** * Listens to handle main navigation changes. * @param {Event} event The event object. * @export */ bite.server.View.prototype.listenToHandleMainNavChanges = function(event) { this.handleMainNavChanges_(event.target.id); }; /** * Handles main navigation changes. * @param {string} id The selected main nav's id. * @private */ bite.server.View.prototype.handleMainNavChanges_ = function(id) { var tabTitle = id.substring('mainnav-'.length); this.layoutHelper_.handleMainNavChanges(id); this.selectedTab_ = this.tabNameObjMap_[tabTitle]; this.selectedTab_.init(); this.selectedTab_.setUpLeftNavs(); }; /** * Inits the create menu. * @export */ bite.server.View.prototype.initCreateMenu = function() { var button = goog.dom.getElement('createButton'); var pm = new goog.ui.PopupMenu(); pm.addChild(new goog.ui.MenuItem('Suite'), true); pm.addChild(new goog.ui.MenuItem('Project'), true); pm.render(document.body); pm.attach( button, goog.positioning.Corner.BOTTOM_LEFT, goog.positioning.Corner.TOP_LEFT); goog.events.listen(pm, 'action', function(e) { var value = e.target.getValue(); var url = ''; switch (value) { case 'Suite': url = '/home#page=set_details'; break; case 'Project': url = '/home#page=project_details'; break; } goog.global.window.open(url); }); }; /** * Destroys this object. * @export */ bite.server.View.prototype.destroy = function() { };
JavaScript