类org.openqa.selenium.Cookie源码实例Demo

下面列出了怎么用org.openqa.selenium.Cookie的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: selenium   文件: RemoteWebDriverUnitTest.java
@Test
public void canHandleGetCookieNamedCommand() throws IOException {
  CommandExecutor executor = prepareExecutorMock(
      echoCapabilities,
      valueResponder(Arrays.asList(
          ImmutableMap.of("name", "cookie1", "value", "value1"),
          ImmutableMap.of("name", "cookie2", "value", "value2"))));

  RemoteWebDriver driver = new RemoteWebDriver(executor, new ImmutableCapabilities());
  Cookie found = driver.manage().getCookieNamed("cookie2");

  assertThat(found).isEqualTo(new Cookie("cookie2", "value2"));
  verifyCommands(
      executor, driver.getSessionId(),
      new CommandPayload(DriverCommand.GET_ALL_COOKIES, emptyMap()));
}
 
源代码2 项目: hsac-fitnesse-fixtures   文件: CookieConverter.java
/**
 * Converts Selenium cookie to Apache http client.
 * @param browserCookie selenium cookie.
 * @return http client format.
 */
protected ClientCookie convertCookie(Cookie browserCookie) {
    BasicClientCookie cookie = new BasicClientCookie(browserCookie.getName(), browserCookie.getValue());
    String domain = browserCookie.getDomain();
    if (domain != null && domain.startsWith(".")) {
        // http client does not like domains starting with '.', it always removes it when it receives them
        domain = domain.substring(1);
    }
    cookie.setDomain(domain);
    cookie.setPath(browserCookie.getPath());
    cookie.setExpiryDate(browserCookie.getExpiry());
    cookie.setSecure(browserCookie.isSecure());
    if (browserCookie.isHttpOnly()) {
        cookie.setAttribute("httponly", "");
    }
    return cookie;
}
 
源代码3 项目: vividus   文件: CookieManagerTests.java
@Test
void testGetCookiesAsHttpCookieStore()
{
    configureMockedWebDriver();
    Cookie seleniumCookie = createSeleniumCookie();
    mockGetCookies(seleniumCookie);
    CookieStore cookieStore = cookieManager.getCookiesAsHttpCookieStore();
    List<org.apache.http.cookie.Cookie> resultCookies = cookieStore.getCookies();
    assertEquals(1, resultCookies.size());
    org.apache.http.cookie.Cookie httpCookie = resultCookies.get(0);
    assertThat(httpCookie, instanceOf(BasicClientCookie.class));
    BasicClientCookie clientCookie = (BasicClientCookie) httpCookie;
    assertAll(
        () -> assertEquals(seleniumCookie.getDomain(), clientCookie.getDomain()),
        () -> assertEquals(seleniumCookie.getExpiry(), clientCookie.getExpiryDate()),
        () -> assertEquals(seleniumCookie.getName(), clientCookie.getName()),
        () -> assertEquals(seleniumCookie.getPath(), clientCookie.getPath()),
        () -> assertEquals(seleniumCookie.getValue(), clientCookie.getValue()),
        () -> assertEquals(seleniumCookie.isSecure(), clientCookie.isSecure()),
        () -> assertEquals(seleniumCookie.getDomain(), clientCookie.getAttribute(ClientCookie.DOMAIN_ATTR)),
        () -> assertEquals(seleniumCookie.getPath(), clientCookie.getAttribute(ClientCookie.PATH_ATTR))
    );
}
 
@Action(object = ObjectType.BROWSER, desc = "delete the cookie having name [<Data>].", input = InputType.YES)
public void deleteCookie() {
    try {
        String strCookieName = Data;
        Cookie oCookie = Driver.manage().getCookieNamed(strCookieName);
        if (oCookie != null) {
            Driver.manage().deleteCookie(oCookie);
            Report.updateTestLog(Action, "Cookie Name- '"
                    + strCookieName + "' is deleted", Status.DONE);
        } else {
            Report.updateTestLog(Action, "Cookie doesn't exist",
                    Status.FAIL);
        }
    } catch (Exception e) {
        Report.updateTestLog(Action, e.getMessage(), Status.FAIL);
        Logger.getLogger(CommonMethods.class.getName()).log(Level.SEVERE, null, e);
    }
}
 
