Skip to content
This repository was archived by the owner on Feb 2, 2025. It is now read-only.

Commit 9c2c5d5

Browse files
committed
Merge branch 'develop' of github.com:Hi-Fi/robotframework-seleniumlibrary-java into selenium4
2 parents 0e85099 + 849b542 commit 9c2c5d5

File tree

12 files changed

+160
-60
lines changed

12 files changed

+160
-60
lines changed

pom.xml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,11 @@
144144
<version>2.18.3</version>
145145
<scope>test</scope>
146146
</dependency>
147+
<dependency>
148+
<groupId>io.github.bonigarcia</groupId>
149+
<artifactId>webdrivermanager</artifactId>
150+
<version>3.4.0</version>
151+
</dependency>
147152
</dependencies>
148153

149154
<build>
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package com.github.markusbernhardt.seleniumlibrary;
2+
3+
import com.github.markusbernhardt.seleniumlibrary.keywords.BrowserManagement;
4+
import com.github.markusbernhardt.seleniumlibrary.keywords.Robot;
5+
import org.openqa.selenium.WebDriver;
6+
7+
import javax.script.ScriptEngine;
8+
import javax.script.ScriptEngineManager;
9+
import javax.script.ScriptException;
10+
import java.lang.reflect.Field;
11+
12+
/**
13+
* For extends of custom keywords of WebDriver actions
14+
*/
15+
public class CustomRobotDriverElement {
16+
17+
private static SeleniumLibrary s;
18+
private static BrowserManagement b;
19+
private Robot robot = new Robot();
20+
21+
public CustomRobotDriverElement() throws NoSuchFieldException, IllegalAccessException {
22+
try {
23+
CustomRobotDriverElement.s = getLibraryInstance();
24+
} catch (ScriptException e) {
25+
throw new SeleniumLibraryNonFatalException("Cannot create SeleniumLibrary instance.", e);
26+
}
27+
Field bmField = SeleniumLibrary.class.getDeclaredField("bm");
28+
bmField.setAccessible(true);
29+
b = (BrowserManagement) bmField.get(s);
30+
bmField.setAccessible(false);
31+
}
32+
33+
private static SeleniumLibrary getLibraryInstance() throws ScriptException {
34+
ScriptEngine engine = new ScriptEngineManager().getEngineByName("python");
35+
engine.put("library", "SeleniumLibrary");
36+
engine.eval("from robot.libraries.BuiltIn import BuiltIn");
37+
engine.eval("instance = BuiltIn().get_library_instance(library)");
38+
return (SeleniumLibrary) engine.get("instance");
39+
}
40+
41+
protected WebDriver getCurrentBrowser() {
42+
return b.getCurrentWebDriver();
43+
}
44+
45+
protected Robot getRobot() {
46+
return robot;
47+
}
48+
49+
}

src/main/java/com/github/markusbernhardt/seleniumlibrary/keywords/BrowserManagement.java

Lines changed: 87 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package com.github.markusbernhardt.seleniumlibrary.keywords;
22

33
import io.appium.java_client.ios.IOSDriver;
4+
import io.github.bonigarcia.wdm.DriverManagerType;
5+
import io.github.bonigarcia.wdm.WebDriverManager;
46
import io.selendroid.client.SelendroidDriver;
57

68
import java.io.File;
@@ -10,7 +12,6 @@
1012
import java.net.URL;
1113
import java.net.UnknownHostException;
1214
import java.util.ArrayList;
13-
import java.util.Iterator;
1415
import java.util.List;
1516
import java.util.Map.Entry;
1617
import java.util.concurrent.TimeUnit;
@@ -166,13 +167,15 @@ public void closeBrowser() {
166167
"| Iphone | iphone |\r\n" +
167168
"| JBrowser | jbrowser |\r\n" +
168169
"\r\n" +
169-
"To be able to actually use one of these browsers, you need to have a matching Selenium browser driver available. See the [https://github.com/Hi-Fi/robotframework-seleniumlibrary-java#browser-drivers|project documentation] for more details.\r\n" +
170+
"To be able to actually use one of these browsers, you need to have a matching Selenium browser driver available. See the [https://github.com/Hi-Fi/robotframework-seleniumlibrary-java#browser-drivers|project documentation] for more details.\r\n" +
170171
"\r\n" +
171172
"Optional ``alias`` is an alias given for this browser instance and it can be used for switching between browsers. An alternative approach for switching is using an index returned by this keyword. These indices start from 1, are incremented when new browsers are opened, and reset back to 1 when `Close All Browsers` is called. See `Switch Browser` for more information and examples.\r\n" +
172173
"\r\n" +
173-
"Optional ``remote_url`` is the URL for a remote Selenium server. If you specify a value for a remote, you can also specify ``desired_capabilities`` to configure, for example, a proxy server for Internet Explorer or a browser and operating system when using [http://saucelabs.com|Sauce Labs]. Desired capabilities can be given as a dictionary. [https://github.com/SeleniumHQ/selenium/wiki/Capabilities| Selenium documentation] lists possible capabilities that can be enabled.\r\n" +
174+
"Optional ``remote_url`` is the URL for a remote Selenium server. If you specify a value for a remote, you can also specify ``desired_capabilities`` to configure, for example, a proxy server for Internet Explorer or a browser and operating system when using [http://saucelabs.com|Sauce Labs]. Desired capabilities can be given as a dictionary. [https://github.com/SeleniumHQ/selenium/wiki/Capabilities| Selenium documentation] lists possible capabilities that can be enabled.\r\n" +
174175
"\r\n" +
175-
"Optional ``ff_profile_dir`` is the path to the Firefox profile directory if you wish to overwrite the default profile Selenium uses. Notice that prior to SeleniumLibrary 3.0, the library contained its own profile that was used by default.\r\n" +
176+
"Optional ``ff_profile_dir`` is the path to the Firefox profile directory if you wish to overwrite the default profile Selenium uses. Notice that prior to SeleniumLibrary 3.0, the library contained its own profile that was used by default.\r\n" +
177+
"\r\n" +
178+
"Optional ``isWebDriverManager`` is a flag of using automation download driver of browser and setting system variable for driver path.\r\n" +
176179
"\r\n" +
177180
"Examples:\r\n" +
178181
"| `Open Browser` | http://example.com | Chrome |\r\n" +
@@ -181,13 +184,18 @@ public void closeBrowser() {
181184
"\r\n" +
182185
"If the provided configuration options are not enough, it is possible to use `Create Webdriver` to customize browser initialization even more.")
183186
@ArgumentNames({ "url", "browserName=firefox", "alias=None", "remoteUrl=None", "desiredCapabilities=None",
184-
"browserOptions=None" })
185-
public String openBrowser(String url, String... args) throws Throwable {
187+
"browserOptions=None", "isWebDriverManager=false" })
188+
public String openBrowser(String url, String... args) {
186189
String browserName = robot.getParamsValue(args, 0, "firefox");
187190
String alias = robot.getParamsValue(args, 1, "None");
188191
String remoteUrl = robot.getParamsValue(args, 2, "None");
189192
String desiredCapabilities = robot.getParamsValue(args, 3, "None");
190193
String browserOptions = robot.getParamsValue(args, 4, "None");
194+
boolean isWebDriverManager = robot.getParamsValue(args, 5, false);
195+
196+
if (isWebDriverManager) {
197+
webDriverManagerSetup(browserName);
198+
}
191199

192200
try {
193201
logging.info("browserName: " + browserName);
@@ -660,7 +668,7 @@ protected WebDriver createLocalWebDriver(String browserName, Capabilities desire
660668
case "ipad":
661669
case "iphone":
662670
try {
663-
return new IOSDriver<WebElement>(new URL(""), desiredCapabilities);
671+
return new IOSDriver<>(new URL(""), desiredCapabilities);
664672
} catch (Exception e) {
665673
throw new SeleniumLibraryFatalException("Creating " + browserName + " instance failed.", e);
666674
}
@@ -669,6 +677,41 @@ protected WebDriver createLocalWebDriver(String browserName, Capabilities desire
669677
}
670678
}
671679

680+
@RobotKeyword("WebDriver Manager Setup")
681+
@ArgumentNames({"browserName=firefox"})
682+
public void webDriverManagerSetup(String browserName) {
683+
initWebDriver(browserName);
684+
logging.info(String.format("Init WebDriver Manager for '%s' browser", browserName));
685+
}
686+
687+
private void initWebDriver(String browserName) {
688+
switch (browserName.toLowerCase()) {
689+
case "ff":
690+
case "firefox":
691+
case "ffheadless":
692+
case "firefoxheadless":
693+
WebDriverManager.getInstance(DriverManagerType.FIREFOX).setup();
694+
break;
695+
case "ie":
696+
case "internetexplorer":
697+
WebDriverManager.getInstance(DriverManagerType.IEXPLORER).setup();
698+
break;
699+
case "edge":
700+
WebDriverManager.getInstance(DriverManagerType.EDGE).setup();
701+
break;
702+
case "gc":
703+
case "chrome":
704+
case "googlechrome":
705+
case "gcheadless":
706+
case "chromeheadless":
707+
case "googlechromeheadless":
708+
WebDriverManager.getInstance(DriverManagerType.CHROME).setup();
709+
break;
710+
default:
711+
throw new SeleniumLibraryFatalException(browserName + " is not a supported browser for WebDriver Manager.");
712+
}
713+
}
714+
672715
protected WebDriver createRemoteWebDriver(Capabilities desiredCapabilities, URL remoteUrl) {
673716
HttpCommandExecutor httpCommandExecutor = new HttpCommandExecutor(remoteUrl);
674717
setRemoteWebDriverProxy(httpCommandExecutor);
@@ -677,7 +720,7 @@ protected WebDriver createRemoteWebDriver(Capabilities desiredCapabilities, URL
677720

678721
protected Capabilities createCapabilities(String browserName, String desiredCapabilitiesString,
679722
String browserOptions) {
680-
Capabilities desiredCapabilities;
723+
MutableCapabilities desiredCapabilities;
681724
switch (browserName.toLowerCase()) {
682725
case "ff":
683726
case "firefox":
@@ -726,17 +769,16 @@ protected Capabilities createCapabilities(String browserName, String desiredCapa
726769
JSONObject jsonObject = (JSONObject) JSONValue.parse(desiredCapabilitiesString);
727770
if (jsonObject != null) {
728771
// Valid JSON
729-
Iterator<?> iterator = jsonObject.entrySet().iterator();
730-
while (iterator.hasNext()) {
731-
Entry<?, ?> entry = (Entry<?, ?>) iterator.next();
732-
((MutableCapabilities) desiredCapabilities).setCapability(entry.getKey().toString(), entry.getValue());
772+
for (Object o : jsonObject.entrySet()) {
773+
Entry<?, ?> entry = (Entry<?, ?>) o;
774+
desiredCapabilities.setCapability(entry.getKey().toString(), entry.getValue());
733775
}
734776
} else {
735777
// Invalid JSON. Old style key-value pairs
736778
for (String capability : desiredCapabilitiesString.split(",")) {
737779
String[] keyValue = capability.split(":");
738780
if (keyValue.length == 2) {
739-
((MutableCapabilities) desiredCapabilities).setCapability(keyValue[0], keyValue[1]);
781+
desiredCapabilities.setCapability(keyValue[0], keyValue[1]);
740782
} else {
741783
logging.warn("Invalid desiredCapabilities: " + desiredCapabilitiesString);
742784
}
@@ -751,34 +793,34 @@ protected void parseBrowserOptionsChrome(String browserOptions, Capabilities des
751793
JSONObject jsonObject = (JSONObject) JSONValue.parse(browserOptions);
752794
if (jsonObject != null) {
753795
// Check all properties for translation to ChromeOptions
754-
for (Iterator<?> iterator = jsonObject.keySet().iterator(); iterator.hasNext(); ) {
755-
String key = (String)iterator.next();
796+
for (Object o : jsonObject.keySet()) {
797+
String key = (String) o;
756798
switch (key) {
757-
case "args": {
758-
// args is a list of strings
759-
List<String> args = new ArrayList<>();
760-
for (Object arg : (JSONArray)jsonObject.get(key)) {
761-
args.add("--"+arg.toString().replace("--", ""));
799+
case "args": {
800+
// args is a list of strings
801+
List<String> args = new ArrayList<>();
802+
for (Object arg : (JSONArray) jsonObject.get(key)) {
803+
args.add("--" + arg.toString().replace("--", ""));
804+
}
805+
((ChromeOptions) desiredCapabilities).addArguments(args);
806+
break;
762807
}
763-
((ChromeOptions) desiredCapabilities).addArguments(args);
764-
break;
765-
}
766-
case "extensions": {
767-
List<File> extensions = new ArrayList<>();
768-
for (Object extension : (JSONArray)jsonObject.get(key)) {
769-
extensions.add(new File(extension.toString().toString().replace('/', File.separatorChar)));
808+
case "extensions": {
809+
List<File> extensions = new ArrayList<>();
810+
for (Object extension : (JSONArray) jsonObject.get(key)) {
811+
extensions.add(new File(extension.toString().replace('/', File.separatorChar)));
812+
}
813+
((ChromeOptions) desiredCapabilities).addExtensions(extensions);
814+
break;
770815
}
771-
((ChromeOptions) desiredCapabilities).addExtensions(extensions);
772-
break;
773-
}
774-
case "disable-extensions":
775-
// change casing
776-
((ChromeOptions) desiredCapabilities).setExperimentalOption("useAutomationExtension", false);
777-
break;
778-
default:
779-
// all unknonw properties are passed as is
780-
((ChromeOptions) desiredCapabilities).setExperimentalOption(key, jsonObject.get(key));
781-
break;
816+
case "disable-extensions":
817+
// change casing
818+
((ChromeOptions) desiredCapabilities).setExperimentalOption("useAutomationExtension", false);
819+
break;
820+
default:
821+
// all unknonw properties are passed as is
822+
((ChromeOptions) desiredCapabilities).setExperimentalOption(key, jsonObject.get(key));
823+
break;
782824
}
783825
}
784826
} else {
@@ -792,16 +834,14 @@ protected void parseBrowserOptionsFirefox(String browserOptions, Capabilities de
792834
JSONObject jsonObject = (JSONObject) JSONValue.parse(browserOptions);
793835
if (jsonObject != null) {
794836
FirefoxProfile firefoxProfile = new FirefoxProfile();
795-
Iterator<?> iterator = jsonObject.entrySet().iterator();
796-
while (iterator.hasNext()) {
797-
Entry<?, ?> entry = (Entry<?, ?>) iterator.next();
837+
for (Object o1 : jsonObject.entrySet()) {
838+
Entry<?, ?> entry = (Entry<?, ?>) o1;
798839
String key = entry.getKey().toString();
799840
if (key.equals("preferences")) {
800841
// Preferences
801842
JSONObject preferences = (JSONObject) entry.getValue();
802-
Iterator<?> iteratorPreferences = preferences.entrySet().iterator();
803-
while (iteratorPreferences.hasNext()) {
804-
Entry<?, ?> entryPreferences = (Entry<?, ?>) iteratorPreferences.next();
843+
for (Object o : preferences.entrySet()) {
844+
Entry<?, ?> entryPreferences = (Entry<?, ?>) o;
805845
Object valuePreferences = entryPreferences.getValue();
806846
logging.debug(String.format("Adding property: %s with value: %s",
807847
entryPreferences.getKey().toString(), valuePreferences));
@@ -810,7 +850,7 @@ protected void parseBrowserOptionsFirefox(String browserOptions, Capabilities de
810850
((Number) valuePreferences).intValue());
811851
} else if (valuePreferences instanceof Boolean) {
812852
firefoxProfile.setPreference(entryPreferences.getKey().toString(),
813-
((Boolean) valuePreferences).booleanValue());
853+
(Boolean) valuePreferences);
814854
} else {
815855
firefoxProfile.setPreference(entryPreferences.getKey().toString(),
816856
valuePreferences.toString());
@@ -819,9 +859,8 @@ protected void parseBrowserOptionsFirefox(String browserOptions, Capabilities de
819859
} else if (key.equals("extensions")) {
820860
// Extensions
821861
JSONArray extensions = (JSONArray) entry.getValue();
822-
Iterator<?> iteratorExtensions = extensions.iterator();
823-
while (iteratorExtensions.hasNext()) {
824-
File file = new File(iteratorExtensions.next().toString().replace('/', File.separatorChar));
862+
for (Object extension : extensions) {
863+
File file = new File(extension.toString().replace('/', File.separatorChar));
825864
firefoxProfile.addExtension(file);
826865
}
827866
} else {

src/main/java/com/github/markusbernhardt/seleniumlibrary/keywords/Cookie.java

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
11
package com.github.markusbernhardt.seleniumlibrary.keywords;
22

3-
import java.text.DateFormat;
43
import java.util.ArrayList;
54
import java.util.Date;
65

76
import org.robotframework.javalib.annotation.ArgumentNames;
87
import org.robotframework.javalib.annotation.Autowired;
98
import org.robotframework.javalib.annotation.RobotKeyword;
10-
import org.robotframework.javalib.annotation.RobotKeywordOverload;
119
import org.robotframework.javalib.annotation.RobotKeywords;
1210

1311
import com.github.markusbernhardt.seleniumlibrary.RunOnFailureKeywordsAdapter;

src/main/java/com/github/markusbernhardt/seleniumlibrary/keywords/Element.java

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
import org.robotframework.javalib.annotation.ArgumentNames;
1616
import org.robotframework.javalib.annotation.Autowired;
1717
import org.robotframework.javalib.annotation.RobotKeyword;
18-
import org.robotframework.javalib.annotation.RobotKeywordOverload;
1918
import org.robotframework.javalib.annotation.RobotKeywords;
2019

2120
import com.github.markusbernhardt.seleniumlibrary.RunOnFailureKeywordsAdapter;
@@ -881,7 +880,7 @@ public void xpathShouldMatchXTimes(String xpath, int expectedXpathCount, String.
881880
int actualXpathCount = elements.size();
882881

883882
if (actualXpathCount != expectedXpathCount) {
884-
if (message == null || message.equals("")) {
883+
if (message.isEmpty()) {
885884
message = String.format("Xpath %s should have matched %s times but matched %s times.", xpath,
886885
expectedXpathCount, actualXpathCount);
887886
}
@@ -892,6 +891,22 @@ public void xpathShouldMatchXTimes(String xpath, int expectedXpathCount, String.
892891
logLevel);
893892
}
894893

894+
@RobotKeyword("Click to element from list elements by locator ``xpath``.")
895+
@ArgumentNames({"xpath", "index=0", "message=NONE"})
896+
public void clickElementByIndex(String xpath, String... params) {
897+
String message = robot.getParamsValue(params, 0, "");
898+
int index = robot.getParamsValue(params, 1, 0);
899+
List<WebElement> elements = elementFind(xpath, false, false);
900+
if (elements.isEmpty()) {
901+
if (message.isEmpty()) {
902+
message = String.format("The Element was not found by locator '%s' with index '%d'", xpath, index);
903+
}
904+
throw new SeleniumLibraryNonFatalException(message);
905+
}
906+
WebElement element = elements.get(index);
907+
element.click();
908+
}
909+
895910
// ##############################
896911
// Internal Methods
897912
// ##############################

src/main/java/com/github/markusbernhardt/seleniumlibrary/keywords/Logging.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
import org.robotframework.javalib.annotation.ArgumentNames;
1313
import org.robotframework.javalib.annotation.Autowired;
1414
import org.robotframework.javalib.annotation.RobotKeyword;
15-
import org.robotframework.javalib.annotation.RobotKeywordOverload;
1615
import org.robotframework.javalib.annotation.RobotKeywords;
1716

1817
import com.github.markusbernhardt.seleniumlibrary.RunOnFailureKeywordsAdapter;

0 commit comments

Comments
 (0)