下面列出了怎么用org.openqa.selenium.firefox.FirefoxOptions的API类实例代码及写法,或者点击链接到github查看源代码。
@BeforeAll
public static void openServerAndBrowser() throws IOException {
FirefoxOptions options = new FirefoxOptions();
options.addArguments("-headless");
// ChromeOptions options = new ChromeOptions();
// options.addArguments(
// "--headless",
// "--disable-web-security",
// "--allow-running-insecure-content",
// "--ignore-certificate-errors");
driver = new FirefoxDriver(options);
percy = new Percy(driver);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
@Test
@SuppressWarnings("unchecked")
void testGetRemoteWebDriverFirefoxDriver() throws MalformedURLException
{
mockCapabilities(remoteWebDriver);
setRemoteDriverUrl();
DesiredCapabilities desiredCapabilities = new DesiredCapabilities(new FirefoxOptions());
when(remoteWebDriverFactory.getRemoteWebDriver(eq(URL.toURL()), argThat(caps ->
{
Map<String, Object> options = (Map<String, Object>) caps.getCapability(FirefoxOptions.FIREFOX_OPTIONS);
Map<String, Object> prefs = (Map<String, Object>) options.get("prefs");
return "about:blank".equals(prefs.get("startup.homepage_welcome_url.additional"))
&& "firefox".equals(caps.getBrowserName());
}))).thenReturn(remoteWebDriver);
Timeouts timeouts = mockTimeouts(remoteWebDriver);
assertEquals(remoteWebDriver,
((WrapsDriver) webDriverFactory.getRemoteWebDriver(desiredCapabilities)).getWrappedDriver());
verify(timeoutConfigurer).configure(timeouts);
assertLogger();
}
@SuppressWarnings("unchecked")
private static DesiredCapabilities testGetFirefoxWebDriver(WebDriverConfiguration configuration) throws Exception
{
DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
FirefoxOptions firefoxOptions = new FirefoxOptions();
whenNew(FirefoxOptions.class).withArguments(desiredCapabilities).thenReturn(firefoxOptions);
whenNew(FirefoxOptions.class).withNoArguments().thenReturn(firefoxOptions);
FirefoxDriver expected = mock(FirefoxDriver.class);
whenNew(FirefoxDriver.class).withParameterTypes(FirefoxOptions.class).withArguments(firefoxOptions)
.thenReturn(expected);
WebDriver actual = WebDriverType.FIREFOX.getWebDriver(desiredCapabilities, configuration);
assertEquals(expected, actual);
Map<String, Object> options = (Map<String, Object>) desiredCapabilities
.getCapability(FirefoxOptions.FIREFOX_OPTIONS);
Map<String, Object> prefs = (Map<String, Object>) options.get("prefs");
assertEquals("about:blank", prefs.get("startup.homepage_welcome_url.additional"));
return desiredCapabilities;
}
public static void main(String... args) throws IOException {
System.setProperty("webdriver.gecko.driver",
"./src/test/resources/drivers/geckodriver 2");
FirefoxProfile profile = new FirefoxProfile();
profile.addExtension(
new File("./src/test/resources/extensions/xpath_finder.xpi"));
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setProfile(profile);
FirefoxDriver driver = new FirefoxDriver(firefoxOptions);
try {
driver.get("http://www.google.com");
} finally {
driver.quit();
}
}
public static void main(String... args) {
System.setProperty("webdriver.gecko.driver",
"./src/test/resources/drivers/geckodriver 2");
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("browser.shell.checkDefaultBrowser", true);
profile.setAssumeUntrustedCertificateIssuer(false);
profile.setAcceptUntrustedCertificates(false);
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setProfile(profile);
FirefoxDriver driver = new FirefoxDriver(firefoxOptions);
driver.get("http://facebook.com");
}
@Override
protected Capabilities newCaps(Capabilities capsToMerge) {
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setAcceptInsecureCerts(true);
// **** 以上capabilities可被传入的caps覆盖 ****
firefoxOptions.merge(capsToMerge);
// **** 以下capabilities具有更高优先级,将覆盖传入的caps ****
if (!StringUtils.isEmpty(browser.getPath())) {
firefoxOptions.setBinary(browser.getPath());
}
return firefoxOptions;
}
@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);
}
private static FirefoxDriver createFirefoxDriver() {
FirefoxOptions options = new FirefoxOptions();
if (BrowserConfig.getFirefoxBinPath() != null) {
options.setBinary(BrowserConfig.getFirefoxBinPath());
}
if (BrowserConfig.getFirefoxDriverPath() != null) {
System.setProperty(FIREFOX_DRIVER_PATH_KEY, BrowserConfig.getChromeDriverPath().toString());
}
if (BrowserConfig.isHeadless()) {
options.setHeadless(true);
}
if (System.getProperty(FIREFOX_DRIVER_PATH_KEY) == null) {
setupDriverManagerConfig();
downloadDriverMessage("firefox");
WebDriverManager.firefoxdriver().setup();
}
return new FirefoxDriver(options);
}
@Override
public void resolve() {
try {
Optional<Object> testInstance = context.getTestInstance();
Optional<Capabilities> capabilities = annotationsReader
.getCapabilities(parameter, testInstance);
FirefoxOptions firefoxOptions = (FirefoxOptions) getOptions(
parameter, testInstance);
if (capabilities.isPresent()) {
firefoxOptions.merge(capabilities.get());
}
object = new FirefoxDriver(firefoxOptions);
} catch (Exception e) {
handleException(e);
}
}
@ParameterizedTest
@MethodSource("testClassProvider")
@SuppressWarnings("unchecked")
void testFirefoxOptions(Class<?> testClass) throws Exception {
Parameter parameter = testClass
.getMethod("webrtcTest", FirefoxDriver.class)
.getParameters()[0];
Optional<Object> testInstance = Optional.of(testClass.newInstance());
FirefoxOptions firefoxOptions = (FirefoxOptions) annotationsReader
.getOptions(parameter, testInstance);
Map<String, Map<String, Boolean>> options = (Map<String, Map<String, Boolean>>) firefoxOptions
.asMap().get(FIREFOX_OPTIONS);
assertTrue(options.get("prefs")
.get("media.navigator.permission.disabled"));
assertTrue(options.get("prefs").get("media.navigator.streams.fake"));
}
@Test
public void testCanInstantiateARemoteDriver() throws MalformedURLException {
factory.setRemoteDriverProvider(new RemoteDriverProvider() {
@Override
public WebDriver createDriver(URL hub, Capabilities capabilities) {
return new FakeWebDriver(capabilities);
}
});
WebDriver driver = factory.getDriver(new URL("http://localhost/"), new FirefoxOptions());
assertTrue(driver instanceof FakeWebDriver);
assertFalse(factory.isEmpty());
factory.dismissDriver(driver);
assertTrue(factory.isEmpty());
}
private WebDriver prepareRemoteDriver(){
if(System.getenv("SAUCE_USERNAME") == null){
throw new RuntimeException("To use remote driver a Sauce lab account is required. Please assign your Sauce labs account name to the environmental variable 'sauce_username'");
}
if(System.getenv("SAUCE_ACCESS_KEY") == null){
throw new RuntimeException("To use remote driver a Sauce lab account is required. Please assign your Sauce labs access key to the environmental variable 'sauce_access_key'");
}
String URL = "http://" + System.getenv("SAUCE_USERNAME") + ":" + System.getenv("SAUCE_ACCESS_KEY") + "@ondemand.saucelabs.com:80/wd/hub";
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setCapability("screenResolution", "1440x900");
try {
return new RemoteWebDriver(new URL(URL), firefoxOptions);
} catch (MalformedURLException e) {
throw new RuntimeException("WARN: An error occurred attempting to create a remote driver connection. See the following error: " + e);
}
}
@Test
public void createContainerWithoutShmVolume() {
try (
BrowserWebDriverContainer webDriverContainer = new BrowserWebDriverContainer<>()
.withSharedMemorySize(512 * FileUtils.ONE_MB)
.withCapabilities(new FirefoxOptions())
) {
webDriverContainer.start();
assertEquals("Shared memory size is configured",
512 * FileUtils.ONE_MB,
webDriverContainer.getShmSize());
assertEquals("No shm mounts present", emptyList(), shmVolumes(webDriverContainer));
}
}
@Test
@Ignore
public void shouldPreferMarionette() {
// Make sure we have at least one of the services available
Capabilities caps = new FirefoxOptions();
RemoteWebDriverBuilder.Plan plan = RemoteWebDriver.builder()
.addAlternative(caps)
.getPlan();
assertThat(new XpiDriverService.Builder().score(caps)).isEqualTo(0);
assertThat(new GeckoDriverService.Builder().score(caps)).isEqualTo(1);
assertThat(plan.isUsingDriverService()).isTrue();
assertThat(plan.getDriverService().getClass()).isEqualTo(GeckoDriverService.class);
}
@Override
public WebDriver createWebDriver(String webDriverPath) {
FirefoxBinary ffox = new FirefoxBinary();
if ("true".equals(System.getenv("TRAVIS"))) {
// xvfb is supposed to run with DISPLAY 99
ffox.setEnvironmentProperty("DISPLAY", ":99");
}
ffox.addCommandLineOptions("--headless");
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.download.dir",
FileUtils.getTempDirectory().toString() + "/firefox/");
profile.setPreference("browser.helperApps.alwaysAsk.force", false);
profile.setPreference("browser.download.manager.showWhenStarting", false);
profile.setPreference("browser.download.manager.showAlertOnComplete", false);
profile.setPreference("browser.download.manager.closeWhenDone", true);
profile.setPreference("app.update.auto", false);
profile.setPreference("app.update.enabled", false);
profile.setPreference("dom.max_script_run_time", 0);
profile.setPreference("dom.max_chrome_script_run_time", 0);
profile.setPreference("browser.helperApps.neverAsk.saveToDisk",
"application/x-ustar,application/octet-stream,application/zip,text/csv,text/plain");
profile.setPreference("network.proxy.type", 0);
System.setProperty(
GeckoDriverService.GECKO_DRIVER_EXE_PROPERTY, webDriverPath);
System.setProperty(
FirefoxDriver.SystemProperty.DRIVER_USE_MARIONETTE, "true");
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setBinary(ffox);
firefoxOptions.setProfile(profile);
firefoxOptions.setLogLevel(FirefoxDriverLogLevel.TRACE);
return new FirefoxDriver(firefoxOptions);
}
@Test
@PrepareForTest(fullyQualifiedNames = "org.vividus.selenium.WebDriverType$1")
public void testGetFirefoxWebDriverWithCommandLineArguments() throws Exception
{
String argument = "headless";
WebDriverConfiguration configuration = new WebDriverConfiguration();
DesiredCapabilities desiredCapabilities = testGetFirefoxWebDriver(configuration);
FirefoxOptions expected = new FirefoxOptions();
expected.addArguments(argument);
assertEquals(expected.asMap(), desiredCapabilities.asMap());
}
@Override
public FirefoxOptions getCapabilities() {
FirefoxOptions firefoxOptions = new FirefoxOptions();
setCapabilities(firefoxOptions);
setFirefoxPrefs(firefoxOptions);
setFirefoxArgs(firefoxOptions);
firefoxOptions.setPageLoadStrategy(getPageLoadStrategy());
return firefoxOptions;
}
private void setFirefoxPrefs(FirefoxOptions options) {
Map<String, Object> configOptions = getBrowserOptions();
configOptions.forEach((key, value) -> {
if (key.equals(getDownloadDirCapabilityKey())) {
options.addPreference(key, getDownloadDir());
} else if(value instanceof Boolean) {
options.addPreference(key, (boolean) value);
} else if (value instanceof Integer) {
options.addPreference(key, (int) value);
} else if (value instanceof String) {
options.addPreference(key, (String) value);
}
});
}
/**
* Sets the webdriver to FireFox. We set our optimal parameters here
* to ensure our proxy is set correctly.
*/
private void setFirefoxDriver() {
FirefoxOptions options = new FirefoxOptions();
FirefoxProfile profile = new FirefoxProfile();
FirefoxBinary binary = new FirefoxBinary(this.driverLocation);
LoggingPreferences logPrefs = new LoggingPreferences();
System.setProperty(FirefoxDriver.SystemProperty.DRIVER_USE_MARIONETTE,"true");
// hide firefox logs from console
System.setProperty(FirefoxDriver.SystemProperty.BROWSER_LOGFILE,"/tmp/rust_");
profile.setPreference("media.volume_scale", "0.0");
profile.setPreference("general.useragent.override", userAgent.randomUA());
profile.setPreference("network.proxy.type", 1);
profile.setPreference("network.proxy.http", this.proxies.getCurrentProxyModel().getIp());
profile.setPreference("network.proxy.http_port", this.proxies.getCurrentProxyModel().getPort());
profile.setPreference("network.proxy.ssl", this.proxies.getCurrentProxyModel().getIp());
profile.setPreference("network.proxy.ssl_port", this.proxies.getCurrentProxyModel().getPort());
logPrefs.enable(LogType.BROWSER, Level.ALL);
logPrefs.enable(LogType.PERFORMANCE, Level.INFO);
options.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);
options.setProfile(profile);
options.setHeadless(true);
options.setBinary(binary);
// options.setProxy(this.proxies.getCurrentProxy());
options.setCapability("proxy", this.proxies.getCurrentProxy());
this.webDriver = new FirefoxDriver(options);
Log.WINFO(this.workerName, this.workerColor, "Firefox Driver Set");
}
private static WebDriver setupFirefoxDriver() throws MalformedURLException {
LOG.i("Setting up Firefox driver...");
setupDriver(firefoxdriver());
final DesiredCapabilities capabilities = new DesiredCapabilities();
final FirefoxOptions options = new FirefoxOptions(capabilities);
final GeckoDriverService firefoxService = GeckoDriverService.createDefaultService();
return new FirefoxDriver(firefoxService, options);
}
public static void main(String... args) {
System.setProperty("webdriver.gecko.driver",
"./src/test/resources/drivers/geckodriver 2");
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("general.useragent.override",
"Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) " +
"AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 " +
" Mobile/15A356 Safari/604.1");
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setProfile(profile);
FirefoxDriver driver = new FirefoxDriver(firefoxOptions);
driver.get("http://facebook.com");
}
public SeleniumConfig(long timeout) {
FirefoxBinary firefoxBinary = new FirefoxBinary();
firefoxBinary.addCommandLineOptions("--headless");
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setBinary(firefoxBinary);
driver = new FirefoxDriver(firefoxOptions);
driver.manage().timeouts().implicitlyWait(timeout, TimeUnit.SECONDS);
}
private static FirefoxDriver createFirefoxDriver(final String binary) {
if (binary != null) {
final FirefoxOptions options = new FirefoxOptions();
options.setBinary(binary);
return new FirefoxDriver(options);
}
return new FirefoxDriver();
}
@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");
}
@Test
private void javascriptExample3() {
FirefoxDriver driver = new FirefoxDriver(new FirefoxOptions());
String animal = "Lion";
int seen = 5;
driver.executeScript("console.log('I have seen a ' + arguments[0] + ' ' + arguments[1] + ' times(s)');", animal, seen);
}
@Override
protected FirefoxDriver createBrowser() {
FirefoxOptions desiredCapabilities = new FirefoxOptions(createCapabilities());
desiredCapabilities.setCapability(FirefoxDriver.PROFILE, createProfile());
return new FirefoxDriver(new GeckoDriverService.Builder().usingFirefoxBinary(new FirefoxBinary()).build(),
desiredCapabilities);
}
@Test
public void shouldCreateFirefox() throws Exception {
FirefoxDriver mockFirefoxDriver = Mockito.mock(FirefoxDriver.class);
whenNew(FirefoxDriver.class)
.withParameterTypes(GeckoDriverService.class, FirefoxOptions.class)
.withArguments(isA(GeckoDriverService.class), isA(FirefoxOptions.class))
.thenReturn(mockFirefoxDriver);
final FirefoxDriver browser = config.createBrowser();
assertThat(browser, is(mockFirefoxDriver));
verifyNew(FirefoxDriver.class, times(1)).withArguments(isA(GeckoDriverService.class), isA(FirefoxOptions.class));
}
public FirefoxOptions get() {
FirefoxOptions firefoxOptions = getFirefoxOptions();
if (!this.customCaps.asMap().isEmpty()) {
firefoxOptions.merge(this.customCaps);
}
return firefoxOptions;
}
private FirefoxOptions getFirefoxOptions() {
FirefoxOptions options = new FirefoxOptions();
options.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, this.alertBehaviour);
options.setCapability(FirefoxDriver.MARIONETTE, false);
options.setCapability(FirefoxDriver.PROFILE, createFirefoxProfile());
options.setCapability("platform", platform);
options.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
setLoggingPrefs(options);
return options;
}
public FirefoxOptions get() {
FirefoxOptions caps = getGeckoOptions();
if (!this.customCaps.asMap().isEmpty()) {
caps.merge(this.customCaps);
}
return caps;
}