How to use toJson method of org.openqa.selenium.Proxy class

Best Selenium code snippet using org.openqa.selenium.Proxy.toJson

Source:JsonTest.java Github

copy

Full Screen

...71 public void canRoundTripNumbers() {72 Map<String, Object> original = ImmutableMap.of(73 "options", ImmutableMap.of("args", ImmutableList.of(1L, "hello")));74 Json json = new Json();75 String converted = json.toJson(original);76 Object remade = json.toType(converted, MAP_TYPE);77 assertEquals(original, remade);78 }79 @Test80 public void roundTripAFirefoxOptions() {81 Map<String, Object> caps = ImmutableMap.of(82 "moz:firefoxOptions", ImmutableMap.of(83 "prefs", ImmutableMap.of("foo.bar", 1)));84 String json = new Json().toJson(caps);85 assertFalse(json, json.contains("1.0"));86 try (JsonInput input = new Json().newInput(new StringReader(json))) {87 json = new Json().toJson(input.read(Json.MAP_TYPE));88 assertFalse(json, json.contains("1.0"));89 }90 }91 @Test92 public void shouldCoerceAListOfCapabilitiesIntoSomethingMutable() {93 // This is needed since Grid expects each of the capabilities to be mutable94 List<Capabilities> expected = ImmutableList.of(95 new ImmutableCapabilities("cheese", "brie"),96 new ImmutableCapabilities("peas", 42L));97 Json json = new Json();98 String raw = json.toJson(expected);99 List<Capabilities> seen = json.toType(raw, new TypeToken<List<Capabilities>>(){}.getType());100 assertEquals(expected, seen);101 assertTrue(seen.get(0) instanceof MutableCapabilities);102 }103 @Test104 public void shouldUseBeanSettersToPopulateFields() {105 Map<String, String> map = ImmutableMap.of("name", "fishy");106 Json json = new Json();107 String raw = json.toJson(map);108 BeanWithSetter seen = json.toType(raw, BeanWithSetter.class);109 assertEquals("fishy", seen.theName);110 }111 public static class BeanWithSetter {112 String theName;113 public void setName(String name) {114 theName = name;115 }116 }117 @Test118 public void shouldAllowUserToPopulateFieldsDirectly() {119 Map<String, String> map = ImmutableMap.of("theName", "fishy");120 Json json = new Json();121 String raw = json.toJson(map);122 BeanWithSetter seen = json.toType(raw, BeanWithSetter.class, PropertySetting.BY_FIELD);123 assertEquals("fishy", seen.theName);124 }125 @Test126 public void testCanConstructASimpleString() {127 String text = new Json().toType("cheese", String.class);128 assertThat(text, is("cheese"));129 }130 @SuppressWarnings("unchecked")131 @Test132 public void testCanPopulateAMap() {133 JsonObject toConvert = new JsonObject();134 toConvert.addProperty("cheese", "brie");135 toConvert.addProperty("foodstuff", "cheese");136 Map<String, String> map = new Json().toType(toConvert.toString(), Map.class);137 assertThat(map.size(), is(2));138 assertThat(map, hasEntry("cheese", "brie"));139 assertThat(map, hasEntry("foodstuff", "cheese"));140 }141 @Test142 public void testCanPopulateAMapThatContainsNull() {143 JsonObject toConvert = new JsonObject();144 toConvert.add("foo", JsonNull.INSTANCE);145 Map<?,?> converted = new Json().toType(toConvert.toString(), Map.class);146 assertEquals(1, converted.size());147 assertTrue(converted.containsKey("foo"));148 assertNull(converted.get("foo"));149 }150 @Test151 public void testCanPopulateASimpleBean() {152 JsonObject toConvert = new JsonObject();153 toConvert.addProperty("value", "time");154 SimpleBean bean = new Json().toType(toConvert.toString(), SimpleBean.class);155 assertThat(bean.getValue(), is("time"));156 }157 @Test158 public void testWillSilentlyDiscardUnusedFieldsWhenPopulatingABean() {159 JsonObject toConvert = new JsonObject();160 toConvert.addProperty("value", "time");161 toConvert.addProperty("frob", "telephone");162 SimpleBean bean = new Json().toType(toConvert.toString(), SimpleBean.class);163 assertThat(bean.getValue(), is("time"));164 }165 @Test166 public void testShouldSetPrimitiveValuesToo() {167 JsonObject toConvert = new JsonObject();168 toConvert.addProperty("magicNumber", 3);169 Map<?,?> map = new Json().toType(toConvert.toString(), Map.class);170 assertEquals(3L, map.get("magicNumber"));171 }172 @Test173 public void testShouldPopulateFieldsOnNestedBeans() {174 JsonObject toConvert = new JsonObject();175 toConvert.addProperty("name", "frank");176 JsonObject child = new JsonObject();177 child.addProperty("value", "lots");178 toConvert.add("bean", child);179 ContainingBean bean = new Json().toType(toConvert.toString(), ContainingBean.class);180 assertThat(bean.getName(), is("frank"));181 assertThat(bean.getBean().getValue(), is("lots"));182 }183 @Test184 public void testShouldProperlyFillInACapabilitiesObject() {185 DesiredCapabilities capabilities =186 new DesiredCapabilities("browser", CapabilityType.VERSION, Platform.ANY);187 capabilities.setJavascriptEnabled(true);188 String text = new Json().toJson(capabilities);189 Capabilities readCapabilities = new Json().toType(text, DesiredCapabilities.class);190 assertEquals(capabilities, readCapabilities);191 }192 @Test193 public void testShouldUseAMapToRepresentComplexObjects() {194 JsonObject toModel = new JsonObject();195 toModel.addProperty("thing", "hairy");196 toModel.addProperty("hairy", "true");197 Map<?,?> modelled = (Map<?,?>) new Json().toType(toModel.toString(), Object.class);198 assertEquals(2, modelled.size());199 }200 @Test201 public void testShouldConvertAResponseWithAnElementInIt() {202 String json =203 "{\"value\":{\"value\":\"\",\"text\":\"\",\"selected\":false,\"enabled\":true,\"id\":\"three\"},\"context\":\"con\",\"sessionId\":\"sess\"}";204 Response converted = new Json().toType(json, Response.class);205 Map<?,?> value = (Map<?,?>) converted.getValue();206 assertEquals("three", value.get("id"));207 }208 @Test209 public void testShouldBeAbleToCopeWithStringsThatLookLikeBooleans() {210 String json =211 "{\"value\":\"false\",\"context\":\"foo\",\"sessionId\":\"1210083863107\"}";212 try {213 new Json().toType(json, Response.class);214 } catch (Exception e) {215 e.printStackTrace();216 fail("This should have worked");217 }218 }219 @Test220 public void testShouldBeAbleToSetAnObjectToABoolean() {221 String json =222 "{\"value\":true,\"context\":\"foo\",\"sessionId\":\"1210084658750\"}";223 Response response = new Json().toType(json, Response.class);224 assertThat(response.getValue(), is(true));225 }226 @Test227 public void testCanHandleValueBeingAnArray() {228 String[] value = {"Cheese", "Peas"};229 Response response = new Response();230 response.setSessionId("bar");231 response.setValue(value);232 response.setStatus(1512);233 String json = new Json().toJson(response);234 Response converted = new Json().toType(json, Response.class);235 assertEquals("bar", response.getSessionId());236 assertEquals(2, ((List<?>) converted.getValue()).size());237 assertEquals(1512, response.getStatus().intValue());238 }239 @Test240 public void testShouldConvertObjectsInArraysToMaps() {241 Date date = new Date();242 Cookie cookie = new Cookie("foo", "bar", "localhost", "/rooted", date, true, true);243 String rawJson = new Json().toJson(Collections.singletonList(cookie));244 List<?> list = new Json().toType(rawJson, List.class);245 Object first = list.get(0);246 assertTrue(first instanceof Map);247 Map<?,?> map = (Map<?,?>) first;248 assertMapEntry(map, "name", "foo");249 assertMapEntry(map, "value", "bar");250 assertMapEntry(map, "domain", "localhost");251 assertMapEntry(map, "path", "/rooted");252 assertMapEntry(map, "secure", true);253 assertMapEntry(map, "httpOnly", true);254 assertMapEntry(map, "expiry", TimeUnit.MILLISECONDS.toSeconds(date.getTime()));255 }256 private void assertMapEntry(Map<?,?> map, String key, Object expected) {257 assertTrue("Missing key: " + key, map.containsKey(key));258 assertEquals("Wrong value for key: " + key + ": " + map.get(key).getClass().getName(),259 expected, map.get(key));260 }261 @Test262 public void testShouldConvertAnArrayBackIntoAnArray() {263 Exception e = new Exception();264 String converted = new Json().toJson(e);265 Map<?,?> reconstructed = new Json().toType(converted, Map.class);266 List<?> trace = (List<?>) reconstructed.get("stackTrace");267 assertTrue(trace.get(0) instanceof Map);268 }269 @Test270 public void testShouldBeAbleToReconsituteASessionId() {271 String json = new Json().toJson(new SessionId("id"));272 SessionId sessionId = new Json().toType(json, SessionId.class);273 assertEquals("id", sessionId.toString());274 }275 @Test276 public void testShouldBeAbleToConvertACommand() {277 SessionId sessionId = new SessionId("session id");278 Command original = new Command(279 sessionId,280 DriverCommand.NEW_SESSION,281 ImmutableMap.of("food", "cheese"));282 String raw = new Json().toJson(original);283 Command converted = new Json().toType(raw, Command.class);284 assertEquals(sessionId.toString(), converted.getSessionId().toString());285 assertEquals(original.getName(), converted.getName());286 assertEquals(1, converted.getParameters().keySet().size());287 assertEquals("cheese", converted.getParameters().get("food"));288 }289 @Test290 public void testShouldConvertCapabilitiesToAMapAndIncludeCustomValues() {291 Capabilities caps = new ImmutableCapabilities("furrfu", "fishy");292 String raw = new Json().toJson(caps);293 Capabilities converted = new Json().toType(raw, Capabilities.class);294 assertEquals("fishy", converted.getCapability("furrfu"));295 }296 @Test297 public void testShouldParseCapabilitiesWithLoggingPreferences() {298 JsonObject prefs = new JsonObject();299 prefs.addProperty("browser", "WARNING");300 prefs.addProperty("client", "DEBUG");301 prefs.addProperty("driver", "ALL");302 prefs.addProperty("server", "OFF");303 JsonObject caps = new JsonObject();304 caps.add(CapabilityType.LOGGING_PREFS, prefs);305 Capabilities converted = new Json().toType(caps.toString(), Capabilities.class);306 LoggingPreferences lp =...

Full Screen

Full Screen

Source:ProtocolHandshake.java Github

copy

Full Screen

...137 Gson gson,138 JsonObject des,139 JsonObject req) throws IOException {140 out.name("desiredCapabilities");141 gson.toJson(des, out);142 out.name("requiredCapabilities");143 gson.toJson(req, out);144 }145 private void streamW3CProtocolParameters(146 JsonWriter out,147 Gson gson,148 JsonObject des,149 JsonObject req) throws IOException {150 // Technically we should be building up a combination of "alwaysMatch" and "firstMatch" options.151 // We're going to do a little processing to figure out what we might be able to do, and assume152 // that people don't really understand the difference between required and desired (which is153 // commonly the case). Wish us luck. Looking at the current implementations, people may have154 // set options for multiple browsers, in which case a compliant W3C remote end won't start155 // a session. If we find this, then we create multiple firstMatch capabilities. Furrfu.156 // The table of options are:157 //158 // Chrome: chromeOptions159 // Firefox: moz:.*, firefox_binary, firefox_profile, marionette160 // Edge: none given161 // IEDriver: ignoreZoomSetting, initialBrowserUrl, enableElementCacheCleanup,162 // browserAttachTimeout, enablePersistentHover, requireWindowFocus, logFile, logLevel, host,163 // extractPath, silent, ie.*164 // Opera: operaOptions165 // SafariDriver: safari.options166 //167 // We can't use the constants defined in the classes because it would introduce circular168 // dependencies between the remote library and the implementations. Yay!169 Map<String, ?> chrome = Stream.of(des, req)170 .map(JsonObject::entrySet)171 .flatMap(Collection::stream)172 .filter(entry ->173 ("browserName".equals(entry.getKey()) && CHROME.equals(entry.getValue().getAsString())) ||174 "chromeOptions".equals(entry.getKey()))175 .distinct()176 .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (left, right) -> right));177 Map<String, ?> edge = Stream.of(des, req)178 .map(JsonObject::entrySet)179 .flatMap(Collection::stream)180 .filter(entry -> ("browserName".equals(entry.getKey()) && EDGE.equals(entry.getValue().getAsString())))181 .distinct()182 .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (left, right) -> right));183 Map<String, ?> firefox = Stream.of(des, req)184 .map(JsonObject::entrySet)185 .flatMap(Collection::stream)186 .filter(entry ->187 ("browserName".equals(entry.getKey()) && FIREFOX.equals(entry.getValue().getAsString())) ||188 entry.getKey().startsWith("firefox_") ||189 entry.getKey().startsWith("moz:"))190 .distinct()191 .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (left, right) -> right));192 Map<String, ?> ie = Stream.of(req, des)193 .map(JsonObject::entrySet)194 .flatMap(Collection::stream)195 .filter(entry ->196 ("browserName".equals(entry.getKey()) && IE.equals(entry.getValue().getAsString())) ||197 "browserAttachTimeout".equals(entry.getKey()) ||198 "enableElementCacheCleanup".equals(entry.getKey()) ||199 "enablePersistentHover".equals(entry.getKey()) ||200 "extractPath".equals(entry.getKey()) ||201 "host".equals(entry.getKey()) ||202 "ignoreZoomSetting".equals(entry.getKey()) ||203 "initialBrowserZoom".equals(entry.getKey()) ||204 "logFile".equals(entry.getKey()) ||205 "logLevel".equals(entry.getKey()) ||206 "requireWindowFocus".equals(entry.getKey()) ||207 "se:ieOptions".equals(entry.getKey()) ||208 "silent".equals(entry.getKey()) ||209 entry.getKey().startsWith("ie."))210 .distinct()211 .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (left, right) -> right));212 Map<String, ?> opera = Stream.of(des, req)213 .map(JsonObject::entrySet)214 .flatMap(Collection::stream)215 .filter(entry ->216 ("browserName".equals(entry.getKey()) && OPERA_BLINK.equals(entry.getValue().getAsString())) ||217 ("browserName".equals(entry.getKey()) && OPERA.equals(entry.getValue().getAsString())) ||218 "operaOptions".equals(entry.getKey()))219 .distinct()220 .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (left, right) -> right));221 Map<String, ?> safari = Stream.of(des, req)222 .map(JsonObject::entrySet)223 .flatMap(Collection::stream)224 .filter(entry ->225 ("browserName".equals(entry.getKey()) && SAFARI.equals(entry.getValue().getAsString())) ||226 "safari.options".equals(entry.getKey()))227 .distinct()228 .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (left, right) -> right));229 Set<String> excludedKeys = Stream.of(chrome, edge, firefox, ie, opera, safari)230 .map(Map::keySet)231 .flatMap(Collection::stream)232 .distinct()233 .collect(ImmutableSet.toImmutableSet());234 JsonObject alwaysMatch = Stream.of(des, req)235 .map(JsonObject::entrySet)236 .flatMap(Collection::stream)237 .filter(entry -> !excludedKeys.contains(entry.getKey()))238 .filter(entry -> entry.getValue() != null)239 .filter(entry -> ACCEPTED_W3C_PATTERNS.test(entry.getKey()))240 .filter(entry ->241 !("platformName".equals(entry.getKey()) &&242 entry.getValue().isJsonPrimitive() &&243 "ANY".equalsIgnoreCase(entry.getValue().getAsString())))244 .distinct()245 .collect(Collector.of(246 JsonObject::new,247 (obj, e) -> obj.add(e.getKey(), e.getValue()),248 (left, right) -> {249 for (Map.Entry<String, JsonElement> entry : right.entrySet()) {250 left.add(entry.getKey(), entry.getValue());251 }252 return left;253 }));254 // Now, hopefully we're left with just the browser-specific pieces. Skip the empty ones.255 JsonArray firstMatch = Stream.of(chrome, edge, firefox, ie, opera, safari)256 .map(map -> {257 JsonObject json = new JsonObject();258 for (Map.Entry<String, ?> entry : map.entrySet()) {259 if (ACCEPTED_W3C_PATTERNS.test(entry.getKey())) {260 json.add(entry.getKey(), gson.toJsonTree(entry.getValue()));261 }262 }263 return json;264 })265 .filter(obj -> !obj.entrySet().isEmpty())266 .collect(Collector.of(267 JsonArray::new,268 JsonArray::add,269 (left, right) -> {270 for (JsonElement element : right) {271 left.add(element);272 }273 return left;274 }275 ));276 // TODO(simon): transform some capabilities that changed in the spec (timeout's "pageLoad")277 Stream.concat(Stream.of(alwaysMatch), StreamSupport.stream(firstMatch.spliterator(), false))278 .map(el -> (JsonObject) el)279 .forEach(obj -> {280 if (obj.has("proxy")) {281 JsonObject proxy = obj.getAsJsonObject("proxy");282 if (proxy.has("proxyType")) {283 proxy.add(284 "proxyType",285 new JsonPrimitive(proxy.get("proxyType").getAsString().toLowerCase()));286 }287 }288 });289 out.name("alwaysMatch");290 gson.toJson(alwaysMatch, out);291 out.name("firstMatch");292 gson.toJson(firstMatch, out);293 }294 public Optional<Result> createSession(HttpClient client, InputStream newSessionBlob, long size)295 throws IOException {296 // Create the http request and send it297 HttpRequest request = new HttpRequest(HttpMethod.POST, "/session");298 request.setHeader(CONTENT_LENGTH, String.valueOf(size));299 request.setHeader(CONTENT_TYPE, JSON_UTF_8.toString());300 request.setContent(newSessionBlob);301 long start = System.currentTimeMillis();302 HttpResponse response = client.execute(request, true);303 long time = System.currentTimeMillis() - start;304 // Ignore the content type. It may not have been set. Strictly speaking we're not following the305 // W3C spec properly. Oh well.306 Map<?, ?> blob;307 try {308 blob = new JsonToBeanConverter().convert(Map.class, response.getContentString());309 } catch (JsonException e) {310 throw new WebDriverException(311 "Unable to parse remote response: " + response.getContentString());312 }313 InitialHandshakeResponse initialResponse = new InitialHandshakeResponse(314 time,315 response.getStatus(),316 blob);317 return Stream.of(318 new JsonWireProtocolResponse().getResponseFunction(),319 new Gecko013ProtocolResponse().getResponseFunction(),320 new W3CHandshakeResponse().getResponseFunction())321 .map(func -> func.apply(initialResponse))322 .filter(Optional::isPresent)323 .map(Optional::get)324 .findFirst();325 }326 private void streamGeckoDriver013Parameters(327 JsonWriter out,328 Gson gson,329 JsonObject des,330 JsonObject req) throws IOException {331 out.name("desiredCapabilities");332 gson.toJson(des, out);333 out.name("requiredCapabilities");334 gson.toJson(req, out);335 }336 public static class Result {337 private static Function<Object, Proxy> massageProxy = obj -> {338 if (obj instanceof Proxy) {339 return (Proxy) obj;340 }341 if (!(obj instanceof Map)) {342 return null;343 }344 Map<?, ?> rawMap = (Map<?, ?>) obj;345 for (Object key : rawMap.keySet()) {346 if (!(key instanceof String)) {347 return null;348 }...

Full Screen

Full Screen

Source:StatusServletTests.java Github

copy

Full Screen

...119 public void testPost() throws IOException {120 String id = "http://machine1:4444";121 Map<String, Object> o = ImmutableMap.of("id", id);122 HttpRequest r = new HttpRequest(POST, proxyApi.toExternalForm());123 r.setContent(new Json().toJson(o).getBytes(UTF_8));124 HttpResponse response = client.execute(r);125 assertEquals(200, response.getStatus());126 Map<String, Object> res = extractObject(response);127 assertEquals(id, res.get("id"));128 }129 @Test130 public void testPostReflection() throws IOException {131 String id = "http://machine5:4444";132 Map<String, Object> o = ImmutableMap.of(133 "id", id,134 "getURL", "",135 "getBoolean", "",136 "getString", "");137 HttpRequest r = new HttpRequest(POST, proxyApi.toExternalForm());138 r.setContent(new Json().toJson(o).getBytes(UTF_8));139 HttpResponse response = client.execute(r);140 assertEquals(200, response.getStatus());141 Map<String, Object> res = extractObject(response);142 assertEquals(MyCustomProxy.MY_BOOLEAN, res.get("getBoolean"));143 assertEquals(MyCustomProxy.MY_STRING, res.get("getString"));144 // url converted to string145 assertEquals(MyCustomProxy.MY_URL.toString(), res.get("getURL"));146 }147 @Test148 public void testSessionApi() throws IOException {149 ExternalSessionKey s = session.getExternalKey();150 Map<String, Object> o = ImmutableMap.of("session", s.toString());151 HttpRequest r = new HttpRequest(POST, testSessionApi.toExternalForm());152 r.setContent(new Json().toJson(o).getBytes(UTF_8));153 HttpResponse response = client.execute(r);154 assertEquals(200, response.getStatus());155 Map<String, Object> res = extractObject(response);156 assertTrue((boolean) res.get("success"));157 assertNotNull(res.get("internalKey"));158 assertEquals(s, ExternalSessionKey.fromJSON((String) res.get("session")));159 assertNotNull(res.get("inactivityTime"));160 assertEquals(p1.getId(), res.get("proxyId"));161 }162 @Test163 public void testSessionGet() throws IOException {164 ExternalSessionKey s = session.getExternalKey();165 String url =166 testSessionApi.toExternalForm() + "?session=" + URLEncoder.encode(s.getKey(), "UTF-8");167 HttpRequest r = new HttpRequest(GET, url);168 HttpResponse response = client.execute(r);169 assertEquals(200, response.getStatus());170 Map<String, Object> o = extractObject(response);171 assertTrue((boolean) o.get("success"));172 assertNotNull(o.get("internalKey"));173 assertEquals(s, ExternalSessionKey.fromJSON((String) o.get("session")));174 assertNotNull(o.get("inactivityTime"));175 assertEquals(p1.getId(), o.get("proxyId"));176 }177 /**178 * if a certain set of parameters are requested to the hub, only those params are returned.179 */180 @Test181 public void testHubGetSpecifiedConfig() throws IOException {182 String url = hubApi.toExternalForm();183 HttpRequest r = new HttpRequest(POST, url);184 Map<String, Object> j = ImmutableMap.of(185 "configuration", ImmutableList.of(186 "timeout",187 "I'm not a valid key",188 "servlets"));189 r.setContent(new Json().toJson(j).getBytes(UTF_8));190 HttpResponse response = client.execute(r);191 assertEquals(200, response.getStatus());192 Map<String, Object> o = extractObject(response);193 assertTrue((Boolean) o.get("success"));194 assertEquals(12345L, o.get("timeout"));195 assertNull(o.get("I'm not a valid key"));196 assertTrue(((Collection) o.get("servlets")).size() == 0);197 assertNull(o.get("capabilityMatcher"));198 }199 /**200 * if a certain set of parameters are requested to the hub, only those params are returned.201 */202 @Test203 public void testHubGetSpecifiedConfigWithQueryString() throws IOException {204 List<String> keys = new ArrayList<>();205 keys.add(URLEncoder.encode("timeout", "UTF-8"));206 keys.add(URLEncoder.encode("I'm not a valid key", "UTF-8"));207 keys.add(URLEncoder.encode("servlets", "UTF-8"));208 String query = "?configuration=" + String.join(",",keys);209 String url = hubApi.toExternalForm() + query ;210 HttpRequest r = new HttpRequest(GET, url);211 HttpResponse response = client.execute(r);212 assertEquals(200, response.getStatus());213 Map<String, Object> o = extractObject(response);214 assertTrue((Boolean) o.get("success"));215 assertEquals(12345L, o.get("timeout"));216 assertNull(o.get("I'm not a valid key"));217 assertTrue(((Collection<?>) o.get("servlets")).size() == 0);218 assertFalse(o.containsKey("capabilityMatcher"));219 }220 /**221 * when no param is specified, a call to the hub API returns all the config params the hub222 * currently uses.223 */224 @Test225 public void testHubGetAllConfig() throws IOException {226 String url = hubApi.toExternalForm();227 HttpRequest r = new HttpRequest(GET, url);228 Map<String, Object> j = ImmutableMap.of("configuration", ImmutableList.of());229 r.setContent(new Json().toJson(j).getBytes(UTF_8));230 HttpResponse response = client.execute(r);231 assertEquals(200, response.getStatus());232 Map<String, Object> o = extractObject(response);233 assertTrue((boolean) o.get("success"));234 assertEquals("org.openqa.grid.internal.utils.DefaultCapabilityMatcher",235 o.get("capabilityMatcher"));236 assertNull(o.get("prioritizer"));237 }238 @Test239 public void testHubGetAllConfigNoParamsWhenNoPostBody() throws IOException {240 String url = hubApi.toExternalForm();241 HttpRequest r = new HttpRequest(GET, url);242 HttpResponse response = client.execute(r);243 assertEquals(200, response.getStatus());244 Map<String, Object> o = extractObject(response);245 assertTrue((Boolean) o.get("success"));246 assertEquals("org.openqa.grid.internal.utils.DefaultCapabilityMatcher",247 o.get("capabilityMatcher"));248 assertNull(o.get("prioritizer"));249 }250 @Test251 public void testHubGetNewSessionRequestCount() throws IOException {252 String url = hubApi.toExternalForm();253 HttpRequest r = new HttpRequest(GET, url);254 Map<String, Object> j = ImmutableMap.of(255 "configuration", ImmutableList.of("newSessionRequestCount"));256 r.setContent(new Json().toJson(j).getBytes(UTF_8));257 HttpResponse response = client.execute(r);258 assertEquals(200, response.getStatus());259 Map<String, Object> o = extractObject(response);260 assertTrue((Boolean) o.get("success"));261 assertEquals(0L, o.get("newSessionRequestCount"));262 }263 @Test264 public void testHubGetSlotCounts() throws IOException {265 String url = hubApi.toExternalForm();266 HttpRequest r = new HttpRequest(POST, url);267 Map<String, Object> j = ImmutableMap.of("configuration", ImmutableList.of("slotCounts"));268 r.setContent(new Json().toJson(j).getBytes(UTF_8));269 HttpResponse response = client.execute(r);270 assertEquals(200, response.getStatus());271 Map<String, Object> o = extractObject(response);272 assertTrue((Boolean) o.get("success"));273 assertNotNull(o.get("slotCounts"));274 Map<?, ?> slotCounts = (Map<?, ?>) o.get("slotCounts");275 assertEquals(4L, slotCounts.get("free"));276 assertEquals(5L, slotCounts.get("total"));277 }278 @Test279 public void testSessionApiNeg() throws IOException {280 String s = "non-existing session";281 Map<String, Object> o = ImmutableMap.of("session", s);282 HttpRequest r = new HttpRequest(POST, testSessionApi.toExternalForm());283 r.setContent(new Json().toJson(o).getBytes(UTF_8));284 HttpResponse response = client.execute(r);285 assertEquals(200, response.getStatus());286 Map<String, Object> res = extractObject(response);287 assertFalse((boolean) res.get("success"));288 }289 @After290 public void teardown() {291 hub.stop();292 }293 private Map<String, Object> extractObject(HttpResponse resp) {294 return new Json().toType(resp.getContentString(), MAP_TYPE);295 }296}...

Full Screen

Full Screen

Source:NetworkCaptureTest.java Github

copy

Full Screen

...34 List<LogEntry> entries = driver.manage().logs().get(LogType.PERFORMANCE).getAll();35 System.out.println(entries.size() + " " + LogType.PERFORMANCE + " log entries found");36 for (LogEntry entry : entries)37 {38 System.out.println(entry.toJson());39 System.out.println("---------------------------");40 // System.out.println(entry.getMessage());41 }42 }43 @Test44 public void bMP() throws Exception {45 //Proxy Operations46 WebDriverManager.chromedriver().setup();47 BrowserMobProxy proxy = new BrowserMobProxyServer();48 proxy.start(); // can specify a port here if you like49 // get the selenium proxy object50 Proxy seleniumProxy = ClientUtil.createSeleniumProxy(proxy);51 DesiredCapabilities capabilities = new DesiredCapabilities();52 capabilities.setCapability(CapabilityType.PROXY, seleniumProxy);...

Full Screen

Full Screen

Source:IECapabilityProcessorTest.java Github

copy

Full Screen

...42 @Test43 public void testJsonMarshalling() throws Exception {44 JsonMessage message = buildJsonMessage(internetExplorer());45 processor.process(message.getDesiredCapabilities());46 String proxyType = (String) new JSONObject(message.toJson())47 .getJSONObject("desiredCapabilities")48 .getJSONObject("proxy")49 .get("proxyType");50 assertThat(proxyType, is(equalTo(DIRECT.name())));51 }52 @Test53 public void testExistingProxyIsNotOverridden() throws Exception {54 DesiredCapabilities caps = internetExplorer();55 org.openqa.selenium.Proxy proxy = new org.openqa.selenium.Proxy();56 proxy.setHttpProxy(PROXY);57 caps.setCapability(PROXY, proxy);58 JsonCapabilities capabilities = buildJsonCapabilities(caps);59 processor.process(capabilities);60 assertThat(capabilities.any().get(PROXY), not(instanceOf(Proxy.class)));...

Full Screen

Full Screen

Source:ChromeOpenSiteTest.java Github

copy

Full Screen

...27// proxy.setAutodetect(false);28 options.setProxy(proxy);29 options.setHeadless(true);30 driver = new ChromeDriver(options);31 System.out.println(new Gson().toJson(driver.getCapabilities().asMap()));32 }33 @After34 public void testAfter() {35 driver.quit();36 }37 @Test38 public void openSite() {39 driver.get("https://www.microsoft.fr");40 WebDriverWait wait = new WebDriverWait(driver, 5000);41 wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("primaryArea")));42 Assert.assertNotNull(driver.findElement(By.id("primaryArea")));43 }44}...

Full Screen

Full Screen

Source:FirefoxOpenSiteTest.java Github

copy

Full Screen

...25// proxy.setAutodetect(false);26 options.setProxy(proxy);27 options.setHeadless(true);28 driver = new FirefoxDriver(options);29 System.out.println(new Gson().toJson(driver.getCapabilities().asMap()));30 }31 @After32 public void testAfter() {33 driver.quit();34 }35 @Test36 public void openSite() {37 driver.get("https://www.microsoft.fr");38 WebDriverWait wait = new WebDriverWait(driver, 5000);39 wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("primaryArea")));40 Assert.assertNotNull(driver.findElement(By.id("primaryArea")));41 }42}...

Full Screen

Full Screen

toJson

Using AI Code Generation

copy

Full Screen

1package com.selenium2.easy.test.server.proxy;2import java.net.MalformedURLException;3import java.net.URL;4import java.util.HashMap;5import java.util.Map;6import org.openqa.selenium.Proxy;7import org.openqa.selenium.WebDriver;8import org.openqa.selenium.chrome.ChromeDriver;9import org.openqa.selenium.chrome.ChromeOptions;10import org.openqa.selenium.remote.CapabilityType;11import org.openqa.selenium.remote.DesiredCapabilities;

Full Screen

Full Screen

toJson

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.Proxy2import org.openqa.selenium.WebDriver3import org.openqa.selenium.chrome.ChromeDriver4import org.openqa.selenium.chrome.ChromeOptions5import java.nio.file.Files6import java.nio.file.Paths7def proxy = new Proxy()8proxy.setHttpProxy(proxyString).setFtpProxy(proxyString).setSslProxy(proxyString)9def options = new ChromeOptions()10options.setProxy(proxy)11WebDriver driver = new ChromeDriver(options)12driver.quit()13import org.openqa.selenium.Proxy14import org.openqa.selenium.WebDriver15import org.openqa.selenium.chrome.ChromeDriver16import org.openqa.selenium.chrome.ChromeOptions17import java.nio.file.Files18import java.nio.file.Paths19def proxy = new Proxy()20proxy.setHttpProxy(proxyString).setFtpProxy(proxyString).setSslProxy(proxyString)21def options = new ChromeOptions()22options.setProxy(proxy)23WebDriver driver = new ChromeDriver(options)24driver.quit()25import org.openqa.selenium.Proxy26import org.openqa.selenium.WebDriver27import org.openqa.selenium.chrome.ChromeDriver28import org.openqa.selenium.chrome.ChromeOptions29import java.nio.file.Files30import java.nio.file.Paths31def proxy = new Proxy()32proxy.setHttpProxy(proxyString).setFtpProxy(proxyString).setSslProxy(proxyString)33def options = new ChromeOptions()34options.setProxy(proxy)35WebDriver driver = new ChromeDriver(options)36driver.quit()37import org.openqa.selenium.Proxy38import org.openqa.selenium.WebDriver39import org.openqa.selenium.chrome.ChromeDriver40import org.openqa.selenium.chrome.ChromeOptions41import java.nio.file.Files42import java.nio.file.Paths43def proxy = new Proxy()44proxy.setHttpProxy(proxyString).setFtpProxy(proxyString).setSslProxy(proxyString)45def options = new ChromeOptions()46options.setProxy(proxy)47WebDriver driver = new ChromeDriver(options)48driver.quit()49import org

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful