Best JavaScript code snippet using appium-android-driver
core_addon.js
Source:core_addon.js
...11 it("should un/enroll in Rally", async function () {12 this.driver = await utils.getFirefoxDriver(true, {});1314 // Switch to browser UI context, so we can inject script to set up Remote Settings.15 await this.driver.setContext(firefox.Context.CHROME);16 await this.driver.executeScript(utils.initRemoteSettings, utils.RALLY_TEST_STUDY_REGISTRY, 1234567);1718 // Switch back to web content context (options page).19 await this.driver.setContext(firefox.Context.CONTENT);2021 await utils.installRally(this.driver);22 await utils.joinRally(this.driver);2324 await this.driver.wait(until.elementLocated(By.css("button")));25 await utils.findAndAct(this.driver, By.xpath(`//button[text()="Join Study"]`), e => e.click());26 await utils.findAndAct(this.driver, By.xpath(`(//button[text()="Accept & Enroll"])`), e => e.click());2728 // Switch to browser UI context, to interact with Firefox add-on install prompts.29 await this.driver.setContext(firefox.Context.CHROME);30 await utils.findAndAct(this.driver, By.css(`[label="Add"]`), e => e.click());31 await utils.findAndAct(this.driver, By.css(`[label="Okay"]`), e => e.click());3233 // Close options page tab and re-open it.34 await this.driver.close();35 const originalTab = (await this.driver.getAllWindowHandles())[0];36 await this.driver.switchTo().window(originalTab);37 await utils.findAndAct(this.driver, By.id("rally-core_mozilla_org-browser-action"), e => e.click());3839 // We expect the extension to load its options page in a new tab.40 const newOptionsTab = (await this.driver.getAllWindowHandles())[0];41 await this.driver.switchTo().window(newOptionsTab);4243 // Switch context to web content to interact with options page.44 await this.driver.setContext(firefox.Context.CONTENT);4546 // Ensure that the study card for the base study is displayed.47 const baseStudySelector = By.xpath(`//span[text()="Rally Base Study"]`);48 await this.driver.findElement(baseStudySelector);4950 // Begin study unenrollment cancel it.51 await utils.findAndAct(this.driver, By.xpath(`//button[text()="Leave Mozilla Rally"]`), e => e.click());52 await utils.findAndAct(this.driver, By.xpath(`//button[text()="Cancel"]`), e => e.click());5354 // Begin unenrollment and confirm it this time.55 const unenrollSelector = By.xpath(`//button[text()="Leave Mozilla Rally"]`);56 const unenrollButton = await this.driver.findElement(unenrollSelector);57 await this.driver.wait(until.elementIsVisible(unenrollButton), utils.WAIT_FOR_PROPERTY);58 unenrollButton.click();5960 await this.driver.wait(61 until.titleIs("Rally: Put your data to work for a better internet"),62 utils.WAIT_FOR_PROPERTY63 );6465 const confirmButton = await this.driver.findElement(66 By.xpath(`//button[text()="Leave Rally"]`)67 );68 await this.driver.wait(until.elementIsVisible(confirmButton), utils.WAIT_FOR_PROPERTY);69 await confirmButton.click();70 // TODO check that core add-on is uninstalled, see https://github.com/mozilla-rally/core-addon/issues/2457172 await this.driver.quit();73 });7475 it("Should be disabled on non en-US locales", async function () {76 this.driver = await utils.getFirefoxDriver(true, {77 "intl.accept_languages": "it-IT"78 });7980 await utils.installRally(this.driver);8182 // Check the content of the page.83 const pageContent = await this.driver.getPageSource();84 assert.ok(pageContent.includes("At this time, Mozilla Rally is only available to participants based in the U.S."));8586 await this.driver.quit();87 });8889 it("Should display and respond to Remote Settings changes", async function () {90 this.driver = await utils.getFirefoxDriver(true, {});9192 // Switch to browser UI context, so we can inject script to set up Remote Settings.93 await this.driver.setContext(firefox.Context.CHROME);94 await this.driver.executeScript(utils.initRemoteSettings, utils.RALLY_TEST_STUDY_REGISTRY, 1234567);95 // Switch back to web content context (options page).96 await this.driver.setContext(firefox.Context.CONTENT);9798 await utils.installRally(this.driver);99 await utils.joinRally(this.driver);100101 // Ensure that the study card for the base study is displayed.102 const baseStudySelector = By.xpath(`//span[text()="Rally Base Study"]`);103 await this.driver.findElement(baseStudySelector);104105 // Switch to browser UI context, so we can inject script to modify Remote Settings.106 const modifiedTestStudy = Object.assign({}, utils.RALLY_TEST_STUDY_REGISTRY);107 modifiedTestStudy.name = "Another Rally Study";108 await this.driver.setContext(firefox.Context.CHROME);109 await this.driver.executeScript(utils.updateRemoteSettings, modifiedTestStudy, (1234567 + 1));110 // Switch back to web content context (options page).111 await this.driver.setContext(firefox.Context.CONTENT);112113 // Ensure that the study card for the base study is displayed.114 const anotherStudySelector = By.xpath(`//span[text()="Another Rally Study"]`);115 await this.driver.wait(until.elementLocated(anotherStudySelector), utils.WAIT_FOR_PROPERTY);116 await this.driver.findElement(anotherStudySelector);117118 // Check that studies are installable.119 await this.driver.wait(until.elementLocated(By.css("button")));120 await utils.findAndAct(this.driver, By.xpath(`//button[text()="Join Study"]`), e => e.click());121 await utils.findAndAct(this.driver, By.xpath(`(//button[text()="Accept & Enroll"])`), e => e.click());122123 // Switch to browser UI context, to interact with Firefox add-on install prompts.124 await this.driver.setContext(firefox.Context.CHROME);125 await utils.findAndAct(this.driver, By.css(`[label="Add"]`), e => e.click());126 await utils.findAndAct(this.driver, By.css(`[label="Okay"]`), e => e.click());127128 await this.driver.quit();129 });130131 it("Should display hidden studies only if already joined", async function () {132 this.driver = await utils.getFirefoxDriver(true, {});133134 // Switch to browser UI context, so we can inject script to set up Remote Settings.135 await this.driver.setContext(firefox.Context.CHROME);136 await this.driver.executeScript(utils.initRemoteSettings, utils.RALLY_TEST_STUDY_REGISTRY, 1234567);137 // Switch back to web content context (options page).138 await this.driver.setContext(firefox.Context.CONTENT);139140 await utils.installRally(this.driver);141 await utils.joinRally(this.driver);142143 // Switch to browser UI context, so we can inject script to modify Remote Settings.144 const modifiedTestStudy = Object.assign({}, utils.RALLY_TEST_STUDY_REGISTRY);145 // Mark study as paused.146 modifiedTestStudy.studyPaused = true;147 await this.driver.setContext(firefox.Context.CHROME);148 await this.driver.executeScript(utils.updateRemoteSettings, modifiedTestStudy, 1234567);149 // Switch back to web content context (options page).150 await this.driver.setContext(firefox.Context.CONTENT);151152 // Check that no studies are displayed.153 const noStudySelector = By.xpath(`//div[text()="No available studies"]`);154 await this.driver.wait(until.elementLocated(noStudySelector), utils.WAIT_FOR_PROPERTY);155156 // Switch to browser UI context, so we can inject script to modify Remote Settings.157 await this.driver.setContext(firefox.Context.CHROME);158 // No more paused studies.159 modifiedTestStudy.studyPaused = false;160 await this.driver.executeScript(utils.updateRemoteSettings, modifiedTestStudy, (1234567 + 2));161 // Switch back to web content context (options page).162 await this.driver.setContext(firefox.Context.CONTENT);163164 // Ensure that the study card for the base study is displayed.165 const baseStudySelector = By.xpath(`//span[text()="Rally Base Study"]`);166 await this.driver.wait(until.elementLocated(baseStudySelector), utils.WAIT_FOR_PROPERTY);167 await this.driver.findElement(baseStudySelector);168169 // Install study, so we can ensure that marking it paused does not hide the "leave" functionality.170 await utils.findAndAct(this.driver, By.xpath(`//button[text()="Join Study"]`), e => e.click());171 await utils.findAndAct(this.driver, By.xpath(`(//button[text()="Accept & Enroll"])`), e => e.click());172173 // Switch to browser UI context, to interact with Firefox add-on install prompts.174 await this.driver.setContext(firefox.Context.CHROME);175 await utils.findAndAct(this.driver, By.css(`[label="Add"]`), e => e.click());176 await utils.findAndAct(this.driver, By.css(`[label="Okay"]`), e => e.click());177178 // Switch to browser UI context, so we can inject script to modify Remote Settings.179 await this.driver.setContext(firefox.Context.CHROME);180 // The study is once again set as paused.181 modifiedTestStudy.studyPaused = true;182 await this.driver.executeScript(utils.updateRemoteSettings, modifiedTestStudy, (1234567 + 3));183184 // We expect the study to open its own options page tab, navigate back to the core add-on options page.185 await utils.findAndAct(this.driver, By.id("rally-core_mozilla_org-browser-action"), e => e.click());186187 // Switch back to web content context (core add-on options page).188 await this.driver.setContext(firefox.Context.CONTENT);189190 // Ensure that the study card for the base study is displayed.191 await utils.findAndAct(this.driver, By.xpath(`//button[text()="Leave Study"]`), e => e.click());192 await utils.findAndAct(this.driver, By.xpath(`(//button[text()="Leave Study"])[2]`), e => e.click());193194 // No studies are available, because the paused study was removed.195 await this.driver.wait(until.elementLocated(noStudySelector), utils.WAIT_FOR_PROPERTY);196197 await this.driver.quit();198 });199200 it("Should filter out studies that are too old for core add-on", async function () {201 this.driver = await utils.getFirefoxDriver(true, {});202203 // Switch to browser UI context, so we can inject script to set up Remote Settings.204 await this.driver.setContext(firefox.Context.CHROME);205 await this.driver.executeScript(utils.initRemoteSettings, utils.RALLY_TEST_STUDY_REGISTRY, 1234567);206 // Switch back to web content context (options page).207 await this.driver.setContext(firefox.Context.CONTENT);208209 await utils.installRally(this.driver);210 await utils.joinRally(this.driver);211212 // Switch to browser UI context, so we can inject script to modify Remote Settings.213 const modifiedTestStudy = Object.assign({}, utils.RALLY_TEST_STUDY_REGISTRY);214 // Mark study as paused.215 // Check that a far future version of the core add-on is incompatible.216 modifiedTestStudy.minimumCoreVersion = "1000.0.1";217 await this.driver.setContext(firefox.Context.CHROME);218 await this.driver.executeScript(utils.updateRemoteSettings, modifiedTestStudy, 1234567);219 // Switch back to web content context (options page).220 await this.driver.setContext(firefox.Context.CONTENT);221222 // Check that no studies are displayed.223 const noStudySelector = By.xpath(`//div[text()="No available studies"]`);224 await this.driver.wait(until.elementLocated(noStudySelector), utils.WAIT_FOR_PROPERTY);225226 // Switch to browser UI context, so we can inject script to modify Remote Settings.227 await this.driver.setContext(firefox.Context.CHROME);228 // Check that a far past version of the core add-on is compatible.229 modifiedTestStudy.minimumCoreVersion = "0.0.1";230 await this.driver.executeScript(utils.updateRemoteSettings, modifiedTestStudy, (1234567 + 2));231 // Switch back to web content context (options page).232 await this.driver.setContext(firefox.Context.CONTENT);233234 // Ensure that the study card for the base study is displayed.235 const baseStudySelector = By.xpath(`//span[text()="Rally Base Study"]`);236 await this.driver.wait(until.elementLocated(baseStudySelector), utils.WAIT_FOR_PROPERTY);237 await this.driver.findElement(baseStudySelector);238239 // Install study, so we can ensure that marking it paused does not hide the "leave" functionality.240 await utils.findAndAct(this.driver, By.xpath(`//button[text()="Join Study"]`), e => e.click());241 await utils.findAndAct(this.driver, By.xpath(`(//button[text()="Accept & Enroll"])`), e => e.click());242243 // Switch to browser UI context, to interact with Firefox add-on install prompts.244 await this.driver.setContext(firefox.Context.CHROME);245 await utils.findAndAct(this.driver, By.css(`[label="Add"]`), e => e.click());246 await utils.findAndAct(this.driver, By.css(`[label="Okay"]`), e => e.click());247248 await this.driver.quit();249 });
...
1-telemetry.js
Source:1-telemetry.js
...25 after(() => {26 driver.quit();27 });28 async function activateCompatMode() {29 driver.setContext(Context.CONTENT);30 await driver.get("https://en.wikipedia.org/wiki/Main_Page");31 driver.setContext(Context.CHROME);32 const tabs = await driver.getAllWindowHandles();33 driver.setContext(Context.CONTENT);34 // Focus the driver on the webextension page so we can use the browser.runtime api to send messages.35 driver.switchTo().window(tabs[1]);36 await driver.sleep(500);37 // We are at the auto-opened extension page, so we can send messages from here.38 // We send a message that the button is "clicked" from tab 2,39 // but we are reporting tab 1 so that real data gets sent.40 driver.setContext(Context.CHROME);41 // Select the wikipedia tab to allow it to have a "DOMContentLoaded" event42 await driver.executeScript(`43 gBrowser.selectedTab = gBrowser.tabs[0];44 `);45 await driver.sleep(500);46 driver.setContext(Context.CONTENT);47 // driver is still focused on the "extension" tab,48 // so can access the "browser" api to send a message reporting the wikipedia tab.49 await driver.executeScript(`browser.runtime.sendMessage({msg: "compat_mode", tabId: 1});`);50 await driver.sleep(500);51 }52 async function resetDriver() {53 driver.quit();54 driver = await utils.setupWebdriver.promiseSetupDriver(55 utils.FIREFOX_PREFERENCES,56 );57 await utils.setPreference(driver, "extensions.cookie-restrictions-breakage_shield_mozilla_org.test.variationName", "ThirdPartyTrackingBasic");58 await utils.setupWebdriver.installAddon(driver);59 }60 function checkTelemetryPayload(nonTracking = false) {61 it("has recorded pings", async () => {62 assert(studyPings.length, "at least one shield telemetry ping");63 });64 it("correctly records etld as a hash", async () => {65 const ping = studyPings[0];66 const attributes = ping.payload.data.attributes;67 assert.exists(attributes.etld, "etld exists");68 assert.notInclude(attributes.etld, "wikipedia", "etld does not contain the domain");69 assert.equal(attributes.etld.length * 4, 256, "etld is a 256 bit hex string");70 });71 it("correctly records the set preferences in the payload", async () => {72 const ping = studyPings[0];73 const attributes = ping.payload.data.attributes;74 const privacy_trackingprotection_enabled = await utils.getPreference(driver, "privacy.trackingprotection.enabled");75 const network_cookie_cookieBehavior = await utils.getPreference(driver, "network.cookie.cookieBehavior");76 const urlclassifier_trackingTable = await utils.getPreference(driver, "urlclassifier.trackingTable");77 assert.equal(attributes.privacy_trackingprotection_enabled, privacy_trackingprotection_enabled.toString(), "privacy_trackingprotection_enabled is set, and equals the pref");78 assert.equal(attributes.network_cookie_cookieBehavior, network_cookie_cookieBehavior.toString(), "network_cookie_cookieBehavior is set, and equals the pref");79 assert.equal(attributes.urlclassifier_trackingTable, urlclassifier_trackingTable.toString(), "privacy_trackingprotection_enabled is set, and equals the pref");80 });81 }82 describe("records shield telemetry when 'compat_mode' message is received", function() {83 before(async () => {84 const time = Date.now();85 await activateCompatMode();86 studyPings = await utils.telemetry.getShieldPingsAfterTimestamp(87 driver,88 time,89 );90 studyPings = studyPings.filter(ping => ping.type === "shield-study-addon");91 });92 checkTelemetryPayload();93 });94 describe("records shield telemetry when user answers survey with no", function() {95 before(async () => {96 const time = Date.now();97 driver.setContext(Context.CHROME);98 // Click the "No" answer on the banner99 const noButton = await driver.wait(until.elementLocated(By.css("notification[value='cookie-restrictions-breakage'] .notification-button[label='No']")), 1000);100 noButton.click();101 await driver.sleep(500);102 studyPings = await utils.telemetry.getShieldPingsAfterTimestamp(103 driver,104 time,105 );106 studyPings = studyPings.filter(ping => ping.type === "shield-study-addon");107 });108 checkTelemetryPayload();109 it("correctly sends a 'No' answer", async () => {110 const ping = studyPings[0];111 const attributes = ping.payload.data.attributes;112 assert.equal(attributes.action, "survey_response_not_fixed", "action is 'survey_response_not_fixed'");113 });114 });115 describe("records shield telemetry when user answers survey with yes, and send plain text url", function() {116 before(async () => {117 await resetDriver();118 utils.joinStudy(driver);119 await activateCompatMode();120 const time = Date.now();121 driver.setContext(Context.CHROME);122 // Click the "Yes" answer on the banner123 const yesButton = await driver.wait(until.elementLocated(By.css("notification[value='cookie-restrictions-breakage'] .notification-button[label='Yes']")), 1000);124 yesButton.click();125 const sendButton = await driver.wait(until.elementLocated(By.css("notification[value='cookie-restrictions-breakage-report-url'] .notification-button[label='Yes']")), 1000);126 sendButton.click();127 await driver.sleep(500);128 studyPings = await utils.telemetry.getShieldPingsAfterTimestamp(129 driver,130 time,131 );132 studyPings = studyPings.filter(ping => ping.type === "shield-study-addon");133 });134 checkTelemetryPayload();135 it("correctly sends a 'Yes' answer", async () => {136 const ping = studyPings[0];137 const attributes = ping.payload.data.attributes;138 assert.equal(attributes.action, "survey_response_fixed", "action is 'survey_response_not_fixed'");139 });140 it("correctly includes a plain text url in the telemetry", async () => {141 const ping = studyPings[0];142 const attributes = ping.payload.data.attributes;143 assert.equal(attributes.plain_text_url, "https://en.wikipedia.org", "ping contains 'https://en.wikipedia.org' in plain text");144 });145 });146 describe("records shield telemetry when user clicks the x on the survey", function() {147 before(async () => {148 await resetDriver();149 utils.joinStudy(driver);150 await activateCompatMode();151 const time = Date.now();152 driver.setContext(Context.CHROME);153 // Click the "x" button on the banner154 const xButton = await driver.wait(until.elementLocated(By.css("notification[value='cookie-restrictions-breakage'] .messageCloseButton")), 1000);155 xButton.click();156 await driver.sleep(500);157 studyPings = await utils.telemetry.getShieldPingsAfterTimestamp(158 driver,159 time,160 );161 studyPings = studyPings.filter(ping => ping.type === "shield-study-addon");162 });163 checkTelemetryPayload();164 it("correctly sends a 'survey closed' answer", async () => {165 const ping = studyPings[0];166 const attributes = ping.payload.data.attributes;167 assert.equal(attributes.action, "survey_closed", "action is 'survey_closed'");168 });169 });170 describe("records shield telemetry when user answers survey with yes, and doesn't send plain text url", function() {171 before(async () => {172 await resetDriver();173 utils.joinStudy(driver);174 await activateCompatMode();175 const time = Date.now();176 driver.setContext(Context.CHROME);177 // Click the "Yes" answer on the banner178 const yesButton = await driver.wait(until.elementLocated(By.css("notification[value='cookie-restrictions-breakage'] .notification-button[label='Yes']")), 1000);179 yesButton.click();180 const doNotSendButton = await driver.wait(until.elementLocated(By.css("notification[value='cookie-restrictions-breakage-report-url'] .notification-button[label='No']")), 1000);181 doNotSendButton.click();182 await driver.sleep(500);183 studyPings = await utils.telemetry.getShieldPingsAfterTimestamp(184 driver,185 time,186 );187 studyPings = studyPings.filter(ping => ping.type === "shield-study-addon");188 });189 checkTelemetryPayload();190 it("correctly sends a 'Yes' answer", async () => {191 const ping = studyPings[0];192 const attributes = ping.payload.data.attributes;193 assert.equal(attributes.action, "survey_response_fixed", "action is 'survey_response_fixed'");194 });195 it("correctly does not include a plain text url in the telemetry", async () => {196 const ping = studyPings[0];197 const attributes = ping.payload.data.attributes;198 assert.equal(attributes.plain_text_url, "", "ping does not contain the url in plain text");199 });200 });201 describe("records number of internal and external navigations", function() {202 before(async () => {203 await resetDriver();204 utils.joinStudy(driver);205 await activateCompatMode();206 const time = Date.now();207 driver.setContext(Context.CHROME);208 const tabs = await driver.getAllWindowHandles();209 await driver.switchTo().window(tabs[0]);210 driver.setContext(Context.CONTENT);211 await driver.get("https://en.wikipedia.org/wiki/Encyclopedia");212 await driver.get("https://github.com/");213 await driver.get("https://www.mozilla.org/en-US/");214 await driver.get("https://en.wikipedia.org/wiki/Encyclopedia");215 driver.setContext(Context.CHROME);216 // Click the "No" answer on the banner217 const noButton = await driver.wait(until.elementLocated(By.css("notification[value='cookie-restrictions-breakage'] .notification-button[label='No']")), 1000);218 noButton.click();219 await driver.sleep(500);220 studyPings = await utils.telemetry.getShieldPingsAfterTimestamp(221 driver,222 time,223 );224 studyPings = studyPings.filter(ping => ping.type === "shield-study-addon");225 });226 checkTelemetryPayload();227 it("correctly sends a 'No' answer", async () => {228 const ping = studyPings[0];229 const attributes = ping.payload.data.attributes;230 assert.equal(attributes.action, "survey_response_not_fixed", "action is 'survey_response_not_fixed'");231 });232 it("correctly sends the count of navigations", async () => {233 const ping = studyPings[0];234 const attributes = ping.payload.data.attributes;235 assert.equal(attributes.navigated_external, "2", "navigated externally");236 assert.equal(attributes.navigated_internal, "2", "navigated internally");237 });238 });239 describe("records shield telemetry after the tab closes", function() {240 before(async () => {241 await resetDriver();242 utils.joinStudy(driver);243 await activateCompatMode();244 const time = Date.now();245 await utils.removeCurrentTab(driver);246 driver.setContext(Context.CHROME);247 const tabs = await driver.getAllWindowHandles();248 await driver.switchTo().window(tabs[0]);249 await driver.sleep(500);250 studyPings = await utils.telemetry.getShieldPingsAfterTimestamp(251 driver,252 time,253 );254 studyPings = studyPings.filter(ping => ping.type === "shield-study-addon");255 });256 checkTelemetryPayload();257 it("correctly sends a 'survey ignored' answer", async () => {258 const ping = studyPings[0];259 const attributes = ping.payload.data.attributes;260 assert.equal(attributes.action, "survey_ignored", "action is 'survey_ignored'");...
5-reload-doorhanger.js
Source:5-reload-doorhanger.js
...33 }34 before(async () => {35 await driver.sleep(DELAY);36 const time = Date.now();37 driver.setContext(Context.CONTENT);38 await driver.get("https://itisatrap.org/firefox/its-a-tracker.html");39 await driver.sleep(DELAY);40 driver.setContext(Context.CHROME);41 while (reloads++ < 6) {42 await driver.executeScript(`document.getElementById("Browser:Reload").click()`);43 await driver.sleep(DELAY);44 const hasSeenDoorhanger = await checkDoorhangerPresent();45 if (hasSeenDoorhanger) {46 break;47 }48 }49 driver.setContext(Context.CONTENT);50 await driver.get("https://example.com");51 await driver.sleep(DELAY);52 studyPings = await utils.telemetry.getShieldPingsAfterTimestamp(53 driver,54 time,55 );56 studyPings = studyPings.filter(ping => ping.type === "shield-study-addon");57 });58 it("shows the doorhanger after at most 6 reloads", async () => {59 assert.isAtMost(reloads, 6, "Should have shown the doorhanger after at most 6 reloads");60 });61 it("correctly records whether the page was reloaded", async () => {62 for (let i = 0; i < studyPings.length; i++) {63 const ping = studyPings[i];64 const attributes = ping.payload.data.attributes;65 if (i === 0) {66 assert.equal(attributes.page_reloaded, "false", `page reloaded is false on ${i}/${reloads}`);67 } else {68 assert.equal(attributes.page_reloaded, "true", `page reloaded is true on ${i}/${reloads}`);69 }70 // The survey will be shown for the second-to-last document, because the last71 // one is where the survey shows (and it gets discarded via navigation so it72 // doesn't receive its own survey).73 if (i === 1) {74 assert.equal(parseInt(attributes.page_reloaded_survey), 1, `page reloaded survey shown on ${i}/${reloads}`);75 } else {76 assert.equal(parseInt(attributes.page_reloaded_survey), 0, `page reloaded survey not shown on ${i}/${reloads}`);77 }78 }79 });80 });81 describe("allows subsequently showing a survey on the same tab after a navigation event", function() {82 let studyPings;83 const reloads = 5;84 before(async () => {85 await driver.sleep(DELAY);86 const time = Date.now();87 driver.setContext(Context.CONTENT);88 await driver.get("https://itisatrap.org/firefox/its-a-tracker.html");89 await driver.sleep(DELAY);90 driver.setContext(Context.CHROME);91 for (let i = 0; i < reloads; i++) {92 await driver.executeScript(`document.getElementById("Browser:Reload").click()`);93 await driver.sleep(DELAY);94 }95 driver.setContext(Context.CONTENT);96 await driver.get("https://example.com");97 await driver.sleep(DELAY);98 studyPings = await utils.telemetry.getShieldPingsAfterTimestamp(99 driver,100 time,101 );102 studyPings = studyPings.filter(ping => ping.type === "shield-study-addon");103 });104 it("shows the doorhanger after at most 6 reloads", async () => {105 assert.isAtMost(reloads, 6, "Should have shown the doorhanger after at most 6 reloads");106 });107 // there will be one extra pings here from the original example.com page108 it("has recorded one ping per page", async () => {109 assert.equal(studyPings.length, reloads + 2, "one shield telemetry ping per page load");110 });111 });112 describe("records the correct survey response for yes", function() {113 let studyPings;114 const reloads = 8;115 let doorhangerShownFor = Infinity;116 async function checkDoorhangerPresent() {117 const result = await driver.findElements(By.id("cookie-restriction-notification"));118 return !!result.length;119 }120 before(async () => {121 // Reset the doorhanger shown state by restarting the browser.122 driver.quit();123 driver = await utils.setupWebdriver.promiseSetupDriver(124 utils.FIREFOX_PREFERENCES,125 );126 await utils.setupWebdriver.installAddon(driver);127 await driver.sleep(DELAY);128 const time = Date.now();129 driver.setContext(Context.CONTENT);130 await driver.get("https://itisatrap.org/firefox/its-a-tracker.html");131 await driver.sleep(DELAY);132 driver.setContext(Context.CHROME);133 for (let i = 0; i < reloads; i++) {134 await driver.executeScript(`document.getElementById("Browser:Reload").click()`);135 await driver.sleep(DELAY);136 const hasSeenDoorhanger = await checkDoorhangerPresent();137 if (hasSeenDoorhanger) {138 doorhangerShownFor = i;139 await driver.executeScript(`document.getElementById("cookie-restriction-notification").button.click()`);140 }141 }142 // Discard the final ping.143 driver.setContext(Context.CONTENT);144 await driver.get("https://example.com");145 await driver.sleep(DELAY);146 studyPings = await utils.telemetry.getShieldPingsAfterTimestamp(147 driver,148 time,149 );150 studyPings = studyPings.filter(ping => ping.type === "shield-study-addon");151 });152 it("shows the doorhanger after at most 6 reloads", async () => {153 assert.isAtMost(doorhangerShownFor, 5, "Should have shown the doorhanger after at most 6 reloads");154 });155 it("has recorded one ping per page", async () => {156 assert.equal(studyPings.length, reloads + 1, "one shield telemetry ping per page load");157 });158 it("correctly records whether the page was reloaded", async () => {159 // The first pings are listed last in this array.160 studyPings.reverse();161 for (let i = 0; i < studyPings.length; i++) {162 const ping = studyPings[i];163 const attributes = ping.payload.data.attributes;164 if (i === studyPings.length - 1) {165 assert.equal(attributes.page_reloaded, "false", `page reloaded is false on ${i}/${reloads}`);166 } else {167 assert.equal(attributes.page_reloaded, "true", `page reloaded is true on ${i}/${reloads}`);168 }169 if (i === doorhangerShownFor) {170 assert.equal(parseInt(attributes.page_reloaded_survey), 2, `page reloaded survey answered on ${i}/${reloads}`);171 } else if (i === studyPings.length - 1) {172 assert.equal(parseInt(attributes.page_reloaded_survey), 0, `page reloaded survey previously answered on ${i}/${reloads}`);173 } else if (i > doorhangerShownFor) {174 assert.equal(parseInt(attributes.page_reloaded_survey), 4, `page reloaded survey previously answered on ${i}/${reloads}`);175 }176 }177 });178 });179 describe("records the correct survey response for no", function() {180 let studyPings;181 const reloads = 8;182 let doorhangerShownFor = Infinity;183 async function checkDoorhangerPresent() {184 const result = await driver.findElements(By.id("cookie-restriction-notification"));185 return !!result.length;186 }187 before(async () => {188 // Reset the doorhanger shown state by restarting the browser.189 driver.quit();190 driver = await utils.setupWebdriver.promiseSetupDriver(191 utils.FIREFOX_PREFERENCES,192 );193 await utils.setupWebdriver.installAddon(driver);194 await driver.sleep(DELAY);195 const time = Date.now();196 driver.setContext(Context.CONTENT);197 await driver.get("https://itisatrap.org/firefox/its-a-tracker.html");198 await driver.sleep(DELAY);199 driver.setContext(Context.CHROME);200 for (let i = 0; i < reloads; i++) {201 await driver.executeScript(`document.getElementById("Browser:Reload").click()`);202 await driver.sleep(DELAY);203 const hasSeenDoorhanger = await checkDoorhangerPresent();204 if (hasSeenDoorhanger) {205 doorhangerShownFor = i;206 await driver.executeScript(`document.getElementById("cookie-restriction-notification").secondaryButton.click()`);207 }208 }209 // Discard the final ping.210 driver.setContext(Context.CONTENT);211 await driver.get("https://example.com");212 await driver.sleep(DELAY);213 studyPings = await utils.telemetry.getShieldPingsAfterTimestamp(214 driver,215 time,216 );217 studyPings = studyPings.filter(ping => ping.type === "shield-study-addon");218 });219 it("shows the doorhanger after at most 6 reloads", async () => {220 assert.isAtMost(doorhangerShownFor, 5, "Should have shown the doorhanger after at most 6 reloads");221 });222 it("has recorded one ping per page", async () => {223 assert.equal(studyPings.length, reloads + 1, "one shield telemetry ping per page load");224 });...
button_test.js
Source:button_test.js
...7// TODO create new profile per test?8// then we can test with a clean profile every time9async function regularPageAnimationTest(driver) {10 // navigate to a regular page11 driver.setContext(Context.CONTENT);12 await driver.get("http://mozilla.org");13 driver.setContext(Context.CHROME);14 await utils.copyUrlBar(driver);15 const { hasClass, hasColor } = await utils.testAnimation(driver);16 assert(hasClass && hasColor);17}18async function regularPagePopupTest(driver) {19 // navigate to a regular page20 driver.setContext(Context.CONTENT);21 await driver.get("http://mozilla.org");22 driver.setContext(Context.CHROME);23 await utils.copyUrlBar(driver);24 const panelOpened = await utils.testPanel(driver);25 assert(panelOpened);26}27describe("Add-on Functional Tests", function() {28 // This gives Firefox time to start, and us a bit longer during some of the tests.29 this.timeout(15000);30 let driver;31 let addonId;32 before(async() => {33 driver = await utils.promiseSetupDriver();34 // install the addon35 addonId = await utils.installAddon(driver);36 // add the share-button to the toolbar37 await utils.addShareButton(driver);38 });39 after(() => driver.quit());40 afterEach(async() => {41 // wait for the animation to end before running subsequent tests42 await utils.waitForAnimationEnd(driver);43 // close the popup44 await utils.closePanel(driver);45 });46 it("should have a URL bar", async() => {47 const urlBar = await utils.promiseUrlBar(driver);48 const text = await urlBar.getAttribute("placeholder");49 assert.equal(text, "Search or enter address");50 });51 it("should have a toolbar button", async() => {52 const button = await utils.promiseAddonButton(driver);53 const text = await button.getAttribute("tooltiptext");54 assert.equal(text, "Share this page");55 });56 it("should have copy paste working", async() => {57 // FIXME testText will automatically be treated as a URL58 // which means that it will be formatted and the clipboard59 // value will be different unless we pass in a URL text at60 // the start61 const testText = "about:test";62 // write dummy value just in case testText is already in clipboard63 await clipboardy.write("foobar");64 const urlBar = await utils.promiseUrlBar(driver);65 await urlBar.sendKeys(testText);66 await utils.copyUrlBar(driver);67 const clipboard = await clipboardy.read();68 assert(clipboard === testText);69 });70 it("animation should not trigger on disabled page", async() => {71 // navigate to a disabled page72 driver.setContext(Context.CONTENT);73 await driver.get("about:blank");74 driver.setContext(Context.CHROME);75 await utils.copyUrlBar(driver);76 const { hasClass, hasColor } = await utils.testAnimation(driver);77 assert(!hasClass && !hasColor);78 });79 it("popup should not trigger on disabled page", async() => {80 // navigate to a regular page81 driver.setContext(Context.CONTENT);82 await driver.get("about:blank");83 driver.setContext(Context.CHROME);84 await utils.copyUrlBar(driver);85 const panelOpened = await utils.testPanel(driver);86 assert(!panelOpened);87 });88 it("animation should trigger on regular page", () => regularPageAnimationTest(driver));89 it("popup should trigger on regular page", () => regularPagePopupTest(driver));90 it("should not trigger treatments if the share button is in the overflow menu", async() => {91 const window = driver.manage().window();92 const currentSize = await window.getSize();93 await window.setSize(640, 480);94 await utils.copyUrlBar(driver);95 assert(!(await utils.testPanel(driver)));96 await window.setSize(currentSize.width, currentSize.height);97 });...
extension.js
Source:extension.js
...7 this.driver = driver;8 this.addonUUID = addonUUID;9 }10 async whenReady() {11 await this.driver.setContext("chrome");12 const id = await this.driver.findElement(13 By.id("secure-proxy_mozilla_com-browser-action")14 );15 assert.ok(!!id, "We have secure-proxy installed");16 const check = async () => {17 const style = await id.getAttribute("style");18 assert.ok(19 style.includes("badge_off.svg") || style.includes("badge_warning.svg"),20 "The extension is not ready yet"21 );22 return style.includes("badge_warning.svg");23 };24 await this.driver.wait(() => check(), 10000);25 return id;26 }27 // We are unable to debug popups with webdriver. Let's open the popup in a new tab.28 async openPanel() {29 await this.driver.setContext("content");30 // Marionette crashes if we load the extension directly. Let's load something in the meantime.31 await this.driver.get("https://fpn.firefox.com");32 await this.driver.get(33 "moz-extension://" + this.addonUUID + "/popup/popup.html"34 );35 const handle = await this.waitForURL(36 "moz-extension://" + this.addonUUID + "/popup/popup.html"37 );38 await this.skipPopupLoading();39 return handle;40 }41 async skipPopupLoading() {42 const check = async () => {43 let titles = await this.driver.findElements(By.css("h2"));44 if (titles.length === 0) {45 return true;46 }47 let found = false;48 for (let title of titles) {49 try {50 const text = await title.getText();51 if (text.includes("Loadingâ¦")) {52 found = true;53 break;54 }55 } catch (e) {}56 }57 return !found;58 };59 await this.driver.wait(() => check(), 10000);60 }61 async setupStaging() {62 const tab = await this.waitForURL(63 "moz-extension://" + this.addonUUID + "/pages/welcome.html"64 );65 await this.driver.setContext("content");66 await this.driver.executeScript(`67 browser.storage.local.set({68 fxaOpenID: '${process.env.FXA_OPEN_ID}',69 sps: '${process.env.SPS}',70 }).then(() => browser.runtime.reload());71 `);72 // Let's go back to an existing handle.73 this.driver.switchTo().window((await this.driver.getAllWindowHandles())[0]);74 // Let's wait until the extension is reloaded.75 await new Promise(r => setTimeout(r, 1000));76 }77 async waitForURL(url) {78 await this.driver.setContext("content");79 // I'm sure there is something better than this, but this is the only80 // solution to monitor the tab loading so far.81 return await new Promise(resolve => {82 const check = async () => {83 const handles = await this.driver.getAllWindowHandles();84 for (let handle of handles) {85 await this.driver.switchTo().window(handle);86 const t = await this.driver.getCurrentUrl();87 if (t.includes(url)) {88 resolve(handle);89 return;90 }91 }92 setTimeout(check, 500);93 };94 check();95 });96 }97 async waitForElement(elmName) {98 await this.driver.setContext("content");99 return await this.driver.wait(until.elementLocated(By.id(elmName)), 10000);100 }101 async waitForWindowClose(handle) {102 await this.driver.setContext("content");103 const check = async () => {104 const handles = await this.driver.getAllWindowHandles();105 return !handles.find(h => h == handle);106 };107 await this.driver.wait(() => check(), 10000);108 }109 async settingsButtonStatus() {110 await this.driver.setContext("content");111 let button = await this.driver.findElement(By.id("settingsButton"));112 assert.ok(!!button);113 return await button.isDisplayed();114 }115 async backButtonStatus() {116 await this.driver.setContext("content");117 let button = await this.driver.findElement(By.id("backButton"));118 assert.ok(!!button);119 return await button.isDisplayed();120 }121 async icon() {122 await this.driver.setContext("chrome");123 const id = await this.driver.findElement(124 By.id("secure-proxy_mozilla_com-browser-action")125 );126 assert.ok(!!id, "We have secure-proxy installed");127 const style = await id.getAttribute("style");128 if (style.includes("badge_warning.svg")) {129 return "warning";130 }131 if (style.includes("badge_off.svg")) {132 return "off";133 }134 if (style.includes("badge_on.svg")) {135 return "on";136 }...
utils.js
Source:utils.js
...39async function setPreference(driver, name, value) {40 if (typeof value === "string") {41 value = `"${value}"`;42 }43 driver.setContext(Context.CHROME);44 await driver.executeScript(`45 var Preferences = ChromeUtils.import("resource://gre/modules/Preferences.jsm", {}).Preferences;46 Preferences.set("${name}", ${value});47 `);48}49async function getPreference(driver, name) {50 driver.setContext(Context.CHROME);51 const value = await driver.executeScript(`52 var Preferences = ChromeUtils.import("resource://gre/modules/Preferences.jsm", {}).Preferences;53 return Preferences.get("${name}");54 `);55 return value;56}57async function clearPreference(driver, name) {58 driver.setContext(Context.CHROME);59 await driver.executeScript(`Services.prefs.clearUserPref("${name}");`);60}61function prefHasUserValue(driver, name) {62 driver.setContext(Context.CHROME);63 return driver.executeScript(`return Services.prefs.prefHasUserValue("${name}");`);64}65async function openNewTab(driver) {66 driver.setContext(Context.CHROME);67 await driver.executeScript(`68 gBrowser.selectedTab = gBrowser.addTab("about:blank", {triggeringPrincipal: Services.scriptSecurityManager.createNullPrincipal({})});69 `);70}71async function removeCurrentTab(driver) {72 driver.setContext(Context.CHROME);73 await driver.executeScript(`74 gBrowser.removeTab(gBrowser.selectedTab);75 `);76}77// What we expose to our add-on-specific tests78module.exports = {79 FIREFOX_PREFERENCES,80 executeJs,81 nav,82 setupWebdriver,83 telemetry,84 ui,85 setPreference,86 getPreference,...
context-specs.js
Source:context-specs.js
...13 });14 it('setting context to \'null\' should work', async function () {15 let contexts = await driver.getContexts();16 contexts.should.have.length(1);17 await driver.setContext(contexts[0]);18 await driver.setContext(null);19 });20 it('setting context to \'NATIVE_APP\' should work', async function () {21 let contexts = await driver.getContexts();22 contexts.should.have.length(1);23 await driver.setContext(contexts[0]);24 await driver.setContext('NATIVE_APP');25 });26 it('setting context to non-existent context should return \'NoSuchContext\' (status: 35)', async function () {27 await B.resolve(driver.setContext('WEBVIEW_42'))28 .catch(throwMatchableError)29 .should.be.rejectedWith(/jsonwpCode: 35/);30 });...
nav.js
Source:nav.js
...3const Context = firefox.Context;4module.exports.nav = {5 gotoURL: async (driver, url) => {6 // navigate to a regular page7 driver.setContext(Context.CONTENT);8 await driver.get(url);9 driver.setContext(Context.CHROME);10 },...
Using AI Code Generation
1var webdriver = require('selenium-webdriver'),2 until = webdriver.until;3var driver = new webdriver.Builder()4 .forBrowser('chrome')5 .build();6driver.findElement(By.name('q')).sendKeys('webdriver');7driver.findElement(By.name('btnG')).click();8driver.wait(until.titleIs('webdriver - Google Search'), 1000);9driver.quit();10driver.setContext('NATIVE_APP', function() {11});12driver.setContext('WEBVIEW_1', function() {13});14driver.setContext('WEBVIEW_2', function() {15});16driver.setContext('WEBVIEW_3', function() {17});18driver.setContext('WEBVIEW_4', function() {19});20driver.setContext('WEBVIEW_5', function() {21});22driver.setContext('WEBVIEW_6', function() {23});24driver.setContext('WEBVIEW_7', function() {25});26driver.setContext('WEBVIEW_8', function() {27});28driver.setContext('WEBVIEW_9', function() {29});30driver.setContext('WEBVIEW_10', function() {31});32driver.setContext('WEBVIEW_11', function() {33});34driver.setContext('WEBVIEW_12', function() {35});36driver.setContext('WEBVIEW_13', function() {37});38driver.setContext('WEBVIEW_14', function() {39});40driver.setContext('WEBVIEW_15', function() {41});42driver.setContext('WEBVIEW_16', function() {43});44driver.setContext('WEBVIEW_17', function() {45});46driver.setContext('WEBVIEW_18', function() {47});48driver.setContext('WEBVIEW_19', function() {49});50driver.setContext('WEBVIEW_20', function() {
Using AI Code Generation
1driver.setContext('NATIVE_APP');2driver.setContext('WEBVIEW_1');3driver.setContext('WEBVIEW_2');4driver.setContext('WEBVIEW_3');5driver.setContext('WEBVIEW_4');6driver.setContext('WEBVIEW_5');7driver.setContext('WEBVIEW_6');8driver.setContext('WEBVIEW_7');9driver.setContext('WEBVIEW_8');10driver.setContext('WEBVIEW_9');11driver.setContext('WEBVIEW_10');12driver.setContext('WEBVIEW_11');13driver.setContext('WEBVIEW_12');14driver.setContext('WEBVIEW_13');15driver.setContext('WEBVIEW_14');16driver.setContext('WEBVIEW_15');17driver.setContext('WEBVIEW_16');18driver.setContext('WEBVIEW_17');19driver.setContext('WEBVIEW_18');20driver.setContext('WEBVIEW_19');21driver.setContext('WEBVIEW_20');22driver.setContext('WEBVIEW_21');23driver.setContext('WEBVIEW_22');24driver.setContext('WEBVIEW_23');25driver.setContext('WEBVIEW_24');26driver.setContext('WEBVIEW_25');27driver.setContext('WEBVIEW_26');28driver.setContext('WEBVIEW_27');29driver.setContext('WEBVIEW_28');30driver.setContext('WEBVIEW_29');31driver.setContext('WEBVIEW_30');32driver.setContext('WEBVIEW_31');33driver.setContext('WEBVIEW_32');34driver.setContext('WEBVIEW_33');35driver.setContext('WEBVIEW_34');36driver.setContext('WEBVIEW_35');37driver.setContext('WEBVIEW_36');38driver.setContext('WEBVIEW_37');39driver.setContext('WEBVIEW_38');40driver.setContext('WEBVIEW_39');41driver.setContext('WEBVIEW_40');42driver.setContext('WEBVIEW_41');43driver.setContext('WEBVIEW_42');44driver.setContext('WEBVIEW_43');45driver.setContext('WEBVIEW_44');46driver.setContext('WEBVIEW_45');47driver.setContext('WEBVIEW_46');48driver.setContext('WEBVIEW_47');49driver.setContext('WEBVIEW_48');50driver.setContext('WEBVIEW_49');51driver.setContext('WEBVIEW_50');52driver.setContext('WEBVIEW_51');53driver.setContext('WEBVIEW_52');54driver.setContext('WEBVIEW_53');55driver.setContext('WEBVIEW_54');56driver.setContext('
Using AI Code Generation
1var webdriver = require('selenium-webdriver');2 build();3driver.setContext(webdriver.Context.CHROME_APP);4driver.findElement(webdriver.By.name('q')).sendKeys('webdriver');5driver.findElement(webdriver.By.name('btnG')).click();6driver.quit();
Using AI Code Generation
1describe('Set Context', function() {2 it('Set Context', function() {3 driver.setContext('WEBVIEW_1');4 driver.context('WEBVIEW_1');5 driver.getContext().should.become('WEBVIEW_1');6 driver.contexts().should.become(['NATIVE_APP', 'WEBVIEW_1']);7 });8});
Using AI Code Generation
1driver.setContext('WEBVIEW_1');2driver.setContext("WEBVIEW_1");3driver.getContext().then(function (context) {4 console.log("Current context is " + context);5});6String context = driver.getContext();7System.out.println("Current context is " + context);8driver.getContexts().then(function (contexts) {9 console.log("Available contexts are " + contexts);10});
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!