Skip to content

Commit 733572e

Browse files
committed
Add examples for http_client java and python
Signed-off-by: Viet Nguyen Duc <[email protected]>
1 parent fa77979 commit 733572e

File tree

12 files changed

+377
-1
lines changed

12 files changed

+377
-1
lines changed

examples/java/src/test/java/dev/selenium/BaseTest.java

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import java.io.IOException;
55
import java.net.URL;
66
import java.nio.file.Files;
7+
import java.nio.file.Path;
78
import java.time.Duration;
89
import java.util.Arrays;
910
import java.util.logging.Level;
@@ -98,6 +99,41 @@ protected URL startStandaloneGrid() {
9899
}
99100
}
100101

102+
protected URL startStandaloneGridAdvanced() {
103+
int port = PortProber.findFreePort();
104+
String username = "admin";
105+
String password = "myStrongPassword";
106+
String trustStorePassword = "seleniumkeystore";
107+
try {
108+
System.setProperty("javax.net.ssl.trustStore", Path.of("src/test/resources/server.jks").toAbsolutePath().toString());
109+
System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword);
110+
System.setProperty("jdk.internal.httpclient.disableHostnameVerification", "true");
111+
Main.main(
112+
new String[] {
113+
"standalone",
114+
"--port",
115+
String.valueOf(port),
116+
"--selenium-manager",
117+
"true",
118+
"--enable-managed-downloads",
119+
"true",
120+
"--log-level",
121+
"WARNING",
122+
"--username",
123+
username,
124+
"--password",
125+
password,
126+
"--https-certificate",
127+
Path.of("src/test/resources/tls.crt").toAbsolutePath().toString(),
128+
"--https-private-key",
129+
Path.of("src/test/resources/tls.key").toAbsolutePath().toString()
130+
});
131+
return new URL("https://localhost:" + port);
132+
} catch (Exception e) {
133+
throw new RuntimeException(e);
134+
}
135+
}
136+
101137
protected void enableLogging() {
102138
Logger logger = Logger.getLogger("");
103139
logger.setLevel(Level.FINE);

examples/java/src/test/java/dev/selenium/drivers/HttpClientTest.java

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,108 @@
22

33
import dev.selenium.BaseTest;
44

5+
import org.openqa.selenium.remote.http.ClientConfig;
6+
import org.junit.jupiter.api.BeforeEach;
7+
import org.junit.jupiter.api.Test;
8+
import org.openqa.selenium.chrome.ChromeOptions;
9+
import org.openqa.selenium.remote.RemoteWebDriver;
10+
11+
import javax.net.ssl.SSLContext;
12+
import javax.net.ssl.TrustManager;
13+
import javax.net.ssl.TrustManagerFactory;
14+
import javax.net.ssl.X509TrustManager;
15+
import java.io.FileInputStream;
16+
import java.net.URL;
17+
import java.nio.file.Path;
18+
import java.security.KeyStore;
19+
import java.security.cert.CertificateFactory;
20+
import java.security.cert.X509Certificate;
21+
import java.time.Duration;
22+
23+
import org.openqa.selenium.UsernameAndPassword;
24+
25+
import static java.net.http.HttpClient.Version.HTTP_1_1;
26+
527
public class HttpClientTest extends BaseTest {
28+
URL gridUrl;
29+
30+
@BeforeEach
31+
public void startGrid() {
32+
gridUrl = startStandaloneGridAdvanced();
33+
}
34+
35+
@Test
36+
public void remoteWebDriverWithClientConfig() throws Exception {
37+
ClientConfig clientConfig = ClientConfig.defaultConfig()
38+
.withRetries()
39+
.sslContext(createSSLContextWithCA(Path.of("src/test/resources/tls.crt").toAbsolutePath().toString()))
40+
.connectionTimeout(Duration.ofSeconds(300))
41+
.readTimeout(Duration.ofSeconds(3600))
42+
.authenticateAs(new UsernameAndPassword("admin", "myStrongPassword"))
43+
.version(HTTP_1_1.toString());
44+
ChromeOptions options = new ChromeOptions();
45+
options.setEnableDownloads(true);
46+
driver = RemoteWebDriver.builder()
47+
.oneOf(options)
48+
.address(gridUrl)
49+
.config(clientConfig)
50+
.build();
51+
driver.quit();
52+
}
53+
54+
@Test
55+
public void remoteWebDriverIgnoreSSL() throws Exception {
56+
ClientConfig clientConfig = ClientConfig.defaultConfig()
57+
.withRetries()
58+
.sslContext(createIgnoreSSLContext())
59+
.connectionTimeout(Duration.ofSeconds(300))
60+
.readTimeout(Duration.ofSeconds(3600))
61+
.authenticateAs(new UsernameAndPassword("admin", "myStrongPassword"))
62+
.version(HTTP_1_1.toString());
63+
ChromeOptions options = new ChromeOptions();
64+
options.setEnableDownloads(true);
65+
driver = RemoteWebDriver.builder()
66+
.oneOf(options)
67+
.address(gridUrl)
68+
.config(clientConfig)
69+
.build();
70+
driver.quit();
71+
}
72+
73+
private SSLContext createSSLContextWithCA(String caCertPath) throws Exception {
74+
// Load the CA certificate
75+
FileInputStream fis = new FileInputStream(caCertPath);
76+
CertificateFactory cf = CertificateFactory.getInstance("X.509");
77+
X509Certificate caCert = (X509Certificate) cf.generateCertificate(fis);
78+
// Create a KeyStore and load the CA certificate
79+
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
80+
keyStore.load(null, null);
81+
keyStore.setCertificateEntry("caCert", caCert);
82+
// Initialize a TrustManagerFactory with the KeyStore
83+
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
84+
tmf.init(keyStore);
85+
// Create and initialize an SSLContext with the TrustManagerFactory
86+
SSLContext sslContext = SSLContext.getInstance("TLS");
87+
sslContext.init(null, tmf.getTrustManagers(), null);
88+
return sslContext;
89+
}
90+
91+
public static SSLContext createIgnoreSSLContext() throws Exception {
92+
TrustManager[] trustAllCerts = new TrustManager[]{
93+
new X509TrustManager() {
94+
public X509Certificate[] getAcceptedIssuers() {
95+
return null;
96+
}
97+
98+
public void checkClientTrusted(X509Certificate[] certs, String authType) {
99+
}
6100

101+
public void checkServerTrusted(X509Certificate[] certs, String authType) {
102+
}
103+
}
104+
};
105+
SSLContext sslContext = SSLContext.getInstance("TLS");
106+
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
107+
return sslContext;
108+
}
7109
}
2.83 KB
Binary file not shown.
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
-----BEGIN CERTIFICATE-----
2+
MIIEAzCCAuugAwIBAgIIPgWI/2ppJPowDQYJKoZIhvcNAQELBQAwgYcxEDAOBgNV
3+
BAYTB1Vua25vd24xEDAOBgNVBAgTB1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xza0AF0KBFp1GzLDW5/KcA26R4IQi2xfQKVyRzb4vu0CY
20+
BDbnzF7Bisj50sSI4WThtF4xLEHVmzJ2GWNp6SgAScIrdGeB320aTqUIDO8YHH+y
21+
oeSu6qQfEcDiBWh3KD85vCIx0+L4AM3WKkP5nDq2FL6nwCdxqV7bo5/BZJEODMiW
22+
xv/hw0r1OBn2T2Z6o3pRI92zu9sjj6PzPP80DUPl7+fqAaRlLFglXd8b+Qxojm9o
23+
B0QN+gEM717L6WqmJGr1VC6HWQCvcCc=
24+
-----END CERTIFICATE-----
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
-----BEGIN PRIVATE KEY-----
2+
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQClU8dHuev++UIB
3+
OROq02D5U5CMQ42cpTjE9mATbgfLyBWZEmgrSxKraNF01VenUHPBnuNUFa5LewyA
4+
9aDeNK71mXZWvf9m1YQrFrEYl5b6yg246FIuZIi3HyiVvnq1FrNvMZyzsG7xjSyw
5+
IxFIrSihqUdb7EjDrrzDfVZ7EpJ/bJgBy09suNQoyqb3ZKvjglHZ6n2I7r1ejrYU
6+
T1xTLA29X2KmXxO32YS3PNOkYN9ai7LDVT8MbelXjWItf3uXFmHiiCUKI7BZKiHb
7+
7u8R7Ue0LtbTXXkKIg4TEu1S3WQ7JwALUCx78gFRAYnAV/eVaxpzk5SnZPlA8Mjj
8+
+nYwiEs1AgMBAAECggEAA2D+tT3SGlmG9Tube2CLaRUW4shSVDBWmcSXn+teBUFv
9+
MDwdfRMGoZJdw4eaXWz0wgaItV7QZjJbMKXfK44ZQaOTtP/4QLuzkjuKE4tXloO7
10+
e5BjS5eaPrSIPGU9S0cDPvjH2oP22dYi4sJYt6ry+2ODC0Mn6o3p8Dc3Ja1HvrXA
11+
SNImimok7YemXVMbdPyaqbu2eXjPvWAA8W9/OW2L1n4U4neM0S5Nt3tVl5sMELj5
12+
iFC7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lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,4 @@ pytest
33
trio
44
pytest-trio
55
flake8
6+
requests

examples/python/tests/conftest.py

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
from selenium.webdriver.common.utils import free_port
88
from datetime import datetime
99
from urllib.request import urlopen
10+
import requests
11+
from requests.auth import HTTPBasicAuth
1012

1113
import pytest
1214
from selenium import webdriver
@@ -236,3 +238,81 @@ def wait_for_server(url, timeout=60):
236238
process.wait(timeout=10)
237239
except subprocess.TimeoutExpired:
238240
process.kill()
241+
242+
243+
def _get_resource_path(file_name: str):
244+
if os.path.abspath("").endswith("tests"):
245+
path = os.path.abspath(f"resources/{file_name}")
246+
else:
247+
path = os.path.abspath(f"tests/resources/{file_name}")
248+
return path
249+
250+
251+
@pytest.fixture(scope="function")
252+
def grid_server():
253+
_host = "localhost"
254+
_port = free_port()
255+
_username = "admin"
256+
_password = "myStrongPassword"
257+
_path_cert = _get_resource_path("tls.crt")
258+
_path_key = _get_resource_path("tls.key")
259+
_path_jks = _get_resource_path("server.jks")
260+
_truststore_pass = "seleniumkeystore"
261+
_path = os.path.join(
262+
os.path.dirname(
263+
os.path.dirname(
264+
os.path.dirname(
265+
os.path.abspath(__file__)
266+
)
267+
)
268+
),
269+
"selenium-server-4.26.0.jar",
270+
)
271+
272+
args = [
273+
"java",
274+
f"-Djavax.net.ssl.trustStore={_path_jks}",
275+
f"-Djavax.net.ssl.trustStorePassword={_truststore_pass}",
276+
"-Djdk.internal.httpclient.disableHostnameVerification=true",
277+
"-jar",
278+
_path,
279+
"standalone",
280+
"--port",
281+
str(_port),
282+
"--selenium-manager",
283+
"true",
284+
"--enable-managed-downloads",
285+
"true",
286+
"--username",
287+
_username,
288+
"--password",
289+
_password,
290+
"--https-certificate",
291+
_path_cert,
292+
"--https-private-key",
293+
_path_key,
294+
]
295+
296+
process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
297+
298+
def wait_for_server(url, timeout=60):
299+
start = time.time()
300+
while time.time() - start < timeout:
301+
try:
302+
requests.get(url, verify=_path_cert, auth=HTTPBasicAuth(_username, _password))
303+
return True
304+
except OSError as e:
305+
print(e)
306+
time.sleep(0.2)
307+
return False
308+
309+
if not wait_for_server(f"https://{_host}:{_port}/status"):
310+
raise RuntimeError(f"Selenium server did not start within the allotted time.")
311+
312+
yield f"https://{_host}:{_port}"
313+
314+
process.terminate()
315+
try:
316+
process.wait(timeout=10)
317+
except subprocess.TimeoutExpired:
318+
process.kill()
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,55 @@
1+
import os
2+
import pytest
3+
import sys
14
from selenium import webdriver
5+
from selenium.webdriver.common.proxy import Proxy
6+
from selenium.webdriver.common.proxy import ProxyType
7+
from selenium.webdriver.remote.client_config import ClientConfig
28

9+
10+
def _get_resource_path(file_name: str):
11+
if os.path.abspath("").endswith("tests"):
12+
path = os.path.abspath(f"resources/{file_name}")
13+
else:
14+
path = os.path.abspath(f"tests/resources/{file_name}")
15+
return path
16+
17+
18+
@pytest.mark.skipif(sys.platform == "win32", reason="Gets stuck on Windows, passes locally")
19+
@pytest.mark.sanity
20+
def test_start_remote_with_client_config(grid_server):
21+
proxy = Proxy({"proxyType": ProxyType.AUTODETECT})
22+
client_config = ClientConfig(remote_server_addr=grid_server,
23+
proxy=proxy,
24+
timeout=3600,
25+
ca_certs=_get_resource_path("tls.crt"),
26+
username="admin", password="myStrongPassword")
27+
options = webdriver.ChromeOptions()
28+
driver = webdriver.Remote(command_executor=grid_server, options=options, client_config=client_config)
29+
30+
assert "localhost" in driver.command_executor._client_config.remote_server_addr
31+
assert driver.command_executor._client_config.timeout == 3600
32+
assert driver.command_executor._client_config.username == "admin"
33+
assert driver.command_executor._client_config.password == "myStrongPassword"
34+
assert driver.command_executor._client_config.ca_certs == _get_resource_path("tls.crt")
35+
driver.quit()
36+
37+
38+
@pytest.mark.skipif(sys.platform == "win32", reason="Gets stuck on Windows, passes locally")
39+
@pytest.mark.sanity
40+
def test_start_remote_ignore_certs(grid_server):
41+
proxy = Proxy({"proxyType": ProxyType.AUTODETECT})
42+
client_config = ClientConfig(remote_server_addr=grid_server,
43+
proxy=proxy,
44+
timeout=3600,
45+
ignore_certificates=True,
46+
username="admin", password="myStrongPassword")
47+
options = webdriver.ChromeOptions()
48+
driver = webdriver.Remote(command_executor=grid_server, options=options, client_config=client_config)
49+
50+
assert "localhost" in driver.command_executor._client_config.remote_server_addr
51+
assert driver.command_executor._client_config.timeout == 3600
52+
assert driver.command_executor._client_config.username == "admin"
53+
assert driver.command_executor._client_config.password == "myStrongPassword"
54+
assert driver.command_executor._client_config.ignore_certificates is True
55+
driver.quit()
2.83 KB
Binary file not shown.
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
-----BEGIN CERTIFICATE-----
2+
MIIEAzCCAuugAwIBAgIIPgWI/2ppJPowDQYJKoZIhvcNAQELBQAwgYcxEDAOBgNV
3+
BAYTB1Vua25vd24xEDAOBgNVBAgTB1Vua25vd24xEDAOBgNVBAcTB1Vua25vd24x
4+
EzARBgNVBAoTClNlbGVuaXVtSFExJTAjBgNVBAsTHFNvZnR3YXJlIEZyZWVkb20g
5+
Q29uc2VydmFuY3kxEzARBgNVBAMTClNlbGVuaXVtSFEwHhcNMjQxMTAzMDkwMDUz
6+
WhcNMzQxMTAxMDkwMDUzWjCBhzEQMA4GA1UEBhMHVW5rbm93bjEQMA4GA1UECBMH
7+
VW5rbm93bjEQMA4GA1UEBxMHVW5rbm93bjETMBEGA1UEChMKU2VsZW5pdW1IUTEl
8+
MCMGA1UECxMcU29mdHdhcmUgRnJlZWRvbSBDb25zZXJ2YW5jeTETMBEGA1UEAxMK
9+
U2VsZW5pdW1IUTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKVTx0e5
10+
6/75QgE5E6rTYPlTkI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