Search in sources :

Example 61 with Cookie

use of org.openqa.selenium.Cookie in project ghostdriver by detro.

the class CookieTest method shouldThrowExceptionIfAddingCookieBeforeLoadingAnyUrl.

@Test(expected = Exception.class)
public void shouldThrowExceptionIfAddingCookieBeforeLoadingAnyUrl() {
    // NOTE: At the time of writing, this test doesn't pass with FirefoxDriver.
    // ChromeDriver is fine instead.
    // < detro: I buy you a beer if you guess what am I quoting here
    String xval = "123456789101112";
    WebDriver d = getDriver();
    // Set cookie, without opening any page: should throw an exception
    d.manage().addCookie(new Cookie("x", xval));
}
Also used : WebDriver(org.openqa.selenium.WebDriver) Cookie(org.openqa.selenium.Cookie) Test(org.junit.Test)

Example 62 with Cookie

use of org.openqa.selenium.Cookie in project ghostdriver by detro.

the class CookieTest method shouldRetainCookieInfo.

@Test
public void shouldRetainCookieInfo() {
    server.setHttpHandler("GET", EMPTY_CALLBACK);
    goToPage();
    // Added cookie (in a sub-path - allowed)
    Cookie addedCookie = new Cookie.Builder("fish", "cod").expiresOn(// < now + 100sec
    new Date(System.currentTimeMillis() + 100 * 1000)).path("/404").domain("localhost").build();
    driver.manage().addCookie(addedCookie);
    // Search cookie on the root-path and fail to find it
    Cookie retrieved = driver.manage().getCookieNamed("fish");
    assertNull(retrieved);
    // Go to the "/404" sub-path (to find the cookie)
    goToPage("404");
    retrieved = driver.manage().getCookieNamed("fish");
    assertNotNull(retrieved);
    // Check that it all matches
    assertEquals(addedCookie.getName(), retrieved.getName());
    assertEquals(addedCookie.getValue(), retrieved.getValue());
    assertEquals(addedCookie.getExpiry(), retrieved.getExpiry());
    assertEquals(addedCookie.isSecure(), retrieved.isSecure());
    assertEquals(addedCookie.getPath(), retrieved.getPath());
    assertTrue(retrieved.getDomain().contains(addedCookie.getDomain()));
}
Also used : Cookie(org.openqa.selenium.Cookie) Date(java.util.Date) Test(org.junit.Test)

Example 63 with Cookie

use of org.openqa.selenium.Cookie in project ghostdriver by detro.

the class CookieTest method shouldBeAbleToCreateCookieViaJavascriptOnGoogle.

@Test
public void shouldBeAbleToCreateCookieViaJavascriptOnGoogle() {
    String ckey = "cookiekey";
    String cval = "cookieval";
    WebDriver d = getDriver();
    d.get("http://www.google.com");
    JavascriptExecutor js = (JavascriptExecutor) d;
    // Of course, no cookie yet(!)
    Cookie c = d.manage().getCookieNamed(ckey);
    assertNull(c);
    // Attempt to create cookie on multiple Google domains
    js.executeScript("javascript:(" + "function() {" + "   cook = document.cookie;" + "   begin = cook.indexOf('" + ckey + "=');" + "   var val;" + "   if (begin !== -1) {" + "       var end = cook.indexOf(\";\",begin);" + "       if (end === -1)" + "           end=cook.length;" + "       val=cook.substring(begin+11,end);" + "   }" + "   val = ['" + cval + "'];" + "   if (val) {" + "       var d=Array('com','co.jp','ca','fr','de','co.uk','it','es','com.br');" + "       for (var i = 0; i < d.length; i++) {" + "           document.cookie = '" + ckey + "='+val+';path=/;domain=.google.'+d[i]+'; ';" + "       }" + "   }" + "})();");
    c = d.manage().getCookieNamed(ckey);
    assertNotNull(c);
    assertEquals(cval, c.getValue());
    // Set cookie as empty
    js.executeScript("javascript:(" + "function() {" + "   var d = Array('com','co.jp','ca','fr','de','co.uk','it','cn','es','com.br');" + "   for(var i = 0; i < d.length; i++) {" + "       document.cookie='" + ckey + "=;path=/;domain=.google.'+d[i]+'; ';" + "   }" + "})();");
    c = d.manage().getCookieNamed(ckey);
    assertNotNull(c);
    assertEquals("", c.getValue());
}
Also used : WebDriver(org.openqa.selenium.WebDriver) Cookie(org.openqa.selenium.Cookie) JavascriptExecutor(org.openqa.selenium.JavascriptExecutor) Test(org.junit.Test)

Example 64 with Cookie

use of org.openqa.selenium.Cookie in project selenium-tests by Wikia.

the class BrowserAndTestEventListener method afterNavigateTo.

@Override
public void afterNavigateTo(String url, WebDriver driver) {
    Method method = TestContext.getCurrentTestMethod();
    if (method != null) {
        Class<?> declaringClass = method.getDeclaringClass();
        String cookieDomain = String.format(".%s", Configuration.getEnvType().getDomain(driver.getCurrentUrl()));
        Date cookieDate = new Date(new DateTime().plusYears(10).getMillis());
        if (!AlertHandler.isAlertPresent(driver)) {
            String command = "Url after navigation";
            if (url.equals(driver.getCurrentUrl())) {
                Log.ok(command, VelocityWrapper.fillLink(driver.getCurrentUrl(), driver.getCurrentUrl()));
            } else {
                // A fast lane to stop executing any test on "not a valid community" page
                if (driver.getCurrentUrl().contains(URLsContent.NOT_A_VALID_COMMUNITY)) {
                    throw new SkipException(String.format("Wrong redirect to: %s", driver.getCurrentUrl()));
                }
                if (driver.getCurrentUrl().contains("data:text/html,chromewebdata ")) {
                    driver.get(url);
                    Log.warning(command, driver.getCurrentUrl());
                } else {
                    Log.warning(command, driver.getCurrentUrl());
                }
            }
        } else {
            Log.warning("Url after navigation", "Unable to check URL after navigation - alert present");
        }
        boolean reload = false;
        if (driver.getCurrentUrl().contains(cookieDomain)) {
            // HACK FOR DISABLING NOTIFICATIONS
            try {
                new JavascriptActions(driver).execute("$('.wds-banner-notification__close').click()");
                new JavascriptActions(driver).execute("$('#WikiaNotifications .sprite.close-notification').click()");
            } catch (WebDriverException e) {
                Log.info("Hack for disabling notifications", "Failed to execute js action");
            }
            if (TestContext.isFirstLoad()) {
                boolean userOptedIn = true;
                boolean userOptedOut = false;
                try {
                    JavascriptExecutor js = DriverProvider.getActiveDriver();
                    Object mobileWikiVersion = js.executeScript("return requirejs.entries['mobile-wiki/config/environment'].module.exports.default.APP.version");
                    Configuration.setTestValue("mobileWikiVersion", mobileWikiVersion.toString());
                } catch (WebDriverException e) {
                    Configuration.setTestValue("mobileWikiVersion", null);
                }
                if (method.isAnnotationPresent(Execute.class) && !method.getAnnotation(Execute.class).trackingOptIn()) {
                    userOptedIn = false;
                }
                if (method.isAnnotationPresent(Execute.class) && method.getAnnotation(Execute.class).trackingOptOut()) {
                    userOptedOut = true;
                }
                String cmpVersion = "2";
                if (userOptedIn) {
                    driver.manage().addCookie(new Cookie("tracking-opt-in-status", "accepted", cookieDomain, "/", cookieDate));
                    driver.manage().addCookie(new Cookie("tracking-opt-in-version", cmpVersion, cookieDomain, "/", cookieDate));
                    reload = true;
                } else if (userOptedOut) {
                    driver.manage().addCookie(new Cookie("tracking-opt-in-status", "rejected", cookieDomain, "/", cookieDate));
                    driver.manage().addCookie(new Cookie("tracking-opt-in-version", cmpVersion, cookieDomain, "/", cookieDate));
                    reload = true;
                }
            }
            /**
             * We want to disable sales pitch dialog for new potential contributors to avoid hiding other
             * UI elements. see https://wikia-inc.atlassian.net/browse/CE-3768
             */
            if (TestContext.isFirstLoad() && "true".equals(Configuration.getDisableCommunityPageSalesPitchDialog())) {
                driver.manage().addCookie(new Cookie("cpBenefitsModalShown", "1", cookieDomain, "/", cookieDate));
                reload = true;
            }
            if (TestContext.isFirstLoad() && "true".equals(Configuration.getMockAds())) {
                driver.manage().addCookie(new Cookie("mock-ads", XMLReader.getValue("mock.ads_token"), cookieDomain, "/", cookieDate));
                reload = true;
                Log.info(String.format("Adding moc-ads cookie with value: %s, and domain: %s", XMLReader.getValue("mock.ads_token"), String.format(".%s", Configuration.getEnvType().getDomain(driver.getCurrentUrl()))));
            }
        }
        if (TestContext.isFirstLoad()) {
            User user = null;
            TestContext.setFirstLoad(false);
            if (declaringClass.isAnnotationPresent(Execute.class)) {
                user = declaringClass.getAnnotation(Execute.class).asUser();
            }
            if (method.isAnnotationPresent(Execute.class)) {
                user = method.getAnnotation(Execute.class).asUser();
            }
            if (user != null && user != User.ANONYMOUS) {
                // log in, make sure user is logged in and flow is on the requested url
                new WikiBasePageObject().loginAs(user);
            }
            NetworkTrafficInterceptor networkTrafficInterceptor = DriverProvider.getActiveDriver().getProxy();
            if (networkTrafficInterceptor != null) {
                networkTrafficInterceptor.startIntercepting();
            }
        }
        if (reload) {
            driver.navigate().refresh();
        }
    }
    Log.logJSError();
}
Also used : Cookie(org.openqa.selenium.Cookie) JavascriptExecutor(org.openqa.selenium.JavascriptExecutor) User(com.wikia.webdriver.common.core.helpers.User) Execute(com.wikia.webdriver.common.core.annotations.Execute) WikiBasePageObject(com.wikia.webdriver.pageobjectsfactory.pageobject.WikiBasePageObject) Method(java.lang.reflect.Method) Date(java.util.Date) DateTime(org.joda.time.DateTime) JavascriptActions(com.wikia.webdriver.common.core.elemnt.JavascriptActions) NetworkTrafficInterceptor(com.wikia.webdriver.common.core.networktrafficinterceptor.NetworkTrafficInterceptor) WikiBasePageObject(com.wikia.webdriver.pageobjectsfactory.pageobject.WikiBasePageObject) SkipException(org.testng.SkipException) WebDriverException(org.openqa.selenium.WebDriverException)

