Best Selenium code snippet using org.openqa.selenium.Cookie.Builder.path
Source:CookieImplementationTest.java
...53 assumeTrue(domainHelper.checkIsOnValidHostname());54 cookiePage = domainHelper.getUrlForFirstValidHostname("/common/cookie");55 deleteAllCookiesOnServerSide();56 // This page is the deepest page we go to in the cookie tests57 // We go to it to ensure that cookies with /common/... paths are deleted58 // Do not write test in this class which use pages other than under /common59 // without ensuring that cookies are deleted on those pages as required60 try {61 driver.get(domainHelper.getUrlForFirstValidHostname("/common/animals"));62 } catch (IllegalArgumentException e) {63 // Ideally we would throw an IgnoredTestError or something here,64 // but our test runner doesn't pay attention to those.65 // Rely on the tests skipping themselves if they need to be on a useful page.66 return;67 }68 driver.manage().deleteAllCookies();69 assertNoCookiesArePresent();70 }71 @JavascriptEnabled72 @Test73 public void testShouldGetCookieByName() {74 String key = generateUniqueKey();75 String value = "set";76 assertCookieIsNotPresentWithName(key);77 addCookieOnServerSide(new Cookie(key, value));78 Cookie cookie = driver.manage().getCookieNamed(key);79 assertEquals(value, cookie.getValue());80 }81 @JavascriptEnabled82 @Test83 public void testShouldBeAbleToAddCookie() {84 String key = generateUniqueKey();85 String value = "foo";86 Cookie cookie = new Cookie.Builder(key, value).build();87 assertCookieIsNotPresentWithName(key);88 driver.manage().addCookie(cookie);89 assertCookieHasValue(key, value);90 openAnotherPage();91 assertCookieHasValue(key, value);92 }93 @Test94 public void testGetAllCookies() {95 String key1 = generateUniqueKey();96 String key2 = generateUniqueKey();97 assertCookieIsNotPresentWithName(key1);98 assertCookieIsNotPresentWithName(key2);99 Set<Cookie> cookies = driver.manage().getCookies();100 int countBefore = cookies.size();101 Cookie one = new Cookie.Builder(key1, "value").build();102 Cookie two = new Cookie.Builder(key2, "value").build();103 driver.manage().addCookie(one);104 driver.manage().addCookie(two);105 openAnotherPage();106 cookies = driver.manage().getCookies();107 assertEquals(countBefore + 2, cookies.size());108 assertTrue(cookies.contains(one));109 assertTrue(cookies.contains(two));110 }111 @JavascriptEnabled112 @Test113 public void testDeleteAllCookies() {114 addCookieOnServerSide(new Cookie("foo", "set"));115 assertSomeCookiesArePresent();116 driver.manage().deleteAllCookies();117 assertNoCookiesArePresent();118 openAnotherPage();119 assertNoCookiesArePresent();120 }121 @JavascriptEnabled122 @Test123 public void testDeleteCookieWithName() {124 String key1 = generateUniqueKey();125 String key2 = generateUniqueKey();126 addCookieOnServerSide(new Cookie(key1, "set"));127 addCookieOnServerSide(new Cookie(key2, "set"));128 assertCookieIsPresentWithName(key1);129 assertCookieIsPresentWithName(key2);130 driver.manage().deleteCookieNamed(key1);131 assertCookieIsNotPresentWithName(key1);132 assertCookieIsPresentWithName(key2);133 openAnotherPage();134 assertCookieIsNotPresentWithName(key1);135 assertCookieIsPresentWithName(key2);136 }137 @Test138 public void testShouldNotDeleteCookiesWithASimilarName() {139 String cookieOneName = "fish";140 Cookie cookie1 = new Cookie.Builder(cookieOneName, "cod").build();141 Cookie cookie2 = new Cookie.Builder(cookieOneName + "x", "earth").build();142 WebDriver.Options options = driver.manage();143 assertCookieIsNotPresentWithName(cookie1.getName());144 options.addCookie(cookie1);145 options.addCookie(cookie2);146 assertCookieIsPresentWithName(cookie1.getName());147 options.deleteCookieNamed(cookieOneName);148 Set<Cookie> cookies = options.getCookies();149 assertFalse(cookies.toString(), cookies.contains(cookie1));150 assertTrue(cookies.toString(), cookies.contains(cookie2));151 }152 @Ignore(OPERA)153 @Test154 public void testAddCookiesWithDifferentPathsThatAreRelatedToOurs() {155 driver.get(domainHelper.getUrlForFirstValidHostname("/common/animals"));156 Cookie cookie1 = new Cookie.Builder("fish", "cod").path("/common/animals").build();157 Cookie cookie2 = new Cookie.Builder("planet", "earth").path("/common/").build();158 WebDriver.Options options = driver.manage();159 options.addCookie(cookie1);160 options.addCookie(cookie2);161 driver.get(domainHelper.getUrlForFirstValidHostname("/common/animals"));162 assertCookieIsPresentWithName(cookie1.getName());163 assertCookieIsPresentWithName(cookie2.getName());164 driver.get(domainHelper.getUrlForFirstValidHostname("/common/simplePage.html"));165 assertCookieIsNotPresentWithName(cookie1.getName());166 }167 @Ignore({CHROME, OPERA})168 @Test169 public void testCannotGetCookiesWithPathDifferingOnlyInCase() {170 String cookieName = "fish";171 Cookie cookie = new Cookie.Builder(cookieName, "cod").path("/Common/animals").build();172 driver.manage().addCookie(cookie);173 driver.get(domainHelper.getUrlForFirstValidHostname("/common/animals"));174 assertNull(driver.manage().getCookieNamed(cookieName));175 }176 @Test177 public void testShouldNotGetCookieOnDifferentDomain() {178 assumeTrue(domainHelper.checkHasValidAlternateHostname());179 String cookieName = "fish";180 driver.manage().addCookie(new Cookie.Builder(cookieName, "cod").build());181 assertCookieIsPresentWithName(cookieName);182 driver.get(domainHelper.getUrlForSecondValidHostname("simpleTest.html"));183 assertCookieIsNotPresentWithName(cookieName);184 }185 @Ignore(value = {ANDROID, CHROME, HTMLUNIT, IE, IPHONE, OPERA},186 reason = "Untested browsers.")187 @Test188 public void testShouldBeAbleToAddToADomainWhichIsRelatedToTheCurrentDomain() {189 String cookieName = "name";190 assertCookieIsNotPresentWithName(cookieName);191 String shorter = domainHelper.getHostName().replaceFirst(".*?\\.", ".");192 Cookie cookie = new Cookie.Builder(cookieName, "value").domain(shorter).build();193 driver.manage().addCookie(cookie);194 assertCookieIsPresentWithName(cookieName);195 }196 @Ignore(value = {ALL})197 @Test198 public void testsShouldNotGetCookiesRelatedToCurrentDomainWithoutLeadingPeriod() {199 String cookieName = "name";200 assertCookieIsNotPresentWithName(cookieName);201 String shorter = domainHelper.getHostName().replaceFirst(".*?\\.", "");202 Cookie cookie = new Cookie.Builder(cookieName, "value").domain(shorter).build();203 driver.manage().addCookie(cookie);204 assertCookieIsNotPresentWithName(cookieName);205 }206 @Ignore({REMOTE, IE})207 @Test208 public void testShouldBeAbleToIncludeLeadingPeriodInDomainName() throws Exception {209 String cookieName = "name";210 assertCookieIsNotPresentWithName(cookieName);211 String shorter = domainHelper.getHostName().replaceFirst(".*?\\.", ".");212 Cookie cookie = new Cookie.Builder("name", "value").domain(shorter).build();213 driver.manage().addCookie(cookie);214 assertCookieIsPresentWithName(cookieName);215 }216 @Ignore(IE)217 @Test218 public void testShouldBeAbleToSetDomainToTheCurrentDomain() throws Exception {219 URI url = new URI(driver.getCurrentUrl());220 String host = url.getHost() + ":" + url.getPort();221 Cookie cookie = new Cookie.Builder("fish", "cod").domain(host).build();222 driver.manage().addCookie(cookie);223 driver.get(domainHelper.getUrlForFirstValidHostname("javascriptPage.html"));224 Set<Cookie> cookies = driver.manage().getCookies();225 assertTrue(cookies.contains(cookie));226 }227 @Test228 public void testShouldWalkThePathToDeleteACookie() {229 Cookie cookie1 = new Cookie.Builder("fish", "cod").build();230 driver.manage().addCookie(cookie1);231 driver.get(domainHelper.getUrlForFirstValidHostname("child/childPage.html"));232 Cookie cookie2 = new Cookie("rodent", "hamster", "/common/child");233 driver.manage().addCookie(cookie2);234 driver.get(domainHelper.getUrlForFirstValidHostname("child/grandchild/grandchildPage.html"));235 Cookie cookie3 = new Cookie("dog", "dalmation", "/common/child/grandchild/");236 driver.manage().addCookie(cookie3);237 driver.get(domainHelper.getUrlForFirstValidHostname("child/grandchild/grandchildPage.html"));238 driver.manage().deleteCookieNamed("rodent");239 assertNull(driver.manage().getCookies().toString(), driver.manage().getCookieNamed("rodent"));240 Set<Cookie> cookies = driver.manage().getCookies();241 assertEquals(2, cookies.size());242 assertTrue(cookies.contains(cookie1));243 assertTrue(cookies.contains(cookie3));244 driver.manage().deleteAllCookies();245 driver.get(domainHelper.getUrlForFirstValidHostname("child/grandchild/grandchildPage.html"));246 assertNoCookiesArePresent();247 }248 @Ignore(IE)249 @Test250 public void testShouldIgnoreThePortNumberOfTheHostWhenSettingTheCookie() throws Exception {251 URI uri = new URI(driver.getCurrentUrl());252 String host = String.format("%s:%d", uri.getHost(), uri.getPort());253 String cookieName = "name";254 assertCookieIsNotPresentWithName(cookieName);255 Cookie cookie = new Cookie.Builder(cookieName, "value").domain(host).build();256 driver.manage().addCookie(cookie);257 assertCookieIsPresentWithName(cookieName);258 }259 @Ignore(OPERA)260 @Test261 public void testCookieEqualityAfterSetAndGet() {262 driver.get(domainHelper.getUrlForFirstValidHostname("animals"));263 driver.manage().deleteAllCookies();264 Cookie addedCookie =265 new Cookie.Builder("fish", "cod")266 .path("/common/animals")267 .expiresOn(someTimeInTheFuture())268 .build();269 driver.manage().addCookie(addedCookie);270 Set<Cookie> cookies = driver.manage().getCookies();271 Cookie retrievedCookie = null;272 for (Cookie temp : cookies) {273 if (addedCookie.equals(temp)) {274 retrievedCookie = temp;275 break;276 }277 }278 assertNotNull("Cookie was null", retrievedCookie);279 // Cookie.equals only compares name, domain and path280 assertEquals(addedCookie, retrievedCookie);281 }282 @Ignore(value = {ANDROID, IE, OPERA}, reason =283 "Selenium, which use JavaScript to retrieve cookies, cannot return expiry info; " +284 "Other suppressed browsers have not been tested.")285 @Test286 public void testRetainsCookieExpiry() {287 Cookie addedCookie =288 new Cookie.Builder("fish", "cod")289 .path("/common/animals")290 .expiresOn(someTimeInTheFuture())291 .build();292 driver.manage().addCookie(addedCookie);293 Cookie retrieved = driver.manage().getCookieNamed("fish");294 assertNotNull(retrieved);295 assertEquals(addedCookie.getExpiry(), retrieved.getExpiry());296 }297 @Ignore(value = {ANDROID, IE, OPERA, OPERA_MOBILE, PHANTOMJS, SAFARI})298 @Test299 public void testRetainsCookieSecure() {300 driver.get(domainHelper.getSecureUrlForFirstValidHostname("animals"));301 Cookie addedCookie =302 new Cookie.Builder("fish", "cod")303 .path("/common/animals")304 .isSecure(true)305 .build();306 driver.manage().addCookie(addedCookie);307 driver.navigate().refresh();308 Cookie retrieved = driver.manage().getCookieNamed("fish");309 assertNotNull(retrieved);310 assertTrue(retrieved.isSecure());311 }312 @Ignore(value = {ANDROID, CHROME, FIREFOX, HTMLUNIT, IE, OPERA, OPERA_MOBILE, PHANTOMJS, SAFARI})313 @Test314 public void testRetainsHttpOnlyFlag() {315 Cookie addedCookie =316 new Cookie.Builder("fish", "cod")317 .path("/common/animals")318 .isHttpOnly(true)319 .build();320 addCookieOnServerSide(addedCookie);321 Cookie retrieved = driver.manage().getCookieNamed("fish");322 assertNotNull(retrieved);323 assertTrue(retrieved.isHttpOnly());324 }325 @Ignore(ANDROID)326 @Test327 public void testSettingACookieThatExpiredInThePast() {328 long expires = System.currentTimeMillis() - 1000;329 Cookie cookie = new Cookie.Builder("expired", "yes").expiresOn(new Date(expires)).build();330 driver.manage().addCookie(cookie);331 cookie = driver.manage().getCookieNamed("fish");332 assertNull(333 "Cookie expired before it was set, so nothing should be returned: " + cookie, cookie);334 }335 @Test336 public void testCanSetCookieWithoutOptionalFieldsSet() {337 String key = generateUniqueKey();338 String value = "foo";339 Cookie cookie = new Cookie(key, value);340 assertCookieIsNotPresentWithName(key);341 driver.manage().addCookie(cookie);342 assertCookieHasValue(key, value);343 }344 @Test345 public void testDeleteNotExistedCookie() {346 String key = generateUniqueKey();347 assertCookieIsNotPresentWithName(key);348 driver.manage().deleteCookieNamed(key);349 }350 @Ignore(value = {ANDROID, CHROME, FIREFOX, IE, OPERA, OPERA_MOBILE, PHANTOMJS, SAFARI})351 @Test352 public void testShouldDeleteOneOfTheCookiesWithTheSameName() {353 driver.get(domainHelper.getUrlForFirstValidHostname("/common/animals"));354 Cookie cookie1 = new Cookie.Builder("fish", "cod")355 .domain(domainHelper.getHostName()).path("/common/animals").build();356 Cookie cookie2 = new Cookie.Builder("fish", "tune")357 .domain(domainHelper.getHostName()).path("/common/").build();358 WebDriver.Options options = driver.manage();359 options.addCookie(cookie1);360 options.addCookie(cookie2);361 assertEquals(driver.manage().getCookies().size(), 2);362 driver.manage().deleteCookie(cookie1);363 assertEquals(driver.manage().getCookies().size(), 1);364 Cookie retrieved = driver.manage().getCookieNamed("fish");365 assertNotNull("Cookie was null", retrieved);366 assertEquals(cookie2, retrieved);367 }368 private String generateUniqueKey() {369 return String.format("key_%d", random.nextInt());370 }371 private void assertNoCookiesArePresent() {372 Set<Cookie> cookies = driver.manage().getCookies();373 assertTrue("Cookies were not empty, present: " + cookies,374 cookies.isEmpty());375 String documentCookie = getDocumentCookieOrNull();376 if (documentCookie != null) {377 assertEquals("Cookies were not empty", "", documentCookie);378 }379 }380 private void assertSomeCookiesArePresent() {381 assertFalse("Cookies were empty",382 driver.manage().getCookies().isEmpty());383 String documentCookie = getDocumentCookieOrNull();384 if (documentCookie != null) {385 assertNotSame("Cookies were empty", "", documentCookie);386 }387 }388 private void assertCookieIsNotPresentWithName(final String key) {389 assertNull("Cookie was present with name " + key, driver.manage().getCookieNamed(key));390 String documentCookie = getDocumentCookieOrNull();391 if (documentCookie != null) {392 assertThat("Cookie was present with name " + key,393 documentCookie,394 not(containsString(key + "=")));395 }396 }397 private void assertCookieIsPresentWithName(final String key) {398 assertNotNull("Cookie was not present with name " + key, driver.manage().getCookieNamed(key));399 String documentCookie = getDocumentCookieOrNull();400 if (documentCookie != null) {401 assertThat("Cookie was not present with name " + key + ", got: " + documentCookie,402 documentCookie,403 containsString(key + "="));404 }405 }406 private void assertCookieHasValue(final String key, final String value) {407 assertEquals("Cookie had wrong value",408 value,409 driver.manage().getCookieNamed(key).getValue());410 String documentCookie = getDocumentCookieOrNull();411 if (documentCookie != null) {412 assertThat("Cookie was present with name " + key,413 documentCookie,414 containsString(key + "=" + value));415 }416 }417 private String getDocumentCookieOrNull() {418 if (!(driver instanceof JavascriptExecutor)) {419 return null;420 }421 try {422 return (String) ((JavascriptExecutor) driver).executeScript("return document.cookie");423 } catch (UnsupportedOperationException e) {424 return null;425 }426 }427 private Date someTimeInTheFuture() {428 return new Date(System.currentTimeMillis() + 100000);429 }430 private void openAnotherPage() {431 driver.get(domainHelper.getUrlForFirstValidHostname("simpleTest.html"));432 }433 private void deleteAllCookiesOnServerSide() {434 driver.get(cookiePage + "?action=deleteAll");435 }436 private void addCookieOnServerSide(Cookie cookie) {437 StringBuilder url = new StringBuilder(cookiePage);438 url.append("?action=add");439 url.append("&name=").append(cookie.getName());440 url.append("&value=").append(cookie.getValue());441 if (cookie.getDomain() != null) {442 url.append("&domain=").append(cookie.getDomain());443 }444 if (cookie.getPath() != null) {445 url.append("&path=").append(cookie.getPath());446 }447 if (cookie.getExpiry() != null) {448 url.append("&expiry=").append(cookie.getExpiry().getTime());449 }450 if (cookie.isSecure()) {451 url.append("&secure=").append(cookie.isSecure());452 }453 if (cookie.isHttpOnly()) {454 url.append("&httpOnly=").append(cookie.isHttpOnly());455 }456 driver.get(url.toString());457 }458}...
Source:WebDriverService.java
1package com.services;2import org.openqa.selenium.Cookie;3import org.openqa.selenium.JavascriptExecutor;4import org.openqa.selenium.WebDriver;5import org.openqa.selenium.WebElement;6import org.openqa.selenium.chrome.ChromeDriver;7import org.openqa.selenium.chrome.ChromeOptions;8import org.openqa.selenium.firefox.FirefoxDriver;9import org.openqa.selenium.firefox.FirefoxOptions;10import org.openqa.selenium.firefox.FirefoxProfile;11import org.openqa.selenium.firefox.internal.ProfilesIni;12import org.openqa.selenium.interactions.Actions;13import org.openqa.selenium.support.ui.ExpectedConditions;14import org.openqa.selenium.support.ui.WebDriverWait;15import org.springframework.beans.factory.annotation.Value;16import org.springframework.stereotype.Service;17import java.io.*;18import java.text.ParseException;19import java.text.SimpleDateFormat;20import java.util.Date;21import java.util.Set;22import java.util.concurrent.TimeUnit;23@Service24public class WebDriverService {25 private static final String COOKIE_FILE = "src/test/resources/cookies/cookies.txt";26 private static final String SEPERATOR = ";";27 private WebDriver driver;28 private WebDriverWait wait;29 private Actions actions;30 @Value("${firefox.driver.location}")31 String firefoxDriverLocation;32 @Value("${chrome.driver.location}")33 String chromeDriverLocation;34 @Value("${firefox.profile.name}")35 String firefoxProfileName;36 @Value("${chrome.profile.location}")37 String chromeProfileLocation;38 public WebDriver getDriver() {39 return driver;40 }41 public JavascriptExecutor getJSExecutor() {42 return (JavascriptExecutor) driver;43 }44 public WebDriverWait getWait() {45 return wait;46 }47 public Actions getActions() {48 return actions;49 }50 public void initDriver(String driverType) {51 if (driverType.equals("chrome")) {52 System.setProperty("webdriver.chrome.driver", chromeDriverLocation);53 ChromeOptions options = new ChromeOptions();54 options.addArguments("user-data-dir=" + chromeProfileLocation);55 driver = new ChromeDriver(options);56 }57 if (driverType.equals("firefox")) {58 System.setProperty("webdriver.gecko.driver", firefoxDriverLocation);59 FirefoxProfile firefoxProfile = new FirefoxProfile();60 FirefoxOptions firefoxOptions = new FirefoxOptions();61 ProfilesIni profilesIni = new ProfilesIni();62 firefoxOptions.setProfile(profilesIni.getProfile(firefoxProfileName));63 driver = new FirefoxDriver(firefoxOptions);64 }65 }66 public void copyCookiesFromDriver() {67 Set<Cookie> cookies = driver.manage().getCookies();68 BufferedWriter bufferedWriter = null;69 try {70 bufferedWriter = new BufferedWriter(new FileWriter(COOKIE_FILE));71 for (Cookie cookie : cookies) {72 StringBuilder cookieBuilder = new StringBuilder();73 cookieBuilder.append(cookie.getName()).append(SEPERATOR);74 cookieBuilder.append(cookie.getValue()).append(SEPERATOR);75 cookieBuilder.append(cookie.getDomain()).append(SEPERATOR);76 cookieBuilder.append(cookie.getPath()).append(SEPERATOR);77 if (cookie.getExpiry() != null)78 cookieBuilder.append(cookie.getExpiry().toString()).append(SEPERATOR);79 else80 cookieBuilder.append(SEPERATOR);81 cookieBuilder.append(cookie.isSecure()).append(SEPERATOR);82 cookieBuilder.append(cookie.isHttpOnly());83 bufferedWriter.write(cookieBuilder.toString());84 }85 bufferedWriter.close();86 } catch (IOException e) {87 //logging88 }89 }90 public void copyCookiesToDriver() {91 try {92 BufferedReader bufferedReader = new BufferedReader(new FileReader(COOKIE_FILE));93 String line;94 while ((line = bufferedReader.readLine()) != null) {95 String[] split = line.split(SEPERATOR);96 if (split.length != 7)97 return;98 Date date = null;99 if (split[4] != null)100 date = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss z").parse(split[4]);101 Cookie cookie = new Cookie(split[0], split[1], split[2], split[3], date, Boolean.parseBoolean(split[5]), Boolean.parseBoolean(split[6]));102 driver.manage().addCookie(cookie);103 }104 bufferedReader.close();105 } catch (FileNotFoundException e) {106 //logging107 } catch (IOException e) {108 //logging109 } catch (ParseException e) {110 //logging111 }112 }113 public void initExplicitWait(Long sec) {114 if (driver != null) {115 wait = new WebDriverWait(driver, sec);116 }117 }118 public void initActions() {119 if (driver != null) {120 actions = new Actions(driver);121 }122 }123 public void explicitWaitUntilElementClickable(WebElement element) {124 wait.until(ExpectedConditions.elementToBeClickable(element));125 }126 public void explicitWaitUntilElementVisible(WebElement element) {127 wait.until(ExpectedConditions.visibilityOf(element));128 }129 public void implicitWait(Long time) {130 try {131 Thread.sleep(time * 1000);132 } catch (InterruptedException e) {133 //logging134 }135 //Implicit wait does not seems to working with some firefox profile.136 // driver.manage().timeouts().implicitlyWait(time, TimeUnit.SECONDS);137 }138 public void closeDriver() {139 if (driver != null) {140 driver.close();141 }142 }143}...
Source:SessionUtil.java
...38 try {39 JSONObject m = (JSONObject) o;40 Cookie.Builder builder = new Cookie.Builder(m.getString("name"), m.getString("value"));41 String domain = m.getString("domain");42 String path = m.getString("path");43 Boolean secure = m.getBoolean("secure");44 Boolean httpOnly = m.getBoolean("httpOnly");45 builder.domain(domain).path(path).isSecure(secure).isHttpOnly(httpOnly);46 Long expiry = m.getLong("expiry");47 if (expiry != null) {48 builder.expiresOn(new Date(expiry));49 }50 Cookie cookie = builder.build();51 driver.manage().addCookie(cookie);52 } catch (Exception e) {53 throw new RuntimeException(e);54 }55 });56 JSONArray lc = session.getJSONArray("lc");57 WebStorage webStorage = (WebStorage) new Augmenter().augment(driver);58 LocalStorage localStorage = webStorage.getLocalStorage();59 lc.forEach(o -> {60 try {61 JSONObject item = (JSONObject) o;62 String key = item.getString("key");63 String value = item.getString("value");64 localStorage.setItem(key, value);65 } catch (Exception e) {66 throw new RuntimeException(e);67 }68 });69 }70 public static JSONObject getSessionV2(WebDriver driver) {71 JSONObject session = new JSONObject();72 Set<Cookie> set = driver.manage().getCookies();73 session.put("cookie", set);74 JSONObject lc = new JSONObject();75 WebStorage webStorage = (WebStorage) new Augmenter().augment(driver);76 LocalStorage localStorage = webStorage.getLocalStorage();77 localStorage.keySet().forEach(c -> {78 lc.put(c, localStorage.getItem(c));79 });80 session.put("lc", lc);81 return session;82 }83 public static void setSessionV2(WebDriver driver, JSONObject session) {84 JSONArray cookies = session.getJSONArray("cookie");85 cookies.forEach(o -> {86 try {87 JSONObject m = (JSONObject) o;88 Cookie.Builder builder = new Cookie.Builder(m.getString("name"), m.getString("value"));89 String domain = m.getString("domain");90 String path = m.getString("path");91 Boolean secure = m.getBoolean("secure");92 Boolean httpOnly = m.getBoolean("httpOnly");93 builder.domain(domain).path(path).isSecure(secure).isHttpOnly(httpOnly);94 Long expiry = m.getLong("expiry");95 if (expiry != null) {96 builder.expiresOn(new Date(expiry));97 }98 Cookie cookie = builder.build();99 driver.manage().addCookie(cookie);100 } catch (Exception e) {101 throw new RuntimeException(e);102 }103 });104 JSONObject lc = session.getJSONObject("lc");105 WebStorage webStorage = (WebStorage) new Augmenter().augment(driver);106 LocalStorage localStorage = webStorage.getLocalStorage();107 lc.forEach((k, v) -> {...
Source:CookieAdapter.java
...33 currentDate.add(Calendar.SECOND, cookie.getMaxAge());34 newCookie.expiresOn(currentDate.getTime());35 }36 if(cookie.getPath() != null){37 newCookie.path(cookie.getPath());38 }39 if(cookie.isSecured()){40 newCookie.isSecure(cookie.isSecured());41 }42 if(cookie.getVersion() != -1){43 System.out.println("NOTE: The cookie taken from RestAssured has a version attribute of '" + cookie.getVersion() + "'. Selenium doesn't support the addition of version so this has been discarded");44 }45 return newCookie.build();46 }47 public Cookie convertToRestAssured(org.openqa.selenium.Cookie cookie) {48 Cookie.Builder newCookie = new Cookie.Builder(cookie.getName(), cookie.getValue());49 if(cookie.getDomain() != null){50 newCookie.setDomain(cookie.getDomain());51 }...
Source:AddCookie.java
...43 }44 45 String name = (String)rawCookie.get("name");46 String value = (String)rawCookie.get("value");47 String path = (String)rawCookie.get("path");48 String domain = (String)rawCookie.get("domain");49 boolean secure = getBooleanFromRaw("secure");50 boolean httpOnly = getBooleanFromRaw("httpOnly");51 52 Number expiryNum = (Number)rawCookie.get("expiry");53 54 Date expiry = expiryNum == null ? null : new Date(TimeUnit.SECONDS.toMillis(expiryNum.longValue()));55 56 return new Cookie.Builder(name, value)57 .path(path)58 .domain(domain)59 .isSecure(secure)60 .expiresOn(expiry)61 .isHttpOnly(httpOnly)62 .build();63 }64 65 private boolean getBooleanFromRaw(String key) {66 if (rawCookie.containsKey(key)) {67 Object value = rawCookie.get(key);68 if ((value instanceof Boolean)) {69 return ((Boolean)value).booleanValue();70 }71 if ((value instanceof String)) {...
Source:CookieTest.java
...30 driver.manage().deleteAllCookies();31 //Cookie aCookie = driver.manage().getCookieNamed("seleniumSimplifiedSearchNumVisits");32 Cookie.Builder newCookie = new Cookie.Builder("seleniumSimplifiedSearchNumVisits","42");33 newCookie.domain("compendiumdev.co.uk");34 newCookie.path("/selenium");35 driver.manage().addCookie(newCookie.build());36 driver.navigate().refresh();37 assertThat(driver.manage().getCookieNamed("seleniumSimplifiedSearchNumVisits").getValue(), is("43"));38 }39 @Test40 public void cookieTestThirdExample(){41 Cookie aCookie = driver.manage().getCookieNamed("seleniumSimplifiedSearchNumVisits");42 Cookie.Builder newCookie = new Cookie.Builder(aCookie.getName(),"43");43 newCookie.domain(aCookie.getDomain());44 newCookie.path(aCookie.getPath());45 driver.manage().deleteCookie(aCookie);46 driver.manage().addCookie(newCookie.build());47 driver.navigate().refresh();48 assertThat(driver.manage().getCookieNamed("seleniumSimplifiedSearchNumVisits").getValue(), is("44"));49 }50 @After51 public void closeDriver(){52 driver.close();53 }54}...
Source:selenium.java
...41 driver.manage().addCookie(42 new Cookie.Builder(cookie.getName(), "A_SHOW_MINICART")43 .domain(cookie.getDomain())44 .expiresOn(cookie.getExpiry())45 .path(cookie.getPath())46 .isSecure(cookie.isSecure())47 .build()48 );49 50 */51 }52}
Source:SeleniumCookieConverter.java
...19 }20 DeserializableCookie d = DeserializableCookie.builder(cookie.getName(), cookie.getValue())21 .domain(cookie.getDomain())22 .expiry(expiryInstant)23 .path(cookie.getPath())24 .secure(cookie.isSecure())25 .httpOnly(cookie.isHttpOnly()).build();26 return d;27 }28 @Override29 protected org.openqa.selenium.Cookie doBackward(DeserializableCookie d) {30 org.openqa.selenium.Cookie c = new org.openqa.selenium.Cookie(d.getName(), d.getValue(), d.getDomain(), d.getPath(), d.getExpiryAsDate(), d.isSecure(), d.isHttpOnly());31 return c;32 }33}...
path
Using AI Code Generation
1Cookie.Builder builder = new Cookie.Builder("name", "value");2builder.domain("example.com");3builder.path("/path");4builder.isSecure(true);5builder.isHttpOnly(true);6builder.expiresOn(new Date(2020, 1, 1));7Cookie cookie = builder.build();8driver.manage().addCookie(cookie);9Cookie.Builder builder = new Cookie.Builder("name", "value");10builder.path("/path");11builder.domain("example.com");12builder.isSecure(true);13builder.isHttpOnly(true);14builder.expiresOn(new Date(2020, 1, 1));15Cookie cookie = builder.build();16driver.manage().addCookie(cookie);17Cookie.Builder builder = new Cookie.Builder("name", "value");18builder.path("/path");19builder.domain("example.com");20builder.isHttpOnly(true);21builder.expiresOn(new Date(2020, 1, 1));22Cookie cookie = builder.build();23driver.manage().addCookie(cookie);24Cookie.Builder builder = new Cookie.Builder("name", "value");25builder.path("/path");26builder.domain("example.com");27builder.isSecure(true);28builder.expiresOn(new Date(2020, 1, 1));29Cookie cookie = builder.build();30driver.manage().addCookie(cookie);31Cookie.Builder builder = new Cookie.Builder("name", "value");32builder.path("/path");33builder.domain("example.com");34builder.isSecure(true);35builder.isHttpOnly(true);36Cookie cookie = builder.build();37driver.manage().addCookie(cookie);38Cookie.Builder builder = new Cookie.Builder("name", "value");39builder.path("/path");40builder.domain("example.com");41builder.isSecure(true);42builder.isHttpOnly(true);43builder.expiresOn(new Date(2020, 1, 1));44Cookie cookie = builder.build();45driver.manage().addCookie(cookie);46Cookie.Builder builder = new Cookie.Builder("name", "value");47builder.path("/path");48builder.domain("example.com");49builder.isSecure(true);50builder.isHttpOnly(true);51builder.expiresOn(new Date(2020, 1, 1));52Cookie cookie = builder.build();
path
Using AI Code Generation
1Cookie cookie = new Cookie.Builder("cookie_name", "cookie_value")2 .domain("example.com")3 .path("/")4 .build();5driver.manage().addCookie(cookie);6Cookie cookie = new Cookie.Builder("cookie_name", "cookie_value")7 .domain("example.com")8 .path("/path")9 .build();10driver.manage().addCookie(cookie);11Cookie cookie = new Cookie.Builder("cookie_name", "cookie_value")12 .domain("example.com")13 .path("/path/")14 .build();15driver.manage().addCookie(cookie);16Cookie cookie = new Cookie.Builder("cookie_name", "cookie_value")17 .domain("example.com")18 .path("/path/another")19 .build();20driver.manage().addCookie(cookie);21Cookie cookie = new Cookie.Builder("cookie_name", "cookie_value")22 .domain("example.com")23 .path("/path/another/")24 .build();25driver.manage().addCookie(cookie);26Cookie cookie = new Cookie.Builder("cookie_name", "cookie_value")27 .domain("example.com")28 .path("/path/another/one")29 .build();30driver.manage().addCookie(cookie);31Cookie cookie = new Cookie.Builder("cookie_name", "cookie_value")32 .domain("example.com")33 .path("/path/another/one/")34 .build();35driver.manage().addCookie(cookie);36Cookie cookie = new Cookie.Builder("cookie_name", "cookie_value")37 .domain("example.com")38 .path("/path/another/one/two")39 .build();40driver.manage().addCookie(cookie);41Cookie cookie = new Cookie.Builder("cookie_name", "cookie_value")42 .domain("example.com
LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.
Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.
What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.
Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.
Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.
How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.
Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.
Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.
LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.
Get 100 minutes of automation test minutes FREE!!