How to use values method of org.openqa.selenium.Enum Proxy.ProxyType class

Best Selenium code snippet using org.openqa.selenium.Enum Proxy.ProxyType.values

Source:JsonTest.java Github

copy

Full Screen

1// Licensed to the Software Freedom Conservancy (SFC) under one2// or more contributor license agreements. See the NOTICE file3// distributed with this work for additional information4// regarding copyright ownership. The SFC licenses this file5// to you under the Apache License, Version 2.0 (the6// "License"); you may not use this file except in compliance7// with the License. You may obtain a copy of the License at8//9// http://www.apache.org/licenses/LICENSE-2.010//11// Unless required by applicable law or agreed to in writing,12// software distributed under the License is distributed on an13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14// KIND, either express or implied. See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.json;18import static java.util.logging.Level.ALL;19import static java.util.logging.Level.FINE;20import static java.util.logging.Level.OFF;21import static java.util.logging.Level.WARNING;22import static org.assertj.core.api.Assertions.assertThat;23import static org.assertj.core.api.Assertions.byLessThan;24import static org.openqa.selenium.Proxy.ProxyType.PAC;25import static org.openqa.selenium.json.Json.MAP_TYPE;26import static org.openqa.selenium.logging.LogType.BROWSER;27import static org.openqa.selenium.logging.LogType.CLIENT;28import static org.openqa.selenium.logging.LogType.DRIVER;29import static org.openqa.selenium.logging.LogType.SERVER;30import com.google.common.collect.ImmutableList;31import com.google.common.collect.ImmutableMap;32import com.google.common.reflect.TypeToken;33import org.junit.Test;34import org.openqa.selenium.Capabilities;35import org.openqa.selenium.Cookie;36import org.openqa.selenium.ImmutableCapabilities;37import org.openqa.selenium.MutableCapabilities;38import org.openqa.selenium.Platform;39import org.openqa.selenium.Proxy;40import org.openqa.selenium.logging.LoggingPreferences;41import org.openqa.selenium.remote.CapabilityType;42import org.openqa.selenium.remote.Command;43import org.openqa.selenium.remote.DesiredCapabilities;44import org.openqa.selenium.remote.DriverCommand;45import org.openqa.selenium.remote.ErrorCodes;46import org.openqa.selenium.remote.Response;47import org.openqa.selenium.remote.SessionId;48import java.io.StringReader;49import java.util.Collections;50import java.util.Date;51import java.util.List;52import java.util.Map;53import java.util.concurrent.TimeUnit;54public class JsonTest {55 @Test56 public void canReadBooleans() {57 assertThat((Boolean) new Json().toType("true", Boolean.class)).isTrue();58 assertThat((Boolean) new Json().toType("false", Boolean.class)).isFalse();59 }60 @Test61 public void canReadANumber() {62 assertThat((Number) new Json().toType("42", Number.class)).isEqualTo(Long.valueOf(42));63 assertThat((Integer) new Json().toType("42", Integer.class)).isEqualTo(Integer.valueOf(42));64 assertThat((Double) new Json().toType("42", Double.class)).isEqualTo(Double.valueOf(42));65 }66 @Test67 public void canRoundTripNumbers() {68 Map<String, Object> original = ImmutableMap.of(69 "options", ImmutableMap.of("args", ImmutableList.of(1L, "hello")));70 Json json = new Json();71 String converted = json.toJson(original);72 Object remade = json.toType(converted, MAP_TYPE);73 assertThat(remade).isEqualTo(original);74 }75 @Test76 public void roundTripAFirefoxOptions() {77 Map<String, Object> caps = ImmutableMap.of(78 "moz:firefoxOptions", ImmutableMap.of(79 "prefs", ImmutableMap.of("foo.bar", 1)));80 String json = new Json().toJson(caps);81 assertThat(json).doesNotContain("1.0");82 try (JsonInput input = new Json().newInput(new StringReader(json))) {83 json = new Json().toJson(input.read(Json.MAP_TYPE));84 assertThat(json).doesNotContain("1.0");85 }86 }87 @Test88 public void shouldCoerceAListOfCapabilitiesIntoSomethingMutable() {89 // This is needed since Grid expects each of the capabilities to be mutable90 List<Capabilities> expected = ImmutableList.of(91 new ImmutableCapabilities("cheese", "brie"),92 new ImmutableCapabilities("peas", 42L));93 Json json = new Json();94 String raw = json.toJson(expected);95 List<Capabilities> seen = json.toType(raw, new TypeToken<List<Capabilities>>(){}.getType());96 assertThat(seen).isEqualTo(expected);97 assertThat(seen.get(0)).isInstanceOf(MutableCapabilities.class);98 }99 @Test100 public void shouldUseBeanSettersToPopulateFields() {101 Map<String, String> map = ImmutableMap.of("name", "fishy");102 Json json = new Json();103 String raw = json.toJson(map);104 BeanWithSetter seen = json.toType(raw, BeanWithSetter.class);105 assertThat(seen.theName).isEqualTo("fishy");106 }107 public static class BeanWithSetter {108 String theName;109 public void setName(String name) {110 theName = name;111 }112 }113 @Test114 public void shouldAllowUserToPopulateFieldsDirectly() {115 Map<String, String> map = ImmutableMap.of("theName", "fishy");116 Json json = new Json();117 String raw = json.toJson(map);118 BeanWithSetter seen = json.toType(raw, BeanWithSetter.class, PropertySetting.BY_FIELD);119 assertThat(seen.theName).isEqualTo("fishy");120 }121 @Test122 public void settingFinalFieldsShouldWork() {123 Map<String, String> map = ImmutableMap.of("theName", "fishy");124 Json json = new Json();125 String raw = json.toJson(map);126 BeanWithFinalField seen = json.toType(raw, BeanWithFinalField.class, PropertySetting.BY_FIELD);127 assertThat(seen.theName).isEqualTo("fishy");128 }129 public static class BeanWithFinalField {130 private final String theName;131 public BeanWithFinalField() {132 this.theName = "magic";133 }134 }135 @Test136 public void canConstructASimpleString() {137 String text = new Json().toType("\"cheese\"", String.class);138 assertThat(text).isEqualTo("cheese");139 }140 @Test141 public void canPopulateAMap() {142 String raw = "{\"cheese\": \"brie\", \"foodstuff\": \"cheese\"}";143 Map<String, String> map = new Json().toType(raw, Map.class);144 assertThat(map)145 .hasSize(2)146 .containsEntry("cheese", "brie")147 .containsEntry("foodstuff", "cheese");148 }149 @Test150 public void canPopulateAMapThatContainsNull() {151 String raw = "{\"foo\": null}";152 Map<?,?> converted = new Json().toType(raw, Map.class);153 assertThat(converted.size()).isEqualTo(1);154 assertThat(converted.containsKey("foo")).isTrue();155 assertThat(converted.get("foo")).isNull();156 }157 @Test158 public void canPopulateASimpleBean() {159 String raw = "{\"value\": \"time\"}";160 SimpleBean bean = new Json().toType(raw, SimpleBean.class);161 assertThat(bean.getValue()).isEqualTo("time");162 }163 @Test164 public void willSilentlyDiscardUnusedFieldsWhenPopulatingABean() {165 String raw = "{\"value\": \"time\", \"frob\": \"telephone\"}";166 SimpleBean bean = new Json().toType(raw, SimpleBean.class);167 assertThat(bean.getValue()).isEqualTo("time");168 }169 @Test170 public void shouldSetPrimitiveValuesToo() {171 String raw = "{\"magicNumber\": 3}";172 Map<?,?> map = new Json().toType(raw, Map.class);173 assertThat(map.get("magicNumber")).isEqualTo(3L);174 }175 @Test176 public void shouldPopulateFieldsOnNestedBeans() {177 String raw = "{\"name\": \"frank\", \"bean\": {\"value\": \"lots\"}}";178 ContainingBean bean = new Json().toType(raw, ContainingBean.class);179 assertThat(bean.getName()).isEqualTo("frank");180 assertThat(bean.getBean().getValue()).isEqualTo("lots");181 }182 @Test183 public void shouldProperlyFillInACapabilitiesObject() {184 DesiredCapabilities capabilities =185 new DesiredCapabilities("browser", CapabilityType.VERSION, Platform.ANY);186 capabilities.setJavascriptEnabled(true);187 String text = new Json().toJson(capabilities);188 Capabilities readCapabilities = new Json().toType(text, DesiredCapabilities.class);189 assertThat(readCapabilities).isEqualTo(capabilities);190 }191 @Test192 public void shouldUseAMapToRepresentComplexObjects() {193 String toModel = "{\"thing\": \"hairy\", \"hairy\": true}";194 Map<?,?> modelled = new Json().toType(toModel, Object.class);195 assertThat(modelled).hasSize(2);196 }197 @Test198 public void shouldConvertAResponseWithAnElementInIt() {199 String json =200 "{\"value\":{\"value\":\"\",\"text\":\"\",\"selected\":false,\"enabled\":true,\"id\":\"three\"},\"context\":\"con\",\"sessionId\":\"sess\"}";201 Response converted = new Json().toType(json, Response.class);202 Map<String, Object> value = (Map<String, Object>) converted.getValue();203 assertThat(value).containsEntry("id", "three");204 }205 @Test206 public void shouldBeAbleToCopeWithStringsThatLookLikeBooleans() {207 String json = "{\"value\":\"false\",\"context\":\"foo\",\"sessionId\":\"1210083863107\"}";208 new Json().toType(json, Response.class);209 }210 @Test211 public void shouldBeAbleToSetAnObjectToABoolean() {212 String json = "{\"value\":true,\"context\":\"foo\",\"sessionId\":\"1210084658750\"}";213 Response response = new Json().toType(json, Response.class);214 assertThat(response.getValue()).isEqualTo(true);215 }216 @Test217 public void canHandleValueBeingAnArray() {218 String[] value = {"Cheese", "Peas"};219 Response response = new Response();220 response.setSessionId("bar");221 response.setValue(value);222 response.setStatus(1512);223 String json = new Json().toJson(response);224 Response converted = new Json().toType(json, Response.class);225 assertThat(response.getSessionId()).isEqualTo("bar");226 assertThat(((List<?>) converted.getValue())).hasSize(2);227 assertThat(response.getStatus().intValue()).isEqualTo(1512);228 }229 @Test230 public void shouldConvertObjectsInArraysToMaps() {231 Date date = new Date();232 Cookie cookie = new Cookie("foo", "bar", "localhost", "/rooted", date, true, true);233 String rawJson = new Json().toJson(Collections.singletonList(cookie));234 List<?> list = new Json().toType(rawJson, List.class);235 Object first = list.get(0);236 assertThat(first instanceof Map).isTrue();237 Map<String, Object> map = (Map<String, Object>) first;238 assertThat(map)239 .containsEntry("name", "foo")240 .containsEntry("value", "bar")241 .containsEntry("domain", "localhost")242 .containsEntry("path", "/rooted")243 .containsEntry("secure", true)244 .containsEntry("httpOnly", true)245 .containsEntry("expiry", TimeUnit.MILLISECONDS.toSeconds(date.getTime()));246 }247 @Test248 public void shouldConvertAnArrayBackIntoAnArray() {249 Exception e = new Exception();250 String converted = new Json().toJson(e);251 Map<?,?> reconstructed = new Json().toType(converted, Map.class);252 List<?> trace = (List<?>) reconstructed.get("stackTrace");253 assertThat(trace.get(0)).isInstanceOf(Map.class);254 }255 @Test256 public void sShouldBeAbleToReconsituteASessionId() {257 String json = new Json().toJson(new SessionId("id"));258 SessionId sessionId = new Json().toType(json, SessionId.class);259 assertThat(sessionId.toString()).isEqualTo("id");260 }261 @Test262 public void shouldBeAbleToConvertACommand() {263 SessionId sessionId = new SessionId("session id");264 Command original = new Command(265 sessionId,266 DriverCommand.NEW_SESSION,267 ImmutableMap.of("food", "cheese"));268 String raw = new Json().toJson(original);269 Command converted = new Json().toType(raw, Command.class);270 assertThat(converted.getSessionId().toString()).isEqualTo(sessionId.toString());271 assertThat(converted.getName()).isEqualTo(original.getName());272 assertThat(converted.getParameters().keySet()).hasSize(1);273 assertThat(converted.getParameters().get("food")).isEqualTo("cheese");274 }275 @Test276 public void shouldConvertCapabilitiesToAMapAndIncludeCustomValues() {277 Capabilities caps = new ImmutableCapabilities("furrfu", "fishy");278 String raw = new Json().toJson(caps);279 Capabilities converted = new Json().toType(raw, Capabilities.class);280 assertThat(converted.getCapability("furrfu")).isEqualTo("fishy");281 }282 @Test283 public void shouldParseCapabilitiesWithLoggingPreferences() {284 String caps = String.format(285 "{\"%s\": {" +286 "\"browser\": \"WARNING\"," +287 "\"client\": \"DEBUG\", " +288 "\"driver\": \"ALL\", " +289 "\"server\": \"OFF\"}}",290 CapabilityType.LOGGING_PREFS);291 Capabilities converted = new Json().toType(caps, Capabilities.class);292 LoggingPreferences lp =293 (LoggingPreferences) converted.getCapability(CapabilityType.LOGGING_PREFS);294 assertThat(lp).isNotNull();295 assertThat(lp.getLevel(BROWSER)).isEqualTo(WARNING);296 assertThat(lp.getLevel(CLIENT)).isEqualTo(FINE);297 assertThat(lp.getLevel(DRIVER)).isEqualTo(ALL);298 assertThat(lp.getLevel(SERVER)).isEqualTo(OFF);299 }300 @Test301 public void shouldNotParseQuotedJsonObjectsAsActualJsonObjects() {302 String jsonStr = "{\"inner\":\"{\\\"color\\\":\\\"green\\\",\\\"number\\\":123}\"}";303 System.out.println(jsonStr);304 Object convertedOuter = new Json().toType(jsonStr, Map.class);305 assertThat(convertedOuter).isInstanceOf(Map.class);306 Object convertedInner = ((Map<?,?>) convertedOuter).get("inner");307 assertThat(convertedInner).isNotNull();308 assertThat(convertedInner).isInstanceOf(String.class);309 assertThat(convertedInner.toString()).isEqualTo("{\"color\":\"green\",\"number\":123}");310 }311 @Test312 public void shouldBeAbleToConvertASelenium3CommandToASelenium2Command() {313 SessionId expectedId = new SessionId("thisisakey");314 // In selenium 2, the sessionId is an object. In selenium 3, it's a straight string.315 String raw = "{\"sessionId\": \"" + expectedId.toString() + "\", " +316 "\"name\": \"some command\"," +317 "\"parameters\": {}}";318 Command converted = new Json().toType(raw, Command.class);319 assertThat(converted.getSessionId()).isEqualTo(expectedId);320 }321 @Test322 public void shouldCallFromJsonMethodIfPresent() {323 JsonAware res = new Json().toType("\"converted\"", JsonAware.class);324 assertThat(res.convertedValue).isEqualTo("converted");325 }326 @Test327 public void fromJsonMethodNeedNotBePublic() {328 JsonAware res = new Json().toType("\"converted\"", PrivatelyAware.class);329 assertThat(res.convertedValue).isEqualTo("converted");330 }331 @Test332 public void fromJsonMethodNeedNotOnlyAcceptAString() {333 Json json = new Json();334 String raw = json.toJson(ImmutableMap.of("cheese", "truffled brie"));335 MapTakingFromJsonMethod res = json.toType(raw, MapTakingFromJsonMethod.class);336 assertThat(res.cheese).isEqualTo("truffled brie");337 }338 // Test for issue 8187339 @Test340 public void decodingResponseWithNumbersInValueObject() {341 Response response = new Json().toType(342 "{\"status\":0,\"value\":{\"width\":96,\"height\":46.19140625}}",343 Response.class);344 @SuppressWarnings("unchecked")345 Map<String, Number> value = (Map<String, Number>) response.getValue();346 assertThat(value.get("width").intValue()).isEqualTo(96);347 assertThat(value.get("height").intValue()).isEqualTo(46);348 assertThat(value.get("height").doubleValue()).isCloseTo(46.19140625, byLessThan(0.00001));349 }350 @Test351 public void shouldRecognizeNumericStatus() {352 Response response = new Json().toType(353 "{\"status\":0,\"value\":\"cheese\"}",354 Response.class);355 assertThat(response.getStatus().intValue()).isEqualTo(0);356 assertThat(response.getState()).isEqualTo(new ErrorCodes().toState(0));357 String value = (String) response.getValue();358 assertThat(value).isEqualTo("cheese");359 }360 @Test361 public void shouldRecognizeStringStatus() {362 Response response = new Json().toType(363 "{\"status\":\"success\",\"value\":\"cheese\"}",364 Response.class);365 assertThat(response.getStatus().intValue()).isEqualTo(0);366 assertThat(response.getState()).isEqualTo(new ErrorCodes().toState(0));367 String value = (String) response.getValue();368 assertThat(value).isEqualTo("cheese");369 }370 @Test371 public void shouldConvertInvalidSelectorError() {372 Response response = new Json().toType(373 "{\"state\":\"invalid selector\",\"message\":\"invalid xpath selector\"}",374 Response.class);375 assertThat(response.getStatus().intValue()).isEqualTo(32);376 assertThat(response.getState()).isEqualTo(new ErrorCodes().toState(32));377 }378 @Test379 public void shouldRecognizeStringState() {380 Response response = new Json()381 .toType(382 "{\"state\":\"success\",\"value\":\"cheese\"}",383 Response.class);384 assertThat(response.getState()).isEqualTo("success");385 assertThat(response.getStatus().intValue()).isEqualTo(0);386 String value = (String) response.getValue();387 assertThat(value).isEqualTo("cheese");388 }389 @Test390 public void noStatusShouldBeNullInResponseObject() {391 Response response = new Json().toType("{\"value\":\"cheese\"}", Response.class);392 assertThat(response.getStatus()).isNull();393 }394 @Test395 public void canConvertAnEnumWithALowerCaseValue() {396 Proxy.ProxyType type = new Json().toType("\"pac\"", Proxy.ProxyType.class);397 assertThat(type).isEqualTo(PAC);398 }399 @Test400 public void canCoerceSimpleValuesToStrings() {401 Map<String, Object> value = ImmutableMap.of(402 "boolean", true,403 "integer", 42,404 "float", 3.14);405 Json json = new Json();406 String raw = json.toJson(value);407 Map<String, String> roundTripped = json.toType(408 raw,409 new TypeToken<Map<String, String>>(){}.getType());410 assertThat(roundTripped.get("boolean")).isEqualTo("true");411 assertThat(roundTripped.get("integer")).isEqualTo("42");412 assertThat(roundTripped.get("float")).isEqualTo("3.14");413 }414 public static class SimpleBean {415 private String value;416 public String getValue() {417 return value;418 }419 public void setValue(String value) {420 this.value = value;421 }422 }423 public static class ContainingBean {424 private String name;425 private SimpleBean bean;426 public String getName() {427 return name;428 }429 public void setName(String name) {430 this.name = name;431 }432 public SimpleBean getBean() {433 return bean;434 }435 public void setBean(SimpleBean bean) {436 this.bean = bean;437 }438 }439 public static class JsonAware {440 private String convertedValue;441 public JsonAware(String convertedValue) {442 this.convertedValue = convertedValue;443 }444 public static JsonAware fromJson(String json) {445 return new JsonAware(json);446 }447 }448 public static class PrivatelyAware {449 private String convertedValue;450 public PrivatelyAware(String convertedValue) {451 this.convertedValue = convertedValue;452 }453 private static JsonAware fromJson(String json) {454 return new JsonAware(json);455 }456 }457 public static class MapTakingFromJsonMethod {458 private String cheese;459 private static MapTakingFromJsonMethod fromJson(Map<String, Object> args) {460 MapTakingFromJsonMethod toReturn = new MapTakingFromJsonMethod();461 toReturn.cheese = String.valueOf(args.get("cheese"));462 return toReturn;463 }464 }465}...