源代码5 项目: selenium   文件: JsonOutputTest.java
@Test
public void shouldBeAbleToConvertACookie() {
  Date expiry = new Date();
  Cookie cookie = new Cookie("name", "value", "domain", "/path", expiry, true, true);

  String jsonStr = convert(cookie);

  JsonObject converted = new JsonParser().parse(jsonStr).getAsJsonObject();

  assertThat(converted.get("name").getAsString()).isEqualTo("name");
  assertThat(converted.get("value").getAsString()).isEqualTo("value");
  assertThat(converted.get("domain").getAsString()).isEqualTo("domain");
  assertThat(converted.get("path").getAsString()).isEqualTo("/path");
  assertThat(converted.get("secure").getAsBoolean()).isTrue();
  assertThat(converted.get("httpOnly").getAsBoolean()).isTrue();
  assertThat(converted.get("expiry").getAsLong())
      .isEqualTo(MILLISECONDS.toSeconds(expiry.getTime()));
}
 
源代码6 项目: selenium   文件: RemoteWebDriverUnitTest.java
@Test
public void canHandleGetCookiesCommand() throws IOException {
  CommandExecutor executor = prepareExecutorMock(
      echoCapabilities,
      valueResponder(Arrays.asList(
          ImmutableMap.of("name", "cookie1", "value", "value1", "sameSite", "Lax"),
          ImmutableMap.of("name", "cookie2", "value", "value2"))));

  RemoteWebDriver driver = new RemoteWebDriver(executor, new ImmutableCapabilities());
  Set<Cookie> cookies = driver.manage().getCookies();

  assertThat(cookies)
      .hasSize(2)
      .contains(
          new Cookie.Builder("cookie1", "value1").sameSite("Lax").build(),
          new Cookie("cookie2", "value2"));
  verifyCommands(
      executor, driver.getSessionId(),
      new CommandPayload(DriverCommand.GET_ALL_COOKIES, ImmutableMap.of()));
}
 
源代码7 项目: matchers-java   文件: HasCookieMatcherTest.java
@Test
public void shouldFindExistingCookie() {
    WebDriver driver = mock(WebDriver.class);
    Options options = mock(Options.class);
    Cookie cookie = new Cookie(cookieName, "oki-doki");


    when(driver.manage()).thenReturn(options);
    when(options.getCookieNamed(eq(cookieName))).thenReturn(cookie);

    assertThat("Cookie not found!", driver, hasCookie(cookieName));
}
 
源代码8 项目: bdt   文件: CommonGTest.java
@Test
public void testCookieExistsNull() throws Exception{
    String cookieName = "cookieFalse";
    org.openqa.selenium.Cookie cookie = new org.openqa.selenium.Cookie("cookieTest", "cookiePath", "cookieValue");
    CommonG commong = new CommonG();
    assertThat(false).isEqualTo(commong.cookieExists(cookieName));
}
 
源代码9 项目: vividus   文件: CookieSteps.java
/**
 * Checks if cookie with name <code>cookieName</code> is set
 * @param cookieName Cookie name
 * @return Optional containing cookie
 */
@Then("a cookie with the name '$cookieName' is set")
public Optional<Cookie> thenCookieWithNameIsSet(String cookieName)
{
    Cookie cookie = cookieManager.getCookie(cookieName);
    softAssert.assertThat(String.format("Cookie with the name '%s' is set", cookieName), cookie, notNullValue());
    return Optional.ofNullable(cookie);
}
 
源代码10 项目: vividus   文件: CookieSteps.java
/**
 * Checks if cookie with name <code>cookieName</code> is not set
 * @param cookieName Cookie name
 */
@Then("a cookie with the name '$cookieName' is not set")
public void thenCookieWithNameIsNotSet(String cookieName)
{
    Cookie cookie = cookieManager.getCookie(cookieName);
    softAssert.assertThat(String.format("Cookie with the name '%s' is not set", cookieName), cookie, nullValue());
}
 
