// Method checking if the edited profile is displayed back to the user and if illegal string like // URL and email id are stripped off from "profile essay" sections private void verifyChanges() { List<WebElement> allElements = driver.findElements(By.cssSelector("div[id='about_myself'] p")); for (WebElement element1 : allElements) { if (element1.getText().contains("www.") || element1.getText().contains(".com")) ; ripOffTextAboutMe++; } List<WebElement> allElements2 = driver.findElements(By.cssSelector("div[id='who_im_looking_for'] p")); for (WebElement element2 : allElements2) { if (element2.getText().contains("www.") || element2.getText().contains(".com")) ; ripOffTextPartnerSearch++; } List<WebElement> allElement3 = driver.findElements(By.cssSelector("ul[class='profileInformation'] li")); for (WebElement element3 : allElement3) { // System.out.println(element3.getText()); if (element3.getText().contains("Mixed") || element3.getText().contains("4ft. 10in.")) profileChangeCheck++; } if (profileChangeCheck > 0) System.out.println("SUCCESS: The changes made in the basic profile are visible"); if (ripOffTextAboutMe != 0) System.out.println( "SUCCESS: The About Myself section has ripped off any illegal strings like URL and Email id"); if (ripOffTextPartnerSearch != 0) System.out.println( "SUCCESS: The What I am Looking For section has ripped off any illegal strings like URL and Email id"); }
@Ignore( value = {ANDROID, IPHONE, OPERA_MOBILE, PHANTOMJS, SAFARI}, reason = "Android/Iphone/PhantomJS - not tested," + "Opera mobile/Safari - not implemented") @NeedsLocalEnvironment @Test public void canConfigureProxyThroughPACFile() { WebServer helloServer = createSimpleHttpServer("<!DOCTYPE html><title>Hello</title><h3>Hello, world!</h3>"); WebServer pacFileServer = createPacfileServer( Joiner.on('\n') .join( "function FindProxyForURL(url, host) {", " return 'PROXY " + getHostAndPort(helloServer) + "';", "}")); Proxy proxy = new Proxy(); proxy.setProxyAutoconfigUrl("http://" + getHostAndPort(pacFileServer) + "/proxy.pac"); DesiredCapabilities caps = new DesiredCapabilities(); caps.setCapability(PROXY, proxy); WebDriver driver = new WebDriverBuilder().setDesiredCapabilities(caps).get(); registerDriverTeardown(driver); driver.get(pages.mouseOverPage); assertEquals( "Should follow proxy to another server", "Hello, world!", driver.findElement(By.tagName("h3")).getText()); }
protected File savePageSourceToFile(String fileName, WebDriver webdriver, boolean retryIfAlert) { File pageSource = new File(reportsFolder, fileName + ".html"); try { writeToFile(webdriver.getPageSource(), pageSource); } catch (UnhandledAlertException e) { if (retryIfAlert) { try { Alert alert = webdriver.switchTo().alert(); log.severe(e + ": " + alert.getText()); alert.accept(); savePageSourceToFile(fileName, webdriver, false); } catch (Exception unableToCloseAlert) { log.severe("Failed to close alert: " + unableToCloseAlert); } } else { printOnce("savePageSourceToFile", e); } } catch (UnreachableBrowserException e) { writeToFile(e.toString(), pageSource); return pageSource; } catch (Exception e) { writeToFile(e.toString(), pageSource); printOnce("savePageSourceToFile", e); } return pageSource; }
public static List<WebElement> createWebElementsList(WebDriver driver, By by) { List<WebElement> webElements; driver.manage().timeouts().implicitlyWait(0, TimeUnit.MILLISECONDS); // Quickly webElements = driver.findElements(by); driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS); return webElements; }
@Test public void basicPromptConfirmHandlingAcceptTest() { WebElement promptButton; WebElement promptResult; promptButton = driver.findElement(By.id("promptexample")); promptResult = driver.findElement(By.id("promptreturn")); assertEquals("pret", promptResult.getText()); promptButton.click(); String alertMessage = "I prompt you"; Alert promptAlert = driver.switchTo().alert(); if (Driver.currentDriver != Driver.BrowserName.IE) { // no point doing this in IE as we know it isn't the actual prompt assertEquals(alertMessage, promptAlert.getText()); } promptAlert.accept(); assertEquals("change me", promptResult.getText()); }
// Q: what happens if I send text to alert? // A: ElementNotVisibleException in Firefox // A: in Chrome the text is sent @Test public void basicAlertHandlingKeysTest() { WebElement alertButton; WebElement alertResult; alertButton = driver.findElement(By.id("alertexamples")); alertButton.click(); String alertMessage = "I am an alert box!"; assertEquals(alertMessage, driver.switchTo().alert().getText()); if (Driver.currentDriver == Driver.BrowserName.FIREFOX) { try { driver.switchTo().alert().sendKeys("Hello keys Accept"); fail("expected a ElementNotVisibleException thrown"); } catch (ElementNotVisibleException e) { assertTrue("Expected to get an exception", true); } } if (Driver.currentDriver == Driver.BrowserName.GOOGLECHROME) { // chrome seems happy to send in text to an alert driver.switchTo().alert().sendKeys("Hello keys Accept"); } driver.switchTo().alert().accept(); }
/** * Finds the menu that can be used by the owner to control the participant. Hovers over it. Finds * the mute link and mute it. Then checks in the second participant page whether it is muted */ public void ownerMutesParticipantAndCheck() { System.err.println("Start ownerMutesParticipantAndCheck."); WebDriver owner = ConferenceFixture.getOwner(); WebElement elem = owner.findElement(By.xpath("//div[@class='remotevideomenu']/i[@class='fa fa-angle-down']")); Actions action = new Actions(owner); action.moveToElement(elem); action.perform(); TestUtils.waitForDisplayedElementByXPath( owner, "//ul[@class='popupmenu']/li/a[@class='mutelink']", 5); owner.findElement(By.xpath("//ul[@class='popupmenu']/li/a[@class='mutelink']")).click(); // and now check whether second participant is muted TestUtils.waitForElementByXPath( ConferenceFixture.getSecondParticipant(), "//span[@class='audioMuted']/i[@class='icon-mic-disabled']", 5); action.release(); }
@Test @Ignore( "I would love for this to work consistently but it fails too often between releases to use as an example") public void multiSelectWithUserInteractions() { WebElement multiSelect; multiSelect = driver.findElement(By.cssSelector("select[multiple='multiple']")); List<WebElement> multiSelectOptions = multiSelect.findElements(By.tagName("option")); // in real life, clicking on a multi select item without holding down // CTRL will deselect all others and select only that one item Actions actions = new Actions(driver); actions .click(multiSelectOptions.get(0)) .click(multiSelectOptions.get(1)) .click(multiSelectOptions.get(2)) .perform(); clickSubmitButton(); new WebDriverWait(driver, 10).until(ExpectedConditions.titleIs("Processed Form Details")); assertEquals( "Expected only 1 match", 1, driver.findElements(By.cssSelector("[id^='_valuemultipleselect']")).size()); }
private void SpecialNeeds() throws IOException { // Click Special Needs driver .findElement( By.xpath( "//ul[@class='vertical-tabs-list']/li/a/strong[contains(text(), \"Special Needs\")]")) .click(); // Select Special Needs Select SpecialNeeds = new Select(driver.findElement(By.id("edit-special-needs"))); // Select Learning Center SpecialNeeds.selectByVisibleText("Learning Center"); // Select Early Syllabus SpecialNeeds.selectByVisibleText("Early syllabus"); // Click Apply driver.findElement(By.id("edit-special-needs-apply-filter")).click(); // Check Result Received or Not try { assertTrue( func.isTextPresent(driver.findElement(By.className("search-total-results")).getText())); } catch (Error e) { verificationErrors.append(e.toString()); } // Click All Selections driver.findElement(By.linkText("Clear All Selections")).click(); }
@Test(expected = ElementNotVisibleException.class) public void throwExceptionWhenInteractingWithInvisibleElement() { server.setGetHandler( new HttpRequestCallback() { @Override public void call(HttpServletRequest req, HttpServletResponse res) throws IOException { res.getOutputStream() .println( "<!DOCTYPE html>" + "<html>" + " <head>\n" + " <title>test</title>\n" + " </head>\n" + " <body>\n" + " <input id=\"visible\">\n" + " <input style=\"display:none\" id=\"invisible\">\n" + " </body>" + "</html>"); } }); WebDriver d = getDriver(); d.get(server.getBaseUrl()); WebElement visibleInput = d.findElement(By.id("visible")); WebElement invisibleInput = d.findElement(By.id("invisible")); String textToType = "text to type"; visibleInput.sendKeys(textToType); assertEquals(textToType, visibleInput.getAttribute("value")); invisibleInput.sendKeys(textToType); }
@Parameters({"useCloudEnv", "userName", "key", "os", "browser", "browserVersion", "url"}) @BeforeMethod public void setUp( @Optional("false") Boolean useCloudEnv, @Optional("rashed1") String userName, @Optional("2601a7b6-4b39-4712-992a-59ddcd85694c") String key, @Optional("Windows 10") String OS, @Optional("firefox") String browser, @Optional("43.0.1") String browserVersion, @Optional("http://www.cigna.com") String url) throws IOException { if (useCloudEnv == true) { // run on cloud logger.setLevel(Level.INFO); logger.info("Test is running on cloud env"); getCloudDriver(userName, key, OS, browser, browserVersion); System.out.println("Tests is running on Saucelabs, please wait for result"); } else { // run on local getLocalDriver(OS, browser, browserVersion); } driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.navigate().to(url); driver.manage().window().maximize(); }
@Ignore({ANDROID, CHROME, HTMLUNIT, IE, IPHONE, OPERA, OPERA_MOBILE, PHANTOMJS, SAFARI}) @NeedsLocalEnvironment @Test public void requiredProxyCapabilityShouldHavePriority() { ProxyServer desiredProxyServer = new ProxyServer(); registerProxyTeardown(desiredProxyServer); Proxy desiredProxy = desiredProxyServer.asProxy(); Proxy requiredProxy = proxyServer.asProxy(); DesiredCapabilities desiredCaps = new DesiredCapabilities(); desiredCaps.setCapability(PROXY, desiredProxy); DesiredCapabilities requiredCaps = new DesiredCapabilities(); requiredCaps.setCapability(PROXY, requiredProxy); WebDriver driver = new WebDriverBuilder() .setDesiredCapabilities(desiredCaps) .setRequiredCapabilities(requiredCaps) .get(); registerDriverTeardown(driver); driver.get(pages.simpleTestPage); assertFalse( "Desired proxy should not have been called.", desiredProxyServer.hasBeenCalled("simpleTest.html")); assertTrue( "Required proxy should have been called.", proxyServer.hasBeenCalled("simpleTest.html")); }
@Test public void basicPromptConfirmHandlingDismissTest() { WebElement promptButton; WebElement promptResult; promptButton = driver.findElement(By.id("promptexample")); promptResult = driver.findElement(By.id("promptreturn")); assertEquals("pret", promptResult.getText()); promptButton.click(); String alertMessage = "I prompt you"; Alert promptAlert = driver.switchTo().alert(); if (Driver.currentDriver == Driver.BrowserName.IE) { // In IE the alert always returns "Script Prompt:" and not the // actual prompt text, so this line is just to alert me if the // functionality changes if (!promptAlert.getText().equals("Script Prompt:")) { throw new RuntimeException("IE now does not do Script Prompt"); } } else { // only check the alert prompt if not in IE assertEquals(alertMessage, promptAlert.getText()); } promptAlert.dismiss(); assertEquals("pret", promptResult.getText()); }
@Override public Windows getWindows() { Windows ret = new Windows(); WebDriver d = getDriver(); ret.setCurrent(d.getWindowHandle()); ret.setAll(d.getWindowHandles()); return ret; }
private void runScenarioWithUnhandledAlert(String expectedAlertText) { driver2.get(pages.alertsPage); driver2.findElement(By.id("prompt-with-default")).click(); try { driver2.findElement(By.id("text")).getText(); } catch (UnhandledAlertException expected) { } waitFor(elementTextToEqual(driver2, By.id("text"), expectedAlertText)); }
@Test public void testSigninNotificador() throws Exception { driver.get(baseUrl + "/sincap/"); driver.findElement(By.id("username")).clear(); driver.findElement(By.id("username")).sendKeys("222.222.222-22"); driver.findElement(By.id("password")).clear(); driver.findElement(By.id("password")).sendKeys("abc123"); driver.findElement(By.id("botaoLogin")).click(); }
/* Given: Logged into a valid account When: I look at the navigation bar Then: I will see a link for my user profile */ @Test public void testProfile(){ driver.findElement(By.id("navbar_username")).clear(); driver.findElement(By.id("navbar_username")).sendKeys("Aytros"); driver.findElement(By.id("navbar_password")).clear(); driver.findElement(By.id("navbar_password")).sendKeys("Mystra@428"); driver.findElement(By.value("Log in")).click(); String test = driver.findElement(By.linkText("Aytros")).getAttribute("title"); assertTrue(test.contains("Profile")); }
@Test public void testSearchFeature() { // find search, check if search works by sending a search time, see that results exist WebElement element = driver.findElement(By.name("search_block_form")); element.sendKeys("Laboon"); element.sendKeys(Keys.RETURN); assert (driver.findElement(By.name("Laboon")) != null); // is it good enough? }
@Test public void testLoginMaster2() throws Exception { driver.get(baseUrl + "/login.html"); driver.findElement(By.name("j_username")).clear(); driver.findElement(By.name("j_username")).sendKeys("*****@*****.**"); driver.findElement(By.name("j_password")).clear(); driver.findElement(By.name("j_password")).sendKeys("master"); driver.findElement(By.xpath("//input[@value='Login']")).click(); driver.findElement(By.linkText("Sign out")).click(); }
public static WebDriver navigateToPage(String url) { String baseUrl = "http://demo.opensourcecms.com/"; driver = TestBase.setDriver("firefox"); driver.get(baseUrl + url); driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS); // Boolean myDynamicElement = (new WebDriverWait(driver, 10)) // .until( ExpectedConditions.titleContains("WordPress") ); // System.out.println(myDynamicElement); return driver; }
@Test public void testBookSearch5() throws Exception { driver.get(baseUrl + "/proyectoBiblioteca/"); new Select(driver.findElement(By.name("type"))).selectByVisibleText("Editorial"); driver.findElement(By.name("search")).clear(); driver.findElement(By.name("search")).sendKeys("De Bolsillo"); driver.findElement(By.xpath("//button[@type='submit']")).click(); assertEquals( "Libros Encontrados", driver.findElement(By.cssSelector("div.panel-heading")).getText()); }
@Test(expected = TimeoutException.class) public void shouldTimeoutWhileChangingIframeSource() { final String iFrameId = "iframeId"; // Define HTTP response for test server.setGetHandler( new HttpRequestCallback() { @Override public void call(HttpServletRequest req, HttpServletResponse res) throws IOException { String pathInfo = req.getPathInfo(); ServletOutputStream out = res.getOutputStream(); if (pathInfo.endsWith("iframe_content.html")) { // nested frame 1 out.println("iframe content"); } else { // main page out.println( "<html>\n" + "<body>\n" + " <iframe id='" + iFrameId + "'></iframe>\n" + " <script>\n" + " setTimeout(function() {\n" + " document.getElementById('" + iFrameId + "').src='iframe_content.html';\n" + " }, 2000);\n" + " </script>\n" + "</body>\n" + "</html>"); } } }); // Launch Driver against the above defined server WebDriver d = getDriver(); d.get(server.getBaseUrl()); // Switch to iframe d.switchTo().frame(iFrameId); assertEquals(0, d.findElements(By.id(iFrameId)).size()); assertFalse(d.getPageSource().toLowerCase().contains("iframe content")); new WebDriverWait(d, 5) .until( new Predicate<WebDriver>() { @Override public boolean apply(@Nullable WebDriver driver) { assertEquals(0, driver.findElements(By.id(iFrameId)).size()); return (Boolean) ((JavascriptExecutor) driver).executeScript("return false;"); } }); }
@Before public void setUp() throws Exception { driver = new FirefoxDriver(); func = new COTFunctions(driver); driver.manage().timeouts().implicitlyWait(func.timeoutOFAllElement, TimeUnit.SECONDS); driver.get(func.baseUrl + "/"); func.CheckLogin(); func.LoginRole("SchoolAdmin"); driver.get(func.baseUrl + "/college-search"); }
/** * Basically visits your baseUrl link and starts over * * @throws InterruptedException */ public void startNewChat(ArrayList<String> topics) throws InterruptedException { chatTranscript = ""; newMessage = ""; driver.get(baseUrl); for (String topic : topics) { addTopic(topic); } driver.findElement(By.id("textbtn")).click(); }
@Before public void setUp() throws Exception { driver = new FirefoxDriver(); func = new COTFunctions(driver); wait = new WebDriverWait(driver, func.timeoutOfOneElement); driver.manage().timeouts().implicitlyWait(func.timeoutOFAllElement, TimeUnit.SECONDS); driver.get(func.baseUrl + "/"); func.CheckLogin(); func.LoginRole("Student"); driver.get(func.baseUrl + "/document-locker"); }
@Test public void checkAttributesOnGoogleSearchBox() { WebDriver d = getDriver(); d.get("http://www.google.com"); WebElement el = d.findElement(By.cssSelector("input[name*='q']")); assertTrue(el.getAttribute("name").toLowerCase().contains("q")); assertTrue(el.getAttribute("type").toLowerCase().contains("text")); assertTrue(el.getAttribute("style").length() > 0); assertTrue(el.getAttribute("type").length() > 0); }
private void runImport() { System.out.println("Importerer RFMDB dump"); Select s = new Select(driver.findElement(new By.ByXPath("//select"))); s.selectByIndex(2); driver.findElement(new By.ByXPath("//input[@value='Importer data']")).click(); selenium.waitForFrameToLoad("content", "30000"); captureScreenshot(); }
private void sendEmails() { System.out.println("Trying to send 50 batch e-mails"); selenium.selectFrame("content"); driver.findElement(new By.ByName("batch_count")).sendKeys("50"); driver.findElement(new By.ByXPath("//form[@name='activate']")).submit(); selenium.waitForFrameToLoad("content", "30000"); captureScreenshot(); }
@Test public void switchToFrameByName() { WebDriver d = getDriver(); d.get("http://docs.wpm.neustar.biz/testscript-api/index.html"); assertEquals("__MAIN_FRAME__", getCurrentFrameName(d)); d.switchTo().frame("packageFrame"); assertEquals("packageFrame", getCurrentFrameName(d)); d.switchTo().defaultContent(); assertEquals("__MAIN_FRAME__", getCurrentFrameName(d)); d.switchTo().frame("packageFrame"); assertEquals("packageFrame", getCurrentFrameName(d)); }
public void mouseHoverByXpath(String locator) { try { WebElement element = driver.findElement(By.xpath(locator)); Actions action = new Actions(driver); Actions hover = action.moveToElement(element); } catch (Exception ex) { System.out.println("First attempt has been done, This is second try"); WebElement element = driver.findElement(By.cssSelector(locator)); Actions action = new Actions(driver); action.moveToElement(element).perform(); } }