Example 65 with Cookie

use of org.openqa.selenium.Cookie in project selenium-tests by Wikia.

the class TrackingOptInPage method setGeoCookie.

public static void setGeoCookie(WikiaWebDriver driver, String continent, String country) {
    Cookie geoCookie = driver.manage().getCookieNamed("Geo");
    if (geoCookie != null) {
        driver.manage().deleteCookie(geoCookie);
    }
    driver.manage().addCookie(new Cookie("Geo", "{%22region%22:%22WP%22%2C%22country%22:%22" + country + "%22%2C%22continent%22:%22" + continent + "%22}", String.format(".%s", Configuration.getEnvType().getDomain(driver.getCurrentUrl())), null, null));
}
Also used : Cookie(org.openqa.selenium.Cookie)

Aggregations

Cookie (org.openqa.selenium.Cookie)73 Test (org.junit.Test)26 WebElement (org.openqa.selenium.WebElement)16 WebDriver (org.openqa.selenium.WebDriver)14 WebDriverWait (org.openqa.selenium.support.ui.WebDriverWait)9 Date (java.util.Date)8 App (com.coveros.selenified.application.App)7 IOException (java.io.IOException)7 AbstractKeycloakTest (org.keycloak.testsuite.AbstractKeycloakTest)7 BasicClientCookie (org.apache.http.impl.cookie.BasicClientCookie)6 Test (org.testng.annotations.Test)6 Collectors (java.util.stream.Collectors)5 BasicCookieStore (org.apache.http.impl.client.BasicCookieStore)5 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)5 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)5 AuthorizeClient (org.gluu.oxauth.client.AuthorizeClient)5 Matchers (org.hamcrest.Matchers)5 Page (org.jboss.arquillian.graphene.page.Page)5 Assert (org.junit.Assert)5 AdminRoles (org.keycloak.models.AdminRoles)5