源代码11 项目: vividus   文件: CookieManagerTests.java
@Test
void testDeleteAllCookiesSafari()
{
    configureMockedWebDriver();
    mockIsSafari(true);
    mockGetCookies(new Cookie(COOKIE_NAME, COOKIE_VALUE));
    cookieManager.deleteAllCookies();
    verify(javascriptActions).executeScript(JS_DELETE_COOKIE_FORMAT);
}
 
源代码12 项目: vividus   文件: CookieManagerTests.java
@Test
void testGetCookie()
{
    configureMockedWebDriver();
    Cookie seleniumCookie = createSeleniumCookie();
    when(options.getCookieNamed(COOKIE_NAME)).thenReturn(seleniumCookie);
    assertEquals(seleniumCookie, cookieManager.getCookie(COOKIE_NAME));
}
 
源代码13 项目: keycloak   文件: AbstractFailoverClusterTest.java
protected Cookie verifyLoggedIn(AbstractPage targetPage, Cookie sessionCookieForVerification) {
    // verify on realm path
    masterRealmPage.navigateTo();
    Cookie sessionCookieOnRealmPath = driver.manage().getCookieNamed(KEYCLOAK_SESSION_COOKIE);
    assertNotNull(sessionCookieOnRealmPath);
    assertEquals(sessionCookieOnRealmPath.getValue(), sessionCookieForVerification.getValue());
    // verify on target page
    targetPage.navigateTo();
    assertCurrentUrlStartsWith(targetPage);
    Cookie sessionCookie = driver.manage().getCookieNamed(KEYCLOAK_SESSION_COOKIE);
    assertNotNull(sessionCookie);
    assertEquals(sessionCookie.getValue(), sessionCookieForVerification.getValue());
    return sessionCookie;
}
 
/**
 * sets the driver's cookies up based on the requestHeaders set
 */
private void setDriverCookies(){
    // You can't set cookies until you have the domain set in the DOM, this is a fix for that
    try {
        driver.get(url);
    }
    catch (TimeoutException e){
        System.err.println("[" + url + "][-] - timeout when connecting.");
    }

    // Set the driver's cookies based on the headers, if there are any
    if (requestHeaders != null){
        for (String header: requestHeaders){
            if (header.startsWith("Cookie: ")){
                // This is a cookie header, split it up
                String cookieString = header.substring(8,header.length());
                for (String kvPair : cookieString.split(";")){
                    String key = kvPair.split("=")[0].trim();
                    String value = kvPair.split("=")[1].trim();
                    Cookie cookieObj = new Cookie(key, value);
                    try {
                        driver.manage().addCookie(cookieObj);
                    }
                    catch (org.openqa.selenium.UnableToSetCookieException d){
                        System.err.println("[JS-SRI][-] Could not set cookie for key " + key + " and value " + value);
                    }
                }
            }
        }
    }
}
 
源代码15 项目: keycloak   文件: RestartCookieTest.java
@Test
public void testRestartCookieBackwardsCompatible_Keycloak19() throws IOException {
    String oldRestartCookie = testingClient.server().fetchString((KeycloakSession session) -> {
        try {
            String cookieVal = OLD_RESTART_COOKIE_JSON.replace("\n", "").replace(" ", "");
            RealmModel realm = session.realms().getRealmByName("test");

            KeyManager.ActiveHmacKey activeKey = session.keys().getActiveHmacKey(realm);

            // There was no KID in the token in Keycloak 1.9.8
            String encodedToken = new JWSBuilder()
                    //.kid(activeKey.getKid())
                    .content(cookieVal.getBytes("UTF-8"))
                    .hmac256(activeKey.getSecretKey());

            return encodedToken;


        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
    });

    oauth.openLoginForm();

    driver.manage().deleteAllCookies();
    driver.manage().addCookie(new Cookie(RestartLoginCookie.KC_RESTART, oldRestartCookie));

    loginPage.login("foo", "bar");
    loginPage.assertCurrent();
    Assert.assertEquals("Your login attempt timed out. Login will start from the beginning.", loginPage.getError());

    events.expectLogin().user((String) null).session((String) null).error(Errors.EXPIRED_CODE).clearDetails()
            .detail(Details.RESTART_AFTER_TIMEOUT, "true")
            .client((String) null)
            .assertEvent();
}
 
源代码16 项目: keycloak   文件: CookieTest.java
private void assertSameSiteCookies(Cookie sameSiteCookie, Cookie legacyCookie) {
    assertNotNull("SameSite cookie shouldn't be null", sameSiteCookie);
    assertNotNull("Legacy cookie shouldn't be null", legacyCookie);

    assertEquals(sameSiteCookie.getValue(), legacyCookie.getValue());
    assertEquals(sameSiteCookie.getDomain(), legacyCookie.getDomain());
    assertEquals(sameSiteCookie.getPath(), legacyCookie.getPath());
    assertEquals(sameSiteCookie.getExpiry(), legacyCookie.getExpiry());
    assertTrue("SameSite cookie should always have Secure attribute", sameSiteCookie.isSecure());
    assertFalse("Legacy cookie shouldn't have Secure attribute", legacyCookie.isSecure()); // this relies on test realm config
    assertEquals(sameSiteCookie.isHttpOnly(), legacyCookie.isHttpOnly());
    // WebDriver currently doesn't support SameSite attribute therefore we cannot check it's present in the cookie
}
 
@Test
public void storeCookies() {

    driver.findElement(By.id("email")).sendKeys("email");
    driver.findElement(By.id("pass")).sendKeys("password");
    driver.findElement(By.id("send2")).submit();

    File dataFile = new File("./target/browser.data");
    try {
        dataFile.delete();
        dataFile.createNewFile();
        FileWriter fos = new FileWriter(dataFile);
        BufferedWriter bos = new BufferedWriter(fos);
        for (Cookie ck : driver.manage().getCookies()) {
            bos.write((ck.getName() + ";" + ck.getValue() + ";" + ck.
                    getDomain()
                    + ";" + ck.getPath() + ";" + ck.getExpiry() + ";" + ck.
                    isSecure()));
            bos.newLine();
        }
        bos.flush();
        bos.close();
        fos.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
 
@Test
public void loadCookies() {
    try {
        File dataFile = new File("./target/browser.data");
        FileReader fr = new FileReader(dataFile);
        BufferedReader br = new BufferedReader(fr);
        String line;
        while ((line = br.readLine()) != null) {
            StringTokenizer str = new StringTokenizer(line, ";");
            while (str.hasMoreTokens()) {
                String name = str.nextToken();
                String value = str.nextToken();
                String domain = str.nextToken();
                String path = str.nextToken();
                Date expiry = null;
                String dt;
                if (!(dt = str.nextToken()).equals("null")) {
                    SimpleDateFormat formatter =
                            new SimpleDateFormat("E MMM d HH:mm:ss z yyyy");
                    expiry = formatter.parse(dt);
                }

                boolean isSecure = new Boolean(str.nextToken()).
                        booleanValue();
                Cookie ck = new Cookie(name, value, domain, path, expiry, isSecure);
                driver.manage().addCookie(ck);
            }
        }

        driver.get("http://demo-store.seleniumacademy.com/customer/account/index/");
        assertThat(driver.findElement(By.cssSelector("div.page-title")).getText())
                .isEqualTo("MY DASHBOARD");

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
 
源代码19 项目: selenium   文件: RemoteWebDriver.java
@Override
public Cookie getCookieNamed(String name) {
  Set<Cookie> allCookies = getCookies();
  for (Cookie cookie : allCookies) {
    if (cookie.getName().equals(name)) {
      return cookie;
    }
  }
  return null;
}
 
private BasicCookieStore getWebDriverCookies(Set<Cookie> seleniumCookieSet) {
    BasicCookieStore copyOfWebDriverCookieStore = new BasicCookieStore();
    for (Cookie seleniumCookie : seleniumCookieSet) {
        BasicClientCookie duplicateCookie = new BasicClientCookie(seleniumCookie.getName(), seleniumCookie.getValue());
        duplicateCookie.setDomain(seleniumCookie.getDomain());
        duplicateCookie.setSecure(seleniumCookie.isSecure());
        duplicateCookie.setExpiryDate(seleniumCookie.getExpiry());
        duplicateCookie.setPath(seleniumCookie.getPath());
        copyOfWebDriverCookieStore.addCookie(duplicateCookie);
    }

    return copyOfWebDriverCookieStore;
}
 
源代码21 项目: hsac-fitnesse-fixtures   文件: CookieConverter.java
/**
 * Converts Selenium cookies to Apache http client ones.
 * @param browserCookies cookies in Selenium format.
 * @param cookieStore store to place coverted cookies in.
 */
public void copySeleniumCookies(Set<Cookie> browserCookies, CookieStore cookieStore) {
    for (Cookie browserCookie : browserCookies) {
        ClientCookie cookie = convertCookie(browserCookie);
        cookieStore.addCookie(cookie);
    }
}
 
private void doTheActualCookieDeleteThenAddOnTheBrowser() {
    driver.get("http://compendiumdev.co.uk/selenium/" + "search.php");

    assertEquals("2 Cookies created on initial visit", 2, driver.manage().getCookies().size());

    // find cookie to cut n paste
    Cookie aCookie = driver.manage().
            getCookieNamed("seleniumSimplifiedSearchNumVisits");

    System.out.println("Going to work with this cookie:");
    System.out.println(aCookie.toString().replaceAll(";",";\n"));

    int cookieCount = driver.manage().getCookies().size();
    // delete cookie
    driver.manage().deleteCookie(aCookie);
    assertEquals("One less cookie expected", cookieCount-1, driver.manage().getCookies().size());

    // recreate the cookie works fine on Firefox, but fails on Chrome
    //driver.manage().addCookie(aCookie);


    // if I build the cookie from scratch then it fails on chrome when I add the domain
    driver.manage().addCookie(
            new Cookie.Builder(aCookie.getName(),
                    aCookie.getValue()).
                    path(aCookie.getPath()).
                    // enable line below to have test fail on chrome
                    // domain(aCookie.getDomain()).
                    expiresOn(aCookie.getExpiry()).
                    isHttpOnly(aCookie.isHttpOnly()).
                    isSecure(aCookie.isSecure()).
                    build());


    System.out.println(driver.manage().getCookies().toString().replaceAll(";",";\n"));
    assertEquals("Same number of cookies expected", cookieCount, driver.manage().getCookies().size());
}
 
源代码23 项目: tutorials   文件: SeleniumCookiesJUnitLiveTest.java
@Test
public void whenOverridingCookie_thenItIsUpdated() {
    driver.navigate().to(navUrl);
    Cookie lpCookie = driver.manage().getCookieNamed("lp_120073");
    driver.manage().deleteCookie(lpCookie);

    Cookie newLpCookie = new Cookie("lp_120073", "foo");
    driver.manage().addCookie(newLpCookie);

    Cookie overriddenCookie = driver.manage().getCookieNamed("lp_120073");

    assertThat(overriddenCookie.getValue(), equalTo("foo"));
}
 
源代码24 项目: selenium   文件: RemoteWebDriverUnitTest.java
@Test
public void canHandleDeleteCookieCommand() throws IOException {
  CommandExecutor executor = prepareExecutorMock(echoCapabilities, nullResponder);

  Cookie cookie = new Cookie("x", "y");
  RemoteWebDriver driver = new RemoteWebDriver(executor, new ImmutableCapabilities());
  driver.manage().deleteCookie(cookie);

  verifyCommands(
      executor, driver.getSessionId(),
      new CommandPayload(DriverCommand.DELETE_COOKIE, ImmutableMap.of("name", "x")));
}
 
源代码25 项目: hsac-fitnesse-fixtures   文件: BrowserTest.java
/**
 * Gets the value of the cookie with the supplied name.
 * @param cookieName name of cookie to get value from.
 * @return cookie's value if any.
 */
public String cookieValue(String cookieName) {
    String result = null;
    Cookie cookie = getSeleniumHelper().getCookie(cookieName);
    if (cookie != null) {
        result = cookie.getValue();
    }
    return result;
}
 
源代码26 项目: NoraUi   文件: AuthUT.java
@Test
public void testPageBehindCookieAuthentication() {
    try {
        Auth.clear();
        System.setProperty(Auth.SESSION_COOKIE, "auth=ok,path=/");
        final Cookie c = Auth.getAuthenticationCookie("http://127.0.0.1");
        bs.goToUrl("UNPROTECTED");
        Auth.loadAuthenticationCookie(c);
        bs.goToUrl("COOKIEPROTECTED");
        Assert.assertTrue("The requested page content must respond 'OK'.",
                Context.getDriver().getPageSource().contains("<head></head><body><pre style=\"word-wrap: break-word; white-space: pre-wrap;\">OK</pre></body>"));
    } catch (final Exception e) {
        Assert.fail("Exception thrown: " + e.getMessage());
    }
}
 
源代码27 项目: ats-framework   文件: AbstractHtmlEngine.java
/**
 *
 * @param cookieName the name of the cookie. May not be null or an empty string.
 * @param cookieValue the cookie value. May not be null.
 */
@PublicAtsApi
public void setCookie(
                       String cookieName,
                       String cookieValue ) {

    Cookie cookie = new Cookie(cookieName, cookieValue);
    webDriver.manage().addCookie(cookie);
}
 
源代码28 项目: ats-framework   文件: AbstractHtmlEngine.java
/**
 *
 * @param name the name of the cookie. May not be null or an empty string.
 * @param value the cookie value. May not be null.
 * @param domain the domain the cookie is visible to.
 * @param path the path the cookie is visible to. If left blank or set to null, will be set to
 *        "/".
 * @param expiry the cookie's expiration date; may be null.
 * @param isSecure whether this cookie requires a secure connection.
 */
@PublicAtsApi
public void setCookie(
                       String name,
                       String value,
                       String domain,
                       String path,
                       Date expiry,
                       boolean isSecure ) {

    Cookie cookie = new Cookie(name, value, domain, path, expiry, isSecure);
    webDriver.manage().addCookie(cookie);
}
 
源代码29 项目: selenium   文件: RemoteWebDriver.java
@Override
@SuppressWarnings({"unchecked"})
public Set<Cookie> getCookies() {
  Object returned = execute(DriverCommand.GET_ALL_COOKIES).getValue();

  Set<Cookie> toReturn = new HashSet<>();

  if (!(returned instanceof Collection)) {
    return toReturn;
  }

  ((Collection<?>) returned).stream()
      .map(o -> (Map<String, Object>) o)
      .map(rawCookie -> {
        // JSON object keys are defined in
        // https://w3c.github.io/webdriver/#dfn-table-for-cookie-conversion.
        Cookie.Builder builder =
            new Cookie.Builder((String) rawCookie.get("name"), (String) rawCookie.get("value"))
                .path((String) rawCookie.get("path"))
                .domain((String) rawCookie.get("domain"))
                .isSecure(rawCookie.containsKey("secure") && (Boolean) rawCookie.get("secure"))
                .isHttpOnly(
                    rawCookie.containsKey("httpOnly") && (Boolean) rawCookie.get("httpOnly"))
                .sameSite((String) rawCookie.get("sameSite"));

        Number expiryNum = (Number) rawCookie.get("expiry");
        builder.expiresOn(expiryNum == null ? null : new Date(SECONDS.toMillis(expiryNum.longValue())));
        return builder.build();
      })
      .forEach(toReturn::add);

  return toReturn;
}
 
源代码30 项目: opentest   文件: AddCookie.java
@Override
public void run() {
    super.run();

    String name = this.readStringArgument("name");
    String value = this.readStringArgument("value");
    String domain = this.readStringArgument("domain", null);
    String path = this.readStringArgument("path", null);
    Boolean isSecure = this.readBooleanArgument("isSecure", false);
    Boolean isHttpOnly = this.readBooleanArgument("isHttpOnly", false);

    Cookie cookie = new Cookie(name, value, domain, path, null, isSecure, isHttpOnly);
    driver.manage().addCookie(cookie);
}
 
 类所在包
 类方法
 同包方法