diff --git a/selenium-bridge/src/test/java/io/appium/java_client/selenium/SeleniumBridgeTest.java b/selenium-bridge/src/test/java/io/appium/java_client/selenium/SeleniumBridgeTest.java index 20ac611a9..1dd6e9afc 100644 --- a/selenium-bridge/src/test/java/io/appium/java_client/selenium/SeleniumBridgeTest.java +++ b/selenium-bridge/src/test/java/io/appium/java_client/selenium/SeleniumBridgeTest.java @@ -18,6 +18,7 @@ import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpServer; +import io.appium.java_client.AppiumClientConfig; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.android.options.UiAutomator2Options; import org.junit.jupiter.api.AfterEach; @@ -37,6 +38,7 @@ import java.io.IOException; import java.io.OutputStream; import java.net.InetSocketAddress; +import java.net.URI; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.List; @@ -261,4 +263,23 @@ void failsToProvideBiDiWithoutTheWebSocketUrlCapability() throws IOException { assertThrows(BiDiException.class, seleniumDriver::getHandle); } + + @Test + void propagatesDirectConnectServerUrlToSeleniumClientConfig() throws IOException { + extraCapabilities = "\"appium:directConnectProtocol\":\"https\"," + + "\"appium:directConnectHost\":\"203.0.113.1\"," + + "\"appium:directConnectPort\":4443," + + "\"appium:directConnectPath\":\"/wd/hub\","; + var clientConfig = AppiumClientConfig.defaultConfig() + .baseUri(URI.create("http://127.0.0.1:" + server.getAddress().getPort())) + .directConnect(true); + var appiumDriver = new AndroidDriver(clientConfig, + new UiAutomator2Options().setDeviceName("Android Emulator")); + + var seleniumDriver = SeleniumBridge.asRemoteWebDriver(appiumDriver); + + assertEquals(URI.create("https://203.0.113.1:4443/wd/hub"), + seleniumDriver.getClientConfig().baseUri()); + seleniumDriver.closeBiDi(); + } } diff --git a/src/main/java/io/appium/java_client/AppiumDriver.java b/src/main/java/io/appium/java_client/AppiumDriver.java index ccdfffd13..c471fbf50 100644 --- a/src/main/java/io/appium/java_client/AppiumDriver.java +++ b/src/main/java/io/appium/java_client/AppiumDriver.java @@ -31,7 +31,7 @@ import io.appium.java_client.remote.options.BaseOptions; import io.appium.java_client.service.local.AppiumDriverLocalService; import io.appium.java_client.service.local.AppiumServiceBuilder; -import lombok.Getter; +import org.jspecify.annotations.Nullable; import org.openqa.selenium.Capabilities; import org.openqa.selenium.ImmutableCapabilities; import org.openqa.selenium.OutputType; @@ -64,8 +64,6 @@ public class AppiumDriver extends AppiumRemoteWebDriver implements private static final ErrorHandler ERROR_HANDLER = new ErrorHandler(new ErrorCodesMobile()); // frequently used command parameters - @Getter - private final URL remoteAddress; private final ExecuteMethod executeMethod; /** @@ -80,7 +78,6 @@ public AppiumDriver(AppiumCommandExecutor executor, Capabilities capabilities) { super(executor, capabilities); this.executeMethod = new AppiumExecutionMethod(this); super.setErrorHandler(ERROR_HANDLER); - this.remoteAddress = executor.getAddressOfRemoteServer(); } /** @@ -216,11 +213,20 @@ public AppiumDriver(URL remoteSessionAddress, String platformName, String automa setCommandExecutor(executor); this.executeMethod = new AppiumExecutionMethod(this); super.setErrorHandler(ERROR_HANDLER); - this.remoteAddress = executor.getAddressOfRemoteServer(); setSessionId(sessionAddress.getId()); } + /** + * Gets the remote server address to which commands are sent. + * + * @return the remote server URL, or {@code null} if not configured + */ + @Nullable + public URL getRemoteAddress() { + return ((AppiumCommandExecutor) getCommandExecutor()).getAddressOfRemoteServer(); + } + @Override public ExecuteMethod getExecuteMethod() { return executeMethod; diff --git a/src/main/java/io/appium/java_client/android/ListensToLogcatMessages.java b/src/main/java/io/appium/java_client/android/ListensToLogcatMessages.java index d3fcb5c7c..457e1eee5 100644 --- a/src/main/java/io/appium/java_client/android/ListensToLogcatMessages.java +++ b/src/main/java/io/appium/java_client/android/ListensToLogcatMessages.java @@ -18,12 +18,9 @@ import io.appium.java_client.CommandExecutionHelper; import io.appium.java_client.ExecutesMethod; -import io.appium.java_client.remote.AppiumCommandExecutor; -import io.appium.java_client.remote.AppiumRemoteWebDriver; -import io.appium.java_client.remote.SessionId; +import io.appium.java_client.internal.LogBroadcastEndpoints; import io.appium.java_client.ws.StringWebSocketClient; -import java.net.URI; import java.net.URL; import java.util.function.Consumer; @@ -40,21 +37,29 @@ public interface ListensToLogcatMessages extends ExecutesMethod { /** * Start logcat messages broadcast via web socket. - * This method assumes that Appium server is running on localhost and - * is assigned to the default port (4723). + * This method uses the current remote server host (mapping wildcard addresses to {@code 127.0.0.1}) + * and port when available, falling back to {@code 127.0.0.1:4723}. */ default void startLogcatBroadcast() { - startLogcatBroadcast("127.0.0.1"); + URL serverUrl = LogBroadcastEndpoints.resolveServerUrl(this); + startLogcatBroadcast( + LogBroadcastEndpoints.resolveHost(serverUrl, "127.0.0.1"), + LogBroadcastEndpoints.resolvePort(serverUrl, DEFAULT_APPIUM_PORT) + ); } /** * Start logcat messages broadcast via web socket. - * This method assumes that Appium server is assigned to the default port (4723). + * This method uses the current remote server port when available, + * falling back to the default port (4723). * * @param host the name of the host where Appium server is running */ default void startLogcatBroadcast(String host) { - startLogcatBroadcast(host, DEFAULT_APPIUM_PORT); + startLogcatBroadcast( + host, + LogBroadcastEndpoints.resolvePort(LogBroadcastEndpoints.resolveServerUrl(this), DEFAULT_APPIUM_PORT) + ); } /** @@ -64,13 +69,7 @@ default void startLogcatBroadcast(String host) { * @param port the port of the host where Appium server is running */ default void startLogcatBroadcast(String host, int port) { - var remoteWebDriver = (AppiumRemoteWebDriver) this; - URL serverUrl = ((AppiumCommandExecutor) remoteWebDriver.getCommandExecutor()).getAddressOfRemoteServer(); - var scheme = "https".equals(serverUrl.getProtocol()) ? "wss" : "ws"; - CommandExecutionHelper.executeScript(this, "mobile: startLogsBroadcast"); - SessionId sessionId = remoteWebDriver.getSessionId(); - var endpoint = String.format("%s://%s:%s/ws/session/%s/appium/device/logcat", scheme, host, port, sessionId); - getLogcatClient().connect(URI.create(endpoint)); + LogBroadcastEndpoints.startBroadcast(this, getLogcatClient(), host, port, "logcat"); } /** diff --git a/src/main/java/io/appium/java_client/internal/LogBroadcastEndpoints.java b/src/main/java/io/appium/java_client/internal/LogBroadcastEndpoints.java new file mode 100644 index 000000000..66cccc23a --- /dev/null +++ b/src/main/java/io/appium/java_client/internal/LogBroadcastEndpoints.java @@ -0,0 +1,195 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.appium.java_client.internal; + +import io.appium.java_client.CommandExecutionHelper; +import io.appium.java_client.ExecutesMethod; +import io.appium.java_client.remote.AppiumCommandExecutor; +import io.appium.java_client.remote.AppiumRemoteWebDriver; +import io.appium.java_client.remote.DirectConnect; +import io.appium.java_client.remote.SessionId; +import io.appium.java_client.ws.StringWebSocketClient; +import org.jspecify.annotations.NullMarked; +import org.jspecify.annotations.Nullable; + +import java.net.URI; +import java.net.URL; +import java.util.List; +import java.util.Locale; +import java.util.Set; + +/** + * Shared endpoint resolution and WebSocket startup helpers for device log broadcast listeners. + */ +@NullMarked +public final class LogBroadcastEndpoints { + private static final Set LOOPBACK_HOSTS = Set.of("localhost", "127.0.0.1", "::1", "0:0:0:0:0:0:0:1"); + private static final Set WILDCARD_HOSTS = Set.of("0.0.0.0", "::", "0:0:0:0:0:0:0:0"); + + private LogBroadcastEndpoints() { + } + + /** + * Resolves the active remote server URL from a driver's command executor. + * + * @param driver the driver executing log broadcast commands + * @return the current remote server URL, or {@code null} if unavailable + */ + @Nullable + public static URL resolveServerUrl(ExecutesMethod driver) { + return getExecutor(driver).getAddressOfRemoteServer(); + } + + /** + * Resolves the host for a log broadcast WebSocket connection from the server URL, + * mapping missing or wildcard bind hosts ({@code 0.0.0.0}, {@code [::]}) to {@code fallbackHost}. + * + * @param serverUrl the active remote server URL, or {@code null} if unknown + * @param fallbackHost the loopback host to return when {@code serverUrl} has no usable host + * @return the resolved broadcast host + */ + public static String resolveHost(@Nullable URL serverUrl, String fallbackHost) { + String host = serverUrl != null ? serverUrl.getHost() : ""; + if (host.isEmpty() || WILDCARD_HOSTS.contains(normalizeHost(host))) { + return fallbackHost; + } + return host; + } + + /** + * Resolves the port for a log broadcast WebSocket connection from the server URL. + * + * @param serverUrl the active remote server URL, or {@code null} if unknown + * @param fallbackPort the port to return when {@code serverUrl} defines neither an explicit nor default port + * @return the resolved broadcast port + */ + public static int resolvePort(@Nullable URL serverUrl, int fallbackPort) { + if (serverUrl == null) { + return fallbackPort; + } + if (serverUrl.getPort() > 0) { + return serverUrl.getPort(); + } + return serverUrl.getDefaultPort() > 0 ? serverUrl.getDefaultPort() : fallbackPort; + } + + /** + * Starts server-side log streaming and connects the WebSocket client to the resolved broadcast endpoint. + * + * @param driver the driver executing {@code mobile: startLogsBroadcast} + * @param client the target WebSocket client + * @param host the target WebSocket host + * @param port the target WebSocket port + * @param deviceLogType the log endpoint suffix (such as {@code logcat} or {@code syslog}) + */ + public static void startBroadcast( + ExecutesMethod driver, + StringWebSocketClient client, + String host, + int port, + String deviceLogType + ) { + var remoteWebDriver = (AppiumRemoteWebDriver) driver; + var executor = getExecutor(driver); + CommandExecutionHelper.executeScript(driver, "mobile: startLogsBroadcast"); + URI endpoint = buildBroadcastUri( + executor.getAddressOfRemoteServer(), + executor.getReplacedHttpServerUrls(), + host, + port, + remoteWebDriver.getSessionId(), + deviceLogType + ); + client.connect(endpoint); + } + + /** + * Builds a device log broadcast WebSocket URI. Uses {@code wss} when {@code serverUrl} uses + * {@code https}, unless the requested {@code host:port} matches a plain-{@code http} server URL + * previously replaced (e.g. by {@code directConnect}) and does not match the active {@code serverUrl}. + * + * @param serverUrl the active remote server URL, or {@code null} if unknown + * @param replacedHttpServerUrls plain-{@code http} server URLs previously replaced on the executor + * @param host the target WebSocket host + * @param port the target WebSocket port + * @param sessionId the active session identifier + * @param deviceLogType the log endpoint suffix (such as {@code logcat} or {@code syslog}) + * @return the WebSocket endpoint URI + */ + public static URI buildBroadcastUri( + @Nullable URL serverUrl, + List replacedHttpServerUrls, + String host, + int port, + @Nullable SessionId sessionId, + String deviceLogType + ) { + String scheme = chooseScheme(serverUrl, replacedHttpServerUrls, host, port); + String endpoint = String.format( + "%s://%s:%s/ws/session/%s/appium/device/%s", + scheme, DirectConnect.formatHost(host), port, sessionId, deviceLogType + ); + return URI.create(endpoint); + } + + private static AppiumCommandExecutor getExecutor(ExecutesMethod driver) { + var remoteWebDriver = (AppiumRemoteWebDriver) driver; + return (AppiumCommandExecutor) remoteWebDriver.getCommandExecutor(); + } + + private static String chooseScheme( + @Nullable URL serverUrl, + List replacedHttpServerUrls, + String host, + int port + ) { + if (serverUrl == null || !"https".equalsIgnoreCase(serverUrl.getProtocol())) { + return "ws"; + } + if (!matchesEndpoint(serverUrl, host, port) + && replacedHttpServerUrls.stream().anyMatch(url -> matchesEndpoint(url, host, port))) { + return "ws"; + } + return "wss"; + } + + private static boolean matchesEndpoint(URL candidateUrl, String host, int port) { + if (resolvePort(candidateUrl, -1) != port) { + return false; + } + String candidateHost = normalizeComparableHost(candidateUrl.getHost()); + String targetHost = normalizeComparableHost(host); + if (candidateHost.isEmpty() || targetHost.isEmpty()) { + return false; + } + return candidateHost.equals(targetHost) + || LOOPBACK_HOSTS.contains(candidateHost) && LOOPBACK_HOSTS.contains(targetHost); + } + + private static String normalizeComparableHost(String host) { + String normalized = normalizeHost(host); + return WILDCARD_HOSTS.contains(normalized) ? "127.0.0.1" : normalized; + } + + private static String normalizeHost(String host) { + String trimmed = host.trim().toLowerCase(Locale.ROOT); + if (trimmed.startsWith("[") && trimmed.endsWith("]") && trimmed.length() > 2) { + return trimmed.substring(1, trimmed.length() - 1); + } + return trimmed; + } +} diff --git a/src/main/java/io/appium/java_client/ios/ListensToSyslogMessages.java b/src/main/java/io/appium/java_client/ios/ListensToSyslogMessages.java index 4558f5d23..73c6e42c8 100644 --- a/src/main/java/io/appium/java_client/ios/ListensToSyslogMessages.java +++ b/src/main/java/io/appium/java_client/ios/ListensToSyslogMessages.java @@ -18,12 +18,9 @@ import io.appium.java_client.CommandExecutionHelper; import io.appium.java_client.ExecutesMethod; -import io.appium.java_client.remote.AppiumCommandExecutor; -import io.appium.java_client.remote.AppiumRemoteWebDriver; -import io.appium.java_client.remote.SessionId; +import io.appium.java_client.internal.LogBroadcastEndpoints; import io.appium.java_client.ws.StringWebSocketClient; -import java.net.URI; import java.net.URL; import java.util.function.Consumer; @@ -41,21 +38,29 @@ public interface ListensToSyslogMessages extends ExecutesMethod { /** * Start syslog messages broadcast via web socket. - * This method assumes that Appium server is running on localhost and - * is assigned to the default port (4723). + * This method uses the current remote server host (mapping wildcard addresses to {@code localhost}) + * and port when available, falling back to {@code localhost:4723}. */ default void startSyslogBroadcast() { - startSyslogBroadcast("localhost"); + URL serverUrl = LogBroadcastEndpoints.resolveServerUrl(this); + startSyslogBroadcast( + LogBroadcastEndpoints.resolveHost(serverUrl, "localhost"), + LogBroadcastEndpoints.resolvePort(serverUrl, DEFAULT_APPIUM_PORT) + ); } /** * Start syslog messages broadcast via web socket. - * This method assumes that Appium server is assigned to the default port (4723). + * This method uses the current remote server port when available, + * falling back to the default port (4723). * * @param host the name of the host where Appium server is running */ default void startSyslogBroadcast(String host) { - startSyslogBroadcast(host, DEFAULT_APPIUM_PORT); + startSyslogBroadcast( + host, + LogBroadcastEndpoints.resolvePort(LogBroadcastEndpoints.resolveServerUrl(this), DEFAULT_APPIUM_PORT) + ); } /** @@ -65,13 +70,7 @@ default void startSyslogBroadcast(String host) { * @param port the port of the host where Appium server is running */ default void startSyslogBroadcast(String host, int port) { - var remoteWebDriver = (AppiumRemoteWebDriver) this; - URL serverUrl = ((AppiumCommandExecutor) remoteWebDriver.getCommandExecutor()).getAddressOfRemoteServer(); - var scheme = "https".equals(serverUrl.getProtocol()) ? "wss" : "ws"; - CommandExecutionHelper.executeScript(this, "mobile: startLogsBroadcast"); - SessionId sessionId = remoteWebDriver.getSessionId(); - var endpoint = String.format("%s://%s:%s/ws/session/%s/appium/device/syslog", scheme, host, port, sessionId); - getSyslogClient().connect(URI.create(endpoint)); + LogBroadcastEndpoints.startBroadcast(this, getSyslogClient(), host, port, "syslog"); } /** diff --git a/src/main/java/io/appium/java_client/remote/AppiumCommandExecutor.java b/src/main/java/io/appium/java_client/remote/AppiumCommandExecutor.java index aea8263c9..0e9487278 100644 --- a/src/main/java/io/appium/java_client/remote/AppiumCommandExecutor.java +++ b/src/main/java/io/appium/java_client/remote/AppiumCommandExecutor.java @@ -37,8 +37,10 @@ import java.net.ConnectException; import java.net.MalformedURLException; import java.net.URL; +import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Optional; @@ -54,16 +56,29 @@ public class AppiumCommandExecutor implements CommandExecutor, Closeable { private static final String JSON_UTF_8 = "application/json; charset=utf-8"; private final Optional serviceOptional; - @Getter - private final AppiumClientConfig appiumClientConfig; - private final @Nullable URL remoteServer; private final Map additionalCommands; @Getter private final Factory httpClientFactory; - private HttpClient client; + private volatile ClientState clientState; private @Nullable CommandCodec commandCodec; private @Nullable ResponseCodec responseCodec; + private static final class ClientState { + private final AppiumClientConfig config; + private final HttpClient client; + private final List replacedHttpServerUrls; + + private ClientState( + AppiumClientConfig config, + HttpClient client, + List replacedHttpServerUrls + ) { + this.config = config; + this.client = client; + this.replacedHttpServerUrls = replacedHttpServerUrls; + } + } + /** * Create an AppiumCommandExecutor instance. * @@ -78,10 +93,16 @@ public AppiumCommandExecutor( @Nullable Factory httpClientFactory, AppiumClientConfig appiumClientConfig) { this.additionalCommands = new HashMap<>(requireNonNull(additionalCommands, "Additional commands")); - this.appiumClientConfig = requireNonNull(appiumClientConfig, "HTTP client configuration"); + AppiumClientConfig effectiveConfig = requireNonNull(appiumClientConfig, "HTTP client configuration"); + if (service != null && effectiveConfig.baseUri() == null) { + effectiveConfig = effectiveConfig.baseUrl(service.getUrl()); + } this.httpClientFactory = ofNullable(httpClientFactory).orElseGet(Factory::createDefault); - this.client = this.httpClientFactory.createClient(appiumClientConfig); - this.remoteServer = appiumClientConfig.baseUrl(); + this.clientState = new ClientState( + effectiveConfig, + this.httpClientFactory.createClient(effectiveConfig), + List.of() + ); this.serviceOptional = ofNullable(service); } @@ -163,11 +184,12 @@ public AppiumCommandExecutor(Map additionalCommands, * Creates an executor that talks to a local Appium service using the given client configuration. * * @param additionalCommands the map of Appium commands - * @param service the local Appium service to send the commands to + * @param service the local Appium service to send the commands to, or {@code null} if none * @param appiumClientConfig the HTTP client configuration */ public AppiumCommandExecutor(Map additionalCommands, - AppiumDriverLocalService service, AppiumClientConfig appiumClientConfig) { + @Nullable AppiumDriverLocalService service, + AppiumClientConfig appiumClientConfig) { this(additionalCommands, service, Factory.createDefault(), appiumClientConfig); } @@ -180,6 +202,15 @@ public Map getAdditionalCommands() { return Collections.unmodifiableMap(additionalCommands); } + /** + * Returns the HTTP client configuration used by this executor. + * + * @return the HTTP client configuration + */ + public AppiumClientConfig getAppiumClientConfig() { + return clientState.config; + } + /** * The address of the server the commands are sent to. * @@ -187,7 +218,16 @@ public Map getAdditionalCommands() { */ @Nullable public URL getAddressOfRemoteServer() { - return remoteServer; + return clientState.config.baseUrl(); + } + + /** + * Returns the plain-{@code http} server URLs previously replaced via {@link #overrideServerUrl(URL)}. + * + * @return unmodifiable list of replaced {@code http} server URLs + */ + public List getReplacedHttpServerUrls() { + return clientState.replacedHttpServerUrls; } /** @@ -224,7 +264,7 @@ public void setResponseCodec(ResponseCodec codec) { * @return the HTTP client */ public HttpClient getClient() { - return this.client; + return clientState.client; } /** @@ -239,12 +279,20 @@ public HttpClient getClient() { * carrier-grade NAT ({@code 100.64.0.0/10}), IPv6 unique-local ({@code fc00::/7}), * and other non-special addresses are not rejected by this check. */ - protected void overrideServerUrl(URL serverUrl) { - DirectConnectUrlSafety.requireSafeOverrideTarget(serverUrl); - HttpClient newClient = getHttpClientFactory().createClient(appiumClientConfig.baseUrl(serverUrl)); - HttpClient oldClient = this.client; - this.client = newClient; - oldClient.close(); + protected synchronized void overrideServerUrl(URL serverUrl) { + DirectConnectUrlSafety.requireSafeOverrideTarget(requireNonNull(serverUrl, "Server URL")); + ClientState previousState = this.clientState; + AppiumClientConfig updatedConfig = previousState.config.baseUrl(serverUrl); + HttpClient newClient = getHttpClientFactory().createClient(updatedConfig); + URL previousUrl = previousState.config.baseUrl(); + List updatedReplacedHttpUrls = previousState.replacedHttpServerUrls; + if (previousUrl != null && "http".equalsIgnoreCase(previousUrl.getProtocol())) { + List next = new ArrayList<>(updatedReplacedHttpUrls); + next.add(previousUrl); + updatedReplacedHttpUrls = List.copyOf(next); + } + this.clientState = new ClientState(updatedConfig, newClient, updatedReplacedHttpUrls); + previousState.client.close(); } private Response createSession(Command command) { @@ -257,7 +305,7 @@ private Response createSession(Command command) { refreshAdditionalCommands(); setResponseCodec(new AppiumW3CHttpResponseCodec()); Response response = result.createResponse(); - if (appiumClientConfig.isDirectConnectEnabled()) { + if (getAppiumClientConfig().isDirectConnectEnabled()) { setDirectConnect(response); } @@ -292,7 +340,7 @@ private void setDirectConnect(Response response) throws SessionNotCreatedExcepti return; } - if (!directConnect.getProtocol().equals("https")) { + if (!"https".equalsIgnoreCase(directConnect.getProtocol())) { throw new SessionNotCreatedException( String.format("The given protocol '%s' as the direct connection url returned by " + "the remote server is not accurate. Only 'https' is supported.", @@ -363,8 +411,9 @@ private Response executeInSession(Command command) { httpRequest.addHeader("Content-Type", JSON_UTF_8); } + HttpClient activeClient = getClient(); try { - HttpResponse httpResponse = client.execute(httpRequest); + HttpResponse httpResponse = activeClient.execute(httpRequest); Response response = responseCodec.decode(httpResponse); if (response.getSessionId() == null) { @@ -372,7 +421,7 @@ private Response executeInSession(Command command) { response.setSessionId(command.getSessionId().toString()); } if (DriverCommand.QUIT.equals(command.getName())) { - client.close(); + activeClient.close(); } return response; } catch (UnsupportedCommandException e) { @@ -394,6 +443,6 @@ private static Throwable getRootCause(Throwable throwable) { @Override public void close() { - client.close(); + getClient().close(); } } diff --git a/src/main/java/io/appium/java_client/remote/DirectConnect.java b/src/main/java/io/appium/java_client/remote/DirectConnect.java index c191c6eb8..9a6a14d42 100644 --- a/src/main/java/io/appium/java_client/remote/DirectConnect.java +++ b/src/main/java/io/appium/java_client/remote/DirectConnect.java @@ -78,15 +78,45 @@ public boolean isValid() { * @throws MalformedURLException if the built url was invalid */ public URL getUrl() throws MalformedURLException { - String newUrlCandidate = String.format("%s://%s:%s%s", this.protocol, this.host, this.port, this.path); + if (!isValid() || Stream.of(this.protocol, this.host, this.port).anyMatch(String::isBlank)) { + throw createMalformedUrlException( + String.format("%s://%s:%s%s", this.protocol, this.host, this.port, this.path) + ); + } + String newUrlCandidate = String.format("%s://%s:%s%s", + this.protocol, formatHost(this.host), this.port, normalizePath(this.path)); try { return new URL(newUrlCandidate); } catch (MalformedURLException e) { - throw new MalformedURLException( - String.format("The remote server returned an invalid value to build the direct connect URL: %s", - newUrlCandidate) - ); + throw createMalformedUrlException(newUrlCandidate); } } + + /** + * Wraps a bare IPv6 host literal in brackets if not already bracketed. + * + * @param host the host name or IP literal + * @return the URL-safe host representation + */ + public static String formatHost(String host) { + if (!host.startsWith("[") && host.indexOf(':') != host.lastIndexOf(':')) { + return "[" + host + "]"; + } + return host; + } + + private static String normalizePath(String path) { + if (path.isEmpty() || path.startsWith("/")) { + return path; + } + return "/" + path; + } + + private static MalformedURLException createMalformedUrlException(String candidate) { + return new MalformedURLException( + String.format("The remote server returned an invalid value to build the direct connect URL: %s", + candidate) + ); + } } diff --git a/src/test/java/io/appium/java_client/internal/DirectConnectTest.java b/src/test/java/io/appium/java_client/internal/DirectConnectTest.java index 8255c3c5d..3c36076d8 100644 --- a/src/test/java/io/appium/java_client/internal/DirectConnectTest.java +++ b/src/test/java/io/appium/java_client/internal/DirectConnectTest.java @@ -55,5 +55,80 @@ void hasInvalidDirectConnect() { Map responseValue = new HashMap<>(); DirectConnect directConnect = new DirectConnect(responseValue); assertFalse(directConnect.isValid()); + assertThrowsExactly(MalformedURLException.class, directConnect::getUrl); + } + + @Test + void formatsBareIpv6HostAndPreservesBracketedIpv6Host() throws MalformedURLException { + Map bareIpv6 = Map.of( + "appium:directConnectProtocol", "https", + "appium:directConnectHost", "2001:db8::1", + "appium:directConnectPort", "4443", + "appium:directConnectPath", "/wd/hub" + ); + DirectConnect bare = new DirectConnect(bareIpv6); + assertTrue(bare.isValid()); + assertEquals("https://[2001:db8::1]:4443/wd/hub", bare.getUrl().toString()); + + Map bracketedIpv6 = Map.of( + "appium:directConnectProtocol", "https", + "appium:directConnectHost", "[2001:db8::1]", + "appium:directConnectPort", "4443", + "appium:directConnectPath", "/wd/hub" + ); + DirectConnect bracketed = new DirectConnect(bracketedIpv6); + assertTrue(bracketed.isValid()); + assertEquals("https://[2001:db8::1]:4443/wd/hub", bracketed.getUrl().toString()); + } + + @Test + void normalizesEmptyAndRelativeDirectConnectPath() throws MalformedURLException { + DirectConnect emptyPath = new DirectConnect(Map.of( + "appium:directConnectProtocol", "https", + "appium:directConnectHost", "203.0.113.1", + "appium:directConnectPort", "4443", + "appium:directConnectPath", "" + )); + assertTrue(emptyPath.isValid()); + assertEquals("https://203.0.113.1:4443", emptyPath.getUrl().toString()); + + DirectConnect relativePath = new DirectConnect(Map.of( + "appium:directConnectProtocol", "https", + "appium:directConnectHost", "203.0.113.1", + "appium:directConnectPort", "4443", + "appium:directConnectPath", "wd/hub" + )); + assertTrue(relativePath.isValid()); + assertEquals("https://203.0.113.1:4443/wd/hub", relativePath.getUrl().toString()); + } + + @Test + void rejectsSingleColonHostAndBlankFields() { + DirectConnect embeddedPortHost = new DirectConnect(Map.of( + "appium:directConnectProtocol", "https", + "appium:directConnectHost", "evil.example.com:8443", + "appium:directConnectPort", "4443", + "appium:directConnectPath", "/wd/hub" + )); + assertTrue(embeddedPortHost.isValid()); + assertThrowsExactly(MalformedURLException.class, embeddedPortHost::getUrl); + + DirectConnect blankHost = new DirectConnect(Map.of( + "appium:directConnectProtocol", "https", + "appium:directConnectHost", " ", + "appium:directConnectPort", "4443", + "appium:directConnectPath", "" + )); + assertTrue(blankHost.isValid()); + assertThrowsExactly(MalformedURLException.class, blankHost::getUrl); + + DirectConnect blankPort = new DirectConnect(Map.of( + "appium:directConnectProtocol", "https", + "appium:directConnectHost", "x", + "appium:directConnectPort", "", + "appium:directConnectPath", "/wd/hub" + )); + assertTrue(blankPort.isValid()); + assertThrowsExactly(MalformedURLException.class, blankPort::getUrl); } } diff --git a/src/test/java/io/appium/java_client/internal/LogBroadcastEndpointsTest.java b/src/test/java/io/appium/java_client/internal/LogBroadcastEndpointsTest.java new file mode 100644 index 000000000..43c0b284f --- /dev/null +++ b/src/test/java/io/appium/java_client/internal/LogBroadcastEndpointsTest.java @@ -0,0 +1,72 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * See the NOTICE file distributed with this work for additional + * information regarding copyright ownership. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.appium.java_client.internal; + +import io.appium.java_client.remote.SessionId; +import org.junit.jupiter.api.Test; + +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URL; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class LogBroadcastEndpointsTest { + + @Test + void mapsWildcardHostsToLoopbackFallbackAndPreservesExplicitHosts() throws MalformedURLException { + assertEquals("127.0.0.1", LogBroadcastEndpoints.resolveHost(null, "127.0.0.1")); + assertEquals("127.0.0.1", LogBroadcastEndpoints.resolveHost(new URL("http://0.0.0.0:4723"), "127.0.0.1")); + assertEquals("localhost", LogBroadcastEndpoints.resolveHost(new URL("http://[::]:4723"), "localhost")); + assertEquals( + "127.0.0.1", + LogBroadcastEndpoints.resolveHost(new URL("http://[0:0:0:0:0:0:0:0]:4723"), "127.0.0.1") + ); + assertEquals("grid.example.com", + LogBroadcastEndpoints.resolveHost(new URL("https://grid.example.com:4443"), "127.0.0.1")); + } + + @Test + void resolvesExplicitAndDefaultPortsBeforeFallback() throws MalformedURLException { + assertEquals(4723, LogBroadcastEndpoints.resolvePort(null, 4723)); + assertEquals(443, LogBroadcastEndpoints.resolvePort(new URL("https://grid.example.com"), 4723)); + assertEquals(4444, LogBroadcastEndpoints.resolvePort(new URL("http://hub.example.com:4444"), 4723)); + } + + @Test + void keepsWssForHttpsUnlessTargetingReplacedHttpEndpoint() throws MalformedURLException { + URL httpsServer = new URL("https://direct.example.com:4443"); + URL replacedHttpHub = new URL("http://hub.example.com:4723"); + SessionId sessionId = new SessionId("s1"); + + URI separateLogHost = LogBroadcastEndpoints.buildBroadcastUri( + httpsServer, List.of(), "10.0.0.5", 443, sessionId, "logcat" + ); + assertEquals("wss://10.0.0.5:443/ws/session/s1/appium/device/logcat", separateLogHost.toString()); + + URI staleHubEndpoint = LogBroadcastEndpoints.buildBroadcastUri( + httpsServer, List.of(replacedHttpHub), "hub.example.com", 4723, sessionId, "logcat" + ); + assertEquals("ws://hub.example.com:4723/ws/session/s1/appium/device/logcat", staleHubEndpoint.toString()); + + URI directTargetIpv6 = LogBroadcastEndpoints.buildBroadcastUri( + httpsServer, List.of(replacedHttpHub), "2001:db8::1", 4443, sessionId, "syslog" + ); + assertEquals("wss://[2001:db8::1]:4443/ws/session/s1/appium/device/syslog", directTargetIpv6.toString()); + } +} diff --git a/src/test/java/io/appium/java_client/remote/AppiumCommandExecutorTest.java b/src/test/java/io/appium/java_client/remote/AppiumCommandExecutorTest.java index b11bd6273..3551038e2 100644 --- a/src/test/java/io/appium/java_client/remote/AppiumCommandExecutorTest.java +++ b/src/test/java/io/appium/java_client/remote/AppiumCommandExecutorTest.java @@ -2,18 +2,92 @@ import io.appium.java_client.AppiumClientConfig; import io.appium.java_client.MobileCommand; +import io.appium.java_client.android.AndroidDriver; +import io.appium.java_client.android.options.UiAutomator2Options; +import io.appium.java_client.http.ClientConfig; +import io.appium.java_client.http.Contents; +import io.appium.java_client.http.HttpClient; +import io.appium.java_client.http.HttpRequest; +import io.appium.java_client.http.HttpResponse; +import io.appium.java_client.http.Message; +import io.appium.java_client.http.WebSocket; +import io.appium.java_client.ios.IOSDriver; +import io.appium.java_client.ios.options.XCUITestOptions; +import io.appium.java_client.service.local.AppiumDriverLocalService; +import io.appium.java_client.service.local.AppiumServiceBuilder; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.openqa.selenium.SessionNotCreatedException; +import java.io.File; +import java.io.IOException; import java.net.MalformedURLException; +import java.net.URI; import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; class AppiumCommandExecutorTest { private static final String APPIUM_URL = "https://appium.example.com"; + private static final File NODE = new File(Path.of(System.getProperty("java.home"), "bin", "java").toString()); + + @TempDir + Path tempDir; + + private static final class RecordingHttpClient implements HttpClient { + private final ClientConfig config; + private final AtomicBoolean closed = new AtomicBoolean(false); + private final String sessionCapabilitiesJson; + private final List socketUris = new ArrayList<>(); + + RecordingHttpClient(ClientConfig config, String sessionCapabilitiesJson) { + this.config = config; + this.sessionCapabilitiesJson = sessionCapabilitiesJson; + } + + @Override + public HttpResponse execute(HttpRequest request) { + String body = "/session".equals(request.getUri()) + ? "{\"value\":{\"sessionId\":\"s1\",\"capabilities\":" + sessionCapabilitiesJson + "}}" + : "{\"value\":null}"; + return new HttpResponse() + .setStatus(200) + .setHeader("Content-Type", "application/json; charset=utf-8") + .setContent(Contents.utf8String(body)); + } + + @Override + public WebSocket openSocket(HttpRequest request, WebSocket.Listener listener) { + socketUris.add(request.getUri()); + return new WebSocket() { + @Override + public WebSocket send(Message message) { + return this; + } + + @Override + public void close() { + } + }; + } + + @Override + public void close() { + closed.set(true); + } + } private AppiumCommandExecutor createExecutor() { URL baseUrl; @@ -38,12 +112,296 @@ void getHttpClientFactory() { @Test void overrideServerUrl() throws MalformedURLException { - assertDoesNotThrow(() -> createExecutor().overrideServerUrl(new URL("https://203.0.113.1/wd/hub"))); + List created = new ArrayList<>(); + HttpClient.Factory factory = cfg -> { + RecordingHttpClient client = new RecordingHttpClient(cfg, "{\"platformName\":\"Android\"}"); + created.add(client); + return client; + }; + AppiumClientConfig initialConfig = AppiumClientConfig.defaultConfig() + .baseUrl(new URL(APPIUM_URL)) + .readTimeout(Duration.ofSeconds(45)); + AppiumCommandExecutor executor = new AppiumCommandExecutor( + MobileCommand.commandRepository, null, factory, initialConfig); + final HttpClient firstClient = executor.getClient(); + + URL overrideUrl = new URL("https://203.0.113.1:4443/wd/hub"); + executor.overrideServerUrl(overrideUrl); + + assertEquals(2, created.size()); + assertTrue(created.get(0).closed.get()); + assertFalse(created.get(1).closed.get()); + assertNotSame(firstClient, executor.getClient()); + assertSame(created.get(1), executor.getClient()); + assertEquals(overrideUrl, executor.getAddressOfRemoteServer()); + assertEquals(overrideUrl, executor.getAppiumClientConfig().baseUrl()); + assertEquals(URI.create("https://203.0.113.1:4443/wd/hub"), created.get(1).config.baseUri()); + assertEquals(Duration.ofSeconds(45), created.get(1).config.readTimeout()); + assertEquals(URI.create("https://203.0.113.1:4443/wd/hub"), executor.getAppiumClientConfig().baseUri()); + assertEquals(Duration.ofSeconds(45), executor.getAppiumClientConfig().readTimeout()); } @Test void overrideServerUrlRejectsLoopbackTarget() throws MalformedURLException { + List created = new ArrayList<>(); + HttpClient.Factory factory = cfg -> { + RecordingHttpClient client = new RecordingHttpClient(cfg, "{\"platformName\":\"Android\"}"); + created.add(client); + return client; + }; + URL initialUrl = new URL(APPIUM_URL); + AppiumCommandExecutor executor = new AppiumCommandExecutor( + MobileCommand.commandRepository, null, factory, + AppiumClientConfig.defaultConfig().baseUrl(initialUrl)); + assertThrows(SessionNotCreatedException.class, - () -> createExecutor().overrideServerUrl(new URL("https://127.0.0.1:4443/wd/hub"))); + () -> executor.overrideServerUrl(new URL("https://127.0.0.1:4443/wd/hub"))); + assertEquals(1, created.size()); + assertFalse(created.get(0).closed.get()); + assertEquals(initialUrl, executor.getAddressOfRemoteServer()); + assertEquals(initialUrl, executor.getAppiumClientConfig().baseUrl()); + } + + @Test + void populatesBaseUrlFromLocalServiceWhenUnsetInClientConfig() throws IOException { + File mainJs = Files.createFile(tempDir.resolve("main.js")).toFile(); + var service = new AppiumServiceBuilder() + .usingDriverExecutable(NODE) + .withAppiumJS(mainJs) + .usingPort(4777) + .withIPAddress("127.0.0.1") + .build(); + AppiumClientConfig customConfig = AppiumClientConfig.defaultConfig() + .readTimeout(Duration.ofSeconds(90)); + + AppiumCommandExecutor executor = new AppiumCommandExecutor( + MobileCommand.commandRepository, service, customConfig); + + assertEquals(service.getUrl(), executor.getAddressOfRemoteServer()); + assertEquals(service.getUrl(), executor.getAppiumClientConfig().baseUrl()); + assertEquals(Duration.ofSeconds(90), executor.getAppiumClientConfig().readTimeout()); + } + + @Test + void acceptsNullableLocalServiceWithClientConfig() throws MalformedURLException { + URL baseUrl = new URL(APPIUM_URL); + AppiumCommandExecutor executor = new AppiumCommandExecutor( + MobileCommand.commandRepository, + (AppiumDriverLocalService) null, + AppiumClientConfig.defaultConfig().baseUrl(baseUrl) + ); + assertEquals(baseUrl, executor.getAddressOfRemoteServer()); + } + + @Test + void directConnectSupportsUppercaseProtocolIpv6LiteralAndRelativePath() throws MalformedURLException { + String caps = "{\"platformName\":\"Android\",\"appium:automationName\":\"UiAutomator2\"," + + "\"appium:directConnectProtocol\":\"HTTPS\"," + + "\"appium:directConnectHost\":\"2001:db8::1\"," + + "\"appium:directConnectPort\":4443," + + "\"appium:directConnectPath\":\"wd/hub\"}"; + HttpClient.Factory factory = cfg -> new RecordingHttpClient(cfg, caps); + AppiumCommandExecutor executor = new AppiumCommandExecutor( + MobileCommand.commandRepository, null, factory, + AppiumClientConfig.defaultConfig().baseUrl(new URL(APPIUM_URL)).directConnect(true)); + + AndroidDriver driver = new AndroidDriver(executor, new UiAutomator2Options().setDeviceName("emu")); + try { + URL expected = new URL("https://[2001:db8::1]:4443/wd/hub"); + assertEquals(expected, executor.getAddressOfRemoteServer()); + assertEquals(expected, executor.getAppiumClientConfig().baseUrl()); + assertEquals(expected, driver.getRemoteAddress()); + + URL nextOverride = new URL("https://203.0.113.2:4443/wd/hub"); + executor.overrideServerUrl(nextOverride); + assertEquals(nextOverride, driver.getRemoteAddress()); + } finally { + driver.quit(); + } + } + + @Test + void broadcastListenersUseUpdatedServerAddressAndKeepExplicitHubEndpointPlainWs() throws MalformedURLException { + String androidCaps = "{\"platformName\":\"Android\",\"appium:automationName\":\"UiAutomator2\"," + + "\"appium:directConnectProtocol\":\"https\"," + + "\"appium:directConnectHost\":\"203.0.113.1\"," + + "\"appium:directConnectPort\":4443," + + "\"appium:directConnectPath\":\"/wd/hub\"}"; + List androidClients = new ArrayList<>(); + HttpClient.Factory androidFactory = cfg -> { + RecordingHttpClient client = new RecordingHttpClient(cfg, androidCaps); + androidClients.add(client); + return client; + }; + AppiumCommandExecutor androidExecutor = new AppiumCommandExecutor( + MobileCommand.commandRepository, + null, + androidFactory, + AppiumClientConfig.defaultConfig() + .baseUrl(new URL("http://hub.example.com:4723")) + .directConnect(true) + ); + + AndroidDriver androidDriver = new AndroidDriver( + androidExecutor, + new UiAutomator2Options().setDeviceName("emu") + ); + try { + androidDriver.startLogcatBroadcast(); + androidDriver.startLogcatBroadcast("hub.example.com", 4723); + androidDriver.startLogcatBroadcast("203.0.113.1", 4443); + + assertEquals( + List.of( + "wss://203.0.113.1:4443/ws/session/s1/appium/device/logcat", + "ws://hub.example.com:4723/ws/session/s1/appium/device/logcat", + "wss://203.0.113.1:4443/ws/session/s1/appium/device/logcat" + ), + androidClients.get(1).socketUris + ); + } finally { + androidDriver.quit(); + } + + String iosCaps = "{\"platformName\":\"iOS\",\"appium:automationName\":\"XCUITest\"," + + "\"appium:directConnectProtocol\":\"https\"," + + "\"appium:directConnectHost\":\"2001:db8::1\"," + + "\"appium:directConnectPort\":4443," + + "\"appium:directConnectPath\":\"/wd/hub\"}"; + List iosClients = new ArrayList<>(); + HttpClient.Factory iosFactory = cfg -> { + RecordingHttpClient client = new RecordingHttpClient(cfg, iosCaps); + iosClients.add(client); + return client; + }; + AppiumCommandExecutor iosExecutor = new AppiumCommandExecutor( + MobileCommand.commandRepository, + null, + iosFactory, + AppiumClientConfig.defaultConfig() + .baseUrl(new URL("http://hub.example.com:4723")) + .directConnect(true) + ); + + IOSDriver iosDriver = new IOSDriver( + iosExecutor, + new XCUITestOptions().setDeviceName("iPhone 16") + ); + try { + iosDriver.startSyslogBroadcast(); + iosDriver.startSyslogBroadcast("hub.example.com", 4723); + iosDriver.startSyslogBroadcast("2001:db8::1", 4443); + + assertEquals( + List.of( + "wss://[2001:db8::1]:4443/ws/session/s1/appium/device/syslog", + "ws://hub.example.com:4723/ws/session/s1/appium/device/syslog", + "wss://[2001:db8::1]:4443/ws/session/s1/appium/device/syslog" + ), + iosClients.get(1).socketUris + ); + } finally { + iosDriver.quit(); + } + } + + @Test + void broadcastListenersPreserveWssOnHttpsServersNormalizeWildcardAndDefaultOneArgPortToServerPort() + throws MalformedURLException { + List httpsClients = new ArrayList<>(); + HttpClient.Factory httpsFactory = cfg -> { + RecordingHttpClient client = new RecordingHttpClient(cfg, "{\"platformName\":\"Android\"}"); + httpsClients.add(client); + return client; + }; + AppiumCommandExecutor httpsExecutor = new AppiumCommandExecutor( + MobileCommand.commandRepository, + null, + httpsFactory, + AppiumClientConfig.defaultConfig().baseUrl(new URL("https://grid.example.com")) + ); + + AndroidDriver httpsDriver = new AndroidDriver( + httpsExecutor, + new UiAutomator2Options().setDeviceName("emu") + ); + try { + httpsDriver.startLogcatBroadcast(); + httpsDriver.startLogcatBroadcast("10.0.0.5"); + httpsDriver.startLogcatBroadcast("10.0.0.5", 4723); + + assertEquals( + List.of( + "wss://grid.example.com:443/ws/session/s1/appium/device/logcat", + "wss://10.0.0.5:443/ws/session/s1/appium/device/logcat", + "wss://10.0.0.5:4723/ws/session/s1/appium/device/logcat" + ), + httpsClients.get(0).socketUris + ); + } finally { + httpsDriver.quit(); + } + + List wildcardClients = new ArrayList<>(); + HttpClient.Factory wildcardFactory = cfg -> { + RecordingHttpClient client = new RecordingHttpClient(cfg, "{\"platformName\":\"iOS\"}"); + wildcardClients.add(client); + return client; + }; + AppiumCommandExecutor wildcardExecutor = new AppiumCommandExecutor( + MobileCommand.commandRepository, + null, + wildcardFactory, + AppiumClientConfig.defaultConfig().baseUrl(new URL("http://[::]:4444")) + ); + + IOSDriver wildcardDriver = new IOSDriver( + wildcardExecutor, + new XCUITestOptions().setDeviceName("iPhone 16") + ); + try { + wildcardDriver.startSyslogBroadcast(); + wildcardDriver.startSyslogBroadcast("log.internal"); + + assertEquals( + List.of( + "ws://localhost:4444/ws/session/s1/appium/device/syslog", + "ws://log.internal:4444/ws/session/s1/appium/device/syslog" + ), + wildcardClients.get(0).socketUris + ); + } finally { + wildcardDriver.quit(); + } + } + + @Test + void blankDirectConnectValuesFailWithSessionNotCreatedException() throws MalformedURLException { + for (String invalidCaps : List.of( + "{\"platformName\":\"Android\"," + + "\"appium:directConnectProtocol\":\"https\"," + + "\"appium:directConnectHost\":\"x\"," + + "\"appium:directConnectPort\":\"\"," + + "\"appium:directConnectPath\":\"/wd/hub\"}", + "{\"platformName\":\"Android\"," + + "\"appium:directConnectProtocol\":\"\"," + + "\"appium:directConnectHost\":\"\"," + + "\"appium:directConnectPort\":\"\"," + + "\"appium:directConnectPath\":\"\"}")) { + HttpClient.Factory factory = cfg -> new RecordingHttpClient(cfg, invalidCaps); + AppiumCommandExecutor executor = new AppiumCommandExecutor( + MobileCommand.commandRepository, + null, + factory, + AppiumClientConfig.defaultConfig() + .baseUrl(new URL("http://hub.example.com:4723")) + .directConnect(true) + ); + + assertThrows( + SessionNotCreatedException.class, + () -> new AndroidDriver(executor, new UiAutomator2Options().setDeviceName("emu")) + ); + } } } diff --git a/src/test/java/io/appium/java_client/remote/DriverWireScenariosTest.java b/src/test/java/io/appium/java_client/remote/DriverWireScenariosTest.java index a8542460b..9ed100e8c 100644 --- a/src/test/java/io/appium/java_client/remote/DriverWireScenariosTest.java +++ b/src/test/java/io/appium/java_client/remote/DriverWireScenariosTest.java @@ -56,6 +56,8 @@ import java.util.function.Function; import java.util.regex.Pattern; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * Pins the HTTP requests a driver sends for each WebDriver/Appium API call, and what it returns * for scripted server responses. Set GOLDEN_UPDATE=1 to regenerate the golden file. @@ -593,6 +595,9 @@ void directConnect() { Map described = new LinkedHashMap<>(); try { var driver = newDriver(transport, AppiumClientConfig.defaultConfig().directConnect(true)); + if ("valid".equals(name)) { + assertEquals("https://203.0.113.1:4443/wd/hub", driver.getRemoteAddress().toString()); + } transport.requests.clear(); driver.getTitle(); } catch (Throwable t) {