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

Feature/code refactoring #81

Merged
merged 4 commits into from
Jul 29, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ public SeleniumLibrary(String timeout, String implicitWait, String keywordToRunO
if (!screenshotPath.isEmpty()) {
screenshot.setScreenshotDirectory(screenshotPath);
}

}

// ##############################
Expand All @@ -79,7 +78,6 @@ public SeleniumLibrary(String timeout, String implicitWait, String keywordToRunO
@Autowired
Screenshot screenshot;


@Override
public String getKeywordDocumentation(String keywordName) {
if (keywordName.equals("__intro__")) {
Expand Down Expand Up @@ -185,6 +183,5 @@ public String getKeywordDocumentation(String keywordName) {
}
}
return keywordName;

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,12 @@ public void deleteCookie(String name) {

@RobotKeyword("Returns all cookies of the current page.")
public String getCookies() {
StringBuffer ret = new StringBuffer();
StringBuilder ret = new StringBuilder();

ArrayList<org.openqa.selenium.Cookie> cookies = new ArrayList<org.openqa.selenium.Cookie>(browserManagement
ArrayList<org.openqa.selenium.Cookie> cookies = new ArrayList<>(browserManagement
.getCurrentWebDriver().manage().getCookies());
for (int i = 0; i < cookies.size(); i++) {
ret.append(cookies.get(i).getName() + "=" + cookies.get(i).getValue());
ret.append(cookies.get(i).getName()).append('=').append(cookies.get(i).getValue());
if (i != cookies.size() - 1) {
ret.append("; ");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -366,7 +366,6 @@ public void elementShouldBeClickable(String locator, String...params) {
}
}


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


@RobotKeyword("Verify the text of the element identified by ``locator`` is not exactly ``text``.\r\n" +
"\r\n" +
"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" +
Expand Down Expand Up @@ -448,7 +446,6 @@ public String getElementAttribute(String attributeLocator) {
"Passing attribute name as part of the locator was removed in SeleniumLibrary 3.2. The explicit attribute argument should be used instead.")
@ArgumentNames({ "locator", "attribute" })
public String getElementAttribute(String locator, String attribute) {

List<WebElement> elements = elementFind(locator, true, false);

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

return eId;

}

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


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

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

if (firstOnly) {
if (elements.size() > 1) {
List<WebElement> tmp = new ArrayList<WebElement>();
List<WebElement> tmp = new ArrayList<>();
tmp.add(elements.get(0));
elements = tmp;
}
Expand Down Expand Up @@ -1079,9 +1074,8 @@ protected boolean pageContains(String text) {
}

List<WebElement> elements = elementFind("xpath://frame|//iframe", false, false);
Iterator<WebElement> it = elements.iterator();
while (it.hasNext()) {
current.switchTo().frame(it.next());
for (WebElement element : elements) {
current.switchTo().frame(element);
boolean found = isTextPresent(text);
current.switchTo().defaultContent();
if (found) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ public String confirmAction() {
@ArgumentNames({ "*code" })
public Object executeJavascript(String... code) {
String js = getJavascriptToExecute(Python.join("", Arrays.asList(code)));
String.format("Executing JavaScript:\n%s", js);
logging.html(String.format("Executing JavaScript:\n%s", js));
return ((JavascriptExecutor) browserManagement.getCurrentWebDriver()).executeScript(js);
}

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

Expand All @@ -165,8 +165,7 @@ public Object executeAsyncJavascript(String... code) {
public String getAlertMessage() {
try {
Alert alert = browserManagement.getCurrentWebDriver().switchTo().alert();
String text = alert.getText().replace("\n", "");
return text;
return alert.getText().replace("\n", "");

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we use .replace('\n', '') instead?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it is not working. only alert.getText().replace("\n", "");

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I see it now. Thanks for correcting me!

} catch (WebDriverException wde) {
throw new SeleniumLibraryNonFatalException("There were no alerts");
}
Expand All @@ -177,14 +176,11 @@ public String getAlertMessage() {
// ##############################

protected static String readFile(String path) throws IOException {
FileInputStream stream = new FileInputStream(new File(path));
try {
try (FileInputStream stream = new FileInputStream(new File(path))) {
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
/* Instead of using default, pass in a decoder. */
return Charset.defaultCharset().decode(bb).toString();
} finally {
stream.close();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public class Logging extends RunOnFailureKeywordsAdapter {
protected static String logDir = null;

static {
VALID_LOG_LEVELS = new HashMap<String, String[]>();
VALID_LOG_LEVELS = new HashMap<>();
VALID_LOG_LEVELS.put("debug", new String[] { "debug", "" });
VALID_LOG_LEVELS.put("html", new String[] { "info", ", True, False" });
VALID_LOG_LEVELS.put("info", new String[] { "info", "" });
Expand Down Expand Up @@ -60,7 +60,6 @@ public List<String> logWindowIdentifiers(String...params) {
return windowIdentifiers;
}


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


@RobotKeyword("Returns the actually supported capabilities of the remote browser instance.\r\n" +
"\r\n" +
"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" +
Expand Down Expand Up @@ -239,7 +237,6 @@ protected void log0(String msg, String methodName, String methodArguments) {
}

protected File getLogDir() {

if (logDir == null
&& !loggingPythonInterpreter.get().eval("EXECUTION_CONTEXTS.current").toString().equals("None")) {
PyString logDirName = (PyString) loggingPythonInterpreter.get()
Expand All @@ -258,14 +255,10 @@ public static void setLogDir(String logDirectory) {
logDir = logDirectory;
}

protected static ThreadLocal<PythonInterpreter> loggingPythonInterpreter = new ThreadLocal<PythonInterpreter>() {

@Override
protected PythonInterpreter initialValue() {
PythonInterpreter pythonInterpreter = new PythonInterpreter();
pythonInterpreter.exec(
"from robot.libraries.BuiltIn import BuiltIn; from robot.running.context import EXECUTION_CONTEXTS; from robot.api import logger;");
return pythonInterpreter;
}
};
protected static ThreadLocal<PythonInterpreter> loggingPythonInterpreter = ThreadLocal.withInitial(() -> {
PythonInterpreter pythonInterpreter = new PythonInterpreter();
pythonInterpreter.exec(
"from robot.libraries.BuiltIn import BuiltIn; from robot.running.context import EXECUTION_CONTEXTS; from robot.api import logger;");
return pythonInterpreter;
});
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
package com.github.markusbernhardt.seleniumlibrary.keywords;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import org.python.util.PythonInterpreter;
import org.robotframework.javalib.annotation.RobotKeywords;

import com.google.gson.Gson;
import java.util.List;
import java.util.Map;

@RobotKeywords
public class Robot {
Expand Down Expand Up @@ -38,20 +36,20 @@ public <T> T getParamsValue(String[] params, int index, T defaultValue) {
}

@SuppressWarnings({ "unchecked", "resource" })
public Map<String, Object> parseRobotDictionary(String dictionary) {
logging.debug("Dictionary going to be parsed to Map: " + dictionary);
Map<String, Object> json = new HashMap<String, Object>();
try {
PythonInterpreter py = new PythonInterpreter();
py.exec("import json");
json = new Gson().fromJson(py.eval("json.dumps(" + dictionary + ")").toString(), Map.class);
} catch (RuntimeException e) {
logging.error(String.format("Parsing of dictionary %s failed.", dictionary));
throw e;
}
return json;
}
public Map<String, Object> parseRobotDictionary(String dictionary) {
logging.debug("Dictionary going to be parsed to Map: " + dictionary);
Map<String, Object> json;
try {
PythonInterpreter py = new PythonInterpreter();
py.exec("import json");
json = new Gson().fromJson(py.eval("json.dumps(" + dictionary + ")").toString(), Map.class);
} catch (RuntimeException e) {
logging.error(String.format("Parsing of dictionary %s failed.", dictionary));
throw e;
}

return json;
}

@SuppressWarnings("unchecked")
public List<String> parseRobotList(String list) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,15 +61,11 @@ public String registerKeywordToRunOnFailure(String keyword) {
// Internal Methods
// ##############################

protected static ThreadLocal<PythonInterpreter> runOnFailurePythonInterpreter = new ThreadLocal<PythonInterpreter>() {

@Override
protected PythonInterpreter initialValue() {
PythonInterpreter pythonInterpreter = new PythonInterpreter();
pythonInterpreter.exec("from robot.libraries.BuiltIn import BuiltIn; from robot.running.context import EXECUTION_CONTEXTS; BIN = BuiltIn();");
return pythonInterpreter;
}
};
protected static ThreadLocal<PythonInterpreter> runOnFailurePythonInterpreter = ThreadLocal.withInitial(() -> {
PythonInterpreter pythonInterpreter = new PythonInterpreter();
pythonInterpreter.exec("from robot.libraries.BuiltIn import BuiltIn; from robot.running.context import EXECUTION_CONTEXTS; BIN = BuiltIn();");
return pythonInterpreter;
});

public void runOnFailure() {
if (runOnFailureKeyword == null) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
package com.github.markusbernhardt.seleniumlibrary.keywords;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import com.github.markusbernhardt.seleniumlibrary.RunOnFailureKeywordsAdapter;
import com.github.markusbernhardt.seleniumlibrary.utils.Robotframework;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
Expand All @@ -13,8 +11,9 @@
import org.robotframework.javalib.annotation.RobotKeyword;
import org.robotframework.javalib.annotation.RobotKeywords;

import com.github.markusbernhardt.seleniumlibrary.RunOnFailureKeywordsAdapter;
import com.github.markusbernhardt.seleniumlibrary.utils.Robotframework;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

@RobotKeywords
public class Screenshot extends RunOnFailureKeywordsAdapter {
Expand Down Expand Up @@ -50,15 +49,15 @@ public String setScreenshotDirectory(String path) {
screenshotDir = new File(path);
return oldDir;
}
@RobotKeyword("Take a screenshot of the current page and embed it into the log.\r\n" +
"\r\n" +
"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" +
"\r\n" +
"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" +
"\r\n" +
"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.")
@ArgumentNames({ "filename=selenium-screenshot-{index}.png" })

@RobotKeyword("Take a screenshot of the current page and embed it into the log.\r\n" +
"\r\n" +
"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" +
"\r\n" +
"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" +
"\r\n" +
"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.")
@ArgumentNames({"filename=selenium-screenshot-{index}.png"})
public void capturePageScreenshot(String...params) {
String filename = robot.getParamsValue(params, 0, null);
File logdir = screenshotDir != null ? screenshotDir : logging.getLogDir();
Expand All @@ -68,7 +67,6 @@ public void capturePageScreenshot(String...params) {

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

Expand Down
Loading