How to use is method of org.openqa.selenium.Interface Capabilities class

Best Selenium code snippet using org.openqa.selenium.Interface Capabilities.is

Source:BaseAugmenterTest.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.remote;18import static org.junit.Assert.assertEquals;19import static org.junit.Assert.assertFalse;20import static org.junit.Assert.assertNotSame;21import static org.junit.Assert.assertSame;22import static org.junit.Assert.assertTrue;23import static org.junit.Assert.fail;24import static org.mockito.Mockito.mock;25import com.google.common.collect.ImmutableMap;26import org.junit.Test;27import org.openqa.selenium.By;28import org.openqa.selenium.Capabilities;29import org.openqa.selenium.HasCapabilities;30import org.openqa.selenium.ImmutableCapabilities;31import org.openqa.selenium.NoSuchElementException;32import org.openqa.selenium.Rotatable;33import org.openqa.selenium.ScreenOrientation;34import org.openqa.selenium.TakesScreenshot;35import org.openqa.selenium.WebDriver;36import org.openqa.selenium.WebElement;37import java.util.ArrayList;38import java.util.HashMap;39import java.util.List;40import java.util.Map;41public abstract class BaseAugmenterTest {42 @Test43 public void shouldReturnANormalWebDriverUntouched() {44 WebDriver driver = mock(WebDriver.class);45 WebDriver returned = getAugmenter().augment(driver);46 assertSame(driver, returned);47 }48 @Test49 public void shouldAddInterfaceFromCapabilityIfNecessary() {50 final Capabilities caps = new ImmutableCapabilities("magic.numbers", true);51 WebDriver driver = new RemoteWebDriver(new StubExecutor(caps), caps);52 BaseAugmenter augmenter = getAugmenter();53 augmenter.addDriverAugmentation("magic.numbers", new AddsMagicNumberHolder());54 WebDriver returned = augmenter.augment(driver);55 assertNotSame(driver, returned);56 assertTrue(returned instanceof TakesScreenshot);57 }58 @Test59 public void shouldNotAddInterfaceWhenBooleanValueForItIsFalse() {60 Capabilities caps = new ImmutableCapabilities("magic.numbers", false);61 WebDriver driver = new RemoteWebDriver(new StubExecutor(caps), caps);62 BaseAugmenter augmenter = getAugmenter();63 augmenter.addDriverAugmentation("magic.numbers", new AddsMagicNumberHolder());64 WebDriver returned = augmenter.augment(driver);65 assertSame(driver, returned);66 assertFalse(returned instanceof MagicNumberHolder);67 }68 @Test69 public void shouldDelegateToHandlerIfAdded() {70 Capabilities caps = new ImmutableCapabilities("foo", true);71 BaseAugmenter augmenter = getAugmenter();72 augmenter.addDriverAugmentation("foo", new AugmenterProvider() {73 public Class<?> getDescribedInterface() {74 return MyInterface.class;75 }76 public InterfaceImplementation getImplementation(Object value) {77 return (executeMethod, self, method, args) -> "Hello World";78 }79 });80 WebDriver driver = new RemoteWebDriver(new StubExecutor(caps), caps);81 WebDriver returned = augmenter.augment(driver);82 String text = ((MyInterface) returned).getHelloWorld();83 assertEquals("Hello World", text);84 }85 @Test86 public void shouldDelegateUnmatchedMethodCallsToDriverImplementation() {87 Capabilities caps = new ImmutableCapabilities("magic.numbers", true);88 StubExecutor stubExecutor = new StubExecutor(caps);89 stubExecutor.expect(DriverCommand.GET_TITLE, new HashMap<>(), "Title");90 WebDriver driver = new RemoteWebDriver(stubExecutor, caps);91 BaseAugmenter augmenter = getAugmenter();92 augmenter.addDriverAugmentation("magic.numbers", new AddsMagicNumberHolder());93 WebDriver returned = augmenter.augment(driver);94 assertEquals("Title", returned.getTitle());95 }96 @Test(expected = NoSuchElementException.class)97 public void proxyShouldNotAppearInStackTraces() {98 // This will force the class to be enhanced99 final Capabilities caps = new ImmutableCapabilities("magic.numbers", true);100 DetonatingDriver driver = new DetonatingDriver();101 driver.setCapabilities(caps);102 BaseAugmenter augmenter = getAugmenter();103 augmenter.addDriverAugmentation("magic.numbers", new AddsMagicNumberHolder());104 WebDriver returned = augmenter.augment(driver);105 returned.findElement(By.id("ignored"));106 }107 @Test108 public void shouldLeaveAnUnAugmentableElementAlone() {109 RemoteWebElement element = new RemoteWebElement();110 element.setId("1234");111 WebElement returned = getAugmenter().augment(element);112 assertSame(element, returned);113 }114 @Test115 public void shouldAllowAnElementToBeAugmented() throws Exception {116 RemoteWebElement element = new RemoteWebElement();117 element.setId("1234");118 BaseAugmenter augmenter = getAugmenter();119 augmenter.addElementAugmentation("foo", new AugmenterProvider() {120 public Class<?> getDescribedInterface() {121 return MyInterface.class;122 }123 public InterfaceImplementation getImplementation(Object value) {124 return (executeMethod, self, method, args) -> "Hello World";125 }126 });127 final Capabilities caps = new ImmutableCapabilities("foo", true);128 StubExecutor executor = new StubExecutor(caps);129 RemoteWebDriver parent = new RemoteWebDriver(executor, caps) {130 @Override131 public Capabilities getCapabilities() {132 return caps;133 }134 };135 element.setParent(parent);136 WebElement returned = augmenter.augment(element);137 assertTrue(returned instanceof MyInterface);138 executor.expect(DriverCommand.CLICK_ELEMENT, ImmutableMap.of("id", "1234"),139 null);140 returned.click();141 }142 @Test143 public void shouldCopyFieldsFromTemplateInstanceIntoChildInstance() {144 ChildRemoteDriver driver = new ChildRemoteDriver();145 driver.setMagicNumber(3);146 MagicNumberHolder holder = (MagicNumberHolder) getAugmenter().augment(driver);147 assertEquals(3, holder.getMagicNumber());148 }149 @Test150 public void shouldNotChokeOnFinalFields() {151 WithFinals withFinals = new WithFinals();152 try {153 getAugmenter().augment(withFinals);154 } catch (Exception e) {155 fail("This is not expected: " + e.getMessage());156 }157 }158 @Test159 public void shouldBeAbleToAugmentMultipleTimes() {160 Capabilities caps = new ImmutableCapabilities("canRotate", true, "magic.numbers", true);161 StubExecutor stubExecutor = new StubExecutor(caps);162 stubExecutor.expect(DriverCommand.GET_SCREEN_ORIENTATION,163 ImmutableMap.<String, Object>of(),164 ScreenOrientation.PORTRAIT.name());165 RemoteWebDriver driver = new RemoteWebDriver(stubExecutor, caps);166 BaseAugmenter augmenter = getAugmenter();167 augmenter.addDriverAugmentation("canRotate", new AddRotatable());168 WebDriver augmented = augmenter.augment(driver);169 assertNotSame(augmented, driver);170 assertTrue(augmented instanceof Rotatable);171 assertFalse(augmented instanceof MagicNumberHolder);172 augmenter = getAugmenter();173 augmenter.addDriverAugmentation("magic.numbers", new AddsMagicNumberHolder());174 WebDriver augmentedAgain = augmenter.augment(augmented);175 assertNotSame(augmentedAgain, augmented);176 assertTrue(augmentedAgain instanceof Rotatable);177 assertTrue(augmentedAgain instanceof MagicNumberHolder);178 ((Rotatable) augmentedAgain).getOrientation(); // Should not throw.179 assertSame(driver.getCapabilities(),180 ((HasCapabilities) augmentedAgain).getCapabilities());181 }182 protected static class StubExecutor implements CommandExecutor {183 private final Capabilities capabilities;184 private final List<Data> expected = new ArrayList<>();185 protected StubExecutor(Capabilities capabilities) {186 this.capabilities = capabilities;187 }188 public Response execute(Command command) {189 if (DriverCommand.NEW_SESSION.equals(command.getName())) {190 Response response = new Response(new SessionId("foo"));191 response.setValue(capabilities.asMap());192 return response;193 }194 for (Data possibleMatch : expected) {195 if (possibleMatch.commandName.equals(command.getName()) &&196 possibleMatch.args.equals(command.getParameters())) {197 Response response = new Response(new SessionId("foo"));198 response.setValue(possibleMatch.returnValue);199 return response;200 }201 }202 fail("Unexpected method invocation: " + command);203 return null; // never reached204 }205 public void expect(String commandName, Map<String, ?> args, Object returnValue) {206 expected.add(new Data(commandName, args, returnValue));207 }208 private static class Data {209 public String commandName;210 public Map<String, ?> args;211 public Object returnValue;212 public Data(String commandName, Map<String, ?> args, Object returnValue) {213 this.commandName = commandName;214 this.args = args;215 this.returnValue = returnValue;216 }217 }218 }219 public interface MyInterface {220 String getHelloWorld();221 }222 public static class DetonatingDriver extends RemoteWebDriver {223 private Capabilities caps;224 public void setCapabilities(Capabilities caps) {225 this.caps = caps;226 }227 @Override228 public Capabilities getCapabilities() {229 return caps;230 }231 @Override232 public WebElement findElementById(String id) {233 throw new NoSuchElementException("Boom");234 }235 }236 private interface MagicNumberHolder {237 public int getMagicNumber();238 public void setMagicNumber(int number);239 }240 public static class ChildRemoteDriver extends RemoteWebDriver implements MagicNumberHolder {241 private int magicNumber;242 @Override243 public Capabilities getCapabilities() {244 return DesiredCapabilities.firefox();245 }246 @Override247 public int getMagicNumber() {248 return magicNumber;249 }250 @Override251 public void setMagicNumber(int magicNumber) {252 this.magicNumber = magicNumber;253 }254 }255 public static class WithFinals extends RemoteWebDriver {256 public final String finalField = "FINAL";257 @Override258 public Capabilities getCapabilities() {259 return new ImmutableCapabilities();260 }261 }262 public abstract BaseAugmenter getAugmenter();263 private static class AddsMagicNumberHolder implements AugmenterProvider {264 @Override265 public Class<?> getDescribedInterface() {266 return MagicNumberHolder.class;...

Full Screen

Full Screen

Source:AugmenterTest.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.remote;18import com.google.common.collect.ImmutableMap;19import org.junit.Test;20import org.openqa.selenium.By;21import org.openqa.selenium.Capabilities;22import org.openqa.selenium.HasCapabilities;23import org.openqa.selenium.ImmutableCapabilities;24import org.openqa.selenium.NoSuchElementException;25import org.openqa.selenium.Rotatable;26import org.openqa.selenium.ScreenOrientation;27import org.openqa.selenium.SearchContext;28import org.openqa.selenium.WebDriver;29import org.openqa.selenium.WebElement;30import org.openqa.selenium.firefox.FirefoxOptions;31import org.openqa.selenium.html5.LocationContext;32import java.util.ArrayList;33import java.util.Collections;34import java.util.HashMap;35import java.util.List;36import java.util.Map;37import static org.assertj.core.api.Assertions.assertThat;38import static org.assertj.core.api.Assertions.assertThatExceptionOfType;39import static org.mockito.Mockito.mock;40import static org.openqa.selenium.remote.DriverCommand.FIND_ELEMENT;41public class AugmenterTest {42 private Augmenter getAugmenter() {43 return new Augmenter();44 }45 @Test46 public void shouldAugmentRotatable() {47 final Capabilities caps = new ImmutableCapabilities(CapabilityType.ROTATABLE, true);48 WebDriver driver = new RemoteWebDriver(new StubExecutor(caps), caps);49 WebDriver returned = getAugmenter().augment(driver);50 assertThat(returned).isNotSameAs(driver);51 assertThat(returned).isInstanceOf(Rotatable.class);52 }53 @Test54 public void shouldAugmentLocationContext() {55 final Capabilities caps = new ImmutableCapabilities(CapabilityType.SUPPORTS_LOCATION_CONTEXT, true);56 WebDriver driver = new RemoteWebDriver(new StubExecutor(caps), caps);57 WebDriver returned = getAugmenter().augment(driver);58 assertThat(returned).isNotSameAs(driver);59 assertThat(returned).isInstanceOf(LocationContext.class);60 }61 @Test62 public void shouldAddInterfaceFromCapabilityIfNecessary() {63 final Capabilities caps = new ImmutableCapabilities("magic.numbers", true);64 WebDriver driver = new RemoteWebDriver(new StubExecutor(caps), caps);65 WebDriver returned = getAugmenter()66 .addDriverAugmentation("magic.numbers", HasMagicNumbers.class, (c, exe) -> () -> 42)67 .augment(driver);68 assertThat(returned).isNotSameAs(driver);69 assertThat(returned).isInstanceOf(HasMagicNumbers.class);70 }71 @Test72 public void shouldNotAddInterfaceWhenBooleanValueForItIsFalse() {73 Capabilities caps = new ImmutableCapabilities("magic.numbers", false);74 WebDriver driver = new RemoteWebDriver(new StubExecutor(caps), caps);75 WebDriver returned = getAugmenter()76 .addDriverAugmentation("magic.numbers", HasMagicNumbers.class, (c, exe) -> () -> 42)77 .augment(driver);78 assertThat(returned).isSameAs(driver);79 assertThat(returned).isNotInstanceOf(HasMagicNumbers.class);80 }81 @Test82 public void shouldDelegateToHandlerIfAdded() {83 Capabilities caps = new ImmutableCapabilities("foo", true);84 WebDriver driver = new RemoteWebDriver(new StubExecutor(caps), caps);85 WebDriver returned = getAugmenter()86 .addDriverAugmentation(87 "foo",88 MyInterface.class,89 (c, exe) -> () -> "Hello World")90 .augment(driver);91 String text = ((MyInterface) returned).getHelloWorld();92 assertThat(text).isEqualTo("Hello World");93 }94 @Test95 public void shouldDelegateUnmatchedMethodCallsToDriverImplementation() {96 Capabilities caps = new ImmutableCapabilities("magic.numbers", true);97 StubExecutor stubExecutor = new StubExecutor(caps);98 stubExecutor.expect(DriverCommand.GET_TITLE, new HashMap<>(), "Title");99 WebDriver driver = new RemoteWebDriver(stubExecutor, caps);100 WebDriver returned = getAugmenter()101 .addDriverAugmentation(102 "magic.numbers",103 HasMagicNumbers.class,104 (c, exe) -> () -> 42)105 .augment(driver);106 assertThat(returned.getTitle()).isEqualTo("Title");107 }108 @Test109 public void proxyShouldNotAppearInStackTraces() {110 // This will force the class to be enhanced111 final Capabilities caps = new ImmutableCapabilities("magic.numbers", true);112 DetonatingDriver driver = new DetonatingDriver();113 driver.setCapabilities(caps);114 WebDriver returned = getAugmenter()115 .addDriverAugmentation(116 "magic.numbers",117 HasMagicNumbers.class,118 (c, exe) -> () -> 42)119 .augment(driver);120 assertThatExceptionOfType(NoSuchElementException.class)121 .isThrownBy(() -> returned.findElement(By.id("ignored")));122 }123 @Test124 public void shouldCopyFieldsFromTemplateInstanceIntoChildInstance() {125 ChildRemoteDriver driver = new ChildRemoteDriver();126 HasMagicNumbers holder = (HasMagicNumbers) getAugmenter().augment(driver);127 assertThat(holder.getMagicNumber()).isEqualTo(3);128 }129 @Test130 public void shouldNotChokeOnFinalFields() {131 WithFinals withFinals = new WithFinals();132 getAugmenter().augment(withFinals);133 }134 @Test135 public void shouldAllowReflexiveCalls() {136 Capabilities caps = new ImmutableCapabilities("find by magic", true);137 StubExecutor executor = new StubExecutor(caps);138 final WebElement element = mock(WebElement.class);139 executor.expect(140 FIND_ELEMENT,141 ImmutableMap.of("using", "magic", "value", "cheese"),142 element);143 WebDriver driver = new RemoteWebDriver(executor, caps);144 WebDriver returned = getAugmenter()145 .addDriverAugmentation(146 "find by magic",147 FindByMagic.class,148 (c, exe) -> magicWord -> element)149 .augment(driver);150 // No exception is a Good Thing151 WebElement seen = returned.findElement(new ByMagic("cheese"));152 assertThat(seen).isSameAs(element);153 }154 private static class ByMagic extends By {155 private final String magicWord;156 public ByMagic(String magicWord) {157 this.magicWord = magicWord;158 }159 @Override160 public List<WebElement> findElements(SearchContext context) {161 return List.of(((FindByMagic) context).findByMagic(magicWord));162 }163 }164 public interface FindByMagic {165 WebElement findByMagic(String magicWord);166 }167 @Test168 public void shouldBeAbleToAugmentMultipleTimes() {169 Capabilities caps = new ImmutableCapabilities("rotatable", true, "magic.numbers", true);170 StubExecutor stubExecutor = new StubExecutor(caps);171 stubExecutor.expect(DriverCommand.GET_SCREEN_ORIENTATION,172 Collections.emptyMap(),173 ScreenOrientation.PORTRAIT.name());174 RemoteWebDriver driver = new RemoteWebDriver(stubExecutor, caps);175 WebDriver augmented = getAugmenter().augment(driver);176 assertThat(driver).isNotSameAs(augmented);177 assertThat(augmented).isInstanceOf(Rotatable.class);178 assertThat(augmented).isNotInstanceOf(HasMagicNumbers.class);179 WebDriver augmentedAgain = getAugmenter()180 .addDriverAugmentation(181 "magic.numbers",182 HasMagicNumbers.class,183 (c, exe) -> () -> 42)184 .augment(augmented);185 assertThat(augmented).isNotSameAs(augmentedAgain);186 assertThat(augmentedAgain).isInstanceOf(Rotatable.class);187 assertThat(augmentedAgain).isInstanceOf(HasMagicNumbers.class);188 ((Rotatable) augmentedAgain).getOrientation(); // Should not throw.189 assertThat(((HasCapabilities) augmentedAgain).getCapabilities())190 .isSameAs(driver.getCapabilities());191 }192 protected static class StubExecutor implements CommandExecutor {193 private final Capabilities capabilities;194 private final List<Data> expected = new ArrayList<>();195 protected StubExecutor(Capabilities capabilities) {196 this.capabilities = capabilities;197 }198 @Override199 public Response execute(Command command) {200 if (DriverCommand.NEW_SESSION.equals(command.getName())) {201 Response response = new Response(new SessionId("foo"));202 response.setValue(capabilities.asMap());203 return response;204 }205 for (Data possibleMatch : expected) {206 if (possibleMatch.commandName.equals(command.getName()) &&207 possibleMatch.args.equals(command.getParameters())) {208 Response response = new Response(new SessionId("foo"));209 response.setValue(possibleMatch.returnValue);210 return response;211 }212 }213 throw new AssertionError("Unexpected method invocation: " + command);214 }215 public void expect(String commandName, Map<String, ?> args, Object returnValue) {216 expected.add(new Data(commandName, args, returnValue));217 }218 private static class Data {219 public String commandName;220 public Map<String, ?> args;221 public Object returnValue;222 public Data(String commandName, Map<String, ?> args, Object returnValue) {223 this.commandName = commandName;224 this.args = args;225 this.returnValue = returnValue;226 }227 }228 }229 public interface MyInterface {230 String getHelloWorld();231 }232 public static class DetonatingDriver extends RemoteWebDriver {233 private Capabilities caps;234 public void setCapabilities(Capabilities caps) {235 this.caps = caps;236 }237 @Override238 public Capabilities getCapabilities() {239 return caps;240 }241 @Override242 public WebElement findElement(By locator) {243 return super.findElement(locator);244 }245 @Override246 protected WebElement findElement(String by, String using) {247 if ("id".equals(by)) {248 throw new NoSuchElementException("Boom");249 }...

Full Screen

Full Screen

Source:Augmenter.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.remote;18import net.bytebuddy.ByteBuddy;19import net.bytebuddy.description.annotation.AnnotationDescription;20import net.bytebuddy.dynamic.DynamicType;21import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;22import net.bytebuddy.implementation.FixedValue;23import net.bytebuddy.implementation.MethodDelegation;24import org.openqa.selenium.Beta;25import org.openqa.selenium.Capabilities;26import org.openqa.selenium.HasCapabilities;27import org.openqa.selenium.ImmutableCapabilities;28import org.openqa.selenium.WebDriver;29import org.openqa.selenium.WebDriverException;30import org.openqa.selenium.WrapsDriver;31import org.openqa.selenium.internal.Require;32import org.openqa.selenium.remote.html5.AddApplicationCache;33import org.openqa.selenium.remote.html5.AddLocationContext;34import org.openqa.selenium.remote.html5.AddWebStorage;35import org.openqa.selenium.remote.mobile.AddNetworkConnection;36import java.lang.reflect.Field;37import java.lang.reflect.Modifier;38import java.util.HashSet;39import java.util.List;40import java.util.ServiceLoader;41import java.util.Set;42import java.util.function.BiFunction;43import java.util.function.Predicate;44import java.util.stream.Collectors;45import java.util.stream.Stream;46import java.util.stream.StreamSupport;47import static java.util.Collections.unmodifiableSet;48import static net.bytebuddy.matcher.ElementMatchers.anyOf;49import static net.bytebuddy.matcher.ElementMatchers.named;50/**51 * Enhance the interfaces implemented by an instance of the52 * {@link org.openqa.selenium.WebDriver} based on the returned53 * {@link org.openqa.selenium.Capabilities} of the driver.54 *55 * Note: this class is still experimental. Use at your own risk.56 */57@Beta58public class Augmenter {59 private final Set<Augmentation<?>> augmentations;60 public Augmenter() {61 Set<Augmentation<?>> augmentations = new HashSet<>();62 Stream.of(63 new AddApplicationCache(),64 new AddLocationContext(),65 new AddNetworkConnection(),66 new AddRotatable(),67 new AddWebStorage()68 ).forEach(provider -> augmentations.add(createAugmentation(provider)));69 StreamSupport.stream(ServiceLoader.load(AugmenterProvider.class).spliterator(), false)70 .forEach(provider -> augmentations.add(createAugmentation(provider)));71 this.augmentations = unmodifiableSet(augmentations);72 }73 private static <X> Augmentation<X> createAugmentation(AugmenterProvider<X> provider) {74 Require.nonNull("Interface provider", provider);75 return new Augmentation<>(provider.isApplicable(),76 provider.getDescribedInterface(),77 provider::getImplementation);78 }79 private Augmenter(Set<Augmentation<?>> augmentations, Augmentation<?> toAdd) {80 Require.nonNull("Current list of augmentations", augmentations);81 Require.nonNull("Augmentation to add", toAdd);82 Set<Augmentation<?>> toUse = new HashSet<>(augmentations.size() + 1);83 toUse.addAll(augmentations);84 toUse.add(toAdd);85 this.augmentations = unmodifiableSet(toUse);86 }87 public <X> Augmenter addDriverAugmentation(AugmenterProvider<X> provider) {88 Require.nonNull("Interface provider", provider);89 return addDriverAugmentation(90 provider.isApplicable(),91 provider.getDescribedInterface(),92 provider::getImplementation);93 }94 public <X> Augmenter addDriverAugmentation(95 String capabilityName,96 Class<X> implementThis,97 BiFunction<Capabilities, ExecuteMethod, X> usingThis) {98 Require.nonNull("Capability name", capabilityName);99 Require.nonNull("Interface to implement", implementThis);100 Require.nonNull("Concrete implementation", usingThis, "of %s", implementThis);101 return addDriverAugmentation(check(capabilityName), implementThis, usingThis);102 }103 public <X> Augmenter addDriverAugmentation(104 Predicate<Capabilities> whenThisMatches,105 Class<X> implementThis,106 BiFunction<Capabilities, ExecuteMethod, X> usingThis) {107 Require.nonNull("Capability predicate", whenThisMatches);108 Require.nonNull("Interface to implement", implementThis);109 Require.nonNull("Concrete implementation", usingThis, "of %s", implementThis);110 Require.precondition(implementThis.isInterface(), "Expected %s to be an interface", implementThis);111 return new Augmenter(augmentations, new Augmentation<>(whenThisMatches, implementThis, usingThis));112 }113 private Predicate<Capabilities> check(String capabilityName) {114 return caps -> {115 Require.nonNull("Capability name", capabilityName);116 Object value = caps.getCapability(capabilityName);117 if (value instanceof Boolean && !((Boolean) value)) {118 return false;119 }120 return value != null;121 };122 }123 /**124 * Enhance the interfaces implemented by this instance of WebDriver iff that instance is a125 * {@link org.openqa.selenium.remote.RemoteWebDriver}.126 *127 * The WebDriver that is returned may well be a dynamic proxy. You cannot rely on the concrete128 * implementing class to remain constant.129 *130 * @param driver The driver to enhance131 * @return A class implementing the described interfaces.132 */133 public WebDriver augment(WebDriver driver) {134 Require.nonNull("WebDriver", driver);135 Require.precondition(driver instanceof HasCapabilities, "Driver must have capabilities", driver);136 Capabilities caps = ImmutableCapabilities.copyOf(((HasCapabilities) driver).getCapabilities());137 // Collect the interfaces to apply138 List<Augmentation<?>> matchingAugmenters = augmentations.stream()139 // Only consider the augmenters that match interfaces we don't already implement140 .filter(augmentation -> !augmentation.interfaceClass.isAssignableFrom(driver.getClass()))141 // And which match an augmentation we have142 .filter(augmentation -> augmentation.whenMatches.test(caps))143 .collect(Collectors.toList());144 if (matchingAugmenters.isEmpty()) {145 return driver;146 }147 // Grab a remote execution method, if possible148 RemoteWebDriver remote = extractRemoteWebDriver(driver);149 ExecuteMethod execute = remote == null ?150 (commandName, parameters) -> { throw new WebDriverException("Cannot execute remote command: " + commandName); } :151 new RemoteExecuteMethod(remote);152 DynamicType.Builder<? extends WebDriver> builder = new ByteBuddy()153 .subclass(driver.getClass())154 .annotateType(AnnotationDescription.Builder.ofType(Augmentable.class).build())155 .method(named("isAugmented")).intercept(FixedValue.value(true));156 for (Augmentation<?> augmentation : augmentations) {157 Class<?> iface = augmentation.interfaceClass;158 Object instance = augmentation.implementation.apply(caps, execute);159 builder = builder.implement(iface)160 .method(anyOf(iface.getDeclaredMethods()))161 .intercept(MethodDelegation.to(instance, iface));162 }163 Class<? extends WebDriver> definition = builder.make()164 .load(driver.getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)165 .getLoaded()166 .asSubclass(driver.getClass());167 try {168 WebDriver toReturn = definition.getDeclaredConstructor().newInstance();169 copyFields(driver.getClass(), driver, toReturn);170 return toReturn;171 } catch (ReflectiveOperationException e) {172 throw new IllegalStateException("Unable to create new proxy", e);173 }174 }175 private RemoteWebDriver extractRemoteWebDriver(WebDriver driver) {176 Require.nonNull("WebDriver", driver);177 if (driver instanceof RemoteWebDriver) {178 return (RemoteWebDriver) driver;179 }180 if (driver instanceof WrapsDriver) {181 return extractRemoteWebDriver(((WrapsDriver) driver).getWrappedDriver());182 }183 return null;184 }185 private void copyFields(Class<?> clazz, Object source, Object target) {186 if (Object.class.equals(clazz)) {187 // Stop!188 return;189 }190 for (Field field : clazz.getDeclaredFields()) {191 copyField(source, target, field);192 }193 copyFields(clazz.getSuperclass(), source, target);194 }195 private void copyField(Object source, Object target, Field field) {196 if (Modifier.isFinal(field.getModifiers())) {197 return;198 }199 try {200 field.setAccessible(true);201 Object value = field.get(source);202 field.set(target, value);203 } catch (IllegalAccessException e) {204 throw new RuntimeException(e);205 }206 }207 private static class Augmentation<X> {208 public final Predicate<Capabilities> whenMatches;209 public final Class<X> interfaceClass;210 public final BiFunction<Capabilities, ExecuteMethod, X> implementation;211 public Augmentation(212 Predicate<Capabilities> whenMatches,213 Class<X> interfaceClass,214 BiFunction<Capabilities, ExecuteMethod, X> implementation) {215 this.whenMatches = Require.nonNull("Capabilities predicate", whenMatches);216 this.interfaceClass = Require.nonNull("Interface to implement", interfaceClass);217 this.implementation = Require.nonNull("Interface implementation", implementation);218 Require.precondition(219 interfaceClass.isInterface(),220 "%s must be an interface, not a concrete class",221 interfaceClass);222 }223 }224}...

Full Screen

Full Screen

Source:UtilsTest.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.remote.server.handler.html5;18import static org.junit.Assert.assertEquals;19import static org.junit.Assert.assertSame;20import static org.junit.Assert.fail;21import static org.mockito.Mockito.mock;22import static org.mockito.Mockito.reset;23import static org.mockito.Mockito.verify;24import static org.mockito.Mockito.when;25import com.google.common.collect.ImmutableMap;26import org.junit.Test;27import org.junit.runner.RunWith;28import org.junit.runners.JUnit4;29import org.openqa.selenium.HasCapabilities;...

Full Screen

Full Screen

Source:LaunchBrowser.java Github

copy

Full Screen

...19 public TestStepExecutionResultVO execute(WebDriver wd, String... params) {20 21 TestStepExecutionResultVO testStepExecutionResultVO = new TestStepExecutionResultVO();22 DesiredCapabilities capabilities = null;23 if(params[1].equalsIgnoreCase("chrome") || params[1].trim().isEmpty())24 {25 try {26 Runtime.getRuntime().exec("taskkill /F /IM chromedriver.exe");27 } catch (IOException e) {28 // TODO Auto-generated catch block29 e.printStackTrace();30 }31 32 capabilities = DesiredCapabilities.chrome();33 34 ChromeOptions options = new ChromeOptions();35 options.addArguments("user-data-dir=C:/Users/"+System.getProperty("user.name")+"/AppData/Local/Google/Chrome/D");36 options.addArguments("--start-maximized");37 options.addArguments("test-type");38 capabilities.setCapability(ChromeOptions.CAPABILITY, options);39 System.setProperty("webdriver.chrome.driver", "chromedriver.exe");40 webDriver = new ChromeDriver(capabilities);41 }42 else if(params[1].equalsIgnoreCase("firefox"))43 {44 capabilities = DesiredCapabilities.firefox();45 46 ProfilesIni profile = new ProfilesIni();47 FirefoxProfile myprofile = profile.getProfile("C:\\Users\\vinusha\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\rwrqdehl.driverTest");48 49 webDriver = new FirefoxDriver(myprofile);50 }51 52 53 else if(params[1].equalsIgnoreCase("ie"))54 {55 try {56 Runtime.getRuntime().exec("taskkill /F /IM IEDriverServer.exe");57 Thread.sleep(2000);58 capabilities = null;59 capabilities = DesiredCapabilities.internetExplorer();60 capabilities.setCapability("nativeEvents", false);61 capabilities.setCapability("ignoreZoomSetting", true); 62 capabilities.setCapability("enablePersistentHover", true);63 capabilities.setCapability(InternetExplorerDriver.ENABLE_PERSISTENT_HOVERING, false);64 capabilities.setCapability(InternetExplorerDriver.REQUIRE_WINDOW_FOCUS, false); 65 capabilities.setCapability(InternetExplorerDriver.UNEXPECTED_ALERT_BEHAVIOR, true);66 capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);67 capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);68 capabilities.setCapability("requireWindowFocus", true); 69 System.setProperty("webdriver.ie.driver", "C:\\Users\\vinusha\\Downloads\\IEDriverServer_x64_2.39.0\\IEDriverServer.exe");70 webDriver=new InternetExplorerDriver(capabilities);71 } catch (Exception e) {72 // TODO Auto-generated catch block73 e.printStackTrace();74 }75 76 }77 else78 {79 testStepExecutionResultVO.setDefectDesc("Unknown browser type");80 return testStepExecutionResultVO;81 }82 webDriver.manage().timeouts().implicitlyWait(120, TimeUnit.SECONDS);83 webDriver.manage().timeouts().pageLoadTimeout(240, TimeUnit.SECONDS);84 webDriver.manage().deleteAllCookies();85 webDriver.manage().window().maximize();86 System.out.println("hit url..");87 webDriver.get(params[0]);88 mainWindowHandle=webDriver.getWindowHandle();89 System.out.println("title.."+webDriver.getTitle());90 91 System.out.println("mainWindowHandle.."+mainWindowHandle);92 testStepExecutionResultVO.setStatus(1);93 return testStepExecutionResultVO;94 }95 public WebDriver getWebDriverInstance() {96 return this.webDriver;97 }98}...

Full Screen

Full Screen

Source:MarionetteDriver.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.firefox;18import com.google.common.base.Throwables;19import org.openqa.selenium.Beta;20import org.openqa.selenium.Capabilities;21import org.openqa.selenium.WebDriverException;22import org.openqa.selenium.WebElement;23import org.openqa.selenium.remote.DesiredCapabilities;24import org.openqa.selenium.remote.FileDetector;25import org.openqa.selenium.remote.RemoteWebDriver;26import org.openqa.selenium.remote.service.DriverCommandExecutor;27import java.util.List;28/**29 * An implementation of the {#link WebDriver} interface that drives Firefox using Marionette interface.30 */31@Beta32public class MarionetteDriver extends RemoteWebDriver {33 /**34 * Port which is used by default.35 */36 private final static int DEFAULT_PORT = 0;37 public MarionetteDriver() {38 this(null, null, DEFAULT_PORT);39 }40 public MarionetteDriver(Capabilities capabilities) {41 this(null, capabilities, DEFAULT_PORT);42 }43 public MarionetteDriver(int port) {44 this(null, null, port);45 }46 public MarionetteDriver(GeckoDriverService service) {47 this(service, null, DEFAULT_PORT);48 }49 public MarionetteDriver(GeckoDriverService service, Capabilities capabilities) {50 this(service, capabilities, DEFAULT_PORT);51 }52 public MarionetteDriver(GeckoDriverService service, Capabilities capabilities,53 int port) {54 if (capabilities == null) {55 capabilities = DesiredCapabilities.firefox();56 }57 if (service == null) {58 service = setupService(port);59 }60 run(service, capabilities);61 }62 @Override63 public int getW3CStandardComplianceLevel() {64 return 1;...

Full Screen

Full Screen

Source:osciseriTest.java Github

copy

Full Screen

23import static org.junit.Assert.assertTrue;4import static org.junit.Assert.fail;56import java.util.ArrayList;7import java.util.concurrent.TimeUnit;89import org.junit.After;10import org.junit.Before;11import org.junit.Test;12import org.openqa.selenium.By;13import org.openqa.selenium.WebDriver;14import org.openqa.selenium.ie.InternetExplorerDriver;15//import org.openqa.selenium.remote.CapabilityType;16import org.openqa.selenium.remote.DesiredCapabilities;17import org.openqa.selenium.support.ui.ExpectedConditions;18import org.openqa.selenium.support.ui.WebDriverWait;1920public class osciseriTest {21 private final String APP = "eri";22 private ErrSnapshot Snap;23 private WebDriver driver;24 private ReadXML userinfo;25 private ArrayList<String> names;26 private static final String KILL = "taskkill /F /IM ";2728 @Before29 public void setUp() throws Exception {30 System.out.println("<OSC IS ERI>");31 System.setProperty("webdriver.ie.driver", "C:\\eclipse-standard-luna-R-win32-x86_64\\IEDriverServer.exe");32 DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();33 capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, false);34 //capabilities.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, org.openqa.selenium.UnexpectedAlertBehaviour.DISMISS);35 driver = new InternetExplorerDriver(capabilities);36 Snap = new ErrSnapshot();37 userinfo = new ReadXML();38 names = userinfo.readXML(APP);39 driver.manage().window().maximize();40 }41 42 @After43 public void tearDown() throws Exception {44 driver.quit();45 killProcess();46 System.out.println("\n");47 }48 49 @Test50 public void test() {51 driver.manage().timeouts().pageLoadTimeout(280, TimeUnit.SECONDS); 52 try {53 driver.get(names.get(0));54 Popup pop = new Popup();55 WebDriverWait wait = new WebDriverWait(driver, 120); 56 if(pop.isAlertPresent(driver)) {57 pop.stupidpopup();58 wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//td[@id='zz1_TopNavigationMenun0']/table/tbody/tr/td/a"))); 59 } 60 assertTrue(driver.getPageSource().contains("Equipment Request Interface"));61 } catch (Throwable e) {62 Snap.take(driver, APP);63 System.out.println("<OSC IS ERI Faiure>");64 fail("***Error: Equipment Request Interface is unavailable***");65 }66 67 try {68 driver.findElement(By.xpath("//td[@id='zz1_TopNavigationMenun0']/table/tbody/tr/td/a")).click();69 assertTrue(driver.getPageSource().contains("Equipment Request Interface"));70 } catch (Throwable e) {71 Snap.take(driver, APP);72 System.out.println("<OSC IS ERI Faiure>");73 fail("***Error: Equipment Request Interface is unavailable***");74 }75 System.out.println("PASS");76 }77 78 public static void killProcess() throws Exception {79 Runtime.getRuntime().exec(KILL + "iexplore.exe");80 }81} ...

Full Screen

Full Screen

Source:Utils.java Github

copy

Full Screen

...41 }42 43 private static <T> T convert(WebDriver driver, Class<T> interfaceClazz, String capability, Class<? extends T> remoteImplementationClazz)44 {45 if (interfaceClazz.isInstance(driver)) {46 return interfaceClazz.cast(driver);47 }48 49 if (((driver instanceof ExecuteMethod)) && ((driver instanceof HasCapabilities)))50 {51 if (((HasCapabilities)driver).getCapabilities().is(capability)) {52 try {53 return 54 55 remoteImplementationClazz.getConstructor(new Class[] { ExecuteMethod.class }).newInstance(new Object[] { (ExecuteMethod)driver });56 } catch (InstantiationException e) {57 throw new WebDriverException(e);58 } catch (IllegalAccessException e) {59 throw new WebDriverException(e);60 } catch (InvocationTargetException e) {61 throw Throwables.propagate(e.getCause());62 } catch (NoSuchMethodException e) {63 throw new WebDriverException(e);64 }65 }...

Full Screen

Full Screen

is

Using AI Code Generation

copy

Full Screen

1package com.selenium;2import org.openqa.selenium.Capabilities;3import org.openqa.selenium.WebDriver;4import org.openqa.selenium.chrome.ChromeDriver;5import org.openqa.selenium.remote.RemoteWebDriver;6public class CapabilitiesClass {7public static void main(String[] args) {8System.setProperty("webdriver.chrome.driver", "C:\\Users\\Admin\\Desktop\\Selenium\\chromedriver.exe");9WebDriver driver = new ChromeDriver();10Capabilities caps = ((RemoteWebDriver)driver).getCapabilities();11String browserName = caps.getBrowserName();12String browserVersion = caps.getVersion();13System.out.println("Browser Name: "+browserName);14System.out.println("Browser Version: "+browserVersion);15String os = System.getProperty("os.name").toLowerCase();16System.out.println("Operating System: "+os);17String platform = caps.getPlatform().toString();18System.out.println("Platform: "+platform);19String browserDriverVersion = caps.getCapability("webdriver.chrome.driver").toString();20System.out.println("Browser Driver Version: "+browserDriverVersion);21String browserDriverName = caps.getCapability("webdriver.chrome.driver").toString();22System.out.println("Browser Driver Name: "+browserDriverName);23driver.quit();24}25}

Full Screen

Full Screen

Selenium 4 Tutorial:

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

Chapters:

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

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

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

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

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

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

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

Selenium 101 certifications:

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

Run Selenium automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful