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

Commit 6b85626

Browse files
authored
Merge pull request #81 from YauheniPo/feature/code_refactoring
Feature/code refactoring
2 parents 3e8bc73 + 9b83f26 commit 6b85626

17 files changed

+254
-350
lines changed

src/main/java/com/github/markusbernhardt/seleniumlibrary/SeleniumLibrary.java

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,6 @@ public SeleniumLibrary(String timeout, String implicitWait, String keywordToRunO
6363
if (!screenshotPath.isEmpty()) {
6464
screenshot.setScreenshotDirectory(screenshotPath);
6565
}
66-
6766
}
6867

6968
// ##############################
@@ -79,7 +78,6 @@ public SeleniumLibrary(String timeout, String implicitWait, String keywordToRunO
7978
@Autowired
8079
Screenshot screenshot;
8180

82-
8381
@Override
8482
public String getKeywordDocumentation(String keywordName) {
8583
if (keywordName.equals("__intro__")) {
@@ -185,6 +183,5 @@ public String getKeywordDocumentation(String keywordName) {
185183
}
186184
}
187185
return keywordName;
188-
189186
}
190187
}

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,12 +42,12 @@ public void deleteCookie(String name) {
4242

4343
@RobotKeyword("Returns all cookies of the current page.")
4444
public String getCookies() {
45-
StringBuffer ret = new StringBuffer();
45+
StringBuilder ret = new StringBuilder();
4646

47-
ArrayList<org.openqa.selenium.Cookie> cookies = new ArrayList<org.openqa.selenium.Cookie>(browserManagement
47+
ArrayList<org.openqa.selenium.Cookie> cookies = new ArrayList<>(browserManagement
4848
.getCurrentWebDriver().manage().getCookies());
4949
for (int i = 0; i < cookies.size(); i++) {
50-
ret.append(cookies.get(i).getName() + "=" + cookies.get(i).getValue());
50+
ret.append(cookies.get(i).getName()).append('=').append(cookies.get(i).getValue());
5151
if (i != cookies.size() - 1) {
5252
ret.append("; ");
5353
}

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

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -366,7 +366,6 @@ public void elementShouldBeClickable(String locator, String...params) {
366366
}
367367
}
368368

369-
370369
@RobotKeyword("Verify the element identified by ``locator`` is not clickable.\r\n" +
371370
"\r\n" +
372371
"Key attributes for arbitrary elements are id and name. See `Introduction` for details about locators.")
@@ -404,7 +403,6 @@ public void elementTextShouldBe(String locator, String text, String...params) {
404403
}
405404
}
406405

407-
408406
@RobotKeyword("Verify the text of the element identified by ``locator`` is not exactly ``text``.\r\n" +
409407
"\r\n" +
410408
"In contrast to `Element Should Not Contain`, this keyword does not try a substring match but an exact match on the element identified by locator.\r\n" +
@@ -448,7 +446,6 @@ public String getElementAttribute(String attributeLocator) {
448446
"Passing attribute name as part of the locator was removed in SeleniumLibrary 3.2. The explicit attribute argument should be used instead.")
449447
@ArgumentNames({ "locator", "attribute" })
450448
public String getElementAttribute(String locator, String attribute) {
451-
452449
List<WebElement> elements = elementFind(locator, true, false);
453450

454451
if (elements.size() == 0) {
@@ -494,7 +491,6 @@ public String getInnerElementId(String locator, String matchid, int index) {
494491
logging.info(String.format("Found element ID: '%s'.", eId));
495492

496493
return eId;
497-
498494
}
499495

500496
@RobotKeyword("Returns horizontal position of element identified by ``locator``.\r\n" +
@@ -778,7 +774,6 @@ public void pressKey(String locator, String key) {
778774
// Keywords - Links
779775
// ##############################
780776

781-
782777
@RobotKeyword("Click on the link identified by ``locator``.\r\n" +
783778
"\r\n" +
784779
"Key attributes for links are id, name, href and link text. See `Introduction` for details about locators.")
@@ -794,7 +789,7 @@ public void clickLink(String locator) {
794789
"\r\n" +
795790
"If a link has no id, an empty string will be in the list instead.")
796791
public ArrayList<String> getAllLinks() {
797-
ArrayList<String> ret = new ArrayList<String>();
792+
ArrayList<String> ret = new ArrayList<>();
798793

799794
List<WebElement> elements = elementFind("tag:a", false, false, "a");
800795
for (WebElement element : elements) {
@@ -965,7 +960,7 @@ protected List<WebElement> elementFind(String locator, boolean firstOnly, boolea
965960

966961
if (firstOnly) {
967962
if (elements.size() > 1) {
968-
List<WebElement> tmp = new ArrayList<WebElement>();
963+
List<WebElement> tmp = new ArrayList<>();
969964
tmp.add(elements.get(0));
970965
elements = tmp;
971966
}
@@ -1079,9 +1074,8 @@ protected boolean pageContains(String text) {
10791074
}
10801075

10811076
List<WebElement> elements = elementFind("xpath://frame|//iframe", false, false);
1082-
Iterator<WebElement> it = elements.iterator();
1083-
while (it.hasNext()) {
1084-
current.switchTo().frame(it.next());
1077+
for (WebElement element : elements) {
1078+
current.switchTo().frame(element);
10851079
boolean found = isTextPresent(text);
10861080
current.switchTo().defaultContent();
10871081
if (found) {

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

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ public String confirmAction() {
137137
@ArgumentNames({ "*code" })
138138
public Object executeJavascript(String... code) {
139139
String js = getJavascriptToExecute(Python.join("", Arrays.asList(code)));
140-
String.format("Executing JavaScript:\n%s", js);
140+
logging.html(String.format("Executing JavaScript:\n%s", js));
141141
return ((JavascriptExecutor) browserManagement.getCurrentWebDriver()).executeScript(js);
142142
}
143143

@@ -155,7 +155,7 @@ public Object executeJavascript(String... code) {
155155
@ArgumentNames({ "*code" })
156156
public Object executeAsyncJavascript(String... code) {
157157
String js = getJavascriptToExecute(Python.join("", Arrays.asList(code)));
158-
String.format("Executing JavaScript:\n%s", js);
158+
logging.html(String.format("Executing JavaScript:\n%s", js));
159159
return ((JavascriptExecutor) browserManagement.getCurrentWebDriver()).executeAsyncScript(js);
160160
}
161161

@@ -165,8 +165,7 @@ public Object executeAsyncJavascript(String... code) {
165165
public String getAlertMessage() {
166166
try {
167167
Alert alert = browserManagement.getCurrentWebDriver().switchTo().alert();
168-
String text = alert.getText().replace("\n", "");
169-
return text;
168+
return alert.getText().replace("\n", "");
170169
} catch (WebDriverException wde) {
171170
throw new SeleniumLibraryNonFatalException("There were no alerts");
172171
}
@@ -177,14 +176,11 @@ public String getAlertMessage() {
177176
// ##############################
178177

179178
protected static String readFile(String path) throws IOException {
180-
FileInputStream stream = new FileInputStream(new File(path));
181-
try {
179+
try (FileInputStream stream = new FileInputStream(new File(path))) {
182180
FileChannel fc = stream.getChannel();
183181
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
184182
/* Instead of using default, pass in a decoder. */
185183
return Charset.defaultCharset().decode(bb).toString();
186-
} finally {
187-
stream.close();
188184
}
189185
}
190186

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

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ public class Logging extends RunOnFailureKeywordsAdapter {
2424
protected static String logDir = null;
2525

2626
static {
27-
VALID_LOG_LEVELS = new HashMap<String, String[]>();
27+
VALID_LOG_LEVELS = new HashMap<>();
2828
VALID_LOG_LEVELS.put("debug", new String[] { "debug", "" });
2929
VALID_LOG_LEVELS.put("html", new String[] { "info", ", True, False" });
3030
VALID_LOG_LEVELS.put("info", new String[] { "info", "" });
@@ -60,7 +60,6 @@ public List<String> logWindowIdentifiers(String...params) {
6060
return windowIdentifiers;
6161
}
6262

63-
6463
@RobotKeyword("Logs and returns the names of all windows known to the current browser instance.\r\n" +
6564
"\r\n" +
6665
"See `Introduction` for details about the ``logLevel``.")
@@ -131,7 +130,6 @@ public String logSystemInfo(String...params) {
131130
return actual;
132131
}
133132

134-
135133
@RobotKeyword("Returns the actually supported capabilities of the remote browser instance.\r\n" +
136134
"\r\n" +
137135
"Not all server implementations will support every WebDriver feature. Therefore, the client and server should use JSON objects with the properties listed below when describing which features a user requests that a session support. *If a session cannot support a capability that is requested in the desired capabilities, no error is thrown*; a read-only capabilities object is returned that indicates the capabilities the session actually supports. For more information see: [https://github.com/SeleniumHQ/selenium/wiki/DesiredCapabilities|DesiredCapabilities]\r\n" +
@@ -239,7 +237,6 @@ protected void log0(String msg, String methodName, String methodArguments) {
239237
}
240238

241239
protected File getLogDir() {
242-
243240
if (logDir == null
244241
&& !loggingPythonInterpreter.get().eval("EXECUTION_CONTEXTS.current").toString().equals("None")) {
245242
PyString logDirName = (PyString) loggingPythonInterpreter.get()
@@ -258,14 +255,10 @@ public static void setLogDir(String logDirectory) {
258255
logDir = logDirectory;
259256
}
260257

261-
protected static ThreadLocal<PythonInterpreter> loggingPythonInterpreter = new ThreadLocal<PythonInterpreter>() {
262-
263-
@Override
264-
protected PythonInterpreter initialValue() {
265-
PythonInterpreter pythonInterpreter = new PythonInterpreter();
266-
pythonInterpreter.exec(
267-
"from robot.libraries.BuiltIn import BuiltIn; from robot.running.context import EXECUTION_CONTEXTS; from robot.api import logger;");
268-
return pythonInterpreter;
269-
}
270-
};
258+
protected static ThreadLocal<PythonInterpreter> loggingPythonInterpreter = ThreadLocal.withInitial(() -> {
259+
PythonInterpreter pythonInterpreter = new PythonInterpreter();
260+
pythonInterpreter.exec(
261+
"from robot.libraries.BuiltIn import BuiltIn; from robot.running.context import EXECUTION_CONTEXTS; from robot.api import logger;");
262+
return pythonInterpreter;
263+
});
271264
}

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

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

3-
import java.util.HashMap;
4-
import java.util.List;
5-
import java.util.Map;
6-
3+
import com.google.gson.Gson;
74
import org.python.util.PythonInterpreter;
85
import org.robotframework.javalib.annotation.RobotKeywords;
96

10-
import com.google.gson.Gson;
7+
import java.util.List;
8+
import java.util.Map;
119

1210
@RobotKeywords
1311
public class Robot {
@@ -38,20 +36,20 @@ public <T> T getParamsValue(String[] params, int index, T defaultValue) {
3836
}
3937

4038
@SuppressWarnings({ "unchecked", "resource" })
41-
public Map<String, Object> parseRobotDictionary(String dictionary) {
42-
logging.debug("Dictionary going to be parsed to Map: " + dictionary);
43-
Map<String, Object> json = new HashMap<String, Object>();
44-
try {
45-
PythonInterpreter py = new PythonInterpreter();
46-
py.exec("import json");
47-
json = new Gson().fromJson(py.eval("json.dumps(" + dictionary + ")").toString(), Map.class);
48-
} catch (RuntimeException e) {
49-
logging.error(String.format("Parsing of dictionary %s failed.", dictionary));
50-
throw e;
51-
}
52-
53-
return json;
54-
}
39+
public Map<String, Object> parseRobotDictionary(String dictionary) {
40+
logging.debug("Dictionary going to be parsed to Map: " + dictionary);
41+
Map<String, Object> json;
42+
try {
43+
PythonInterpreter py = new PythonInterpreter();
44+
py.exec("import json");
45+
json = new Gson().fromJson(py.eval("json.dumps(" + dictionary + ")").toString(), Map.class);
46+
} catch (RuntimeException e) {
47+
logging.error(String.format("Parsing of dictionary %s failed.", dictionary));
48+
throw e;
49+
}
50+
51+
return json;
52+
}
5553

5654
@SuppressWarnings("unchecked")
5755
public List<String> parseRobotList(String list) {

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

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -61,15 +61,11 @@ public String registerKeywordToRunOnFailure(String keyword) {
6161
// Internal Methods
6262
// ##############################
6363

64-
protected static ThreadLocal<PythonInterpreter> runOnFailurePythonInterpreter = new ThreadLocal<PythonInterpreter>() {
65-
66-
@Override
67-
protected PythonInterpreter initialValue() {
68-
PythonInterpreter pythonInterpreter = new PythonInterpreter();
69-
pythonInterpreter.exec("from robot.libraries.BuiltIn import BuiltIn; from robot.running.context import EXECUTION_CONTEXTS; BIN = BuiltIn();");
70-
return pythonInterpreter;
71-
}
72-
};
64+
protected static ThreadLocal<PythonInterpreter> runOnFailurePythonInterpreter = ThreadLocal.withInitial(() -> {
65+
PythonInterpreter pythonInterpreter = new PythonInterpreter();
66+
pythonInterpreter.exec("from robot.libraries.BuiltIn import BuiltIn; from robot.running.context import EXECUTION_CONTEXTS; BIN = BuiltIn();");
67+
return pythonInterpreter;
68+
});
7369

7470
public void runOnFailure() {
7571
if (runOnFailureKeyword == null) {

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

Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
11
package com.github.markusbernhardt.seleniumlibrary.keywords;
22

3-
import java.io.File;
4-
import java.io.FileOutputStream;
5-
import java.io.IOException;
6-
3+
import com.github.markusbernhardt.seleniumlibrary.RunOnFailureKeywordsAdapter;
4+
import com.github.markusbernhardt.seleniumlibrary.utils.Robotframework;
75
import org.apache.commons.lang3.exception.ExceptionUtils;
86
import org.openqa.selenium.OutputType;
97
import org.openqa.selenium.TakesScreenshot;
@@ -13,8 +11,9 @@
1311
import org.robotframework.javalib.annotation.RobotKeyword;
1412
import org.robotframework.javalib.annotation.RobotKeywords;
1513

16-
import com.github.markusbernhardt.seleniumlibrary.RunOnFailureKeywordsAdapter;
17-
import com.github.markusbernhardt.seleniumlibrary.utils.Robotframework;
14+
import java.io.File;
15+
import java.io.FileOutputStream;
16+
import java.io.IOException;
1817

1918
@RobotKeywords
2019
public class Screenshot extends RunOnFailureKeywordsAdapter {
@@ -50,15 +49,15 @@ public String setScreenshotDirectory(String path) {
5049
screenshotDir = new File(path);
5150
return oldDir;
5251
}
53-
54-
@RobotKeyword("Take a screenshot of the current page and embed it into the log.\r\n" +
55-
"\r\n" +
56-
"The ``filename`` argument specifies the name of the file to write the screenshot into. If no filename is given, the screenshot is saved into file selenium-screenshot-{index}.png under the directory where the Robot Framework log file is written into. The filename is also considered relative to the same directory, if it is not given in absolute format.\r\n" +
57-
"\r\n" +
58-
"if ``filename`` contains marker {index}, it will be automatically replaced with unique running index preventing files to be overwritten. Indices start from 1.\r\n" +
59-
"\r\n" +
60-
"A CSS can be used to modify how the screenshot is taken. By default the background color is changed to avoid possible problems with background leaking when the page layout is somehow broken.")
61-
@ArgumentNames({ "filename=selenium-screenshot-{index}.png" })
52+
53+
@RobotKeyword("Take a screenshot of the current page and embed it into the log.\r\n" +
54+
"\r\n" +
55+
"The ``filename`` argument specifies the name of the file to write the screenshot into. If no filename is given, the screenshot is saved into file selenium-screenshot-{index}.png under the directory where the Robot Framework log file is written into. The filename is also considered relative to the same directory, if it is not given in absolute format.\r\n" +
56+
"\r\n" +
57+
"if ``filename`` contains marker {index}, it will be automatically replaced with unique running index preventing files to be overwritten. Indices start from 1.\r\n" +
58+
"\r\n" +
59+
"A CSS can be used to modify how the screenshot is taken. By default the background color is changed to avoid possible problems with background leaking when the page layout is somehow broken.")
60+
@ArgumentNames({"filename=selenium-screenshot-{index}.png"})
6261
public void capturePageScreenshot(String...params) {
6362
String filename = robot.getParamsValue(params, 0, null);
6463
File logdir = screenshotDir != null ? screenshotDir : logging.getLogDir();
@@ -68,7 +67,6 @@ public void capturePageScreenshot(String...params) {
6867

6968
if (currentWebDriver.getClass().toString().contains("HtmlUnit")) {
7069
logging.warn("HTMLunit is not supporting screenshots.");
71-
return;
7270
} else {
7371
try {
7472
TakesScreenshot takesScreenshot = ((TakesScreenshot) currentWebDriver);
@@ -79,8 +77,7 @@ public void capturePageScreenshot(String...params) {
7977
"</td></tr><tr><td colspan=\"3\"><a href=\"%s\"><img src=\"%s\" width=\"800px\"></a>", link, link));
8078
} catch (NullPointerException e) {
8179
logging.warn("Can't take screenshot. No open browser found");
82-
return;
83-
}
80+
}
8481
}
8582
}
8683

0 commit comments

Comments
 (0)