How to use config method of org.openqa.selenium.remote.RemoteWebDriverBuilder class

Best Selenium code snippet using org.openqa.selenium.remote.RemoteWebDriverBuilder.config

Source:RemoteWebDriverBuilder.java Github

copy

Full Screen

...93 private final List<Capabilities> requestedCapabilities = new ArrayList<>();94 private final Map<String, Object> additionalCapabilities = new TreeMap<>();95 private final Map<String, Object> metadata = new TreeMap<>();96 private Function<ClientConfig, HttpHandler> handlerFactory =97 config -> {98 HttpClient.Factory factory = HttpClient.Factory.createDefault();99 HttpClient client = factory.createClient(config);100 return client.with(101 next -> req -> {102 try {103 return client.execute(req);104 } finally {105 if (req.getMethod() == DELETE) {106 HttpSessionId.getSessionId(req.getUri()).ifPresent(id -> {107 if (("/session/" + id).equals(req.getUri())) {108 try {109 client.close();110 } catch (UncheckedIOException e) {111 LOG.log(WARNING, "Swallowing exception while closing http client", e);112 }113 factory.cleanupIdleClients();114 }115 });116 }117 }118 });119 };120 private ClientConfig clientConfig = ClientConfig.defaultConfig();121 private URI remoteHost = null;122 private DriverService driverService;123 private Credentials credentials = null;124 RemoteWebDriverBuilder() {125 // Access through RemoteWebDriver.builder126 }127 /**128 * Clears the current set of alternative browsers and instead sets the list of possible choices to129 * the arguments given to this method.130 */131 public RemoteWebDriverBuilder oneOf(Capabilities maybeThis, Capabilities... orOneOfThese) {132 Require.nonNull("Capabilities to use", maybeThis);133 if (!requestedCapabilities.isEmpty()) {134 LOG.log(getDebugLogLevel(), "Removing existing requested capabilities: " + requestedCapabilities);135 requestedCapabilities.clear();136 }137 addAlternative(maybeThis);138 for (Capabilities caps : orOneOfThese) {139 Require.nonNull("Capabilities to use", caps);140 addAlternative(caps);141 }142 return this;143 }144 /**145 * Add to the list of possible configurations that might be asked for. It is possible to ask for146 * more than one type of browser per session. For example, perhaps you have an extension that is147 * available for two different kinds of browser, and you'd like to test it).148 */149 public RemoteWebDriverBuilder addAlternative(Capabilities options) {150 Require.nonNull("Capabilities to use", options);151 requestedCapabilities.add(new ImmutableCapabilities(options));152 return this;153 }154 /**155 * Adds metadata to the outgoing new session request, which can be used by intermediary of end156 * nodes for any purpose they choose (commonly, this is used to request additional features from157 * cloud providers, such as video recordings or to set the timezone or screen size). Neither158 * parameter can be {@code null}.159 */160 public RemoteWebDriverBuilder addMetadata(String key, Object value) {161 Require.nonNull("Metadata key", key);162 Require.nonNull("Metadata value", value);163 if (ILLEGAL_METADATA_KEYS.contains(key)) {164 throw new IllegalArgumentException(String.format("Cannot add %s as metadata key", key));165 }166 Object previous = metadata.put(key, value);167 if (previous != null) {168 LOG.log(169 getDebugLogLevel(),170 String.format("Overwriting metadata %s. Previous value %s, new value %s", key, previous, value));171 }172 return this;173 }174 /**175 * Sets a capability for every single alternative when the session is created. These capabilities176 * are only set once the session is created, so this will be set on capabilities added via177 * {@link #addAlternative(Capabilities)} or {@link #oneOf(Capabilities, Capabilities...)} even178 * after this method call.179 */180 public RemoteWebDriverBuilder setCapability(String capabilityName, Object value) {181 Require.nonNull("Capability name", capabilityName);182 Require.nonNull("Capability value", value);183 Object previous = additionalCapabilities.put(capabilityName, value);184 if (previous != null) {185 LOG.log(186 getDebugLogLevel(),187 String.format("Overwriting capability %s. Previous value %s, new value %s", capabilityName, previous, value));188 }189 return this;190 }191 /**192 * @see #address(URI)193 */194 public RemoteWebDriverBuilder address(String uri) {195 Require.nonNull("Address", uri);196 try {197 return address(new URI(uri));198 } catch (URISyntaxException e) {199 throw new IllegalArgumentException("Unable to create URI from " + uri);200 }201 }202 /**203 * @see #address(URI)204 */205 public RemoteWebDriverBuilder address(URL url) {206 Require.nonNull("Address", url);207 try {208 return address(url.toURI());209 } catch (URISyntaxException e) {210 throw new IllegalArgumentException("Unable to create URI from " + url);211 }212 }213 /**214 * Set the URI of the remote server. If this URI is not set, then it assumed that a local running215 * remote webdriver session is needed. It is an error to call this method and also216 * {@link #withDriverService(DriverService)}.217 */218 public RemoteWebDriverBuilder address(URI uri) {219 Require.nonNull("URI", uri);220 if (driverService != null || (clientConfig.baseUri() != null && !clientConfig.baseUri().equals(uri))) {221 throw new IllegalArgumentException(222 "Attempted to set the base uri on both this builder and the http client config. " +223 "Please set in only one place. " + uri);224 }225 remoteHost = uri;226 return this;227 }228 public RemoteWebDriverBuilder authenticateAs(UsernameAndPassword usernameAndPassword) {229 Require.nonNull("User name and password", usernameAndPassword);230 this.credentials = usernameAndPassword;231 return this;232 }233 /**234 * Allows precise control of the {@link ClientConfig} to use with remote235 * instances. If {@link ClientConfig#baseUri(URI)} has been called, then236 * that will be used as the base URI for the session.237 */238 public RemoteWebDriverBuilder config(ClientConfig config) {239 Require.nonNull("HTTP client config", config);240 if (config.baseUri() != null) {241 if (remoteHost != null || driverService != null) {242 throw new IllegalArgumentException("Base URI has already been set. Cannot also set it via client config");243 }244 }245 this.clientConfig = config;246 return this;247 }248 /**249 * Use the given {@link DriverService} to set up the webdriver instance. It is an error to set250 * both this and also call {@link #address(URI)}.251 */252 public RemoteWebDriverBuilder withDriverService(DriverService service) {253 Require.nonNull("Driver service", service);254 if (clientConfig.baseUri() != null || remoteHost != null) {255 throw new IllegalArgumentException("Base URI has already been set. Cannot also set driver service.");256 }257 this.driverService = service;258 return this;259 }...

Full Screen

Full Screen

Source:RemoteWebDriverBuilderTest.java Github

copy

Full Screen

...69 public void mustSpecifyAtLeastOneSetOfOptions() {70 List<List<Capabilities>> caps = new ArrayList<>();71 RemoteWebDriver.builder().oneOf(new FirefoxOptions())72 .address("http://localhost:34576")73 .connectingWith(config -> req -> {74 caps.add(listCapabilities(req));75 return CANNED_SESSION_RESPONSE;76 })77 .build();78 assertThat(caps).hasSize(1);79 List<Capabilities> caps0 = caps.get(0);80 assertThat(caps0.get(0).getBrowserName()).isEqualTo(FIREFOX);81 }82 @Test83 public void settingAGlobalCapabilityCountsAsAnOption() {84 AtomicBoolean match = new AtomicBoolean(false);85 RemoteWebDriver.builder().setCapability("se:cheese", "anari")86 .address("http://localhost:34576")87 .connectingWith(config -> req -> {88 listCapabilities(req).stream()89 .map(caps -> "anari".equals(caps.getCapability("se:cheese")))90 .reduce(Boolean::logicalOr)91 .ifPresent(match::set);92 return CANNED_SESSION_RESPONSE;93 })94 .build();95 assertThat(match.get()).isTrue();96 }97 @Test98 public void shouldForbidGlobalCapabilitiesFromClobberingFirstMatchCapabilities() {99 RemoteWebDriverBuilder builder = RemoteWebDriver.builder()100 .oneOf(new ImmutableCapabilities("se:cheese", "stinking bishop"))101 .setCapability("se:cheese", "cheddar")102 .address("http://localhost:38746");103 assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(builder::build);104 }105 @Test106 public void requireAllOptionsAreW3CCompatible() {107 RemoteWebDriverBuilder builder = RemoteWebDriver.builder()108 .setCapability("cheese", "casu marzu")109 .address("http://localhost:45734");110 assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(builder::build);111 }112 @Test113 public void shouldRejectOldJsonWireProtocolNames() {114 RemoteWebDriverBuilder builder = RemoteWebDriver.builder()115 .oneOf(new ImmutableCapabilities("platform", Platform.getCurrent()))116 .address("http://localhost:35856");117 assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(builder::build);118 }119 @Test120 public void shouldAllowMetaDataToBeSet() {121 AtomicBoolean seen = new AtomicBoolean(false);122 RemoteWebDriver.builder()123 .oneOf(new FirefoxOptions())124 .addMetadata("cloud:options", "merhaba")125 .address("http://localhost:34576")126 .connectingWith(config -> req -> {127 Map<String, Object> payload = new Json().toType(Contents.string(req), MAP_TYPE);128 seen.set("merhaba".equals(payload.getOrDefault("cloud:options", "")));129 return CANNED_SESSION_RESPONSE;130 })131 .build();132 assertThat(seen.get()).isTrue();133 }134 @Test135 public void doesNotAllowFirstMatchToBeUsedAsAMetadataNameAsItIsConfusing() {136 RemoteWebDriverBuilder builder = RemoteWebDriver.builder();137 assertThatExceptionOfType(IllegalArgumentException.class)138 .isThrownBy(() -> builder.addMetadata("firstMatch", "cheese"));139 }140 @Test141 public void doesNotAllowAlwaysMatchToBeUsedAsAMetadataNameAsItIsConfusing() {142 RemoteWebDriverBuilder builder = RemoteWebDriver.builder();143 assertThatExceptionOfType(IllegalArgumentException.class)144 .isThrownBy(() -> builder.addMetadata("alwaysMatch", "cheese"));145 }146 @Test147 public void doesNotAllowCapabilitiesToBeUsedAsAMetadataName() {148 RemoteWebDriverBuilder builder = RemoteWebDriver.builder();149 assertThatExceptionOfType(IllegalArgumentException.class)150 .isThrownBy(() -> builder.addMetadata("capabilities", "cheese"));151 }152 @Test153 public void shouldAllowCapabilitiesToBeSetGlobally() {154 AtomicBoolean seen = new AtomicBoolean(false);155 RemoteWebDriver.builder()156 .oneOf(new FirefoxOptions())157 .setCapability("se:option", "cheese")158 .address("http://localhost:34576")159 .connectingWith(config -> req -> {160 listCapabilities(req).stream()161 .map(caps -> "cheese".equals(caps.getCapability("se:option")))162 .reduce(Boolean::logicalAnd)163 .ifPresent(seen::set);164 return CANNED_SESSION_RESPONSE;165 })166 .build();167 assertThat(seen.get()).isTrue();168 }169 @Test170 public void ifARemoteUrlIsGivenThatIsUsedForTheSession() {171 URI uri = URI.create("http://localhost:7575");172 AtomicReference<URI> seen = new AtomicReference<>();173 RemoteWebDriver.builder()174 .oneOf(new FirefoxOptions())175 .address(uri)176 .connectingWith(config -> req -> {177 seen.set(config.baseUri());178 return CANNED_SESSION_RESPONSE;179 })180 .build();181 assertThat(seen.get()).isEqualTo(uri);182 }183 @Test184 public void shouldUseGivenDriverServiceForUrlIfProvided() throws IOException {185 URI uri = URI.create("http://localhost:9898");186 URL url = uri.toURL();187 DriverService service = new FakeDriverService() {188 @Override189 public URL getUrl() {190 return url;191 }192 };193 AtomicReference<URI> seen = new AtomicReference<>();194 RemoteWebDriver.builder()195 .oneOf(new FirefoxOptions())196 .withDriverService(service)197 .connectingWith(config -> {198 seen.set(config.baseUri());199 return req -> CANNED_SESSION_RESPONSE;200 })201 .build();202 assertThat(seen.get()).isEqualTo(uri);203 }204 @Test205 public void settingBothDriverServiceAndUrlIsAnError() throws IOException {206 RemoteWebDriverBuilder builder = RemoteWebDriver.builder()207 .withDriverService(new FakeDriverService());208 assertThatExceptionOfType(IllegalArgumentException.class)209 .isThrownBy(() -> builder.address("http://localhost:89789"));210 }211 @Test212 public void oneOfWillClearOutTheCurrentlySetCapabilities() {213 AtomicBoolean allOk = new AtomicBoolean();214 RemoteWebDriver.builder()215 .oneOf(new FirefoxOptions())216 .addAlternative(new InternetExplorerOptions())217 .oneOf(new ChromeOptions())218 .address("http://localhost:34576")219 .connectingWith(config -> req -> {220 List<Capabilities> caps = listCapabilities(req);221 allOk.set(caps.size() == 1 && caps.get(0).getBrowserName().equals(CHROME));222 return CANNED_SESSION_RESPONSE;223 })224 .build();225 assertThat(allOk.get()).isTrue();226 }227 @Test228 public void shouldBeAbleToSetClientConfigDirectly() {229 URI uri = URI.create("http://localhost:5763");230 AtomicReference<URI> seen = new AtomicReference<>();231 RemoteWebDriver.builder()232 .address(uri.toString())233 .oneOf(new FirefoxOptions())234 .connectingWith(config -> {235 seen.set(config.baseUri());236 return req -> CANNED_SESSION_RESPONSE;237 })238 .build();239 assertThat(seen.get()).isEqualTo(uri);240 }241 @Test242 public void shouldSetRemoteHostUriOnClientConfigIfSet() {243 URI uri = URI.create("http://localhost:6546");244 ClientConfig config = ClientConfig.defaultConfig().baseUri(uri);245 AtomicReference<URI> seen = new AtomicReference<>();246 RemoteWebDriver.builder()247 .config(config)248 .oneOf(new FirefoxOptions())249 .connectingWith(c -> {250 seen.set(c.baseUri());251 return req -> CANNED_SESSION_RESPONSE;252 })253 .build();254 assertThat(seen.get()).isEqualTo(uri);255 }256 @Test257 public void shouldSetSessionIdFromW3CResponse() {258 RemoteWebDriver driver = (RemoteWebDriver) RemoteWebDriver.builder()259 .oneOf(new FirefoxOptions())260 .address("http://localhost:34576")261 .connectingWith(config -> req -> CANNED_SESSION_RESPONSE)262 .build();263 assertThat(driver.getSessionId()).isEqualTo(SESSION_ID);264 }265 @Test266 public void commandsShouldBeSentWithW3CHeaders() {267 AtomicBoolean allOk = new AtomicBoolean(false);268 RemoteWebDriver.builder()269 .oneOf(new FirefoxOptions())270 .address("http://localhost:34576")271 .connectingWith(config -> req -> {272 allOk.set("no-cache".equals(req.getHeader("Cache-Control")) && JSON_UTF_8.equals(req.getHeader("Content-Type")));273 return CANNED_SESSION_RESPONSE;274 })275 .build();276 assertThat(allOk.get()).isTrue();277 }278 @Test279 public void shouldUseWebDriverInfoToFindAMatchingDriverImplementationForRequestedCapabilitiesIfRemoteUrlNotSet() {280 }281 @Test282 public void shouldAugmentDriverIfPossible() {283 }284 @SuppressWarnings("unchecked")285 private List<Capabilities> listCapabilities(HttpRequest request) {...

Full Screen

Full Screen

Source:FirefoxDriver.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 static org.openqa.selenium.remote.CapabilityType.PROXY;19import com.google.common.collect.ImmutableMap;20import org.openqa.selenium.Beta;21import org.openqa.selenium.Capabilities;22import org.openqa.selenium.ImmutableCapabilities;23import org.openqa.selenium.MutableCapabilities;24import org.openqa.selenium.OutputType;25import org.openqa.selenium.PersistentCapabilities;26import org.openqa.selenium.Proxy;27import org.openqa.selenium.WebDriverException;28import org.openqa.selenium.devtools.CdpEndpointFinder;29import org.openqa.selenium.devtools.CdpInfo;30import org.openqa.selenium.devtools.CdpVersionFinder;31import org.openqa.selenium.devtools.Connection;32import org.openqa.selenium.devtools.DevTools;33import org.openqa.selenium.devtools.DevToolsException;34import org.openqa.selenium.devtools.HasDevTools;35import org.openqa.selenium.devtools.noop.NoOpCdpInfo;36import org.openqa.selenium.html5.LocalStorage;37import org.openqa.selenium.html5.SessionStorage;38import org.openqa.selenium.html5.WebStorage;39import org.openqa.selenium.internal.Require;40import org.openqa.selenium.remote.CommandInfo;41import org.openqa.selenium.remote.FileDetector;42import org.openqa.selenium.remote.RemoteWebDriver;43import org.openqa.selenium.remote.RemoteWebDriverBuilder;44import org.openqa.selenium.remote.html5.RemoteWebStorage;45import org.openqa.selenium.remote.http.ClientConfig;46import org.openqa.selenium.remote.http.HttpClient;47import org.openqa.selenium.remote.service.DriverCommandExecutor;48import org.openqa.selenium.remote.service.DriverService;49import java.net.URI;50import java.nio.file.Path;51import java.util.Map;52import java.util.Optional;53/**54 * An implementation of the {#link WebDriver} interface that drives Firefox.55 * <p>56 * The best way to construct a {@code FirefoxDriver} with various options is to make use of the57 * {@link FirefoxOptions}, like so:58 *59 * <pre>60 * FirefoxOptions options = new FirefoxOptions()61 * .addPreference("browser.startup.page", 1)62 * .addPreference("browser.startup.homepage", "https://www.google.co.uk")63 * .setAcceptInsecureCerts(true)64 * .setHeadless(true);65 * WebDriver driver = new FirefoxDriver(options);66 * </pre>67 */68public class FirefoxDriver extends RemoteWebDriver69 implements WebStorage, HasExtensions, HasFullPageScreenshot, HasContext, HasDevTools {70 private final Capabilities capabilities;71 private final RemoteWebStorage webStorage;72 private final HasExtensions extensions;73 private final HasFullPageScreenshot fullPageScreenshot;74 private final HasContext context;75 private final Optional<URI> cdpUri;76 protected FirefoxBinary binary;77 private DevTools devTools;78 public FirefoxDriver() {79 this(new FirefoxOptions());80 }81 /**82 * @deprecated Use {@link #FirefoxDriver(FirefoxOptions)}.83 */84 @Deprecated85 public FirefoxDriver(Capabilities desiredCapabilities) {86 this(new FirefoxOptions(Require.nonNull("Capabilities", desiredCapabilities)));87 }88 /**89 * @deprecated Use {@link #FirefoxDriver(FirefoxDriverService, FirefoxOptions)}.90 */91 @Deprecated92 public FirefoxDriver(FirefoxDriverService service, Capabilities desiredCapabilities) {93 this(94 Require.nonNull("Driver service", service),95 new FirefoxOptions(desiredCapabilities));96 }97 public FirefoxDriver(FirefoxOptions options) {98 this(new FirefoxDriverCommandExecutor(GeckoDriverService.createDefaultService()), options);99 }100 public FirefoxDriver(FirefoxDriverService service) {101 this(service, new FirefoxOptions());102 }103 public FirefoxDriver(FirefoxDriverService service, FirefoxOptions options) {104 this(new FirefoxDriverCommandExecutor(service), options);105 }106 private FirefoxDriver(FirefoxDriverCommandExecutor executor, FirefoxOptions options) {107 super(executor, checkCapabilitiesAndProxy(options));108 webStorage = new RemoteWebStorage(getExecuteMethod());109 extensions = new AddHasExtensions().getImplementation(getCapabilities(), getExecuteMethod());110 fullPageScreenshot = new AddHasFullPageScreenshot().getImplementation(getCapabilities(), getExecuteMethod());111 context = new AddHasContext().getImplementation(getCapabilities(), getExecuteMethod());112 Capabilities capabilities = super.getCapabilities();113 HttpClient.Factory clientFactory = HttpClient.Factory.createDefault();114 Optional<URI> cdpUri = CdpEndpointFinder.getReportedUri("moz:debuggerAddress", capabilities)115 .flatMap(reported -> CdpEndpointFinder.getCdpEndPoint(clientFactory, reported));116 this.cdpUri = cdpUri;117 this.capabilities = cdpUri.map(uri ->118 new ImmutableCapabilities(119 new PersistentCapabilities(capabilities)120 .setCapability("se:cdp", uri.toString())121 .setCapability("se:cdpVersion", "85.0")))122 .orElse(new ImmutableCapabilities(capabilities));123 }124 @Beta125 public static RemoteWebDriverBuilder builder() {126 return RemoteWebDriver.builder().oneOf(new FirefoxOptions());127 }128 /**129 * Check capabilities and proxy if it is set130 */131 private static Capabilities checkCapabilitiesAndProxy(Capabilities capabilities) {132 if (capabilities == null) {133 return new ImmutableCapabilities();134 }135 MutableCapabilities caps = new MutableCapabilities(capabilities);136 // Ensure that the proxy is in a state fit to be sent to the extension137 Proxy proxy = Proxy.extractFrom(capabilities);138 if (proxy != null) {139 caps.setCapability(PROXY, proxy);140 }141 return caps;142 }143 @Override144 public Capabilities getCapabilities() {145 return capabilities;146 }147 @Override148 public void setFileDetector(FileDetector detector) {149 throw new WebDriverException(150 "Setting the file detector only works on remote webdriver instances obtained " +151 "via RemoteWebDriver");152 }153 @Override154 public LocalStorage getLocalStorage() {155 return webStorage.getLocalStorage();156 }157 @Override158 public SessionStorage getSessionStorage() {159 return webStorage.getSessionStorage();160 }161 @Override162 public String installExtension(Path path) {163 Require.nonNull("Path", path);164 return extensions.installExtension(path);165 }166 @Override167 public String installExtension(Path path, Boolean temporary) {168 Require.nonNull("Path", path);169 Require.nonNull("Temporary", temporary);170 return extensions.installExtension(path, temporary);171 }172 @Override173 public void uninstallExtension(String extensionId) {174 Require.nonNull("Extension ID", extensionId);175 extensions.uninstallExtension(extensionId);176 }177 /**178 * Capture the full page screenshot and store it in the specified location.179 *180 * @param <X> Return type for getFullPageScreenshotAs.181 * @param outputType target type, @see OutputType182 * @return Object in which is stored information about the screenshot.183 * @throws WebDriverException on failure.184 */185 @Override186 public <X> X getFullPageScreenshotAs(OutputType<X> outputType) throws WebDriverException {187 Require.nonNull("OutputType", outputType);188 return fullPageScreenshot.getFullPageScreenshotAs(outputType);189 }190 @Override191 public FirefoxCommandContext getContext() {192 return context.getContext();193 }194 @Override195 public void setContext(FirefoxCommandContext commandContext) {196 Require.nonNull("Firefox Command Context", commandContext);197 context.setContext(commandContext);198 }199 @Override200 public Optional<DevTools> maybeGetDevTools() {201 if (devTools != null) {202 return Optional.of(devTools);203 }204 if (!cdpUri.isPresent()) {205 return Optional.empty();206 }207 URI wsUri = cdpUri.orElseThrow(() ->208 new DevToolsException("This version of Firefox or geckodriver does not support CDP"));209 HttpClient.Factory clientFactory = HttpClient.Factory.createDefault();210 ClientConfig wsConfig = ClientConfig.defaultConfig().baseUri(wsUri);211 HttpClient wsClient = clientFactory.createClient(wsConfig);212 Connection connection = new Connection(wsClient, wsUri.toString());213 CdpInfo cdpInfo = new CdpVersionFinder().match("85.0").orElseGet(NoOpCdpInfo::new);214 devTools = new DevTools(cdpInfo::getDomains, connection);215 return Optional.of(devTools);216 }217 @Override218 public DevTools getDevTools() {219 if (!cdpUri.isPresent()) {220 throw new DevToolsException("This version of Firefox or geckodriver does not support CDP");221 }222 return maybeGetDevTools()223 .orElseThrow(() -> new DevToolsException("Unable to initialize CDP connection"));224 }225 public static final class SystemProperty {226 /**227 * System property that defines the location of the Firefox executable file.228 */229 public static final String BROWSER_BINARY = "webdriver.firefox.bin";230 /**231 * System property that defines the location of the file where Firefox log should be stored.232 */233 public static final String BROWSER_LOGFILE = "webdriver.firefox.logfile";234 /**235 * System property that defines the profile that should be used as a template.236 * When the driver starts, it will make a copy of the profile it is using,237 * rather than using that profile directly.238 */239 public static final String BROWSER_PROFILE = "webdriver.firefox.profile";240 }241 public static final class Capability {242 public static final String BINARY = "firefox_binary";243 public static final String PROFILE = "firefox_profile";244 public static final String MARIONETTE = "marionette";245 }246 private static class FirefoxDriverCommandExecutor extends DriverCommandExecutor {247 public FirefoxDriverCommandExecutor(DriverService service) {248 super(service, getExtraCommands());249 }250 private static Map<String, CommandInfo> getExtraCommands() {251 return ImmutableMap.<String, CommandInfo>builder()252 .putAll(new AddHasContext().getAdditionalCommands())253 .putAll(new AddHasExtensions().getAdditionalCommands())254 .putAll(new AddHasFullPageScreenshot().getAdditionalCommands())255 .build();256 }257 }258}...

Full Screen

Full Screen

Source:WdpDocker.java Github

copy

Full Screen

...17import com.github.dockerjava.core.DockerClientConfig;18import com.github.dockerjava.core.DockerClientImpl;19import com.github.dockerjava.httpclient5.ApacheDockerHttpClient;20import com.github.dockerjava.transport.DockerHttpClient;21import net.ghue.jelenium.api.config.JeleniumConfig;22import net.ghue.jelenium.impl.Utils;23import net.ghue.jelenium.impl.suite.WebDriverSessionBase;24public final class WdpDocker implements WebDriverProvider {25 private static final class WdSessionDocker extends WebDriverSessionBase {26 private final String browser;27 private final String containerId;28 private final DockerClient docker;29 public WdSessionDocker( RemoteWebDriver driver, DockerClient docker, String containerId,30 String browser ) {31 super( driver );32 this.containerId = containerId;33 this.docker = docker;34 this.browser = browser;35 }...

Full Screen

Full Screen

Source:EdgeDriverFunctionalTest.java Github

copy

Full Screen

...53 }54 @Test55 public void builderWithClientConfigthrowsException() {56 ClientConfig clientConfig = ClientConfig.defaultConfig().readTimeout(Duration.ofMinutes(1));57 RemoteWebDriverBuilder builder = EdgeDriver.builder().config(clientConfig);58 assertThatExceptionOfType(IllegalArgumentException.class)59 .isThrownBy(builder::build)60 .withMessage("ClientConfig instances do not work for Local Drivers");61 }62 @Test63 public void canSetPermission() {64 HasPermissions permissions = (HasPermissions) driver;65 driver.get(pages.clicksPage);66 assumeThat(checkPermission(driver, CLIPBOARD_READ)).isEqualTo("prompt");67 assumeThat(checkPermission(driver, CLIPBOARD_WRITE)).isEqualTo("granted");68 permissions.setPermission(CLIPBOARD_READ, "denied");69 permissions.setPermission(CLIPBOARD_WRITE, "prompt");70 assertThat(checkPermission(driver, CLIPBOARD_READ)).isEqualTo("denied");71 assertThat(checkPermission(driver, CLIPBOARD_WRITE)).isEqualTo("prompt");...

Full Screen

Full Screen

Source:ChromeDriver.java Github

copy

Full Screen

...34 */35public class ChromeDriver extends ChromiumDriver {36 /**37 * Creates a new ChromeDriver using the {@link ChromeDriverService#createDefaultService default}38 * server configuration.39 *40 * @see #ChromeDriver(ChromeDriverService, ChromeOptions)41 */42 public ChromeDriver() {43 this(ChromeDriverService.createDefaultService(), new ChromeOptions());44 }45 /**46 * Creates a new ChromeDriver instance. The {@code service} will be started along with the driver,47 * and shutdown upon calling {@link #quit()}.48 *49 * @param service The service to use.50 * @see RemoteWebDriver#RemoteWebDriver(org.openqa.selenium.remote.CommandExecutor, Capabilities)51 */52 public ChromeDriver(ChromeDriverService service) {...

Full Screen

Full Screen

Source:InternetExplorerDriverTest.java Github

copy

Full Screen

...49 }50 @Test51 public void builderWithClientConfigthrowsException() {52 ClientConfig clientConfig = ClientConfig.defaultConfig().readTimeout(Duration.ofMinutes(1));53 RemoteWebDriverBuilder builder = InternetExplorerDriver.builder().config(clientConfig);54 assertThatExceptionOfType(IllegalArgumentException.class)55 .isThrownBy(builder::build)56 .withMessage("ClientConfig instances do not work for Local Drivers");57 }58 @Test59 @NoDriverBeforeTest60 public void canRestartTheIeDriverInATightLoop() {61 for (int i = 0; i < 5; i++) {62 WebDriver driver = newIeDriver();63 driver.quit();64 }65 }66 @Test67 @NoDriverBeforeTest...

Full Screen

Full Screen

Source:SafariDriverTest.java Github

copy

Full Screen

...63 }64 @Test65 public void builderWithClientConfigthrowsException() {66 ClientConfig clientConfig = ClientConfig.defaultConfig().readTimeout(Duration.ofMinutes(1));67 RemoteWebDriverBuilder builder = SafariDriver.builder().config(clientConfig);68 assertThatExceptionOfType(IllegalArgumentException.class)69 .isThrownBy(builder::build)70 .withMessage("ClientConfig instances do not work for Local Drivers");71 }72 @Test73 public void canStartADriverUsingAService() throws IOException {74 removeDriver();75 int port = PortProber.findFreePort();76 service = new SafariDriverService.Builder().usingPort(port).build();77 service.start();78 driver2 = new SafariDriver(service);79 driver2.get(pages.xhtmlTestPage);80 assertThat(driver2.getTitle()).isEqualTo("XHTML Test Page");81 }...

Full Screen

Full Screen

config

Using AI Code Generation

copy

Full Screen

1RemoteWebDriverBuilder builder = new RemoteWebDriverBuilder();2builder.config().setAcceptInsecureCerts(true);3builder.config().setPageLoadStrategy("eager");4builder.config().setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.ACCEPT);5builder.config().setProxy(Proxy.NO_PROXY);6builder.config().setLogLevel(Level.OFF);7builder.config().setEnableNativeEvents(true);8builder.config().setEnablePersistentHover(true);9builder.config().setEnableUntrustedCertificateIssuer(true);10builder.config().setRequireWindowFocus(false);11builder.config().setEnableVNC(true);12builder.config().setEnableVideo(true);13builder.config().setVideoName("video.mp4");14builder.config().setVideoScreenSize("1280x720");15builder.config().setVideoFrameRate(24);16builder.config().setVideoCodec("h264");17builder.config().setVideoBitrate(1000);18builder.config().setVideoPixelFormat("yuv420p");19builder.config().setVideoLossless(true);20builder.config().setVideoOptions(Arrays.asList("-preset", "ultrafast"));21builder.config().setEnableLog(true);22builder.config().setLogName("log.txt");23builder.config().setLogOptions(Arrays.asList("-v", "quiet"));24builder.config().setEnableNetwork(true);25builder.config().setNetworkTraffic(true);26builder.config().setNetworkLogs(true);27builder.config().setNetworkOptions(Arrays.asList("-v", "quiet"));28builder.config().setEnablePerformance(true);29builder.config().setPerformanceLogs(true);30builder.config().setPerformanceOptions(Arrays.asList("-v", "quiet"));31builder.config().setEnableTimeline(true);32builder.config().setTimelineLogs(true);33builder.config().setTimelineOptions(Arrays.asList("-v", "quiet"));34builder.config().setEnableHeadless(true);35builder.config().setEnableMobileEmulation(true);36builder.config().setMobileEmulationDeviceName("iPhone X");37builder.config().setMobileEmulationDeviceMetrics(375, 812, 3.0);38builder.config().setMobileEmulationUserAgent("Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1 Mobile/15E148 Safari/604.1");39builder.config().setEnableChrome(true);40builder.config().setChromeBinary("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe");41builder.config().setChromeArguments(Arrays.asList("--headless"));

Full Screen

Full Screen

config

Using AI Code Generation

copy

Full Screen

1RemoteWebDriverBuilder builder = new RemoteWebDriverBuilder();2builder.setDesiredCapabilities(DesiredCapabilities.chrome());3builder.setBrowserSessionReuse(true);4builder.setSessionReuseTimeout(10);5RemoteWebDriver driver = builder.build();6driver.quit();7RemoteWebDriver driver = new RemoteWebDriverBuilder()8 .setDesiredCapabilities(DesiredCapabilities.chrome())9 .setBrowserSessionReuse(true)10 .setSessionReuseTimeout(10)11 .build();12driver.quit();13RemoteWebDriverBuilder builder = new RemoteWebDriverBuilder();14builder.setDesiredCapabilities(DesiredCapabilities.chrome());15builder.setBrowserSessionReuse(true);16builder.setSessionReuseTimeout(10);17RemoteWebDriver driver = builder.build();18driver.quit();19RemoteWebDriver driver = new RemoteWebDriverBuilder()20 .setDesiredCapabilities(DesiredCapabilities.chrome())21 .setBrowserSessionReuse(true)22 .setSessionReuseTimeout(10)23 .build();24driver.quit();25Chrome v70.0.3538.77 (Official Build) (64-bit)26import org.openqa.selenium.By;27import org.openqa.selenium.WebDriver;28import org.openqa.selenium.chrome.ChromeDriver;29public class Test {30 public static void main(String[] args) {31 WebDriver driver = new ChromeDriver();32 driver.findElement(By.name("q")).sendKeys("hello");33 driver.quit();34 }35}

Full Screen

Full Screen

config

Using AI Code Generation

copy

Full Screen

1import org.openqa.selenium.remote.RemoteWebDriverBuilder2import org.openqa.selenium.remote.RemoteWebDriverBuilder.*3RemoteWebDriverBuilder.builder()4 .config(new Config().withCapabilities(new DesiredCapabilities()))5 .build()6import org.openqa.selenium.remote.RemoteWebDriverBuilder7import org.openqa.selenium.remote.RemoteWebDriverBuilder.*8RemoteWebDriverBuilder.builder()9 .config(new Config().withCapabilities(new DesiredCapabilities()))10 .build()11import org.openqa.selenium.remote.RemoteWebDriverBuilder12import org.openqa.selenium.remote.RemoteWebDriverBuilder.*13RemoteWebDriverBuilder.builder()14 .config(new Config().withCapabilities(new DesiredCapabilities()))15 .build()16import org.openqa.selenium.remote.RemoteWebDriverBuilder17import org.openqa.selenium.remote.RemoteWebDriverBuilder.*18RemoteWebDriverBuilder.builder()19 .config(new Config().withCapabilities(new DesiredCapabilities()))20 .build()21import org.openqa.selenium.remote.RemoteWebDriverBuilder22import org.openqa.selenium.remote.RemoteWebDriverBuilder.*23RemoteWebDriverBuilder.builder()24 .config(new Config().withCapabilities(new DesiredCapabilities()))25 .build()26import org.openqa.selenium.remote.RemoteWebDriverBuilder27import org.openqa.selenium.remote.RemoteWebDriverBuilder.*28RemoteWebDriverBuilder.builder()29 .config(new Config().withCapabilities(new DesiredCapabilities()))30 .build()31import org.openqa.selenium.remote.RemoteWebDriverBuilder32import org.openqa.selenium.remote.RemoteWebDriverBuilder.*33RemoteWebDriverBuilder.builder()34 .config(new Config().withCapabilities(new DesiredCapabilities()))35 .build()36import org.openqa.selenium.remote.RemoteWebDriverBuilder37import org.openqa.selenium.remote.RemoteWebDriverBuilder.*38RemoteWebDriverBuilder.builder()39 .config(new Config().withCapabilities(new DesiredCapabilities()))40 .build()41import org.openqa.selenium.remote.RemoteWebDriverBuilder42import org.openqa.selenium.remote.RemoteWebDriverBuilder.*43RemoteWebDriverBuilder.builder()44 .config(new Config().withCapabilities(new DesiredCapabilities()))45 .build()46import org.openqa

Full Screen

Full Screen

config

Using AI Code Generation

copy

Full Screen

1package com.automationrhapsody.selenium4;2import org.openqa.selenium.Dimension;3import org.openqa.selenium.MutableCapabilities;4import org.openqa.selenium.Point;5import org.openqa.selenium.chrome.ChromeOptions;6import org.openqa.selenium.remote.RemoteWebDriverBuilder;7import org.openqa.selenium.remote.RemoteWebDriverBuilder.RemoteWebDriverBuilderOptions;8import org.openqa.selenium.remote.RemoteWebDriverBuilder.RemoteWebDriverBuilderOptions.RemoteWebDriverBuilderOptionsOptions;9import org.openqa.selenium.remote.RemoteWebDriverBuilder.RemoteWebDriverBuilderOptions.RemoteWebDriverBuilderOptionsOptions.RemoteWebDriverBuilderOptionsOptionsOptions;10import org.testng.annotations.Test;11public class RemoteWebDriverBuilderTest {12 public void testRemoteWebDriverBuilder() {13 new RemoteWebDriverBuilderOptionsOptionsOptions()14 .setWindowSize(new Dimension(1024, 768))15 .setWindowPosition(new Point(0, 0))16 .setAcceptInsecureCerts(true)17 .setUnhandledPromptBehavior("ignore");18 new RemoteWebDriverBuilderOptionsOptions()19 .setOptions(new MutableCapabilities())20 .setOptions(new ChromeOptions())21 .setOptions(remoteWebDriverBuilderOptionsOptionsOptions);22 new RemoteWebDriverBuilderOptions()23 .setOptions(remoteWebDriverBuilderOptionsOptions);24 new RemoteWebDriverBuilder()25 .config(remoteWebDriverBuilderOptions);26 }27}28RemoteWebDriverBuilderTest > testRemoteWebDriverBuilder() PASSED

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