Full Screen

Full Screen

Source:JsonToBeanConverterTest.java Github

copy

Full Screen

1// Licensed to the Software Freedom Conservancy (SFC) under one2// or more contributor license agreements. See the NOTICE file3// distributed with this work for additional information4// regarding copyright ownership. The SFC licenses this file5// to you under the Apache License, Version 2.0 (the6// "License"); you may not use this file except in compliance7// with the License. You may obtain a copy of the License at8//9// http://www.apache.org/licenses/LICENSE-2.010//11// Unless required by applicable law or agreed to in writing,12// software distributed under the License is distributed on an13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY14// KIND, either express or implied. See the License for the15// specific language governing permissions and limitations16// under the License.17package org.openqa.selenium.json;18import static org.hamcrest.Matchers.equalTo;19import static org.hamcrest.Matchers.hasEntry;20import static org.hamcrest.Matchers.instanceOf;21import static org.hamcrest.Matchers.is;22import static org.junit.Assert.assertEquals;23import static org.junit.Assert.assertFalse;24import static org.junit.Assert.assertNotNull;25import static org.junit.Assert.assertNull;26import static org.junit.Assert.assertThat;27import static org.junit.Assert.assertTrue;28import static org.junit.Assert.fail;29import com.google.gson.JsonArray;30import com.google.gson.JsonNull;31import com.google.gson.JsonObject;32import com.google.gson.JsonPrimitive;33import org.junit.Assert;34import org.junit.Test;35import org.junit.runner.RunWith;36import org.junit.runners.JUnit4;37import org.openqa.selenium.Capabilities;38import org.openqa.selenium.Cookie;39import org.openqa.selenium.ImmutableCapabilities;40import org.openqa.selenium.Platform;41import org.openqa.selenium.Proxy;42import org.openqa.selenium.logging.LogType;43import org.openqa.selenium.logging.LoggingPreferences;44import org.openqa.selenium.remote.CapabilityType;45import org.openqa.selenium.remote.Command;46import org.openqa.selenium.remote.DesiredCapabilities;47import org.openqa.selenium.remote.DriverCommand;48import org.openqa.selenium.remote.ErrorCodes;49import org.openqa.selenium.remote.Response;50import org.openqa.selenium.remote.SessionId;51import java.util.Collections;52import java.util.Date;53import java.util.HashMap;54import java.util.List;55import java.util.Map;56import java.util.concurrent.TimeUnit;57import java.util.logging.Level;58@RunWith(JUnit4.class)59public class JsonToBeanConverterTest {60 @Test61 public void testCanConstructASimpleString() throws Exception {62 String text = new JsonToBeanConverter().convert(String.class, "cheese");63 assertThat(text, is("cheese"));64 }65 @SuppressWarnings("unchecked")66 @Test67 public void testCanPopulateAMap() throws Exception {68 JsonObject toConvert = new JsonObject();69 toConvert.addProperty("cheese", "brie");70 toConvert.addProperty("foodstuff", "cheese");71 Map<String, String> map = new JsonToBeanConverter().convert(Map.class, toConvert.toString());72 assertThat(map.size(), is(2));73 assertThat(map, hasEntry("cheese", "brie"));74 assertThat(map, hasEntry("foodstuff", "cheese"));75 }76 @Test77 public void testCanPopulateAMapThatContainsNull() throws Exception {78 JsonObject toConvert = new JsonObject();79 toConvert.add("foo", JsonNull.INSTANCE);80 Map<?,?> converted = new JsonToBeanConverter().convert(Map.class, toConvert.toString());81 assertEquals(1, converted.size());82 assertTrue(converted.containsKey("foo"));83 assertNull(converted.get("foo"));84 }85 @Test86 public void testCanPopulateASimpleBean() throws Exception {87 JsonObject toConvert = new JsonObject();88 toConvert.addProperty("value", "time");89 SimpleBean bean = new JsonToBeanConverter().convert(SimpleBean.class, toConvert.toString());90 assertThat(bean.getValue(), is("time"));91 }92 @Test93 public void testWillSilentlyDiscardUnusedFieldsWhenPopulatingABean() throws Exception {94 JsonObject toConvert = new JsonObject();95 toConvert.addProperty("value", "time");96 toConvert.addProperty("frob", "telephone");97 SimpleBean bean = new JsonToBeanConverter().convert(SimpleBean.class, toConvert.toString());98 assertThat(bean.getValue(), is("time"));99 }100 @Test101 public void testShouldSetPrimitiveValuesToo() throws Exception {102 JsonObject toConvert = new JsonObject();103 toConvert.addProperty("magicNumber", 3);104 Map<?,?> map = new JsonToBeanConverter().convert(Map.class, toConvert.toString());105 assertEquals(3L, map.get("magicNumber"));106 }107 @Test108 public void testShouldPopulateFieldsOnNestedBeans() throws Exception {109 JsonObject toConvert = new JsonObject();110 toConvert.addProperty("name", "frank");111 JsonObject child = new JsonObject();112 child.addProperty("value", "lots");113 toConvert.add("bean", child);114 ContainingBean bean =115 new JsonToBeanConverter().convert(ContainingBean.class, toConvert.toString());116 assertThat(bean.getName(), is("frank"));117 assertThat(bean.getBean().getValue(), is("lots"));118 }119 @Test120 public void testShouldProperlyFillInACapabilitiesObject() throws Exception {121 DesiredCapabilities capabilities =122 new DesiredCapabilities("browser", CapabilityType.VERSION, Platform.ANY);123 capabilities.setJavascriptEnabled(true);124 String text = new BeanToJsonConverter().convert(capabilities);125 Capabilities readCapabilities =126 new JsonToBeanConverter().convert(DesiredCapabilities.class, text);127 assertEquals(capabilities, readCapabilities);128 }129 @Test130 public void testShouldBeAbleToInstantiateBooleans() throws Exception {131 JsonArray array = new JsonArray();132 array.add(new JsonPrimitive(true));133 array.add(new JsonPrimitive(false));134 boolean first = new JsonToBeanConverter().convert(Boolean.class, array.get(0));135 boolean second = new JsonToBeanConverter().convert(Boolean.class, array.get(1));136 assertTrue(first);137 assertFalse(second);138 }139 @Test140 public void testShouldUseAMapToRepresentComplexObjects() throws Exception {141 JsonObject toModel = new JsonObject();142 toModel.addProperty("thing", "hairy");143 toModel.addProperty("hairy", "true");144 Map<?,?> modelled = (Map<?,?>) new JsonToBeanConverter().convert(145 Object.class,146 toModel.toString());147 assertEquals(2, modelled.size());148 }149 @Test150 public void testShouldConvertAResponseWithAnElementInIt() throws Exception {151 String json =152 "{\"value\":{\"value\":\"\",\"text\":\"\",\"selected\":false,\"enabled\":true,\"id\":\"three\"},\"context\":\"con\",\"sessionId\":\"sess\"}";153 Response154 converted = new JsonToBeanConverter().convert(Response.class, json);155 Map<?,?> value = (Map<?,?>) converted.getValue();156 assertEquals("three", value.get("id"));157 }158 @Test159 public void testConvertABlankStringAsAStringEvenWhenAskedToReturnAnObject() throws Exception {160 Object o = new JsonToBeanConverter().convert(Object.class, "");161 assertTrue(o instanceof String);162 }163 @Test164 public void testShouldBeAbleToCopeWithStringsThatLookLikeBooleans() throws Exception {165 String json =166 "{\"value\":\"false\",\"context\":\"foo\",\"sessionId\":\"1210083863107\"}";167 try {168 new JsonToBeanConverter().convert(Response.class, json);169 } catch (Exception e) {170 e.printStackTrace();171 fail("This should have worked");172 }173 }174 @Test175 public void testShouldBeAbleToSetAnObjectToABoolean() throws Exception {176 String json =177 "{\"value\":true,\"context\":\"foo\",\"sessionId\":\"1210084658750\"}";178 Response response = new JsonToBeanConverter().convert(Response.class, json);179 assertThat((Boolean) response.getValue(), is(true));180 }181 @Test182 public void testCanHandleValueBeingAnArray() throws Exception {183 String[] value = {"Cheese", "Peas"};184 Response response = new Response();185 response.setSessionId("bar");186 response.setValue(value);187 response.setStatus(1512);188 String json = new BeanToJsonConverter().convert(response);189 Response converted = new JsonToBeanConverter().convert(Response.class, json);190 assertEquals("bar", response.getSessionId());191 assertEquals(2, ((List<?>) converted.getValue()).size());192 assertEquals(1512, response.getStatus().intValue());193 }194 @Test195 public void testShouldConvertObjectsInArraysToMaps() throws Exception {196 Date date = new Date();197 Cookie cookie = new Cookie("foo", "bar", "localhost", "/rooted", date, true, true);198 String rawJson = new BeanToJsonConverter().convert(Collections.singletonList(cookie));199 List<?> list = new JsonToBeanConverter().convert(List.class, rawJson);200 Object first = list.get(0);201 assertTrue(first instanceof Map);202 Map<?,?> map = (Map<?,?>) first;203 assertMapEntry(map, "name", "foo");204 assertMapEntry(map, "value", "bar");205 assertMapEntry(map, "domain", "localhost");206 assertMapEntry(map, "path", "/rooted");207 assertMapEntry(map, "secure", true);208 assertMapEntry(map, "httpOnly", true);209 assertMapEntry(map, "expiry", TimeUnit.MILLISECONDS.toSeconds(date.getTime()));210 }211 private void assertMapEntry(Map<?,?> map, String key, Object expected) {212 assertTrue("Missing key: " + key, map.containsKey(key));213 assertEquals("Wrong value for key: " + key + ": " + map.get(key).getClass().getName(),214 expected, map.get(key));215 }216 @Test217 public void testShouldConvertAnArrayBackIntoAnArray() throws Exception {218 Exception e = new Exception();219 String converted = new BeanToJsonConverter().convert(e);220 Map<?,?> reconstructed = new JsonToBeanConverter().convert(Map.class, converted);221 List<?> trace = (List<?>) reconstructed.get("stackTrace");222 assertTrue(trace.get(0) instanceof Map);223 }224 @Test225 public void testShouldBeAbleToReconsituteASessionId() throws Exception {226 String json = new BeanToJsonConverter().convert(new SessionId("id"));227 SessionId sessionId = new JsonToBeanConverter().convert(SessionId.class, json);228 assertEquals("id", sessionId.toString());229 }230 @Test231 public void testShouldBeAbleToConvertACommand() throws Exception {232 SessionId sessionId = new SessionId("session id");233 Command original = new Command(sessionId, DriverCommand.NEW_SESSION,234 new HashMap<String, String>() {235 {236 put("food", "cheese");237 }238 });239 String raw = new BeanToJsonConverter().convert(original);240 Command converted = new JsonToBeanConverter().convert(Command.class, raw);241 assertEquals(sessionId.toString(), converted.getSessionId().toString());242 assertEquals(original.getName(), converted.getName());243 assertEquals(1, converted.getParameters().keySet().size());244 assertEquals("cheese", converted.getParameters().get("food"));245 }246 @Test247 public void testShouldConvertCapabilitiesToAMapAndIncludeCustomValues() throws Exception {248 Capabilities caps = new ImmutableCapabilities("furrfu", "fishy");249 String raw = new BeanToJsonConverter().convert(caps);250 Capabilities converted = new JsonToBeanConverter().convert(Capabilities.class, raw);251 assertEquals("fishy", converted.getCapability("furrfu"));252 }253 @Test254 public void testShouldParseCapabilitiesWithLoggingPreferences() throws Exception {255 JsonObject prefs = new JsonObject();256 prefs.addProperty("browser", "WARNING");257 prefs.addProperty("client", "DEBUG");258 prefs.addProperty("driver", "ALL");259 prefs.addProperty("server", "OFF");260 JsonObject caps = new JsonObject();261 caps.add(CapabilityType.LOGGING_PREFS, prefs);262 Capabilities converted = new JsonToBeanConverter()263 .convert(Capabilities.class, caps.toString());264 LoggingPreferences lp =265 (LoggingPreferences) converted.getCapability(CapabilityType.LOGGING_PREFS);266 assertNotNull(lp);267 assertEquals(Level.WARNING, lp.getLevel(LogType.BROWSER));268 assertEquals(Level.FINE, lp.getLevel(LogType.CLIENT));269 assertEquals(Level.ALL, lp.getLevel(LogType.DRIVER));270 assertEquals(Level.OFF, lp.getLevel(LogType.SERVER));271 }272 @Test273 public void testShouldNotParseQuotedJsonObjectsAsActualJsonObjects() {274 JsonObject inner = new JsonObject();275 inner.addProperty("color", "green");276 inner.addProperty("number", 123);277 JsonObject outer = new JsonObject();278 outer.addProperty("inner", inner.toString());279 String jsonStr = outer.toString();280 Object convertedOuter = new JsonToBeanConverter().convert(Map.class, jsonStr);281 assertThat(convertedOuter, instanceOf(Map.class));282 Object convertedInner = ((Map<?,?>) convertedOuter).get("inner");283 assertNotNull(convertedInner);284 assertThat(convertedInner, instanceOf(String.class));285 assertThat(convertedInner.toString(), equalTo(inner.toString()));286 }287 @Test288 public void shouldBeAbleToConvertASelenium3CommandToASelenium2Command() {289 SessionId expectedId = new SessionId("thisisakey");290 JsonObject rawJson = new JsonObject();291 // In selenium 2, the sessionId is an object. In selenium 3, it's a straight string.292 rawJson.addProperty("sessionId", expectedId.toString());293 rawJson.addProperty("name", "some command");294 rawJson.add("parameters", new JsonObject());295 String stringified = rawJson.toString();296 Command converted = new JsonToBeanConverter().convert(Command.class, stringified);297 assertEquals(expectedId, converted.getSessionId());298 }299 @Test300 public void testShouldCallFromJsonMethodIfPresent() {301 JsonAware res = new JsonToBeanConverter().convert(JsonAware.class, "converted");302 assertEquals("converted", res.convertedValue);303 }304 // Test for issue 8187305 @Test306 public void testDecodingResponseWithNumbersInValueObject() {307 Response response = new JsonToBeanConverter()308 .convert(Response.class, "{\"status\":0,\"value\":{\"width\":96,\"height\":46.19140625}}");309 @SuppressWarnings("unchecked")310 Map<String, Number> value = (Map<String, Number>) response.getValue();311 assertEquals(96, value.get("width").intValue());312 assertEquals(46, value.get("height").intValue());313 assertEquals(46.19140625, value.get("height").doubleValue(), 0.00001);314 }315 @Test316 public void testShouldRecognizeNumericStatus() {317 Response response = new JsonToBeanConverter()318 .convert(Response.class, "{\"status\":0,\"value\":\"cheese\"}");319 assertEquals(0, response.getStatus().intValue());320 Assert.assertEquals(new ErrorCodes().toState(0), response.getState());321 String value = (String) response.getValue();322 assertEquals("cheese", value);323 }324 @Test325 public void testShouldRecognizeStringStatus() {326 Response response = new JsonToBeanConverter()327 .convert(Response.class, "{\"status\":\"success\",\"value\":\"cheese\"}");328 assertEquals(0, response.getStatus().intValue());329 assertEquals(new ErrorCodes().toState(0), response.getState());330 String value = (String) response.getValue();331 assertEquals("cheese", value);332 }333 @Test334 public void testShouldConvertInvalidSelectorError() {335 Response response = new JsonToBeanConverter()336 .convert(Response.class, "{\"state\":\"invalid selector\",\"message\":\"invalid xpath selector\"}");337 assertEquals(32, response.getStatus().intValue());338 assertEquals(new ErrorCodes().toState(32), response.getState());339 }340 @Test341 public void testShouldRecognizeStringState() {342 Response response = new JsonToBeanConverter()343 .convert(Response.class, "{\"state\":\"success\",\"value\":\"cheese\"}");344 assertEquals("success", response.getState());345 assertEquals(0, response.getStatus().intValue());346 String value = (String) response.getValue();347 assertEquals("cheese", value);348 }349 @Test350 public void testNoStatusShouldBeNullInResponseObject() {351 Response response = new JsonToBeanConverter()352 .convert(Response.class, "{\"value\":\"cheese\"}");353 assertNull(response.getStatus());354 }355 @Test356 public void canConvertAnEnumWithALowerCaseValue() {357 Proxy.ProxyType type = new JsonToBeanConverter().convert(Proxy.ProxyType.class, "pac");358 assertEquals(Proxy.ProxyType.PAC, type);359 }360 public static class SimpleBean {361 private String value;362 public String getValue() {363 return value;364 }365 public void setValue(String value) {366 this.value = value;367 }368 }369 public static class ContainingBean {370 private String name;371 private SimpleBean bean;372 public String getName() {373 return name;374 }375 public void setName(String name) {376 this.name = name;377 }378 public SimpleBean getBean() {379 return bean;380 }381 public void setBean(SimpleBean bean) {382 this.bean = bean;383 }384 }385 public static class JsonAware {386 private String convertedValue;387 public JsonAware(String convertedValue) {388 this.convertedValue = convertedValue;389 }390 public static JsonAware fromJson(String json) {391 return new JsonAware(json);392 }393 }394}...

Full Screen

Full Screen

Source:BaseTest.java Github

copy

Full Screen

...239 if (disableImagesInBrowser) {240 HashMap<String, Object> images = new HashMap<String, Object>();241 images.put("images", 2);242 HashMap<String, Object> prefs = new HashMap<String, Object>();243 prefs.put("profile.default_content_setting_values", images);244 option.setExperimentalOption("prefs", prefs);245 } 246 247 // option.addArguments("--headless");248 driver = new ChromeDriver(option);249 break;250 251 case "Firefox":252 System.setProperty("webdriver.gecko.driver", "src/test/resources/geckodriver.exe");253 /*254 * Proxy proxy = new Proxy(); //proxy.setHttpProxy("94.237.35.41:9152");255 * proxy.setSocksProxy("94.237.35.41:9152"); proxy.setSocksVersion(5);256 * FirefoxOptions firefoxOptions = new FirefoxOptions();257 * firefoxOptions.setCapability("marionette", true); ...

Full Screen

Full Screen

Source:WebDriverFactory.java Github

copy

Full Screen

...28 private WebDriverFactory() {29 }30 static {31 binaries = new HashMap<>();32 for (BinaryType binaryType : BinaryType.values()) {33 for (String filename : binaryType.getBinaryFilenames()) {34 binaries.put(filename, binaryType.getDriverSystemProperty());35 }36 }37 }38 private static void initEnv() {39 String directory = Env.getProperty("binary.directory", "selenium_standalone");40 try {41 Path dir = Paths.get(directory);42 logger.debug("binary directory:" + dir.toAbsolutePath().toString());43 Files.walk(dir)44 .filter(path -> Files.isRegularFile(path))45 .forEach(path -> {46 String filename = path.getFileName().toString();47 if (binaries.containsKey(filename)) {48 String binaryPath = path.toAbsolutePath().toString();49 System.setProperty(binaries.get(filename), binaryPath);50 logger.debug("set system property:" + binaryPath);51 }52 });53 } catch (IOException e) {54 logger.error(e);55 }56 }57 static WebDriver create() {58 initEnv();59 String webDriverProperty = Env.getProperty("webdriver");60 if (webDriverProperty == null || webDriverProperty.isEmpty()) {61 throw new IllegalStateException("The webdriver system property must be set");62 }63 try {64 Proxy proxy = null;65 if (Boolean.valueOf(Env.getProperty("proxy.enable", "false"))) {66 String proxyDetails = String.format("%s:%d", Env.getProperty("proxy.host"), Integer.valueOf(Env.getProperty("proxy.port")));67 proxy = new Proxy();68 proxy.setProxyType(MANUAL);69 proxy.setHttpProxy(proxyDetails);70 proxy.setSslProxy(proxyDetails);71 }72 return Drivers.valueOf(webDriverProperty.toUpperCase()).newDriver(proxy, Env.getProperty("remote.hub"));73 } catch (Exception e) {74 String msg = String.format("The webdriver system property '%s' did not match any " +75 "existing browser or the browser was not supported on your operating system. " +76 "Valid values are %s",77 webDriverProperty, Arrays.stream(Drivers78 .values())79 .map(Enum::name)80 .map(String::toLowerCase)81 .collect(Collectors.toList()));82 throw new RuntimeException(msg, e);83 }84 }85 private enum Drivers {86 FIREFOX {87 @Override88 public WebDriver newDriver(Proxy proxy, String hub) throws MalformedURLException {89 DesiredCapabilities capabilities = DesiredCapabilities.firefox();90 if (proxy != null) {91 capabilities.setCapability(PROXY, proxy);92 }...

Full Screen

Full Screen

values

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.Proxy.ProxyType2def proxyType = ProxyType.valueOf("MANUAL")3def proxyTypeValues = ProxyType.values()4import org.openqa.selenium.Proxy.ProxyType5def proxyType = ProxyType.valueOf("MANUAL")6def proxyTypeValues = ProxyType.values()7import org.openqa.selenium.Proxy.ProxyType8def proxyType = ProxyType.valueOf("MANUAL")9def proxyTypeValues = ProxyType.values()10import org.openqa.selenium.Proxy.ProxyType11def proxyType = ProxyType.valueOf("MANUAL")12def proxyTypeValues = ProxyType.values()13import org.openqa.selenium.Proxy.ProxyType14def proxyType = ProxyType.valueOf("MANUAL")15def proxyTypeValues = ProxyType.values()16import org.openqa.selenium.Proxy.ProxyType17def proxyType = ProxyType.valueOf("MANUAL")18def proxyTypeValues = ProxyType.values()19import org.openqa.selenium.Proxy.ProxyType20def proxyType = ProxyType.valueOf("MANUAL")21def proxyTypeValues = ProxyType.values()22import org.openqa.selenium.Proxy.ProxyType23def proxyType = ProxyType.valueOf("MANUAL")24def proxyTypeValues = ProxyType.values()25import org.openqa.selenium.Proxy.ProxyType26def proxyType = ProxyType.valueOf("MANUAL")27def proxyTypeValues = ProxyType.values()28import org.openqa.selenium.Proxy.ProxyType29def proxyType = ProxyType.valueOf("MANUAL")30def proxyTypeValues = ProxyType.values()

Full Screen

Full Screen

values

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.Proxy.ProxyType;2ProxyType proxyType = Proxy.ProxyType.valueOf("MANUAL");3System.out.println("proxy type is: " + proxyType);4import org.openqa.selenium.Proxy.ProxyType;5Proxy.ProxyType[] proxyTypes = Proxy.ProxyType.values();6for(Proxy.ProxyType proxyType : proxyTypes){7System.out.println("proxy type is: " + proxyType);8}9import org.openqa.selenium.Proxy.ProxyType;10Proxy.ProxyType proxyType = Proxy.ProxyType.valueOf("DIRECT");11System.out.println("proxy type is: " + proxyType);12import org.openqa.selenium.Proxy.ProxyType;13Proxy.ProxyType proxyType = Proxy.ProxyType.valueOf("UNSPECIFIED");14System.out.println("proxy type is: " + proxyType);15import org.openqa.selenium.Proxy.ProxyType;16Proxy.ProxyType proxyType = Proxy.ProxyType.valueOf("UNSUPPORTED");17System.out.println("proxy type is: " + proxyType);18import org.openqa.selenium.Proxy.ProxyType;19Proxy.ProxyType proxyType = Proxy.ProxyType.valueOf("AUTODETECT");20System.out.println("proxy type is: " + proxyType);21import org.openqa.selenium.Proxy.ProxyType;22Proxy.ProxyType proxyType = Proxy.ProxyType.valueOf("PAC");23System.out.println("proxy type is: " + proxyType);24import org.openqa.selenium.Proxy

Full Screen

Full Screen

values

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.Proxy.ProxyType;2Proxy.ProxyType[] values = Proxy.ProxyType.values();3for (Proxy.ProxyType value : values) {4 System.out.println(value);5}6package org.example;7import org.openqa.selenium.Proxy.ProxyType;8public class App {9 public static void main(String[] args) {10 Proxy.ProxyType[] values = Proxy.ProxyType.values();11 for (Proxy.ProxyType value : values) {12 System.out.println(value);13 }14 }15}

Full Screen

Full Screen

values

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.Proxy.ProxyType;2import org.openqa.selenium.Proxy;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.firefox.FirefoxDriver;5public class SeleneseTestCase {6public static void main(String[] args) {7WebDriver driver = new FirefoxDriver();8Proxy proxy = new Proxy();9for (String s : Proxy.ProxyType.values()) {10if (proxy.isTypeValid(s))11System.out.println(s + " is valid");12System.out.println(s + " is not valid");13}14driver.quit();15}16}17[INFO] --- maven-resources-plugin:2.4.3:resources (default-resources) @ SeleniumTest ---18[INFO] --- melenium-maven-plugin:1.1.0:run (default-cli) @ SeleniumTest ---19[INFO] --- maven-resources-plugin:2.4.3:testResources (default-testResources) @ SeleniumTest ---20[INFO] --- maven-compiler-plugin:2.3.2:testCompile (default-testCompile) @ SeleniumTest ---21[INFO] --- maven-surefire-plugin:2.4.3:test (default-test) @ SeleniumTest ---

Full Screen

Full Screen

Selenium 4 Tutorial:

LambdaTest’s Selenium 4 tutorial is covering every aspects of Selenium 4 testing with examples and best practices. Here you will learn basics, such as how to upgrade from Selenium 3 to Selenium 4, to some advanced concepts, such as Relative locators and Selenium Grid 4 for Distributed testing. Also will learn new features of Selenium 4, such as capturing screenshots of specific elements, opening a new tab or window on the browser, and new protocol adoptions.

Chapters:

  1. Upgrading From Selenium 3 To Selenium 4?: In this chapter, learn in detail how to update Selenium 3 to Selenium 4 for Java binding. Also, learn how to upgrade while using different build tools such as Maven or Gradle and get comprehensive guidance for upgrading Selenium.

  2. What’s New In Selenium 4 & What’s Being Deprecated? : Get all information about new implementations in Selenium 4, such as W3S protocol adaption, Optimized Selenium Grid, and Enhanced Selenium IDE. Also, learn what is deprecated for Selenium 4, such as DesiredCapabilites and FindsBy methods, etc.

  3. Selenium 4 With Python: Selenium supports all major languages, such as Python, C#, Ruby, and JavaScript. In this chapter, learn how to install Selenium 4 for Python and the features of Python in Selenium 4, such as Relative locators, Browser manipulation, and Chrom DevTool protocol.

  4. Selenium 4 Is Now W3C Compliant: JSON Wireframe protocol is retiring from Selenium 4, and they are adopting W3C protocol to learn in detail about the advantages and impact of these changes.

  5. How To Use Selenium 4 Relative Locator? : Selenium 4 came with new features such as Relative Locators that allow constructing locators with reference and easily located constructors nearby. Get to know its different use cases with examples.

  6. Selenium Grid 4 Tutorial For Distributed Testing: Selenium Grid 4 allows you to perform tests over different browsers, OS, and device combinations. It also enables parallel execution browser testing, reads up on various features of Selenium Grid 4 and how to download it, and runs a test on Selenium Grid 4 with best practices.

  7. Selenium Video Tutorials: Binge on video tutorials on Selenium by industry experts to get step-by-step direction from automating basic to complex test scenarios with Selenium.

Selenium 101 certifications:

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

Run Selenium automation tests on LambdaTest cloud grid

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

Most used method in Enum-Proxy.ProxyType

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful