Skip to content

Commit

Permalink
clean up deprecated features in Selenium.
Browse files Browse the repository at this point in the history
* `CapabilityType.TAKES_SCREENSHOT`: remove its use.
* `CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR`: replace with equivalent code.
* `DesiredCapabilities.setJavascriptEnabled(boolean)`: replace with equivalent code.
  • Loading branch information
vmi committed Aug 17, 2022
1 parent a97bb31 commit 7b5f77b
Show file tree
Hide file tree
Showing 7 changed files with 69 additions and 24 deletions.
50 changes: 47 additions & 3 deletions src/generator/OptionGenerator.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ genDir = Paths.get(sourceUri).parent
baseDir = genDir.resolveSibling("main/java/jp/vmi/selenium")
config = new ConfigSlurper().parse(genDir.resolve('config.groovy').toUri().toURL())

INDENT = " "

def toUpperCamelCase(s) {
s.replaceAll(/(^|_)([a-z])/) { m -> m[2].toUpperCase() }
}
Expand Down Expand Up @@ -43,8 +45,15 @@ def updateOptions(iConfig, dConfig, dOpts) {
def optStr = oName.replace('_', '-')
def option = "name = \"--\" + ${cName}"
def fType = "String"
def deprecated = false
odef.forEach { name, value ->
switch (name) {
case "deprecated":
if (value instanceof Boolean && value) {
deprecated = true
}
break

case "type":
fType = value
break
Expand All @@ -53,7 +62,11 @@ def updateOptions(iConfig, dConfig, dOpts) {
if (value instanceof Boolean && !value) {
break
}
enumItems += " /** --${optStr} */\n ${cName}"
enumItems += "${INDENT}/** --${optStr} */\n"
if (deprecated) {
enumItems += "${INDENT}@Deprecated\n"
}
enumItems += "${INDENT}${cName}"
def t = (value instanceof String) ? value : fType
if (t != "String") {
enumItems += "(${t}.class)"
Expand All @@ -70,6 +83,9 @@ def updateOptions(iConfig, dConfig, dOpts) {
value = value.replaceAll(/"/, "\\\\\"").replaceAll(/%(\w+)%/) {
"\" + ${it[1]} + \""
}
if (deprecated) {
value = "[deprecated] " + value
}
}
option += " ${name} = \"${value}\""
break
Expand All @@ -83,31 +99,59 @@ def updateOptions(iConfig, dConfig, dOpts) {
mgPrefix = "is"
dValue = "false"
}
if (deprecated) {
oNames += " @Deprecated\n"
}
oNames += """\
public static final String ${cName} = "${optStr}";
"""
if (deprecated) {
getters += "\n @Deprecated"
}
getters += """
${mType} ${mgPrefix}${uName}();
"""
if (deprecated) {
fields += "\n @Deprecated\n @SuppressWarnings(\"deprecation\")"
}
fields += "\n @Option(${option})\n private ${fType} ${lName};\n"
accessors += """
if (deprecated) {
accessors += """
@Override
@Deprecated
public ${mType} ${mgPrefix}${uName}() {
return ${dValue};
}
"""
} else {
accessors += """
@Override
public ${mType} ${mgPrefix}${uName}() {
return ${lName} != null ? ${lName} : (parentOptions != null ? parentOptions.${mgPrefix}${uName}() : ${dValue});
}
"""
}
if (fType == "String[]") {
accessors += """
public void add${uName}(String ${lName}Item) {
this.${lName} = ArrayUtils.add(this.${lName}, ${lName}Item);
}
"""
} else {
accessors += """
if (deprecated) {
accessors += """
@Deprecated
public void set${uName}(${mType} ${lName}) {
log.warn("--${optStr} is deprecated.");
}
"""
} else {
accessors += """
public void set${uName}(${mType} ${lName}) {
this.${lName} = ${lName};
}
"""
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/generator/config.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ width {
}

alerts_policy {
usage = "The default behaviour for unexpected alerts (accept/ignore/dismiss)"
usage = "The default behaviour for unexpected alerts (accept/dismiss/accept_and_notify/dismiss_and_notify/ignore)"
driverOption = "UnexpectedAlertBehaviour"
}

Expand Down
4 changes: 1 addition & 3 deletions src/main/java/jp/vmi/selenium/selenese/Runner.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.output.NullOutputStream;
import org.openqa.selenium.Alert;
import org.openqa.selenium.HasCapabilities;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
Expand Down Expand Up @@ -61,7 +60,6 @@
import jp.vmi.selenium.webdriver.WebDriverPreparator;

import static jp.vmi.selenium.selenese.result.Unexecuted.*;
import static org.openqa.selenium.remote.CapabilityType.*;

/**
* Provide Java API to run Selenese script.
Expand Down Expand Up @@ -205,7 +203,7 @@ public PrintStream getPrintStream() {
protected TakesScreenshot getTakesScreenshot() {
if (driver instanceof TakesScreenshot) {
return (TakesScreenshot) driver;
} else if (driver instanceof RemoteWebDriver && ((HasCapabilities) driver).getCapabilities().is(TAKES_SCREENSHOT)) {
} else if (driver instanceof RemoteWebDriver) {
return (TakesScreenshot) new Augmenter().augment(driver);
} else {
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ private static String statusListItem(Level level) {
@Option(name = "--" + WIDTH, metaVar = "<width>", usage = "set initial width. (excluding mobile)")
private String width;

@Option(name = "--" + ALERTS_POLICY, usage = "The default behaviour for unexpected alerts (accept/ignore/dismiss)")
@Option(name = "--" + ALERTS_POLICY, usage = "The default behaviour for unexpected alerts (accept/dismiss/accept_and_notify/dismiss_and_notify/ignore)")
private String alertsPolicy;

@Option(name = "--" + DEFINE, aliases = "-D", metaVar = "<key>[:<type>][+]=<value>",
Expand Down
15 changes: 8 additions & 7 deletions src/main/java/jp/vmi/selenium/webdriver/DriverOptions.java
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ public boolean has(DriverOption opt) {
case CHROME_EXTENSION:
return !chromeExtensions.isEmpty();
case ALERTS_POLICY:
return caps.getCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR) != null;
return caps.getCapability(CapabilityType.UNHANDLED_PROMPT_BEHAVIOUR) != null;
default:
return map.containsKey(opt);
}
Expand Down Expand Up @@ -241,11 +241,10 @@ private static UnexpectedAlertBehaviour parseUnexpectedAlertBehaviour(Object val
if (value == null || value instanceof UnexpectedAlertBehaviour)
return (UnexpectedAlertBehaviour) value;
if (value instanceof String) {
try {
return Enum.valueOf(UnexpectedAlertBehaviour.class, ((String) value).toUpperCase());
} catch (IllegalArgumentException e) {
// fall through.
}
String canon = ((String) value).trim().replaceAll("[\\-_\t ]+", " ");
UnexpectedAlertBehaviour uab = UnexpectedAlertBehaviour.fromString(canon);
if (uab != null)
return uab;
}
throw new IllegalArgumentException(String.format(
"The value of %s is \"%s\". It must be one of the following: accept, dismiss, accept_and_notify, dismiss_and_notify, ignore",
Expand Down Expand Up @@ -292,7 +291,7 @@ public DriverOptions set(DriverOption opt, Object value) {
break;
case ALERTS_POLICY:
UnexpectedAlertBehaviour uab = parseUnexpectedAlertBehaviour(value);
caps.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, uab);
caps.setCapability(CapabilityType.UNHANDLED_PROMPT_BEHAVIOUR, uab);
return this;
default:
if (value == null)
Expand All @@ -305,8 +304,10 @@ public DriverOptions set(DriverOption opt, Object value) {
opt, opt.valueType.getSimpleName(), value.getClass().getSimpleName(), value));
}

@SuppressWarnings("deprecation")
private static Object getTypedValue(String name, String type, String value, Consumer<String> errorHandler) {
switch (name) {
case CapabilityType.UNHANDLED_PROMPT_BEHAVIOUR:
case CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR:
return parseUnexpectedAlertBehaviour(value);
default:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package jp.vmi.selenium.webdriver;

import java.lang.reflect.Field;

import org.openqa.selenium.Capabilities;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.Platform;
Expand Down Expand Up @@ -34,10 +36,12 @@ public String getBrowserName() {
public WebDriver newInstance(DriverOptions driverOptions) {
DesiredCapabilities caps = new DesiredCapabilities(Browser.HTMLUNIT.browserName(), "", Platform.ANY);
setupProxy(caps, driverOptions);
caps.setJavascriptEnabled(true);
caps.merge(driverOptions.getCapabilities());
try {
Class<?> htmlUnitDriverClass = Class.forName(HTML_UNIT_DRIVER);
Field javascriptEnabledField = htmlUnitDriverClass.getDeclaredField("JAVASCRIPT_ENABLED");
String javascriptEnabled = (String) javascriptEnabledField.get(null);
caps.setCapability(javascriptEnabled, true);
WebDriver driver = (WebDriver) htmlUnitDriverClass.getConstructor(Capabilities.class).newInstance(caps);
//HtmlUnitDriver driver = new HtmlUnitDriver(caps);
Class.forName(HTML_UNIT_CONSOLE).getMethod("setHtmlUnitConsole", WebDriver.class).invoke(null, driver);
Expand Down
14 changes: 6 additions & 8 deletions src/test/java/jp/vmi/selenium/webdriver/DriverOptionsTest.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package jp.vmi.selenium.webdriver;

import org.junit.Test;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.HasCapabilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;

Expand Down Expand Up @@ -48,21 +48,19 @@ public void defineBool() {
WebDriverManager wdm = WebDriverManager.newInstance();
wdm.setWebDriverFactory(WebDriverManager.HTMLUNIT);
DriverOptions driverOptions = new DriverOptions();
driverOptions.addDefinitions("javascriptEnabled:bool=false");
driverOptions.addDefinitions("acceptInsecureCerts:bool=true");
wdm.setDriverOptions(driverOptions);
WebDriver driver = wdm.get();
WebServer ws = new WebServer();
ws.start();
Exception actual = null;
DesiredCapabilities caps = null;
try {
driver.get(ws.getBaseURL());
((JavascriptExecutor) driver).executeScript("true");
} catch (Exception e) {
actual = e;
HasCapabilities hasCaps = (HasCapabilities) driver;
caps = (DesiredCapabilities) hasCaps.getCapabilities();
} finally {
ws.stop();
}
assertThat(actual, is(instanceOf(UnsupportedOperationException.class)));
assertThat(actual.getMessage(), equalTo("Javascript is not enabled for this HtmlUnitDriver instance"));
assertThat(caps.acceptInsecureCerts(), is(true));
}
}

0 comments on commit 7b5f77b

Please sign in to comment.