How to use equals method of org.openqa.selenium.Cookie class

Best Selenium code snippet using org.openqa.selenium.Cookie.equals

Source:AbstractHttpCommandCodec.java Github

copy

Full Screen

...150 get("/session/:sessionId/element/:id/css/:propertyName"));151 defineCommand(FIND_CHILD_ELEMENT, post("/session/:sessionId/element/:id/element"));152 defineCommand(FIND_CHILD_ELEMENTS, post("/session/:sessionId/element/:id/elements"));153 defineCommand(IS_ELEMENT_ENABLED, get("/session/:sessionId/element/:id/enabled"));154 defineCommand(ELEMENT_EQUALS, get("/session/:sessionId/element/:id/equals/:other"));155 defineCommand(GET_ELEMENT_RECT, get("/session/:sessionId/element/:id/rect"));156 defineCommand(GET_ELEMENT_LOCATION, get("/session/:sessionId/element/:id/location"));157 defineCommand(GET_ELEMENT_TAG_NAME, get("/session/:sessionId/element/:id/name"));158 defineCommand(IS_ELEMENT_SELECTED, get("/session/:sessionId/element/:id/selected"));159 defineCommand(GET_ELEMENT_SIZE, get("/session/:sessionId/element/:id/size"));160 defineCommand(GET_ELEMENT_TEXT, get("/session/:sessionId/element/:id/text"));161 defineCommand(SEND_KEYS_TO_ELEMENT, post("/session/:sessionId/element/:id/value"));162 defineCommand(GET_ALL_COOKIES, get("/session/:sessionId/cookie"));163 defineCommand(GET_COOKIE, get("/session/:sessionId/cookie/:name"));164 defineCommand(ADD_COOKIE, post("/session/:sessionId/cookie"));165 defineCommand(DELETE_ALL_COOKIES, delete("/session/:sessionId/cookie"));166 defineCommand(DELETE_COOKIE, delete("/session/:sessionId/cookie/:name"));167 defineCommand(SET_TIMEOUT, post("/session/:sessionId/timeouts"));168 defineCommand(SET_SCRIPT_TIMEOUT, post("/session/:sessionId/timeouts/async_script"));169 defineCommand(IMPLICITLY_WAIT, post("/session/:sessionId/timeouts/implicit_wait"));170 defineCommand(GET_APP_CACHE_STATUS, get("/session/:sessionId/application_cache/status"));171 defineCommand(IS_BROWSER_ONLINE, get("/session/:sessionId/browser_connection"));172 defineCommand(SET_BROWSER_ONLINE, post("/session/:sessionId/browser_connection"));173 defineCommand(GET_LOCATION, get("/session/:sessionId/location"));174 defineCommand(SET_LOCATION, post("/session/:sessionId/location"));175 defineCommand(GET_SCREEN_ORIENTATION, get("/session/:sessionId/orientation"));176 defineCommand(SET_SCREEN_ORIENTATION, post("/session/:sessionId/orientation"));177 defineCommand(GET_SCREEN_ROTATION, get("/session/:sessionId/rotation"));178 defineCommand(SET_SCREEN_ROTATION, post("/session/:sessionId/rotation"));179 defineCommand(IME_GET_AVAILABLE_ENGINES, get("/session/:sessionId/ime/available_engines"));180 defineCommand(IME_GET_ACTIVE_ENGINE, get("/session/:sessionId/ime/active_engine"));181 defineCommand(IME_IS_ACTIVATED, get("/session/:sessionId/ime/activated"));182 defineCommand(IME_DEACTIVATE, post("/session/:sessionId/ime/deactivate"));183 defineCommand(IME_ACTIVATE_ENGINE, post("/session/:sessionId/ime/activate"));184 // Mobile Spec185 defineCommand(GET_NETWORK_CONNECTION, get("/session/:sessionId/network_connection"));186 defineCommand(SET_NETWORK_CONNECTION, post("/session/:sessionId/network_connection"));187 defineCommand(SWITCH_TO_CONTEXT, post("/session/:sessionId/context"));188 defineCommand(GET_CURRENT_CONTEXT_HANDLE, get("/session/:sessionId/context"));189 defineCommand(GET_CONTEXT_HANDLES, get("/session/:sessionId/contexts"));190 defineCommand(NETWORK_LOG_CAPTURE, post("/session/:sessionId/networklog"));191 defineCommand(GET_MONITOR_STATS, post("/session/:sessionId/monitorstats"));192 }193 @Override194 public HttpRequest encode(Command command) {195 String name = aliases.getOrDefault(command.getName(), command.getName());196 //System.out.println(" [DEBUG] "+String.format("name = %s , Command Name = %s ",name,command.getName()));197 CommandSpec spec = nameToSpec.get(name);198 //System.out.println(" [DEBUG] "+String.format("spec = %s ",spec));199 if (spec == null) {200 throw new UnsupportedCommandException(command.getName());201 }202 Map<String, ?> parameters = amendParameters(command.getName(), command.getParameters());203 String uri = buildUri(name, command.getSessionId(), parameters, spec);204 HttpRequest request = new HttpRequest(spec.method, uri);205 if (HttpMethod.POST == spec.method) {206 String content = json.toJson(parameters);207 byte[] data = content.getBytes(UTF_8);208 request.setHeader(CONTENT_LENGTH, String.valueOf(data.length));209 request.setHeader(CONTENT_TYPE, JSON_UTF_8.toString());210 request.setContent(data);211 }212 if (HttpMethod.GET == spec.method) {213 request.setHeader(CACHE_CONTROL, "no-cache");214 }215 return request;216 }217 protected abstract Map<String,?> amendParameters(String name, Map<String, ?> parameters);218 @Override219 public Command decode(final HttpRequest encodedCommand) {220 final String path = Strings.isNullOrEmpty(encodedCommand.getUri())221 ? "/" : encodedCommand.getUri();222 final ImmutableList<String> parts = ImmutableList.copyOf(PATH_SPLITTER.split(path));223 int minPathLength = Integer.MAX_VALUE;224 CommandSpec spec = null;225 String name = null;226 for (Map.Entry<String, CommandSpec> nameValue : nameToSpec.entrySet()) {227 if ((nameValue.getValue().pathSegments.size() < minPathLength)228 && nameValue.getValue().isFor(encodedCommand.getMethod(), parts)) {229 name = nameValue.getKey();230 spec = nameValue.getValue();231 }232 }233 if (name == null) {234 throw new UnsupportedCommandException(235 encodedCommand.getMethod() + " " + encodedCommand.getUri());236 }237 Map<String, Object> parameters = new HashMap<>();238 spec.parsePathParameters(parts, parameters);239 String content = encodedCommand.getContentString();240 if (!content.isEmpty()) {241 @SuppressWarnings("unchecked")242 Map<String, Object> tmp = json.toType(content, MAP_TYPE);243 parameters.putAll(tmp);244 }245 SessionId sessionId = null;246 if (parameters.containsKey(SESSION_ID_PARAM)) {247 String id = (String) parameters.remove(SESSION_ID_PARAM);248 if (id != null) {249 sessionId = new SessionId(id);250 }251 }252 return new Command(sessionId, name, parameters);253 }254 /**255 * Defines a new command mapping.256 *257 * @param name The command name.258 * @param method The HTTP method to use for the command.259 * @param pathPattern The URI path pattern for the command. When encoding a command, each260 * path segment prefixed with a ":" will be replaced with the corresponding parameter261 * from the encoded command.262 */263 public void defineCommand(String name, HttpMethod method, String pathPattern) {264 defineCommand(name, new CommandSpec(method, pathPattern));265 }266 @Override267 public void alias(String commandName, String isAnAliasFor) {268 aliases.put(commandName, isAnAliasFor);269 }270 protected void defineCommand(String name, CommandSpec spec) {271 //System.out.println("[ DEBUG ] Command Spec Initiated for String Name ="+name);272 checkNotNull(name, "null name");273 //System.out.println("[ DEBUG ] Command Spec = "+spec+" String Name ="+name);274 nameToSpec.put(name, spec);275 }276 protected static CommandSpec delete(String path) {277 return new CommandSpec(HttpMethod.DELETE, path);278 }279 protected static CommandSpec get(String path) {280 return new CommandSpec(HttpMethod.GET, path);281 }282 protected static CommandSpec post(String path) {283 return new CommandSpec(HttpMethod.POST, path);284 }285 private String buildUri(286 String commandName,287 SessionId sessionId,288 Map<String, ?> parameters,289 CommandSpec spec) {290 StringBuilder builder = new StringBuilder();291 //System.out.println("[DEBUG] Path segments "+spec.pathSegments);292 for (String part : spec.pathSegments) {293 if (part.isEmpty()) {294 continue;295 }296 builder.append("/");297 if (part.startsWith(":")) {298 builder.append(getParameter(part.substring(1), commandName, sessionId, parameters));299 } else {300 builder.append(part);301 }302 }303 return builder.toString();304 }305 private String getParameter(306 String parameterName,307 String commandName,308 SessionId sessionId,309 Map<String, ?> parameters) {310 if ("sessionId".equals(parameterName)) {311 SessionId id = sessionId;312 checkArgument(id != null, "Session ID may not be null for command %s", commandName);313 return id.toString();314 }315 Object value = parameters.get(parameterName);316 checkArgument(value != null,317 "Missing required parameter \"%s\" for command %s", parameterName, commandName);318 return Urls.urlEncode(String.valueOf(value));319 }320 protected static class CommandSpec {321 private final HttpMethod method;322 private final String path;323 private final ImmutableList<String> pathSegments;324 private CommandSpec(HttpMethod method, String path) {325 this.method = checkNotNull(method, "null method");326 this.path = path;327 this.pathSegments = ImmutableList.copyOf(PATH_SPLITTER.split(path));328 }329 @Override330 public boolean equals(Object o) {331 if (o instanceof CommandSpec) {332 CommandSpec that = (CommandSpec) o;333 return this.method.equals(that.method)334 && this.path.equals(that.path);335 }336 return false;337 }338 @Override339 public int hashCode() {340 return Objects.hashCode(method, path);341 }342 /**343 * Returns whether this instance matches the provided HTTP request.344 *345 * @param method The request method.346 * @param parts The parsed request path segments.347 * @return Whether this instance matches the request.348 */349 boolean isFor(HttpMethod method, ImmutableList<String> parts) {350 if (!this.method.equals(method)) {351 return false;352 }353 if (parts.size() != this.pathSegments.size()) {354 return false;355 }356 for (int i = 0; i < parts.size(); ++i) {357 String reqPart = parts.get(i);358 String specPart = pathSegments.get(i);359 if (!(specPart.startsWith(":") || specPart.equals(reqPart))) {360 return false;361 }362 }363 return true;364 }365 void parsePathParameters(ImmutableList<String> parts, Map<String, Object> parameters) {366 for (int i = 0; i < parts.size(); ++i) {367 if (pathSegments.get(i).startsWith(":")) {368 parameters.put(pathSegments.get(i).substring(1), parts.get(i));369 }370 }371 }372 }373}...

