下面列出了怎么用org.openqa.selenium.Proxy的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void usingAProxyToTrackNetworkTrafficStep2() {
BrowserMobProxy browserMobProxy = new BrowserMobProxyServer();
browserMobProxy.start();
Proxy seleniumProxyConfiguration = ClientUtil.createSeleniumProxy(browserMobProxy);
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setCapability(CapabilityType.PROXY, seleniumProxyConfiguration);
driver = new FirefoxDriver(firefoxOptions);
browserMobProxy.newHar();
driver.get("https://www.google.co.uk");
Har httpArchive = browserMobProxy.getHar();
assertThat(getHTTPStatusCode("https://www.google.co.uk/", httpArchive))
.isEqualTo(200);
}
/**
* Call this method to create a {@link Proxy} instance for use when creating a {@link org.openqa.selenium.WebDriver}
* instance. The values/settings of the proxy depends entirely on the values set on this config instance.
*
* @return a {@link Proxy}
*/
public Proxy createProxy() {
switch (getProxyType()) {
case PROXY_PAC:
return proxyFactory.getConfigUrlProxy(getProxyPacUrl());
case DIRECT:
return proxyFactory.getDirectProxy();
case AUTO_DETECT:
return proxyFactory.getAutodetectProxy();
case MANUAL:
if (isUseHttpSettingsForAllProtocols()) {
ProxyHostPort proxy = new ProxyHostPort(getHttpHost(), getHttpPort());
return proxyFactory.getManualProxy(proxy, proxy, proxy, proxy, getNoProxyHost());
}
ProxyHostPort http = new ProxyHostPort(getHttpHost(), getHttpPort());
ProxyHostPort https = new ProxyHostPort(getHttpsHost(), getHttpsPort());
ProxyHostPort ftp = new ProxyHostPort(getFtpHost(), getFtpPort());
ProxyHostPort socks = new ProxyHostPort(getSocksHost(), getSocksPort());
return proxyFactory.getManualProxy(http, https, ftp, socks, getNoProxyHost());
default:
return proxyFactory.getSystemProxy();
}
}
@Test
public void shouldCreateManualProxy() {
ProxyHostPort http = new ProxyHostPort("http.com", 1234);
ProxyHostPort https = new ProxyHostPort("https.com", 1234);
ProxyHostPort ftp = new ProxyHostPort("ftp", 1234);
ProxyHostPort socks = new ProxyHostPort("socks", 1234);
String noProxy = "none";
Proxy proxy = factory.getManualProxy(http, https, ftp, socks, noProxy);
assertThat(proxy.getProxyType(), is(Proxy.ProxyType.MANUAL));
assertThat(proxy.getHttpProxy(), is(http.toUnifiedForm()));
assertThat(proxy.getSslProxy(), is(https.toUnifiedForm()));
assertThat(proxy.getFtpProxy(), is(ftp.toUnifiedForm()));
assertThat(proxy.getSocksProxy(), is(socks.toUnifiedForm()));
assertThat(proxy.getNoProxy(), is(noProxy));
}
@Test
public void shouldDelegateToProxyFactoryWhenCreatingManualProxyWithAllValuesSpecified() {
final ProxyHostPort http = new ProxyHostPort("http", 1);
final ProxyHostPort https = new ProxyHostPort("https", 2);
final ProxyHostPort ftp = new ProxyHostPort("ftp", 3);
final ProxyHostPort socks = new ProxyHostPort("socks", 4);
final String noProxy = "host1, host2";
config.setHttpHost(http.getHost());
config.setHttpPort(http.getPort());
config.setUseHttpSettingsForAllProtocols(false);
config.setHttpsHost(https.getHost());
config.setHttpsPort(https.getPort());
config.setFtpHost(ftp.getHost());
config.setFtpPort(ftp.getPort());
config.setSocksHost(socks.getHost());
config.setSocksPort(socks.getPort());
config.setNoProxyHost(noProxy);
when(proxyFactory.getManualProxy(http, https, ftp, socks, noProxy)).thenReturn(new Proxy());
config.setProxyType(ProxyType.MANUAL);
Proxy proxy = config.createProxy();
assertThat(proxy, is(notNullValue()));
verify(proxyFactory, times(1)).getManualProxy(http, https, ftp, socks, noProxy);
}
@Test
public void shouldDelegateToProxyFactoryWhenCreatingManualProxyWithHttpAsDefault() {
final ProxyHostPort http = new ProxyHostPort("http", 1);
final String noProxy = "host1, host2";
config.setHttpHost(http.getHost());
config.setHttpPort(http.getPort());
config.setUseHttpSettingsForAllProtocols(true);
config.setNoProxyHost(noProxy);
when(proxyFactory.getManualProxy(http, http, http, http, noProxy)).thenReturn(new Proxy());
config.setProxyType(ProxyType.MANUAL);
Proxy proxy = config.createProxy();
assertThat(proxy, is(notNullValue()));
verify(proxyFactory, times(1)).getManualProxy(http, http, http, http, noProxy);
}
private ProxyDriverIntegrator getProxyDriverIntegrator(RequestFilter recordRequestFilter,
WebDriverSupplier webDriverSupplier,
DriverServiceSupplier driverServiceSupplier,
@Named(PATH_TO_DRIVER) String pathToDriverExecutable,
@Named(SCREEN) String screen,
@Named(TIMEOUT) int timeout,
ResponseFilter responseFilter) throws IOException {
BrowserMobProxy proxy = createBrowserMobProxy(timeout, recordRequestFilter, responseFilter);
proxy.start(0);
logger.info("Proxy running on port " + proxy.getPort());
Proxy seleniumProxy = createSeleniumProxy(proxy);
DesiredCapabilities desiredCapabilities = createDesiredCapabilities(seleniumProxy);
DriverService driverService = driverServiceSupplier.getDriverService(pathToDriverExecutable, screen);
WebDriver driver = webDriverSupplier.get(driverService, desiredCapabilities);
return new ProxyDriverIntegrator(driver, proxy, driverService);
}
/**
* Valid inputs are system, autodetect, direct or http://{hostname}:{port}
*
* <p>This does not currently cope with PAC (Proxy auto-configuration from URL)
*
* @param proxyProperty the string representing the proxy required
* @return a Selenium {@link Proxy} representation of proxyProperty
*/
public static Proxy createProxy(String proxyProperty) {
Proxy proxy = new Proxy();
switch (proxyProperty.toLowerCase()) {
case "system":
logger.debug("Using system proxy");
proxy.setProxyType(Proxy.ProxyType.SYSTEM);
break;
case "autodetect":
logger.debug("Using autodetect proxy");
proxy.setProxyType(Proxy.ProxyType.AUTODETECT);
break;
case "direct":
logger.debug("Using direct i.e. (no) proxy");
proxy.setProxyType(Proxy.ProxyType.DIRECT);
break;
default:
return createManualProxy(proxyProperty);
}
return proxy;
}
@Override
public Collection<Map.Entry<String, Object>> apply(Map.Entry<String, Object> entry) {
if (!"proxy".equals(entry.getKey())) {
return singleton(entry);
}
Object rawProxy = entry.getValue();
Map<String, Object> proxy;
if (rawProxy instanceof Proxy) {
proxy = new TreeMap<>(((Proxy) rawProxy).toJson());
} else {
//noinspection unchecked
proxy = new TreeMap<>((Map<String, Object>) rawProxy);
}
if (proxy.containsKey("proxyType")) {
proxy.put(
"proxyType",
String.valueOf(proxy.get("proxyType")).toLowerCase());
}
return singleton(new AbstractMap.SimpleImmutableEntry<>(entry.getKey(), proxy));
}
@Test
public void shouldConvertAProxyCorrectly() {
Proxy proxy = new Proxy();
proxy.setHttpProxy("localhost:4444");
MutableCapabilities caps = new DesiredCapabilities("foo", "1", Platform.LINUX);
caps.setCapability(CapabilityType.PROXY, proxy);
Map<String, ?> asMap = ImmutableMap.of("desiredCapabilities", caps);
Command command = new Command(new SessionId("empty"), DriverCommand.NEW_SESSION, asMap);
String json = convert(command.getParameters());
JsonObject converted = new JsonParser().parse(json).getAsJsonObject();
JsonObject capsAsMap = converted.get("desiredCapabilities").getAsJsonObject();
assertThat(capsAsMap.get(CapabilityType.PROXY).getAsJsonObject().get("httpProxy").getAsString())
.isEqualTo(proxy.getHttpProxy());
}
private static void setupFirefox() {
final DesiredCapabilities capabilities = new DesiredCapabilities();
final String proxyHost = System.getProperty("http.proxyHost");
final String proxyPort = System.getProperty("http.proxyPort");
if (proxyHost != null) {
System.out
.println("Configuring Firefox Selenium web driver with proxy "
+ proxyHost
+ (proxyPort == null ? "" : ":" + proxyPort)
+ " (requires Firefox browser)");
final Proxy proxy = new Proxy();
final String proxyString = proxyHost
+ (proxyPort == null ? "" : ":" + proxyPort);
proxy.setHttpProxy(proxyString).setSslProxy(proxyString);
proxy.setNoProxy("localhost");
capabilities.setCapability(CapabilityType.PROXY, proxy);
} else {
System.out
.println("Configuring Firefox Selenium web driver without proxy (requires Firefox browser)");
}
driver = new FirefoxDriver(capabilities);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}
private void configureProxy(final ITestContext context, final Method method) {
final MonitorNetwork monitorNetwork = method.getAnnotation(MonitorNetwork.class);
if (monitorNetwork != null && monitorNetwork.enabled()) {
final String initialPageID = context.getName() + " : " + method.getName();
harDetailsLink = HAR_STORAGE.getHarDetailsURL(initialPageID);
proxy = new BrowserMobProxy(PROXY_IP, PROXY_PORT);
proxy.setSocketOperationTimeout(DEFAULT_SOCKET_TIMEOUT);
proxy.setRequestTimeout(DEFAULT_REQUEST_TIMEOUT);
// Getting port for Selenium proxy
final int port = proxy.getPort();
proxy.setPort(port);
// Creating har on raised proxy for monitoring net statistics before first page is loaded.
proxy.newHar(initialPageID, monitorNetwork.captureHeaders(), monitorNetwork.captureContent(),
monitorNetwork.captureBinaryContent());
// Get the Selenium proxy object
final String actualProxy = PROXY_IP + ":" + port;
seleniumProxy = new Proxy();
seleniumProxy.setHttpProxy(actualProxy).setFtpProxy(actualProxy)
.setSslProxy(actualProxy);
}
}
private Proxy createSeleniumProxy(boolean remoteExecution)
{
try
{
return ClientUtil.createSeleniumProxy(proxy.getProxyServer(),
remoteExecution ? InetAddress.getLocalHost() : InetAddress.getLoopbackAddress());
}
catch (UnknownHostException e)
{
throw new IllegalStateException(e);
}
}
/**
* Creates a Selenium Proxy object using the specified connectableAddressAndPort as the HTTP proxy server.
*
* @param connectableAddressAndPort the network address (or hostname) and port the Selenium Proxy will use to reach its
* proxy server (the InetSocketAddress may be unresolved).
* @return a Selenium Proxy instance, configured to use the specified address and port as its proxy server
*/
public static org.openqa.selenium.Proxy createSeleniumProxy(InetSocketAddress connectableAddressAndPort) {
Proxy proxy = new Proxy();
proxy.setProxyType(Proxy.ProxyType.MANUAL);
String proxyStr = String.format("%s:%d", connectableAddressAndPort.getHostString(), connectableAddressAndPort.getPort());
proxy.setHttpProxy(proxyStr);
proxy.setSslProxy(proxyStr);
return proxy;
}
@Test
public void usingAProxyToTrackNetworkTrafficStep1() {
BrowserMobProxy browserMobProxy = new BrowserMobProxyServer();
browserMobProxy.start();
Proxy seleniumProxyConfiguration = ClientUtil.createSeleniumProxy(browserMobProxy);
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setCapability(CapabilityType.PROXY, seleniumProxyConfiguration);
driver = new FirefoxDriver(firefoxOptions);
browserMobProxy.newHar();
driver.get("https://www.google.co.uk");
}
private void instantiateWebDriver(DriverType driverType) throws MalformedURLException {
System.out.println(" ");
System.out.println("Local Operating System: " + operatingSystem);
System.out.println("Local Architecture: " + systemArchitecture);
System.out.println("Selected Browser: " + selectedDriverType);
System.out.println("Connecting to Selenium Grid: " + useRemoteWebDriver);
System.out.println(" ");
DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
if (proxyEnabled) {
Proxy proxy = new Proxy();
proxy.setProxyType(MANUAL);
proxy.setHttpProxy(proxyDetails);
proxy.setSslProxy(proxyDetails);
desiredCapabilities.setCapability(PROXY, proxy);
}
if (useRemoteWebDriver) {
URL seleniumGridURL = new URL(System.getProperty("gridURL"));
String desiredBrowserVersion = System.getProperty("desiredBrowserVersion");
String desiredPlatform = System.getProperty("desiredPlatform");
if (null != desiredPlatform && !desiredPlatform.isEmpty()) {
desiredCapabilities.setPlatform(Platform.valueOf(desiredPlatform.toUpperCase()));
}
if (null != desiredBrowserVersion && !desiredBrowserVersion.isEmpty()) {
desiredCapabilities.setVersion(desiredBrowserVersion);
}
desiredCapabilities.setBrowserName(selectedDriverType.toString());
webDriver = new RemoteWebDriver(seleniumGridURL, desiredCapabilities);
} else {
webDriver = driverType.getWebDriverObject(desiredCapabilities);
}
}
@Test
public void shouldCreateAnAutoDetectProxy() {
Proxy proxy = factory.getAutodetectProxy();
assertThat(proxy.getProxyType(), is(Proxy.ProxyType.AUTODETECT));
assertThat(proxy.isAutodetect(), is(true));
}
@Test
public void shouldCreateConfigUrlProxy() throws MalformedURLException {
String pacUrl = "http://example.com/proxy.pac";
Proxy proxy = factory.getConfigUrlProxy(pacUrl);
assertThat(proxy.getProxyType(), is(Proxy.ProxyType.PAC));
assertThat(proxy.getProxyAutoconfigUrl(), is(pacUrl));
}
@Test
public void shouldDelegateToProxyFactoryWhenCreatingSystemProxy() {
when(proxyFactory.getSystemProxy()).thenReturn(new Proxy());
config.setProxyType(ProxyType.SYSTEM);
Proxy proxy = config.createProxy();
assertThat(proxy, is(notNullValue()));
verify(proxyFactory, times(1)).getSystemProxy();
}
@Test
public void shouldDelegateToProxyFactoryWhenCreatingDirectProxy() {
when(proxyFactory.getDirectProxy()).thenReturn(new Proxy());
config.setProxyType(ProxyType.DIRECT);
Proxy proxy = config.createProxy();
assertThat(proxy, is(notNullValue()));
verify(proxyFactory, times(1)).getDirectProxy();
}
@Test
public void shouldDelegateToProxyFactoryWhenCreatingAutoDetectProxy() {
when(proxyFactory.getAutodetectProxy()).thenReturn(new Proxy());
config.setProxyType(ProxyType.AUTO_DETECT);
Proxy proxy = config.createProxy();
assertThat(proxy, is(notNullValue()));
verify(proxyFactory, times(1)).getAutodetectProxy();
}
@Test
public void shouldDelegateToProxyFactoryWhenCreatingProxyPacProxy() throws MalformedURLException {
String url = "http://proxy/pac.url";
when(proxyFactory.getConfigUrlProxy(url)).thenReturn(new Proxy());
config.setProxyPacUrl(url);
config.setProxyType(ProxyType.PROXY_PAC);
Proxy proxy = config.createProxy();
assertThat(proxy, is(notNullValue()));
verify(proxyFactory, times(1)).getConfigUrlProxy(Mockito.isA(String.class));
}
private void setFirefoxProxyIfAvailable(
DesiredCapabilities capabilities ) {
if (!StringUtils.isNullOrEmpty(AtsSystemProperties.SYSTEM_HTTP_PROXY_HOST)
&& !StringUtils.isNullOrEmpty(AtsSystemProperties.SYSTEM_HTTP_PROXY_PORT)) {
capabilities.setCapability(CapabilityType.PROXY,
new Proxy().setHttpProxy(AtsSystemProperties.SYSTEM_HTTP_PROXY_HOST
+ ':'
+ AtsSystemProperties.SYSTEM_HTTP_PROXY_PORT));
}
}
public static Proxy createProxyCapabilities()
{
final String proxyHost = Neodymium.configuration().getProxyHost() + ":" + Neodymium.configuration().getProxyPort();
final Proxy webdriverProxy = new Proxy();
webdriverProxy.setHttpProxy(proxyHost);
webdriverProxy.setSslProxy(proxyHost);
webdriverProxy.setFtpProxy(proxyHost);
if (!StringUtils.isAllEmpty(Neodymium.configuration().getProxySocketUsername(), Neodymium.configuration().getProxySocketPassword())
|| Neodymium.configuration().getProxySocketVersion() != null)
{
webdriverProxy.setSocksProxy(proxyHost);
if (StringUtils.isNoneEmpty(Neodymium.configuration().getProxySocketUsername(),
Neodymium.configuration().getProxySocketPassword()))
{
webdriverProxy.setSocksUsername(Neodymium.configuration().getProxySocketUsername());
webdriverProxy.setSocksPassword(Neodymium.configuration().getProxySocketPassword());
}
if (Neodymium.configuration().getProxySocketVersion() != null)
{
webdriverProxy.setSocksVersion(4);
}
}
webdriverProxy.setNoProxy(Neodymium.configuration().getProxyBypass());
return webdriverProxy;
}
public DesiredCapabilities createDesiredCapabilities(Proxy proxy) {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, proxy);
ChromeOptions options = new ChromeOptions();
options.addArguments("--test-type");
options.addArguments("--start-maximized");
options.addArguments("--disable-web-security");
options.addArguments("--allow-file-access-from-files");
options.addArguments("--allow-running-insecure-content");
options.addArguments("--allow-cross-origin-auth-prompt");
options.addArguments("--allow-file-access");
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
return capabilities;
}
/**
* Создает настойки прокси для запуска драйвера
*/
@Before(order = 1)
public void setDriverProxy() {
if (!Strings.isNullOrEmpty(System.getProperty("proxy"))) {
Proxy proxy = new Proxy().setHttpProxy(System.getProperty("proxy"));
setProxy(proxy);
log.info("Проставлена прокси: " + proxy);
}
}
/**
* если установлен -Dproxy=true стартует прокси
* har для прослушки указывается в application.properties
* @param capabilities
*/
private void enableProxy(DesiredCapabilities capabilities) {
proxy.setTrustAllServers(Boolean.valueOf(loadProperty(TRUST_ALL_SERVERS, "true")));
proxy.start();
Proxy seleniumProxy = ClientUtil.createSeleniumProxy(proxy);
capabilities.setCapability(PROXY, seleniumProxy);
capabilities.setCapability(ACCEPT_SSL_CERTS, Boolean.valueOf(loadProperty(ACCEPT_SSL_CERTS, "true")));
capabilities.setCapability(SUPPORTS_JAVASCRIPT, Boolean.valueOf(loadProperty(SUPPORTS_JAVASCRIPT, "true")));
proxy.enableHarCaptureTypes(CaptureType.REQUEST_CONTENT, CaptureType.REQUEST_HEADERS, CaptureType.RESPONSE_CONTENT, CaptureType.RESPONSE_HEADERS);
proxy.newHar(loadProperty(NEW_HAR));
}
DesiredCapabilities proxyCapabilities(BrowserMobProxy browserMobProxy) {
browserMobProxy.enableHarCaptureTypes(
CaptureType.REQUEST_HEADERS,
CaptureType.RESPONSE_HEADERS,
CaptureType.REQUEST_CONTENT,
CaptureType.RESPONSE_CONTENT);
Proxy seleniumProxy = ClientUtil.createSeleniumProxy(browserMobProxy);
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, seleniumProxy);
return capabilities;
}
private DesiredCapabilities enableProxy(Capabilities capabilities) {
DesiredCapabilities caps = new DesiredCapabilities(capabilities);
try {
InetAddress proxyInetAddress = InetAddress.getByName(proxyIp);
BrowserMobProxy browserMobProxy = proxyController.startProxyServer(proxyInetAddress);
Proxy seleniumProxy = ClientUtil.createSeleniumProxy(browserMobProxy, proxyInetAddress);
caps.setCapability(CapabilityType.PROXY, seleniumProxy);
} catch (UnknownHostException e) {
throw new IllegalStateException(e);
}
return caps;
}
private void setOptionalProxyConfiguration(DesiredCapabilities capabilities) {
if (proxyConfiguration != null) {
Proxy proxy = new Proxy();
proxyConfiguration.configureProxy(proxy);
capabilities.setCapability(CapabilityType.PROXY, proxy);
}
}
protected void setOptionalProxyConfiguration(DesiredCapabilities capabilities) {
if (proxyConfiguration != null && !(proxyConfiguration instanceof NoProxyConfiguration)) {
Proxy proxy = new Proxy();
proxyConfiguration.configureProxy(proxy);
capabilities.setCapability(CapabilityType.PROXY, proxy);
}
}