Best Selenium code snippet using org.openqa.selenium.remote.SessionId.equals
Source:AbstractHttpCommandCodec.java
...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}...
Source:ProtocolConverterTest.java
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.remote.server;18import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;19import static java.nio.charset.StandardCharsets.UTF_8;20import static org.junit.Assert.assertEquals;21import static org.junit.Assert.assertNull;22import static org.junit.Assert.assertTrue;23import static org.openqa.selenium.remote.Dialect.W3C;24import static org.openqa.selenium.remote.ErrorCodes.UNHANDLED_ERROR;25import com.google.common.collect.ImmutableList;26import com.google.common.collect.ImmutableMap;27import com.google.common.net.MediaType;28import com.google.gson.Gson;29import com.google.gson.GsonBuilder;30import com.google.gson.JsonNull;31import com.google.gson.JsonObject;32import com.google.gson.reflect.TypeToken;33import org.junit.Test;34import org.openqa.selenium.WebDriverException;35import org.openqa.selenium.json.Json;36import org.openqa.selenium.remote.Command;37import org.openqa.selenium.remote.DriverCommand;38import org.openqa.selenium.remote.SessionId;39import org.openqa.selenium.remote.http.HttpRequest;40import org.openqa.selenium.remote.http.HttpResponse;41import org.openqa.selenium.remote.http.JsonHttpCommandCodec;42import org.openqa.selenium.remote.http.JsonHttpResponseCodec;43import org.openqa.selenium.remote.http.W3CHttpCommandCodec;44import org.openqa.selenium.remote.http.W3CHttpResponseCodec;45import java.io.IOException;46import java.net.HttpURLConnection;47import java.net.URL;48import java.util.Map;49public class ProtocolConverterTest {50 private final static TypeToken<Map<String, Object>> MAP_TYPE = new TypeToken<Map<String, Object>>() {};51 private final static Gson gson = new GsonBuilder().serializeNulls().create();52 @Test53 public void shouldRoundTripASimpleCommand() throws IOException {54 SessionId sessionId = new SessionId("1234567");55 SessionCodec handler = new ProtocolConverter(56 new URL("http://example.com/wd/hub"),57 new W3CHttpCommandCodec(),58 new W3CHttpResponseCodec(),59 new JsonHttpCommandCodec(),60 new JsonHttpResponseCodec()) {61 @Override62 protected HttpResponse makeRequest(HttpRequest request) throws IOException {63 HttpResponse response = new HttpResponse();64 response.setHeader("Content-Type", MediaType.JSON_UTF_8.toString());65 response.setHeader("Cache-Control", "none");66 JsonObject obj = new JsonObject();67 obj.addProperty("sessionId", sessionId.toString());68 obj.addProperty("status", 0);69 obj.add("value", JsonNull.INSTANCE);70 String payload = gson.toJson(obj);71 response.setContent(payload.getBytes(UTF_8));72 return response;73 }74 };75 Command command = new Command(76 sessionId,77 DriverCommand.GET,78 ImmutableMap.of("url", "http://example.com/cheese"));79 HttpRequest w3cRequest = new W3CHttpCommandCodec().encode(command);80 HttpResponse resp = new HttpResponse();81 handler.handle(w3cRequest, resp);82 assertEquals(MediaType.JSON_UTF_8, MediaType.parse(resp.getHeader("Content-type")));83 assertEquals(HttpURLConnection.HTTP_OK, resp.getStatus());84 Map<String, Object> parsed = new Gson().fromJson(resp.getContentString(), MAP_TYPE.getType());85 assertNull(parsed.toString(), parsed.get("sessionId"));86 assertTrue(parsed.toString(), parsed.containsKey("value"));87 assertNull(parsed.toString(), parsed.get("value"));88 }89 @Test90 public void shouldAliasAComplexCommand() throws IOException {91 SessionId sessionId = new SessionId("1234567");92 // Downstream is JSON, upstream is W3C. This way we can force "isDisplayed" to become JS93 // execution.94 SessionCodec handler = new ProtocolConverter(95 new URL("http://example.com/wd/hub"),96 new JsonHttpCommandCodec(),97 new JsonHttpResponseCodec(),98 new W3CHttpCommandCodec(),99 new W3CHttpResponseCodec()) {100 @Override101 protected HttpResponse makeRequest(HttpRequest request) throws IOException {102 assertEquals(String.format("/session/%s/execute/sync", sessionId), request.getUri());103 Map<String, Object> params = gson.fromJson(request.getContentString(), MAP_TYPE.getType());104 assertEquals(105 ImmutableList.of(106 ImmutableMap.of(W3C.getEncodedElementKey(), "4567890")),107 params.get("args"));108 HttpResponse response = new HttpResponse();109 response.setHeader("Content-Type", MediaType.JSON_UTF_8.toString());110 response.setHeader("Cache-Control", "none");111 JsonObject obj = new JsonObject();112 obj.addProperty("sessionId", sessionId.toString());113 obj.addProperty("status", 0);114 obj.addProperty("value", true);115 String payload = gson.toJson(obj);116 response.setContent(payload.getBytes(UTF_8));117 return response;118 }119 };120 Command command = new Command(121 sessionId,122 DriverCommand.IS_ELEMENT_DISPLAYED,123 ImmutableMap.of("id", "4567890"));124 HttpRequest w3cRequest = new JsonHttpCommandCodec().encode(command);125 HttpResponse resp = new HttpResponse();126 handler.handle(w3cRequest, resp);127 assertEquals(MediaType.JSON_UTF_8, MediaType.parse(resp.getHeader("Content-type")));128 assertEquals(HttpURLConnection.HTTP_OK, resp.getStatus());129 Map<String, Object> parsed = new Gson().fromJson(resp.getContentString(), MAP_TYPE.getType());130 assertNull(parsed.get("sessionId"));131 assertTrue(parsed.containsKey("value"));132 assertEquals(true, parsed.get("value"));133 }134 @Test135 public void shouldConvertAnException() throws IOException {136 // Json upstream, w3c downstream137 SessionId sessionId = new SessionId("1234567");138 SessionCodec handler = new ProtocolConverter(139 new URL("http://example.com/wd/hub"),140 new W3CHttpCommandCodec(),141 new W3CHttpResponseCodec(),142 new JsonHttpCommandCodec(),143 new JsonHttpResponseCodec()) {144 @Override145 protected HttpResponse makeRequest(HttpRequest request) throws IOException {146 HttpResponse response = new HttpResponse();147 response.setHeader("Content-Type", MediaType.JSON_UTF_8.toString());148 response.setHeader("Cache-Control", "none");149 String payload = new Json().toJson(150 ImmutableMap.of(151 "sessionId", sessionId.toString(),152 "status", UNHANDLED_ERROR,153 "value", new WebDriverException("I love cheese and peas")));154 response.setContent(payload.getBytes(UTF_8));155 response.setStatus(HTTP_INTERNAL_ERROR);156 return response;157 }158 };159 Command command = new Command(160 sessionId,161 DriverCommand.GET,162 ImmutableMap.of("url", "http://example.com/cheese"));163 HttpRequest w3cRequest = new W3CHttpCommandCodec().encode(command);164 HttpResponse resp = new HttpResponse();165 handler.handle(w3cRequest, resp);166 assertEquals(MediaType.JSON_UTF_8, MediaType.parse(resp.getHeader("Content-type")));167 assertEquals(HTTP_INTERNAL_ERROR, resp.getStatus());168 Map<String, Object> parsed = new Gson().fromJson(resp.getContentString(), MAP_TYPE.getType());169 assertNull(parsed.get("sessionId"));170 assertTrue(parsed.containsKey("value"));171 @SuppressWarnings("unchecked") Map<String, Object> value =172 (Map<String, Object>) parsed.get("value");173 System.out.println("value = " + value.keySet());174 assertEquals("unknown error", value.get("error"));175 assertTrue(((String) value.get("message")).startsWith("I love cheese and peas"));176 }177}...
Source:DriverServletTest.java
1/*2 Copyright 2011 Software Freedom Conservancy.3 Licensed under the Apache License, Version 2.0 (the "License");4 you may not use this file except in compliance with the License.5 You may obtain a copy of the License at6 http://www.apache.org/licenses/LICENSE-2.07 Unless required by applicable law or agreed to in writing, software8 distributed under the License is distributed on an "AS IS" BASIS,9 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.10 See the License for the specific language governing permissions and11 limitations under the License.12 */13package org.openqa.selenium.remote.server;14import static org.junit.Assert.assertEquals;15import static org.junit.Assert.assertFalse;16import static org.junit.Assert.assertNotNull;17import static org.junit.Assert.assertTrue;18import static org.mockito.Mockito.verify;19import com.google.common.base.Supplier;20import com.google.common.collect.Iterators;21import org.json.JSONException;22import org.json.JSONObject;23import org.junit.Before;24import org.junit.Test;25import org.openqa.selenium.WebDriver;26import org.openqa.selenium.remote.BrowserType;27import org.openqa.selenium.remote.CapabilityType;28import org.openqa.selenium.remote.ErrorCodes;29import org.openqa.selenium.remote.JsonToBeanConverter;30import org.openqa.selenium.remote.Response;31import org.openqa.selenium.remote.SessionId;32import org.openqa.selenium.remote.server.testing.FakeHttpServletRequest;33import org.openqa.selenium.remote.server.testing.FakeHttpServletResponse;34import org.openqa.selenium.remote.server.testing.TestSessions;35import org.openqa.selenium.remote.server.testing.UrlInfo;36import org.openqa.selenium.server.RemoteControlConfiguration;37import org.seleniumhq.jetty7.server.handler.ContextHandler;38import java.io.IOException;39import java.util.logging.Logger;40import javax.servlet.ServletContext;41import javax.servlet.ServletException;42import javax.servlet.http.HttpServletResponse;43public class DriverServletTest {44 45 private static final String BASE_URL = "http://localhost:4444";46 private static final String CONTEXT_PATH = "/wd/hub";47 private TestSessions testSessions;48 private DriverServlet driverServlet;49 private long clientTimeout;50 private long browserTimeout;51 @Before52 public void setUp() throws ServletException {53 testSessions = new TestSessions();54 // Override log methods for testing.55 driverServlet = new DriverServlet(createSupplier(testSessions)) {56 @Override57 public void log(String msg) {58 }59 @Override60 public void log(String message, Throwable t) {61 }62 @Override63 public ServletContext getServletContext() {64 final ContextHandler.Context servletContext = new ContextHandler().getServletContext();65 servletContext.setInitParameter("webdriver.server.session.timeout", "18");66 servletContext.setInitParameter("webdriver.server.browser.timeout", "2");67 servletContext.setAttribute(RemoteControlConfiguration.KEY,68 new RemoteControlConfiguration());69 return servletContext;70 }71 @Override72 protected void createSessionCleaner(Logger logger, DriverSessions driverSessions,73 long sessionTimeOutInMs, long browserTimeoutInMs) {74 clientTimeout = sessionTimeOutInMs;75 browserTimeout = browserTimeoutInMs;76 }77 };78 driverServlet.init();79 }80 @Test81 public void navigateToUrlCommandHandler() throws IOException, ServletException, JSONException {82 final SessionId sessionId = createSession();83 WebDriver driver = testSessions.get(sessionId).getDriver();84 FakeHttpServletResponse response = sendCommand("POST",85 String.format("/session/%s/url", sessionId),86 new JSONObject().put("url", "http://www.google.com"));87 assertEquals(HttpServletResponse.SC_OK, response.getStatus());88 verify(driver).get("http://www.google.com");89 }90 @Test91 public void reportsBadRequestForMalformedCrossDomainRpcs()92 throws IOException, ServletException {93 FakeHttpServletResponse response = sendCommand("POST", "/xdrpc",94 new JSONObject());95 assertEquals(HttpServletResponse.SC_BAD_REQUEST, response.getStatus());96 assertEquals("Missing required parameter: method\r\n", response.getBody());97 }98 @Test99 public void handlesWelformedAndSuccessfulCrossDomainRpcs()100 throws IOException, ServletException, JSONException {101 final SessionId sessionId = createSession();102 WebDriver driver = testSessions.get(sessionId).getDriver();103 FakeHttpServletResponse response = sendCommand("POST", "/xdrpc",104 new JSONObject()105 .put("method", "POST")106 .put("path", String.format("/session/%s/url", sessionId))107 .put("data", new JSONObject()108 .put("url", "http://www.google.com")));109 verify(driver).get("http://www.google.com");110 assertEquals(HttpServletResponse.SC_OK, response.getStatus());111 assertEquals("application/json; charset=utf-8",112 response.getHeader("content-type"));113 JSONObject jsonResponse = new JSONObject(response.getBody());114 assertEquals(ErrorCodes.SUCCESS, jsonResponse.getInt("status"));115 assertEquals(sessionId.toString(), jsonResponse.getString("sessionId"));116 assertTrue(jsonResponse.isNull("value"));117 }118 @Test119 public void doesNotRedirectForNewSessionsRequestedViaCrossDomainRpc()120 throws JSONException, IOException, ServletException {121 FakeHttpServletResponse response = sendCommand("POST",122 String.format("/xdrpc"),123 new JSONObject()124 .put("method", "POST")125 .put("path", "/session")126 .put("data", new JSONObject()127 .put("desiredCapabilities", new JSONObject()128 .put(CapabilityType.BROWSER_NAME, BrowserType.FIREFOX)129 .put(CapabilityType.VERSION, true))));130 assertEquals(HttpServletResponse.SC_OK, response.getStatus());131 assertEquals("application/json; charset=utf-8",132 response.getHeader("content-type"));133 JSONObject jsonResponse = new JSONObject(response.getBody());134 assertEquals(ErrorCodes.SUCCESS, jsonResponse.getInt("status"));135 assertFalse(jsonResponse.isNull("sessionId"));136 JSONObject value = jsonResponse.getJSONObject("value");137 // values: browsername, version, remote session id.138 assertEquals(3, Iterators.size(value.keys()));139 assertEquals(BrowserType.FIREFOX, value.getString(CapabilityType.BROWSER_NAME));140 assertTrue(value.getBoolean(CapabilityType.VERSION));141 }142 private SessionId createSession() throws IOException, ServletException {143 FakeHttpServletResponse response = sendCommand("POST", "/session", null);144 assertEquals(HttpServletResponse.SC_OK, response.getStatus());145 Response resp = new JsonToBeanConverter().convert(146 Response.class, response.getBody());147 String sessionId = resp.getSessionId();148 assertNotNull(sessionId);149 assertFalse(sessionId.isEmpty());150 return new SessionId(sessionId);151 }152 153 private FakeHttpServletResponse sendCommand(String method, String commandPath,154 JSONObject parameters) throws IOException, ServletException {155 FakeHttpServletRequest request = new FakeHttpServletRequest(method, createUrl(commandPath));156 if (parameters != null) {157 request.setBody(parameters.toString());158 }159 FakeHttpServletResponse response = new FakeHttpServletResponse();160 driverServlet.service(request, response);161 return response;162 }163 private static UrlInfo createUrl(String path) {164 return new UrlInfo(BASE_URL, CONTEXT_PATH, path);165 }166 private static Supplier<DriverSessions> createSupplier(final DriverSessions sessions) {167 return new Supplier<DriverSessions>() {168 public DriverSessions get() {169 return sessions;170 }171 };172 }173 @Test174 public void timeouts() throws IOException, ServletException, JSONException {175 assertEquals(2000, browserTimeout);176 assertEquals(18000, clientTimeout);177 }178}...
equals
Using AI Code Generation
1package org.openqa.selenium.example;2import org.openqa.selenium.By;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.WebElement;5import org.openqa.selenium.chrome.ChromeDriver;6import org.openqa.selenium.remote.SessionId;7public class SessionIdExample {8 public static void main(String[] args) {9 WebDriver driver = new ChromeDriver();10 SessionId sessionId = ((ChromeDriver) driver).getSessionId();11 System.out.println("Session id: " + sessionId.toString());12 WebElement searchBox = driver.findElement(By.name("q"));13 searchBox.sendKeys("ChromeDriver");14 searchBox.submit();15 driver.quit();16 }17}
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!!