Full Screen

Full Screen

Source:DriverUtil.java Github

copy

Full Screen

...33import org.openqa.selenium.support.ui.ExpectedConditions;34import org.openqa.selenium.support.ui.WebDriverWait;35public class DriverUtil{36 public static String unicodetoString(String unicode){37 if(unicode==null||"".equals(unicode)){38 return null;39 }40 StringBuilder sb = new StringBuilder();41 int i = -1;42 int pos = 0;43 while((i=unicode.indexOf("\\u", pos)) != -1){44 sb.append(unicode.substring(pos, i));45 if(i+5 < unicode.length()){46 pos = i+6;47 sb.append((char)Integer.parseInt(unicode.substring(i+2, i+6), 16));48 }49 }50 return sb.toString();51 }52 private static void upLoadByCommonPost(String uploadUrl) throws IOException {53 String end = "\r\n";54 String twoHyphens = "--";55 String boundary = "******";56 URL url = new URL(uploadUrl);57 HttpURLConnection httpURLConnection = (HttpURLConnection) url58 .openConnection();59 httpURLConnection.setChunkedStreamingMode(128 * 1024);// 128K 应该按照文件大小来定义60 // 允许输入输出流61 httpURLConnection.setDoInput(true);62 httpURLConnection.setDoOutput(true);63 httpURLConnection.setUseCaches(false);64 // 使用POST方法65 httpURLConnection.setRequestMethod("POST");66 httpURLConnection.setRequestProperty("Connection", "Keep-Alive");67 httpURLConnection.setRequestProperty("Charset", "UTF-8");68 httpURLConnection.setRequestProperty("Content-Type",69 "multipart/form-data;boundary=" + boundary);70 DataOutputStream dos = new DataOutputStream(71 httpURLConnection.getOutputStream());72 dos.writeBytes(twoHyphens + boundary + end);73 dos.writeBytes("Content-Disposition: form-data; name=\"uploadfile\"; filename=\"1.jpg\";" + end);74 dos.writeBytes("Content-Type: image/jpeg" + end);75 dos.writeBytes(end);76 FileInputStream fis = new FileInputStream("d:\\test.jpg");77 byte[] buffer = new byte[1024*100]; // 100k78 int count = 0;79 // 读取文件80 while ((count = fis.read(buffer)) != -1) {81 dos.write(buffer, 0, count);82 }83 fis.close();84 dos.writeBytes(end);85 dos.writeBytes(twoHyphens + boundary + twoHyphens + end);86 dos.flush();87 InputStream is = httpURLConnection.getInputStream();88 InputStreamReader isr = new InputStreamReader(is, "utf-8");89 BufferedReader br = new BufferedReader(isr);90 String result;91 while ((result=br.readLine()) != null){92 System.out.println(result);93 }94 dos.close();95 is.close();96 }97 /**98 * WebDriver切换到当前页面99 */100 public static void switchToCurrentPage(WebDriver driver) {101 String handle = driver.getWindowHandle();102 for (String tempHandle : driver.getWindowHandles()) {103 if(!tempHandle.equals(handle)) {104 driver.switchTo().window(tempHandle);105 }106 }107 }108 /**109 * 切换frame110 * @param locator111 * @return 这个驱动程序切换到给定的frame112 */113 public static void switchToFrame(By locator,WebDriver driver) {114 driver.switchTo().frame(driver.findElement(locator));115 }116 117 /**118 * 判断是否有弹窗,如有弹窗则返回弹窗内的text,否则返回空119 */120 public static String alertFlag(WebDriver driver){121 String str = "";122 try {123 Alert alt = driver.switchTo().alert();124 str = alt.getText();125 System.out.println(str);126 alt.accept();127 128 } catch (Exception e) {129 //不做任何处理130 }131 return str;132 }133 134 135 136 /**137 * 关闭所有进程(针对64位的),仅支持同步138 * @param driver139 * @throws IOException 140 */141 public static void close(WebDriver driver,String exec) throws IOException{142 if(driver != null){143 driver.close();144 Runtime.getRuntime().exec(exec);145 }146 }147 148 149 /**150 * 关闭所有进程(针对32位的)151 * @param driver152 */153 public static void close(WebDriver driver){154 if(driver != null){155 driver.quit();156 }157 }158 159 160 /**161 * 162 * @param type ie 或 chrome163 * @return164 */165 public static WebDriver getDriverInstance(String type){166 WebDriver driver = null;167 if(type.equals("ie")){168 System.setProperty("webdriver.ie.driver", "C:/ie/IEDriverServer.exe");169 DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();170 ieCapabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);171 ieCapabilities.setCapability(InternetExplorerDriver.BROWSER_ATTACH_TIMEOUT,15000);172 driver = new InternetExplorerDriver(ieCapabilities);173 driver.manage().window().maximize();174 }175 if (type.equals("chrome")){176 ChromeOptions options = new ChromeOptions();177 options.addArguments("disable-infobars");// 设置chrome浏览器的参数,使其不弹框提示(chrome正在受自动测试软件的控制)178 options.setBinary("C:/Users/Administrator/AppData/Local/Google/Chrome/Application/chrome.exe");179 System.setProperty("webdriver.chrome.driver", "C:/chrome/chromedriver.exe");180 driver = new ChromeDriver(options);181 driver.manage().window().maximize();182 }183 return driver;184 }185 /**186 * 使用代理ip187 * @param type ie 或 chrome188 * @return189 */190 public static WebDriver getDriverInstance(String type,String ip,int port){191 WebDriver driver = null;192 if(type.equals("ie")){193 System.setProperty("webdriver.ie.driver", "C:/ie/IEDriverServer.exe");194 195 String proxyIpAndPort = ip+ ":" + port;196 Proxy proxy=new Proxy();197 proxy.setHttpProxy(proxyIpAndPort).setFtpProxy(proxyIpAndPort).setSslProxy(proxyIpAndPort);198 199 DesiredCapabilities cap = DesiredCapabilities.internetExplorer();200 //代理201 cap.setCapability(CapabilityType.ForSeleniumServer.AVOIDING_PROXY, true);202 cap.setCapability(CapabilityType.ForSeleniumServer.ONLY_PROXYING_SELENIUM_TRAFFIC, true);203 System.setProperty("http.nonProxyHosts", ip);204 cap.setCapability(CapabilityType.PROXY, proxy);205 206 cap.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);207 cap.setCapability(InternetExplorerDriver.BROWSER_ATTACH_TIMEOUT,15000);208 driver = new InternetExplorerDriver(cap);209 driver.manage().window().maximize();210 }211 return driver;212 }213 214 215 /**216 * 获取cookie217 * @param driver218 * @return219 */220 public static String getCookie(WebDriver driver) {221 //获得cookie用于发包222 Set<org.openqa.selenium.Cookie> cookies = driver.manage().getCookies(); 223 StringBuffer tmpcookies = new StringBuffer();224 for (org.openqa.selenium.Cookie cookie : cookies) {225 String name = cookie.getName();226 String value = cookie.getValue();227 tmpcookies.append(name + "="+ value + ";");228 }229 String str = tmpcookies.toString();230 if(!str.isEmpty()){231 str = str.substring(0,str.lastIndexOf(";"));232 }233 return str; 234 }235 236 /**237 * 获取cookie238 * @param driver239 * @param jsession240 * @return241 */242 public static String getCookie(WebDriver driver,String jsession) {243 //获得cookie用于发包244 Set<org.openqa.selenium.Cookie> cookies = driver.manage().getCookies(); 245 StringBuffer tmpcookies = new StringBuffer();246 247 for (org.openqa.selenium.Cookie cookie : cookies) {248 String name = cookie.getName();249 String value = cookie.getValue();250 tmpcookies.append(name + "="+ value + ";");251 }252 tmpcookies.append("JSESSIONID");253 tmpcookies.append("=");254 tmpcookies.append(jsession);255 String str = tmpcookies.toString();256 return str; 257 }258 /**259 * 获取cookie 招商260 * @param driver261 * @return262 */263 public static String getCookieCmd(WebDriver driver) {264 //获得cookie用于发包265 Set<org.openqa.selenium.Cookie> cookies = driver.manage().getCookies();266 StringBuffer tmpcookies = new StringBuffer();267 for (org.openqa.selenium.Cookie cookie : cookies) {268 String name = cookie.getName();269 String value = cookie.getValue();270 if (name.equals("ProVersion")){271 tmpcookies.append(name + "=;");272 }else {273 tmpcookies.append(name + "="+ value + ";");274 }275 }276 String str = tmpcookies.toString();277 if(!str.isEmpty()){278 str = str.substring(0,str.lastIndexOf(";"));279 }280 return str;281 }282 /**283 * 根据节点位置,对节点进行裁剪,获得截图284 * @param driver...

Full Screen

Full Screen

Source:CookieTest.java Github

copy

Full Screen

1/**2 * This file is part of the GhostDriver by Ivan De Marino <http://ivandemarino.me>.3 *4 * Copyright (c) 2012-2014, Ivan De Marino <http://ivandemarino.me>5 * All rights reserved.6 *7 * Redistribution and use in source and binary forms, with or without modification,8 * are permitted provided that the following conditions are met:9 *10 * Redistributions of source code must retain the above copyright notice,11 * this list of conditions and the following disclaimer.12 * Redistributions in binary form must reproduce the above copyright notice,13 * this list of conditions and the following disclaimer in the documentation14 * and/or other materials provided with the distribution.15 *16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE19 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR20 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON23 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.26 */27package ghostdriver;28import ghostdriver.server.EmptyPageHttpRequestCallback;29import ghostdriver.server.HttpRequestCallback;30import java.io.IOException;31import java.util.Date;32import javax.servlet.http.Cookie;33import javax.servlet.http.HttpServletRequest;34import javax.servlet.http.HttpServletResponse;35import org.junit.Assert;36import org.junit.Test;37import org.openqa.selenium.InvalidCookieDomainException;38import org.openqa.selenium.JavascriptExecutor;39import org.openqa.selenium.WebDriver;40public class CookieTest extends BaseTestWithServer {41 private WebDriver driver;42 private static final HttpRequestCallback COOKIE_SETTING_CALLBACK = new EmptyPageHttpRequestCallback() {43 @Override44 public void call(HttpServletRequest req, HttpServletResponse res) throws IOException {45 super.call(req, res);46 Cookie cookie = new Cookie("test", "test");47 cookie.setDomain(".localhost");48 cookie.setMaxAge(360);49 res.addCookie(cookie);50 cookie = new Cookie("test2", "test2");51 cookie.setDomain(".localhost");52 res.addCookie(cookie);53 }54 };55 private static final HttpRequestCallback EMPTY_CALLBACK = new EmptyPageHttpRequestCallback();56 @Test57 public void gettingAllCookies() {58 server.setHttpHandler("GET", CookieTest.COOKIE_SETTING_CALLBACK);59 goToPage();60 org.openqa.selenium.Cookie[] cookies = getCookies();61 Assert.assertEquals(2, cookies.length);62 org.openqa.selenium.Cookie cookie = driver.manage().getCookieNamed("test");63 Assert.assertEquals("test", cookie.getName());64 Assert.assertEquals("test", cookie.getValue());65 Assert.assertEquals(".localhost", cookie.getDomain());66 Assert.assertEquals("/", cookie.getPath());67 Assert.assertTrue(((cookie.getExpiry()) != null));68 Assert.assertEquals(false, cookie.isSecure());69 org.openqa.selenium.Cookie cookie2 = driver.manage().getCookieNamed("test2");70 Assert.assertEquals("test2", cookie2.getName());71 Assert.assertEquals("test2", cookie2.getValue());72 Assert.assertEquals(".localhost", cookie2.getDomain());73 Assert.assertEquals("/", cookie2.getPath());74 Assert.assertEquals(false, cookie2.isSecure());75 Assert.assertTrue(((cookie2.getExpiry()) == null));76 }77 @Test78 public void gettingAllCookiesOnANonCookieSettingPage() {79 server.setHttpHandler("GET", CookieTest.EMPTY_CALLBACK);80 goToPage();81 Assert.assertEquals(0, getCookies().length);82 }83 @Test84 public void deletingAllCookies() {85 server.setHttpHandler("GET", CookieTest.COOKIE_SETTING_CALLBACK);86 goToPage();87 driver.manage().deleteAllCookies();88 Assert.assertEquals(0, getCookies().length);89 }90 @Test91 public void deletingOneCookie() {92 server.setHttpHandler("GET", CookieTest.COOKIE_SETTING_CALLBACK);93 goToPage();94 driver.manage().deleteCookieNamed("test");95 org.openqa.selenium.Cookie[] cookies = getCookies();96 Assert.assertEquals(1, cookies.length);97 Assert.assertEquals("test2", cookies[0].getName());98 }99 @Test100 public void addingACookie() {101 server.setHttpHandler("GET", CookieTest.EMPTY_CALLBACK);102 goToPage();103 driver.manage().addCookie(new org.openqa.selenium.Cookie("newCookie", "newValue", ".localhost", "/", null, false, false));104 org.openqa.selenium.Cookie[] cookies = getCookies();105 Assert.assertEquals(1, cookies.length);106 Assert.assertEquals("newCookie", cookies[0].getName());107 Assert.assertEquals("newValue", cookies[0].getValue());108 Assert.assertEquals(".localhost", cookies[0].getDomain());109 Assert.assertEquals("/", cookies[0].getPath());110 Assert.assertEquals(false, cookies[0].isSecure());111 Assert.assertEquals(false, cookies[0].isHttpOnly());112 }113 @Test114 public void modifyingACookie() {115 server.setHttpHandler("GET", CookieTest.COOKIE_SETTING_CALLBACK);116 goToPage();117 driver.manage().addCookie(new org.openqa.selenium.Cookie("test", "newValue", "localhost", "/", null, false));118 org.openqa.selenium.Cookie[] cookies = getCookies();119 Assert.assertEquals(2, cookies.length);120 Assert.assertEquals("test", cookies[1].getName());121 Assert.assertEquals("newValue", cookies[1].getValue());122 Assert.assertEquals(".localhost", cookies[1].getDomain());123 Assert.assertEquals("/", cookies[1].getPath());124 Assert.assertEquals(false, cookies[1].isSecure());125 Assert.assertEquals("test2", cookies[0].getName());126 Assert.assertEquals("test2", cookies[0].getValue());127 Assert.assertEquals(".localhost", cookies[0].getDomain());128 Assert.assertEquals("/", cookies[0].getPath());129 Assert.assertEquals(false, cookies[0].isSecure());130 }131 @Test132 public void shouldRetainCookieInfo() {133 server.setHttpHandler("GET", CookieTest.EMPTY_CALLBACK);134 goToPage();135 // Added cookie (in a sub-path - allowed)136 org.openqa.selenium.Cookie addedCookie = // < now + 100sec137 new org.openqa.selenium.Cookie.Builder("fish", "cod").expiresOn(new Date(((System.currentTimeMillis()) + (100 * 1000)))).path("/404").domain("localhost").build();138 driver.manage().addCookie(addedCookie);139 // Search cookie on the root-path and fail to find it140 org.openqa.selenium.Cookie retrieved = driver.manage().getCookieNamed("fish");141 Assert.assertNull(retrieved);142 // Go to the "/404" sub-path (to find the cookie)143 goToPage("404");144 retrieved = driver.manage().getCookieNamed("fish");145 Assert.assertNotNull(retrieved);146 // Check that it all matches147 Assert.assertEquals(addedCookie.getName(), retrieved.getName());148 Assert.assertEquals(addedCookie.getValue(), retrieved.getValue());149 Assert.assertEquals(addedCookie.getExpiry(), retrieved.getExpiry());150 Assert.assertEquals(addedCookie.isSecure(), retrieved.isSecure());151 Assert.assertEquals(addedCookie.getPath(), retrieved.getPath());152 Assert.assertTrue(retrieved.getDomain().contains(addedCookie.getDomain()));153 }154 @Test(expected = InvalidCookieDomainException.class)155 public void shouldNotAllowToCreateCookieOnDifferentDomain() {156 goToPage();157 // Added cookie (in a sub-path)158 org.openqa.selenium.Cookie addedCookie = // < now + 100sec159 new org.openqa.selenium.Cookie.Builder("fish", "cod").expiresOn(new Date(((System.currentTimeMillis()) + (100 * 1000)))).path("/404").domain("github.com").build();160 driver.manage().addCookie(addedCookie);161 }162 @Test163 public void shouldAllowToDeleteCookiesEvenIfNotSet() {164 WebDriver d = getDriver();165 d.get("https://github.com/");166 // Clear all cookies167 Assert.assertTrue(((d.manage().getCookies().size()) > 0));168 d.manage().deleteAllCookies();169 Assert.assertEquals(d.manage().getCookies().size(), 0);170 // All cookies deleted, call deleteAllCookies again. Should be a no-op.171 d.manage().deleteAllCookies();172 d.manage().deleteCookieNamed("non_existing_cookie");173 Assert.assertEquals(d.manage().getCookies().size(), 0);174 }175 @Test176 public void shouldAllowToSetCookieThatIsAlreadyExpired() {177 WebDriver d = getDriver();178 d.get("https://github.com/");179 // Clear all cookies180 Assert.assertTrue(((d.manage().getCookies().size()) > 0));181 d.manage().deleteAllCookies();182 Assert.assertEquals(d.manage().getCookies().size(), 0);183 // Added cookie that expires in the past184 org.openqa.selenium.Cookie addedCookie = // < now - 1 second185 new org.openqa.selenium.Cookie.Builder("expired", "yes").expiresOn(new Date(((System.currentTimeMillis()) - 1000))).build();186 d.manage().addCookie(addedCookie);187 org.openqa.selenium.Cookie cookie = d.manage().getCookieNamed("expired");188 Assert.assertNull(cookie);189 }190 @Test(expected = Exception.class)191 public void shouldThrowExceptionIfAddingCookieBeforeLoadingAnyUrl() {192 // NOTE: At the time of writing, this test doesn't pass with FirefoxDriver.193 // ChromeDriver is fine instead.194 String xval = "123456789101112";// < detro: I buy you a beer if you guess what am I quoting here195 WebDriver d = getDriver();196 // Set cookie, without opening any page: should throw an exception197 d.manage().addCookie(new org.openqa.selenium.Cookie("x", xval));198 }199 @Test200 public void shouldBeAbleToCreateCookieViaJavascriptOnGoogle() {201 String ckey = "cookiekey";202 String cval = "cookieval";203 WebDriver d = getDriver();204 d.get("http://www.google.com");205 JavascriptExecutor js = ((JavascriptExecutor) (d));206 // Of course, no cookie yet(!)207 org.openqa.selenium.Cookie c = d.manage().getCookieNamed(ckey);208 Assert.assertNull(c);209 // Attempt to create cookie on multiple Google domains210 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]+'; ';") + " }") + " }") + "})();"));211 c = d.manage().getCookieNamed(ckey);212 Assert.assertNotNull(c);213 Assert.assertEquals(cval, c.getValue());214 // Set cookie as empty215 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]+'; ';") + " }") + "})();"));216 c = d.manage().getCookieNamed(ckey);217 Assert.assertNotNull(c);218 Assert.assertEquals("", c.getValue());219 }220 @Test221 public void addingACookieWithDefaults() {222 server.setHttpHandler("GET", CookieTest.EMPTY_CALLBACK);223 goToPage();224 long startTime = new Date().getTime();225 driver.manage().addCookie(new org.openqa.selenium.Cookie("newCookie", "newValue"));226 org.openqa.selenium.Cookie[] cookies = getCookies();227 Assert.assertEquals(1, cookies.length);228 Assert.assertEquals("newCookie", cookies[0].getName());229 Assert.assertEquals("newValue", cookies[0].getValue());230 Assert.assertEquals(".localhost", cookies[0].getDomain());231 Assert.assertEquals("/", cookies[0].getPath());232 Assert.assertEquals(false, cookies[0].isSecure());233 Assert.assertEquals(false, cookies[0].isHttpOnly());234 // expiry > 19 years in the future235 Assert.assertTrue(((startTime + 599184000000L) <= (cookies[0].getExpiry().getTime())));236 }237}...

Full Screen

Full Screen

Source:OkHttpRequest.java Github

copy

Full Screen

...65 if (responseBody != null) {66 String body = responseBody.string();67 log.info("登录返回={}", body);68 JSONObject jsonObject = JSONObject.parseObject(body);69 if (!jsonObject.getInteger(ERR_CODE).equals(SUCCESS_CODE)) {70 return Result.fail(jsonObject.getString(ERR_MSG));71 }72 accessToken = jsonObject.getString("access_token");73 return Result.success(jsonObject);74 }75 }76 } catch (IOException e) {77 log.error("登录oa系统异常", e);78 return Result.fail("登录oa系统异常" + e.getMessage());79 }80 return Result.fail("登录oa系统失败");81 }82 public boolean auth(Integer type) {83 String authUrl = "http://115.238.110.210:8998/emp/api/agent/client/link/home?agentid=-1&corpid=em4ce4068d933411eaaaec000c2985ba71&em_client_type="84 + type;85 Request request = new Request.Builder().url(authUrl).addHeader("access_token", accessToken).get().build();86 try {87 Response response = client.newCall(request).execute();88 if (response.isSuccessful()) {89 ResponseBody responseBody = response.body();90 if (responseBody != null) {91 String body = responseBody.string();92 log.info("授权返回={}", body);93 JSONObject jsonObject = JSONObject.parseObject(body);94 if (jsonObject.getInteger(ERR_CODE).equals(SUCCESS_CODE)) {95 toUrl = jsonObject.getString(TO_URL);96 return true;97 }98 }99 }100 } catch (IOException e) {101 log.error("授权异常", e);102 }103 return false;104 }105 public boolean getCookies() {106 if (null == toUrl) {107 return false;108 }109 String loginIdWeaver;110 String languageIdWeaver;111 String jSessionId;112 String host = "http://115.238.110.210";113 // 创建chrome参数对象114 ChromeOptions options = new ChromeOptions();115 // 浏览器后台运行116 options.addArguments("--headless");117 options.addArguments("--disable-gpu");118 options.addArguments("window-size=1024,768");119 options.addArguments("--no-sandbox");120 options.addArguments("--verbose");121 options.addArguments("--whitelisted-ips=");122 options.addArguments("blink-settings=imagesEnabled=false");123 options.addArguments("--disable-javascript");124 WebDriver driver = null;125 try {126 driver = new ChromeDriver(service, options);127 driver.get(toUrl);128 WebDriverWait wait = new WebDriverWait(driver, 20);129 wait.until(ExpectedConditions.presenceOfElementLocated(By.id("more")));130 Set<org.openqa.selenium.Cookie> coo = driver.manage().getCookies();131 log.info("coo={}", coo);132 loginIdWeaver = coo.stream().filter(cookie -> "loginidweaver".equals(cookie.getName()))133 .map(org.openqa.selenium.Cookie::getValue).collect(Collectors.toList()).get(0);134 languageIdWeaver = coo.stream().filter(cookie -> "languageidweaver".equals(cookie.getName()))135 .map(org.openqa.selenium.Cookie::getValue).collect(Collectors.toList()).get(0);136 jSessionId = coo.stream().filter(cookie -> "ecology_JSessionid".equals(cookie.getName()))137 .map(org.openqa.selenium.Cookie::getValue).collect(Collectors.toList()).get(0);138 } catch (Exception e) {139 log.error("getCookies执行异常", e);140 return false;141 } finally {142 try {143 if (driver != null) {144 driver.quit();145 }146 } catch (Exception e) {147 log.error("driver quit异常", e);148 }149 }150 if (null != loginIdWeaver && null != languageIdWeaver && null != jSessionId) {151 List<okhttp3.Cookie> cookieList = new ArrayList<>();152 okhttp3.Cookie cookie1 = new okhttp3.Cookie.Builder().name("loginidweaver").value(loginIdWeaver)153 .domain(HttpUrl.get(host).host()).build();154 cookieList.add(cookie1);155 okhttp3.Cookie cookie2 = new okhttp3.Cookie.Builder().name("languageidweaver").value(languageIdWeaver)156 .domain(HttpUrl.get(host).host()).build();157 cookieList.add(cookie2);158 okhttp3.Cookie cookie3 = new okhttp3.Cookie.Builder().name("ecology_JSessionid").value(jSessionId)159 .domain(HttpUrl.get(host).host()).build();160 cookieList.add(cookie3);161 client.cookieJar().saveFromResponse(HttpUrl.get(punchUrl), cookieList);162 return true;163 } else {164 return false;165 }166 }167 public boolean punch(String longitude, String latitude) {168 FormBody formBody = new FormBody.Builder().add("longitude", longitude).add("latitude", latitude).build();169 Request request = new Request.Builder().url(punchUrl).post(formBody).build();170 try {171 Response response = client.newCall(request).execute();172 if (response.isSuccessful()) {173 ResponseBody responseBody = response.body();174 if (responseBody != null) {175 String body = responseBody.string();176 log.info("打卡返回={}", body);177 JSONObject jsonObject = JSONObject.parseObject(body);178 if (SUCCESS_STRING.equals(jsonObject.getString(SUCCESS))) {179 return true;180 }181 }182 }183 } catch (IOException e) {184 log.error("打卡异常", e);185 }186 return false;187 }188}...

Full Screen

Full Screen

Source:BrowserUtils.java Github

copy

Full Screen

...51 try{52 sBrowserName = "Mozilla";53 sPlatform = "WINDOWS";5455 if(sBrowserName.equalsIgnoreCase("Mozilla")){56 driver = CreateDriverFireFox(sPlatform);57 } else if(sBrowserName.equalsIgnoreCase("Chrome")){58 driver = CreateDriverFireFox(sPlatform);59 }60 61 } catch (Exception e) {62 throw(e);63 }64 return driver;65 } //end method6667 68 69 private static WebDriver CreateDriverFireFox(String sPlatform) {70 // Configure Firefox for cookies acceptance71 FirefoxProfile profile = new ProfilesIni().getProfile("default");72 profile.setPreference("network.cookie.cookieBehavior", 0);7374 if (sPlatform.equals("WINDOWS")){75 // Configure Firefox Gecko Driver76 // 0.20.077 //System.setProperty("webdriver.gecko.driver","W:\\w\\Java\\lib\\Selenium.3.11.0\\SeleniumWebDrivers\\geckodriver\\geckodriver-v0.20.1-win64\\geckodriver.exe");78 // 0.19.179 //System.setProperty("webdriver.gecko.driver","W:\\w\\tools\\SeleniumWebDrivers\\geckodriver\\geckodriver-v0.19.1-win64\\geckodriver.exe");80 System.setProperty("webdriver.gecko.driver","res\\geckodriver\\geckodriver-v0.19.1-win64\\geckodriver.exe");81 }8283 if (sPlatform.equalsIgnoreCase("LINUX")){84 // Configure Firefox Gecko Driver85 System.setProperty("webdriver.gecko.driver","res/geckodriver/geckodriver-v0.19.1-linux64/geckodriver.exe");86 }87 88 if (sPlatform.equalsIgnoreCase("MACOS")){89 // Configure Firefox Gecko Driver90 System.setProperty("webdriver.gecko.bin","/Applications/Firefox.app/Contents/MacOS/firefox-bin");91 System.setProperty("webdriver.gecko.driver","geckodriver");92 }9394 // Create web driver95 driver = new FirefoxDriver();9697 // driver = new FirefoxDriver();98// TestLog.info("New driver instantiated");99 driver.manage().deleteAllCookies();100 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);101 driver.manage().timeouts().pageLoadTimeout(120, TimeUnit.SECONDS);102 return driver;103 }104 105 private static WebDriver CreateDriverChrome(String sPlatform) {106 //Configure Chrome for cookies acceptance107 //ChromeProfile profile = new ProfilesIni().getProfile("default");108 //profile.setPreference("network.cookie.cookieBehavior", 0);109110 if (sPlatform.equals("WINDOWS")){111 System.setProperty("webdriver.chrome.driver","res\\chromedriver\\chromedriver-v2.40.0-win64\\chromedriver.exe");112 }113114 if (sPlatform.equalsIgnoreCase("LINUX")){115 // Configure Chrome Driver116 System.setProperty("webdriver.chrome.driver","res/chromedriver/chromedriver-v2.40.0-linux64/chromedriver.exe");117 }118 119 if (sPlatform.equalsIgnoreCase("MACOS")){120 // Configure Chrome Driver121 //System.setProperty("webdriver.gecko.bin","/Applications/Firefox.app/Contents/MacOS/firefox-bin");122 System.setProperty("webdriver.chrome.driver","chromedriver");123 }124125 // Create web driver126 driver = new ChromeDriver();127128// TestLog.info("New driver instantiated");129 driver.manage().deleteAllCookies();130 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);131 driver.manage().timeouts().pageLoadTimeout(120, TimeUnit.SECONDS);132 133 return driver;134 }135136 public static void BrowserClose() {137 driver.close();138 driver.quit(); 139 }140141 public static void BrowserGet() {142 driver.get("http://www.unityconstruct.org");143 }144 145 public static void waitForElementToBeReady(String elType, String elTypeIdentifier) {146 WebDriverWait wait = new WebDriverWait(driver, 10);147 148 switch (elType) {149 case "xpath":150 element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath(elTypeIdentifier))); 151 break;152 case "id":153 element = wait.until(ExpectedConditions.elementToBeClickable(By.id(elTypeIdentifier))); 154 break;155 default:156 break;157 }158 }159 160 public static void waitForPageToBeReady() 161 {162 JavascriptExecutor js = (JavascriptExecutor)driver;163 164 //This loop will rotate for 100 times to check If page Is ready after every 1 second.165 //You can replace your if you wants to Increase or decrease wait time.166 for (int i=0; i<30; i++)167 {168 if (js.executeScript("return document.readyState").toString().equals("complete") ||169 js.executeScript("return document.readyState").toString().equals("complete")) 170 171 { 172// TestLog.info("waitForPageToBeReady - executeScript complete [or loaded]");173 break; 174 }175 try 176 {177// TestLog.info("waitForPageToBeReady: Add Sleep time 1000 ms");178 Thread.sleep(1000);179 }catch (InterruptedException e) {} 180 //To check page ready state.181 }182 }183 ...

Full Screen

Full Screen

Source:CleanSessionTest.java Github

copy

Full Screen

1// Licensed to the Software Freedom Conservancy (SFC) under one2// or more contributor license agreements. See the NOTICE file3// distributed with this work for additional information4// regarding copyright ownership. The SFC licenses this file5// to you under the Apache License, Version 2.0 (the6// "License"); you may not use this file except in compliance7// with the License. You may obtain a copy of the License at8//9// http://www.apache.org/licenses/LICENSE-2.010//11// Unless required by applicable law or agreed to in writing,12// software distributed under the License is distributed on an13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14// KIND, either express or implied. See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.safari;18import static org.junit.Assert.assertEquals;19import static org.junit.Assert.assertTrue;20import static org.openqa.selenium.testing.Driver.SAFARI;21import org.junit.After;22import org.junit.Test;23import org.openqa.selenium.By;24import org.openqa.selenium.Cookie;25import org.openqa.selenium.JavascriptExecutor;26import org.openqa.selenium.WebDriver;27import org.openqa.selenium.testing.Ignore;28import org.openqa.selenium.testing.JUnit4TestBase;29import org.openqa.selenium.testing.NeedsLocalEnvironment;30@NeedsLocalEnvironment(reason = "Requires local browser launching environment")31public class CleanSessionTest extends JUnit4TestBase {32 private static final Cookie COOKIE = new Cookie("foo", "bar");33 private WebDriver driver2;34 @After35 public void quitDriver() {36 if (driver2 != null) {37 driver2.quit();38 }39 }40 private void createCleanSession() {41 removeDriver();42 quitDriver();43 SafariOptions safariOptions = new SafariOptions();44 driver2 = new SafariDriver(safariOptions);45 driver2.get(pages.alertsPage);46 }47 @Test48 public void shouldClearCookiesWhenStartingWithACleanSession() {49 createCleanSession();50 assertNoCookies();51 driver2.manage().addCookie(COOKIE);52 assertHasCookie(COOKIE);53 createCleanSession();54 assertNoCookies();55 }56 @Test57 public void isResilientToPagesRedefiningDependentDomFunctions() {58 runFunctionRedefinitionTest("window.dispatchEvent = function() {};");59 runFunctionRedefinitionTest("window.postMessage = function() {};");60 runFunctionRedefinitionTest("document.createEvent = function() {};");61 runFunctionRedefinitionTest("document.documentElement.setAttribute = function() {};");62 runFunctionRedefinitionTest("document.documentElement.getAttribute = function() {};");63 runFunctionRedefinitionTest("document.documentElement.removeAttribute = function() {};");64 }65 private void runFunctionRedefinitionTest(String script) {66 driver.get(appServer.whereIs("messages.html"));67 JavascriptExecutor executor = (JavascriptExecutor) driver;68 executor.executeScript(script);69 // If the above actually returns, then we are good to go.70 }71 @Test72 @Ignore(SAFARI)73 public void executeAsyncScriptIsResilientToPagesRedefiningSetTimeout() {74 driver.get(appServer.whereIs("messages.html"));75 JavascriptExecutor executor = (JavascriptExecutor) driver;76 executor.executeScript("setTimeout = function() {}");77 long result = (Long) executor.executeAsyncScript(78 "var callback = arguments[arguments.length - 1];" +79 "window.constructor.prototype.setTimeout.call(window, function() {" +80 "callback(123);\n}, 0);");81 assertEquals(123L, result);82 }83 @Test84 public void doesNotLeakInternalMessagesToThePageUnderTest() {85 driver.get(appServer.whereIs("messages.html"));86 JavascriptExecutor executor = (JavascriptExecutor) driver;87 executor.executeScript("window.postMessage('hi', '*');");88 long numMessages = (Long) executor.executeScript(89 "return window.messages.length;");90 assertEquals(1L, numMessages);91 }92 @Test93 public void doesNotCreateExtraIframeOnPageUnderTest() {94 driver.get(appServer.whereIs("messages.html"));95 assertEquals(0, driver.findElements(By.tagName("iframe")).size());96 ((JavascriptExecutor) driver).executeScript("return location.href;");97 assertEquals(0, driver.findElements(By.tagName("iframe")).size());98 }99 private void assertHasCookie(Cookie cookie) {100 assertTrue(driver2.manage().getCookies().contains(cookie));101 }102 private void assertNoCookies() {103 assertTrue(driver2.manage().getCookies().isEmpty());104 }105}...

Full Screen

Full Screen

Source:WebDriver81CookiesTest.java Github

copy

Full Screen

1package com.compendiumdev.test;23 import static org.hamcrest.CoreMatchers.equalTo;4import static org.junit.Assert.*;56import java.time.Duration;7import java.util.Set;8import java.util.function.Function;91011import org.junit.AfterClass;12 import org.junit.Before;13 import org.junit.BeforeClass;14 import org.junit.Test;15 import org.openqa.selenium.By;16import org.openqa.selenium.Cookie;17import org.openqa.selenium.NotFoundException;18 import org.openqa.selenium.WebDriver;19 import org.openqa.selenium.WebElement;20 import org.openqa.selenium.firefox.FirefoxDriver;21 import org.openqa.selenium.support.ui.ExpectedCondition;22 import org.openqa.selenium.support.ui.ExpectedConditions;23 import org.openqa.selenium.support.ui.FluentWait;24 import org.openqa.selenium.support.ui.WebDriverWait;2526 public class WebDriver81CookiesTest {2728 private static WebDriver driver;29 private WebDriverWait wait;30 private WebElement searchBox;31 private WebElement searchButton;32 3334 @BeforeClass35 public static void createDriver() {36 System.setProperty("webdriver.gecko.driver", "src/main/resources/geckodriver.exe");37 driver = new FirefoxDriver();3839 }4041 @Before42 public void refreshPage() {43 driver.get("http://www.compendiumdev.co.uk/selenium/search.php"); 44 driver.manage().deleteAllCookies();45 refreshSearchPage();46 }47 48 public void refreshSearchPage() {49 searchBox = driver.findElement(By.name("q"));50 searchButton = driver.findElement(By.name("btnG"));51 }5253 @Test54 public void webDriverGetCookieFromList() {5556 searchBox.clear();57 searchBox.sendKeys("Cookie Test");58 searchButton.click();5960 Set<Cookie> cookies = driver.manage().getCookies();61 for(Cookie aCookie : cookies) {62 if(aCookie.getName().contentEquals("seleniumSimplifiedSearchNumVisits")) {63 assertEquals("This should be my first visit", "1", aCookie.getValue());64 }65 } 66 }67 68 @Test69 public void webDriverGetCookieDirectly() {7071 searchBox.clear();72 searchBox.sendKeys("Cookie Test");73 searchButton.click();7475 Cookie aCookie = driver.manage().getCookieNamed("seleniumSimplifiedSearchNumVisits");76 assertEquals("This should be my first visit", "1", aCookie.getValue());77 }78 79 @Test80 public void webDriverUpdateClonedCookie() {81 82 searchBox.clear();83 searchBox.sendKeys("Cookie Test");84 searchButton.click();85 86 refreshSearchPage();87 88 Cookie aCookie = driver.manage().getCookieNamed("seleniumSimplifiedSearchNumVisits");89 assertEquals("This should be my first visit", "1", aCookie.getValue());90 91 // Clone Cookie and set Value to what is wanted92 Cookie aNewCookie = new Cookie( aCookie.getName(),93 String.valueOf(42),94 aCookie.getDomain(),95 aCookie.getPath(),96 aCookie.getExpiry(),aCookie.isSecure());97 98 driver.manage().deleteCookie(aCookie);99 driver.manage().addCookie(aNewCookie);100 101 searchBox.clear();102 searchBox.sendKeys("New Cookie Test");103 searchButton.click();104 105 aCookie = driver.manage().getCookieNamed("seleniumSimplifiedSearchNumVisits");106 assertEquals("This should be my first visit", "43", aCookie.getValue());107 108 }109 110 @Test111 public void webDriverUpdateCookieBuilder() {112 113 searchBox.clear();114 searchBox.sendKeys("Cookie Test");115 searchButton.click();116 117 refreshSearchPage();118 119 Cookie aCookie = driver.manage().getCookieNamed("seleniumSimplifiedSearchNumVisits");120 assertEquals("This should be my first visit", "1", aCookie.getValue());121 122 // Clone Cookie and set Value to what is wanted123 Cookie aNewCookie = new Cookie.Builder( aCookie.getName(), String.valueOf(29))124 .domain(aCookie.getDomain())125 .path(aCookie.getPath())126 .expiresOn(aCookie.getExpiry())127 .isSecure(aCookie.isSecure()).build();128 129 driver.manage().deleteCookie(aCookie);130 driver.manage().addCookie(aNewCookie);131 132 searchBox.clear();133 searchBox.sendKeys("Another Cookie Test");134 searchButton.click();135 136 aCookie = driver.manage().getCookieNamed("seleniumSimplifiedSearchNumVisits");137 assertEquals("This should be my first visit", "30", aCookie.getValue());138 139 }140 141 @AfterClass142 public static void tearDown() {143 driver.quit();144 }145146} ...

Full Screen

Full Screen

Source:CookieTst.java Github

copy

Full Screen

1package Tests;2import static org.junit.Assert.assertEquals;3import org.junit.Before;4import org.junit.Test;5import org.openqa.selenium.By;6import org.openqa.selenium.Cookie;7import org.openqa.selenium.WebDriver;8import org.openqa.selenium.firefox.FirefoxDriver;9import org.openqa.selenium.support.ui.ExpectedConditions;10import org.openqa.selenium.support.ui.WebDriverWait;11public class CookieTst {12 WebDriver driver = new FirefoxDriver();13 WebDriverWait wait = new WebDriverWait(driver, 10);14 @Before15 public void setup(){16 driver.get("http://www.compendiumdev.co.uk/selenium/search.php");17 wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("title")));18 }19 @Test20 public void testFirstVistit(){21 //delete number of visits cookie22 driver.manage().deleteCookieNamed("seleniumSimplifiedSearchNumVisits");23 //find and click search button, then wait for results to be present24 driver.findElement(By.cssSelector("input[name='btnG']")).click();25 wait.until(ExpectedConditions.presenceOfElementLocated(By.id("resultList")));26 //get number of times visited in cookie and assert = 127 Cookie aCookie = driver.manage().getCookieNamed("seleniumSimplifiedSearchNumVisits");28 assertEquals("1", aCookie.getValue());29 driver.quit();30 }31 @Test32 public void changeVisitValue (){33 String cookieName = "seleniumSimplifiedSearchNumVisits";34 Cookie newCookie;35 //delete original cookie36 driver.manage().deleteCookieNamed(cookieName);37 //set number of visits cookie in new cookie38 //build new cookie from values and change visits to 4239 newCookie = new Cookie(cookieName, "42");40 //check value41 assertEquals("42", newCookie.getValue());42 driver.quit();43 }44}...

Full Screen

Full Screen

equals

Using AI Code Generation

copy

Full Screen

1Cookie cookie = new Cookie("name", "value");2driver.manage().addCookie(cookie);3driver.manage().getCookies().contains(cookie);4Cookie cookie = new Cookie("name", "value");5driver.manage().addCookie(cookie);6driver.manage().getCookies().contains(cookie);7Cookie cookie = new Cookie("name", "value");8driver.manage().addCookie(cookie);9driver.manage().getCookies().contains(cookie);10Cookie cookie = new Cookie("name", "value");11driver.manage().addCookie(cookie);12driver.manage().getCookies().contains(cookie);13Cookie cookie = new Cookie("name", "value");14driver.manage().addCookie(cookie);15driver.manage().getCookies().contains(cookie);16Cookie cookie = new Cookie("name", "value");17driver.manage().addCookie(cookie);18driver.manage().getCookies().contains(cookie);19Cookie cookie = new Cookie("name", "value");20driver.manage().addCookie(cookie);21driver.manage().getCookies().contains(cookie);22Cookie cookie = new Cookie("name", "value");23driver.manage().addCookie(cookie);24driver.manage().getCookies().contains(cookie);25Cookie cookie = new Cookie("name", "value");26driver.manage().addCookie(cookie);27driver.manage().getCookies().contains(cookie);28Cookie cookie = new Cookie("name", "value");29driver.manage().addCookie(cookie);30driver.manage().getCookies().contains(cookie);31Cookie cookie = new Cookie("name", "value");32driver.manage().addCookie(cookie);33driver.manage().getCookies().contains(cookie);34Cookie cookie = new Cookie("name", "value");35driver.manage().addCookie(cookie);36driver.manage().getCookies().contains(cookie);37Cookie cookie = new Cookie("name", "value");38driver.manage().addCookie(cookie);

Full Screen

Full Screen

equals

Using AI Code Generation

copy

Full Screen

1Cookie cookie = new Cookie.Builder(name, value).build();2Cookie cookie = new Cookie.Builder(name, value).build();3Cookie cookie = new Cookie.Builder(name, value).build();4Cookie cookie = new Cookie.Builder(name, value).build();5Cookie cookie = new Cookie.Builder(name, value).build();6Cookie cookie = new Cookie.Builder(name, value).build();7Cookie cookie = new Cookie.Builder(name, value).build();8Cookie cookie = new Cookie.Builder(name, value).build();9Cookie cookie = new Cookie.Builder(name, value).build();10Cookie cookie = new Cookie.Builder(name, value).build();11Cookie cookie = new Cookie.Builder(name, value).build();12Cookie cookie = new Cookie.Builder(name, value).build();13Cookie cookie = new Cookie.Builder(name, value).build();14Cookie cookie = new Cookie.Builder(name, value).build();15Cookie cookie = new Cookie.Builder(name, value).build();16Cookie cookie = new Cookie.Builder(name, value).build();17Cookie cookie = new Cookie.Builder(name, value).build();18Cookie cookie = new Cookie.Builder(name, value).build();19Cookie cookie = new Cookie.Builder(name, value).build();20Cookie cookie = new Cookie.Builder(name, value).build();

Full Screen

Full Screen

equals

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.Cookie; 2import org.openqa.selenium.WebDriver; 3import org.openqa.selenium.chrome.ChromeDriver; 4import org.openqa.selenium.chrome.ChromeOptions; 5import org.openqa.selenium.remote.DesiredCapabilities; 6import org.openqa.selenium.remote.RemoteWebDriver; 7import org.testng.annotations.Test;8import java.net.MalformedURLException; 9import java.net.URL; 10import java.util.Set;11public class CookieTest {12public void testCookie() throws MalformedURLException { 13DesiredCapabilities capabilities = DesiredCapabilities.chrome(); 14ChromeOptions options = new ChromeOptions(); 15options.addArguments(“–start-maximized”); 16capabilities.setCapability(ChromeOptions.CAPABILITY, options); 17driver.manage().addCookie(new Cookie(“foo”, “bar”)); 18Set<Cookie> cookies = driver.manage().getCookies(); 19for (Cookie cookie : cookies) { 20System.out.println(cookie.getName() + “:” + cookie.getValue()); 21} 22driver.manage().deleteCookieNamed(“foo”); 23driver.manage().deleteAllCookies(); 24driver.quit(); 25} 26}

Full Screen

Full Screen

Selenium 4 Tutorial:

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.

Chapters:

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

  6. 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.

  7. 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.

Selenium 101 certifications:

LambdaTest also provides certification for Selenium testing to accelerate your career in Selenium automation testing.

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful