Best Selenium code snippet using org.openqa.selenium.remote.Response.equals
Source:SeleneseCommandExecutor.java
...177 String browser = capabilities.getBrowserName();178 if (browser.startsWith("*")) {179 return browser;180 }181 if (DesiredCapabilities.firefox().getBrowserName().equals(browser)) {182 return "*chrome";183 }184 if ("safari".equals(browser)) {185 String path = findSafari();186 return "*safari " + path;187 }188 if (DesiredCapabilities.chrome().getBrowserName().equals(browser)) {189 return "*googlechrome /Applications/Google Chrome.app/Contents/MacOS/Google Chrome";190 }191 throw new IllegalArgumentException(192 "Cannot determine which selenium type to use: " + capabilities.getBrowserName());193 }194 private static String findSafari() {195 if (Platform.getCurrent().is(Platform.WINDOWS)) {196 File[] locations = new File[] {197 new File("C:\\Program Files (x86)\\Safari\\safari.exe"),198 new File("C:\\Program Files\\Safari\\safari.exe")199 };200 for (File location : locations) {201 if (location.exists()) {202 return location.getAbsolutePath();...
Source:ResultConfig.java
...87 ((JsonParametersAware) handler).setJsonParameters(parameters);88 }89 }90 throwUpIfSessionTerminated(sessionId);91 if (DriverCommand.STATUS.equals(command.getName())) {92 log.fine(String.format("Executing: %s)", handler));93 } else {94 log.info(String.format("Executing: %s)", handler));95 }96 Object value = handler.handle();97 if (value instanceof Response) {98 response = (Response) value;99 } else {100 response.setValue(value);101 response.setState(ErrorCodes.SUCCESS_STRING);102 response.setStatus(ErrorCodes.SUCCESS);103 }104 if (DriverCommand.STATUS.equals(command.getName())) {105 log.fine("Done: " + handler);106 } else {107 log.info("Done: " + handler);108 }109 } catch (UnreachableBrowserException e) {110 throwUpIfSessionTerminated(sessionId);111 return Responses.failure(sessionId, e);112 } catch (Exception e) {113 log.log(Level.WARNING, "Exception thrown", e);114 Throwable toUse = getRootExceptionCause(e);115 log.warning("Exception: " + toUse.getMessage());116 Optional<String> screenshot = Optional.empty();117 if (handler instanceof WebDriverHandler) {118 screenshot = Optional.ofNullable(((WebDriverHandler<?>) handler).getScreenshot());119 }120 response = Responses.failure(sessionId, toUse, screenshot);121 } catch (Error e) {122 log.info("Error: " + e.getMessage());123 response = Responses.failure(sessionId, e);124 }125 if (handler instanceof DeleteSession) {126 // Yes, this is funky. See javadoc on cleatThreadTempLogs for details.127 final PerSessionLogHandler logHandler = LoggingManager.perSessionLogHandler();128 logHandler.transferThreadTempLogsToSessionLogs(sessionId);129 logHandler.removeSessionLogs(sessionId);130 }131 return response;132 }133 private void throwUpIfSessionTerminated(SessionId sessId) throws NoSuchSessionException {134 if (sessId == null) return;135 Session session = sessions.get(sessId);136 final boolean isTerminated = session == null;137 if (isTerminated) {138 throw new NoSuchSessionException();139 }140 }141 public Throwable getRootExceptionCause(Throwable originalException) {142 Throwable toReturn = originalException;143 if (originalException instanceof UndeclaredThrowableException) {144 // An exception was thrown within an invocation handler. Not smart.145 // Extract the original exception146 toReturn = originalException.getCause().getCause();147 }148 // When catching an exception here, it is most likely wrapped by149 // several other exceptions. Peel the layers and use the original150 // exception as the one to return to the client. That is the most151 // likely to contain informative data about the error.152 // This is a safety measure to make sure this loop is never endless153 List<Throwable> chain = new ArrayList<>(10);154 for (Throwable current = toReturn; current != null && chain.size() < 10; current =155 current.getCause()) {156 chain.add(current);157 }158 if (chain.isEmpty()) {159 return null;160 }161 // If the root cause came from another server implementing the wire protocol, there might162 // not have been enough information to fully reconstitute its error, in which case we'll163 // want to return the last 2 causes - with the outer error providing context to the164 // true root cause. These case are identified by the root cause not being mappable to a165 // standard WebDriver error code, but its wrapper is mappable.166 //167 // Of course, if we only have one item in our chain, go ahead and return.168 ErrorCodes ec = new ErrorCodes();169 Iterator<Throwable> reversedChain = Lists.reverse(chain).iterator();170 Throwable rootCause = reversedChain.next();171 if (!reversedChain.hasNext() || ec.isMappableError(rootCause)) {172 return rootCause;173 }174 Throwable nextCause = reversedChain.next();175 return ec.isMappableError(nextCause) ? nextCause : rootCause;176 }177 private HandlerFactory getHandlerFactory(Class<? extends RestishHandler<?>> handlerClazz) {178 final Constructor<? extends RestishHandler<?>> sessionAware = getConstructor(handlerClazz, Session.class);179 if (sessionAware != null) {180 return (sessionId) ->181 sessionAware.newInstance(sessionId != null ? sessions.get(sessionId) : null);182 }183 final Constructor<? extends RestishHandler<?>> driverSessions =184 getConstructor(handlerClazz, DriverSessions.class);185 if (driverSessions != null) {186 return (sessionId) -> driverSessions.newInstance(sessions);187 }188 final Constructor<? extends RestishHandler<?>> noArgs = getConstructor(handlerClazz);189 if (noArgs != null) {190 return (sessionId) -> noArgs.newInstance();191 }192 throw new IllegalArgumentException("Don't know how to construct " + handlerClazz);193 }194 private static Constructor<? extends RestishHandler<?>> getConstructor(195 Class<? extends RestishHandler<?>> handlerClazz, Class<?>... types) {196 try {197 return handlerClazz.getConstructor(types);198 } catch (NoSuchMethodException e) {199 return null;200 }201 }202 @Override203 public boolean equals(Object o) {204 if (this == o) {205 return true;206 }207 if (!(o instanceof ResultConfig)) {208 return false;209 }210 ResultConfig that = (ResultConfig) o;211 return commandName.equals(that.commandName);212 }213 @Override214 public int hashCode() {215 return commandName.hashCode();216 }217}...
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}...
Source:AppiumCommandExecutor.java
...80 return remoteServer;81 }82 private Response doExecute(Command command) throws IOException, WebDriverException {83 if (command.getSessionId() == null) {84 if (QUIT.equals(command.getName())) {85 return new Response();86 }87 if (!GET_ALL_SESSIONS.equals(command.getName())88 && !NEW_SESSION.equals(command.getName())) {89 throw new NoSuchSessionException(90 "Session ID is null. Using WebDriver after calling quit()?");91 }92 }93 if (NEW_SESSION.equals(command.getName())) {94 if (commandCodec != null) {95 throw new SessionNotCreatedException("Session already exists");96 }97 AppiumProtocolHandShake handshake = new AppiumProtocolHandShake();98 AppiumProtocolHandShake.Result result = handshake.createSession(client, command);99 Dialect dialect = result.getDialect();100 commandCodec = dialect.getCommandCodec();101 additionalCommands.forEach((key, value) -> {102 checkNotNull(key);103 checkNotNull(value);104 commandCodec.defineCommand(key, value.getMethod(), value.getUrl());105 } );106 responseCodec = dialect.getResponseCodec();107 return result.createResponse();108 }109 if (commandCodec == null || responseCodec == null) {110 throw new WebDriverException(111 "No command or response codec has been defined. Unable to proceed");112 }113 HttpRequest httpRequest = commandCodec.encode(command);114 try {115 HttpResponse httpResponse = client.execute(httpRequest, true);116 Response response = responseCodec.decode(httpResponse);117 if (response.getSessionId() == null) {118 if (httpResponse.getTargetHost() != null) {119 response.setSessionId(HttpSessionId.getSessionId(httpResponse.getTargetHost()));120 } else {121 response.setSessionId(command.getSessionId().toString());122 }123 }124 if (QUIT.equals(command.getName())) {125 client.close();126 }127 return response;128 } catch (UnsupportedCommandException e) {129 if (e.getMessage() == null || "".equals(e.getMessage())) {130 throw new UnsupportedOperationException(131 "No information from server. Command name was: " + command.getName(),132 e.getCause());133 }134 throw e;135 }136 }137 @Override public Response execute(Command command) throws IOException, WebDriverException {138 if (DriverCommand.NEW_SESSION.equals(command.getName()) && service != null) {139 service.start();140 }141 try {142 return doExecute(command);143 } catch (Throwable t) {144 Throwable rootCause = getRootCause(t);145 if (rootCause instanceof ConnectException146 && rootCause.getMessage().contains("Connection refused")147 && service != null) {148 if (service.isRunning()) {149 throw new WebDriverException("The session is closed!", t);150 }151 if (!service.isRunning()) {152 throw new WebDriverException("The appium server has accidentally died!", t);153 }154 }155 throwIfUnchecked(t);156 throw new WebDriverException(t);157 } finally {158 if (DriverCommand.QUIT.equals(command.getName()) && service != null) {159 service.stop();160 }161 }162 }163}...
Source:myHttpCommandExecutor.java
...35 myresponseCodec = new W3CHttpResponseCodec();36 }37 public Response execute(Command command) throws IOException {38 if (command.getSessionId() == null) {39 if (QUIT.equals(command.getName())) {40 return new Response();41 }42 if (!GET_ALL_SESSIONS.equals(command.getName()) && !NEW_SESSION.equals(command.getName())) {43 throw new NoSuchSessionException("Session ID is null. Using WebDriver after calling quit()?");44 }45 }46 if (NEW_SESSION.equals(command.getName())) {47 if (mycommandCodec != null) {48 throw new SessionNotCreatedException("Session already exists");49 }50 ProtocolHandshake handshake = new ProtocolHandshake();51 ProtocolHandshake.Result result = handshake.createSession(myclient, command);52 Dialect dialect = result.getDialect();53 mycommandCodec = dialect.getCommandCodec();54 myresponseCodec = dialect.getResponseCodec();55 return result.createResponse();56 }57 if (mycommandCodec == null || myresponseCodec == null) {58 throw new WebDriverException("No command or response codec has been defined. Unable to proceed");59 }60 HttpRequest httpRequest = mycommandCodec.encode(command);61 try {62 HttpResponse httpResponse = myclient.execute(httpRequest);63 Response response = myresponseCodec.decode(httpResponse);64 if (response.getSessionId() == null) {65 if (httpResponse.getTargetHost() != null) {66 response.setSessionId(HttpSessionId.getSessionId(httpResponse.getTargetHost()));67 } else {68 // Spam in the session id from the request69 response.setSessionId(command.getSessionId().toString());70 }71 }72 if (QUIT.equals(command.getName())) {73 }74 return response;75 } catch (UnsupportedCommandException e) {76 if (e.getMessage() == null || "".equals(e.getMessage())) {77 throw new UnsupportedOperationException(78 "No information from server. Command name was: " + command.getName(), e.getCause());79 }80 throw e;81 }82 }83}...
Source:ExceptionHandlerTest.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.commandhandler;18import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;19import static org.junit.Assert.assertEquals;20import com.google.gson.Gson;21import com.google.gson.reflect.TypeToken;22import org.junit.Test;23import org.openqa.selenium.NoAlertPresentException;24import org.openqa.selenium.NoSuchSessionException;25import org.openqa.selenium.SessionNotCreatedException;26import org.openqa.selenium.remote.ErrorCodes;27import org.openqa.selenium.remote.http.HttpMethod;28import org.openqa.selenium.remote.http.HttpRequest;29import org.openqa.selenium.remote.http.HttpResponse;30import org.openqa.selenium.remote.server.commandhandler.ExceptionHandler;31import java.lang.reflect.Type;32import java.util.Map;33import java.util.concurrent.ExecutionException;34public class ExceptionHandlerTest {35 private final static Type MAP_TYPE = new TypeToken<Map<String, Object>>(){}.getType();36 @Test37 public void shouldSetErrorCodeForJsonWireProtocol() {38 Exception e = new NoSuchSessionException("This does not exist");39 HttpResponse response = new HttpResponse();40 new ExceptionHandler(e).execute(new HttpRequest(HttpMethod.POST, "/session"), response);41 assertEquals(HTTP_INTERNAL_ERROR, response.getStatus());42 Map<String, Object> err = new Gson().fromJson(response.getContentString(), MAP_TYPE);43 assertEquals(ErrorCodes.NO_SUCH_SESSION, ((Number) err.get("status")).intValue());44 }45 @Test46 public void shouldSetErrorCodeForW3cSpec() {47 Exception e = new NoAlertPresentException("This does not exist");48 HttpResponse response = new HttpResponse();49 new ExceptionHandler(e).execute(new HttpRequest(HttpMethod.POST, "/session"), response);50 Map<String, Object> err = new Gson().fromJson(response.getContentString(), MAP_TYPE);51 Map<?, ?> value = (Map<?, ?>) err.get("value");52 assertEquals(value.toString(),"no such alert", value.get("error"));53 }54 @Test55 public void shouldUnwrapAnExecutionException() {56 Exception noSession = new SessionNotCreatedException("This does not exist");57 Exception e = new ExecutionException(noSession);58 HttpResponse response = new HttpResponse();59 new ExceptionHandler(e).execute(new HttpRequest(HttpMethod.POST, "/session"), response);60 Map<String, Object> err = new Gson().fromJson(response.getContentString(), MAP_TYPE);61 Map<?, ?> value = (Map<?, ?>) err.get("value");62 assertEquals(ErrorCodes.SESSION_NOT_CREATED, ((Number) err.get("status")).intValue());63 assertEquals("session not created", value.get("error"));64 }65}...
Source:ActiveSessionCommandExecutor.java
...31 this.session = Objects.requireNonNull(session, "Session must not be null");32 }33 @Override34 public Response execute(Command command) throws IOException {35 if (DriverCommand.NEW_SESSION.equals(command.getName())) {36 if (active) {37 throw new WebDriverException("Cannot start session twice! " + session);38 }39 active = true;40 // We already have a running session.41 Response response = new Response(session.getId());42 response.setValue(session.getCapabilities());43 return response;44 }45 HttpRequest request = session.getUpstreamDialect().getCommandCodec().encode(command);46 HttpResponse httpResponse = new HttpResponse();47 session.execute(request, httpResponse);48 return session.getDownstreamDialect().getResponseCodec().decode(httpResponse);49 }...
equals
Using AI Code Generation
1import org.openqa.selenium.remote.Response;2public class ResponseEquals {3 public static void main(String[] args) {4 Response response1 = new Response();5 response1.setSessionId("session1");6 response1.setStatus(0);7 response1.setValue("value1");8 Response response2 = new Response();9 response2.setSessionId("session2");10 response2.setStatus(0);11 response2.setValue("value2");12 System.out.println(response1.equals(response2));13 }14}15public boolean equals(Object o) {16 if (this == o) {17 return true;18 }19 if (o == null || getClass() != o.getClass()) {20 return false;21 }22 Response response = (Response) o;23 if (status != response.status) {24 return false;25 }26 if (sessionId != null ? !sessionId.equals(response.sessionId) : response.sessionId != null) {27 return false;28 }29 return value != null ? value.equals(response.value) : response.value == null;30}
equals
Using AI Code Generation
1import org.openqa.selenium.remote.Response;2import org.testng.annotations.Test;3public class TestResponse {4 public void test() {5 Response response = new Response();6 response.setStatus(1);7 response.setState("state1");8 response.setValue("value1");9 System.out.println(response);10 Response response2 = new Response();11 response2.setStatus(1);12 response2.setState("state1");13 response2.setValue("value1");14 System.out.println(response2);15 System.out.println(response.equals(response2));16 }17}18Response{sessionId='null', status=1, value=value1, state=state1}19Response{sessionId='null', status=1, value=value1, state=state1}
equals
Using AI Code Generation
1import org.openqa.selenium.remote.Response;2import org.openqa.selenium.remote.RemoteWebDriver;3import org.openqa.selenium.remote.DesiredCapabilities;4import org.openqa.selenium.WebDriver;5import org.openqa.selenium.By;6import org.openqa.selenium.WebElement;7import org.openqa.selenium.chrome.ChromeDriver;8import org.openqa.selenium.chrome.ChromeOptions;9import org.openqa.selenium.chrome.ChromeDriverService;10import java.util.HashMap;11import java.util.Map;12import java.util.List;13import java.util.ArrayList;14import java.util.Set;15import java.util.Iterator;16import java.util.concurrent.TimeUnit;17import java.util.Date;18import java.text.SimpleDateFormat;19import java.io.File;20import java.io.IOException;21import java.io.FileNotFoundException;22import java.io.FileReader;23import java.io.BufferedReader;24import java.io.BufferedWriter;25import java.io.FileWriter;26import java.io.PrintWriter;27import java.io.InputStream;28import java.io.InputStreamReader;29import java.util.regex.Pattern;30import java.util.regex.Matcher;31import java.util.logging.Level;32import java.util.logging.Logger;33import org.openqa.selenium.logging.LogEntries;34import org.openqa.selenium.logging.LogEntry;35import org.openqa.selenium.logging.LogType;36import org.openqa.selenium.logging.LoggingPreferences;37import org.openqa.selenium.remote.CapabilityType;38import org.openqa.selenium.remote.DesiredCapabilities;39import org.openqa.selenium.remote.RemoteWebDriver;40import org.openqa.selenium.support.ui.ExpectedCondition;41import org.openqa.selenium.support.ui.WebDriverWait;42import org.openqa.selenium.JavascriptExecutor;43import org.openqa.selenium.NoSuchElementException;44import org.openqa.selenium.TimeoutException;45import org.openqa.selenium.WebDriverException;46import org.openqa.selenium.support.ui.Select;47import org.openqa.selenium.interactions.Actions;48import org.openqa.selenium.Alert;49import org.openqa.selenium.Keys;50import org.openqa.selenium.WebDriver;51import org.openqa.selenium.WebDriverException;52import org.openqa.selenium.WebElement;53import org.openqa.selenium.interactions.Action;54import org.openqa.selenium.interactions.Actions;55import org.openqa.selenium.internal.Locatable;56import org.openqa.selenium.remote.RemoteWebDriver;57import org.openqa.selenium.support.ui.ExpectedConditions;58import org.openqa.selenium.support.ui.WebDriverWait;59import org.openqa.selenium.By;60import org.openqa.selenium.WebElement;61import org.openqa.selenium.chrome.ChromeDriver;62import org.openqa.selenium.chrome.ChromeOptions;63import org.openqa.selenium.chrome.ChromeDriverService;64import java.util.HashMap;65import java.util
equals
Using AI Code Generation
1public boolean compareResponse(Response actualResponse, Response expectedResponse) {2 if (!actualResponse.equals(expectedResponse)) {3 throw new RuntimeException("The actual response does not match the expected response.\n"4 + "Expected response: " + expectedResponse + "\n");5 }6 else {7 return true;8 }9}10Response expectedResponse = new Response();11expectedResponse.setStatus(200);12Response expectedResponse = new Response();13expectedResponse.setStatus(200);14expectedResponse.setSessionId(sessionId);15Response expectedResponse = new Response();16expectedResponse.setStatus(200);17expectedResponse.setSessionId(sessionId);18expectedResponse.setValue(elementId);19Response expectedResponse = new Response();20expectedResponse.setStatus(200);21expectedResponse.setSessionId(sessionId);22expectedResponse.setValue(elementId);23expectedResponse.setSessionId(elementText);24Response expectedResponse = new Response();25expectedResponse.setStatus(200);26expectedResponse.setSessionId(sessionId);
equals
Using AI Code Generation
1public boolean isResponseNotNull(org.openqa.selenium.remote.Response response){2 if(response==null)3 return false;4 return true;5}6public boolean isResponseNotNull(org.openqa.selenium.remote.Response response){7 if(response==null)8 return false;9 return true;10}
equals
Using AI Code Generation
1public class Response {2 private final int status;3 private final String sessionId;4 private final Object value;5 private final Map<String, Object> additionalInformation;6 public Response(int status, String sessionId, Object value, Map<String, Object> additionalInformation) {7 this.status = status;8 this.sessionId = sessionId;9 this.value = value;10 this.additionalInformation = additionalInformation;11 }12 public int getStatus() {13 return status;14 }15 public String getSessionId() {16 return sessionId;17 }18 public Object getValue() {19 return value;20 }21 public Map<String, Object> getAdditionalInformation() {22 return additionalInformation;23 }24 public String toString() {25 return "Response [status=" + status + ", sessionId=" + sessionId + ", value=" + value + ", additionalInformation=" + additionalInformation + "]";26 }27 public boolean equals(Object obj) {28 if (this == obj) {29 return true;30 }31 if (obj == null) {32 return false;33 }34 if (getClass() != obj.getClass()) {35 return false;36 }37 Response other = (Response) obj;38 if (additionalInformation == null) {39 if (other.additionalInformation != null) {40 return false;41 }42 } else if (!additionalInformation.equals(other.additionalInformation)) {43 return false;44 }45 if (sessionId == null) {46 if (other.sessionId != null) {47 return false;48 }49 } else if (!sessionId.equals(other.sessionId)) {50 return false;51 }52 if (status != other.status) {53 return false;54 }55 if (value == null) {56 if (other.value != null) {57 return false;58 }59 } else if (!value.equals(other.value)) {60 return false;61 }62 return true;63 }64}
equals
Using AI Code Generation
1Response response = new Response();2response.setStatus(0);3response.setValue("Hello World");4Response response2 = new Response();5response2.setStatus(0);6response2.setValue("Hello World");7if(response.equals(response2)){8 System.out.println("Test Case Passed");9}10else{11 System.out.println("Test Case Failed");12}13How to compare two objects in Java using equals() method?14How to compare two objects in Java using compareTo() method?15How to compare two objects in Java using equals() method and == operator?16How to compare two objects in Java using compareTo() method and == operator?17How to compare two objects in Java using equals() method and compareTo() method?18How to compare two objects in Java using == operator and compareTo() method?19How to compare two objects in Java using == operator and equals() method?20How to compare two objects in Java using compareTo() method and equals() method?21How to compare two objects in Java using equals() method and hashCode() method?22How to compare two objects in Java using hashCode() method and equals() method?23How to compare two objects in Java using hashCode() method and compareTo() method?24How to compare two objects in Java using compareTo() method and hashCode() method?25How to compare two objects in Java using equals() method and == operator?26How to compare two objects in Java using == operator and equals() method?27How to compare two objects in Java using compareTo() method and == operator?28How to compare two objects in Java using == operator and compareTo() method?29How to compare two objects in Java using equals() method and compareTo() method?
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!!