Run Selenium automation tests on LambdaTest cloud grid
Perform automation testing on 3000+ real desktop and mobile devices online.
package tk.gustavo;
import org.fluentlenium.adapter.junit.FluentTest;
import org.junit.BeforeClass;
import org.openqa.selenium.os.ExecutableFinder;
public abstract class AbstractChromeTest extends FluentTest {
private static final String PATH_TO_CHROME_DRIVER =
"C:\\Users\\Gustavo Maciel\\Documents\\Diversos\\Projects\\flask-selenium-test\\driver\\chromedriver.exe";
private static final String CHROME_DRIVER_PROPERTY = "webdriver.chrome.driver";
@BeforeClass
public static void setup() {
if (systemPropertyNotSet() && executableNotPresentInPath()) {
setSystemProperty();
}
}
private static boolean executableNotPresentInPath() {
return new ExecutableFinder().find("chromedriver") == null;
}
private static boolean systemPropertyNotSet() {
return System.getProperty(CHROME_DRIVER_PROPERTY) == null;
}
private static void setSystemProperty() {
System.setProperty(CHROME_DRIVER_PROPERTY, PATH_TO_CHROME_DRIVER);
}
}
package com.kms.katalon.core.webui.util;
import static org.openqa.selenium.Platform.MAC;
import static org.openqa.selenium.Platform.UNIX;
import static org.openqa.selenium.Platform.WINDOWS;
import java.io.File;
import java.io.IOException;
import org.apache.commons.lang.math.NumberUtils;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.os.ExecutableFinder;
import org.openqa.selenium.os.WindowsUtils;
import org.openqa.selenium.remote.DesiredCapabilities;
import com.google.common.collect.ImmutableList;
// This class duplicated codes from org.openqa.selenium.firefox.internal.Executable as it is internal.
// Should not be re-factored.
public class FirefoxExecutable {
private static final String VERSION_SEPARATOR_REGEX = "\\.";
private static final String MOZILLA_FIREFOX_VERSION_STRING_PREFIX = "Mozilla Firefox";
private static final File SYSTEM_BINARY = locateFirefoxBinaryFromSystemProperty();
private static final File PLATFORM_BINARY = locateFirefoxBinaryFromPlatform();
private FirefoxExecutable() {
}
public static int getFirefoxVersion(DesiredCapabilities desiredCapabilities) {
File defaultFirefoxBinary = FirefoxExecutable.getFirefoxBinaryFile(getFirefoxBinary(desiredCapabilities));
try {
String firefoxVersionString = ConsoleCommandExecutor.runConsoleCommandAndCollectFirstResult(
new String[] { defaultFirefoxBinary.getAbsolutePath(), "-v", "|", "more" });
if (firefoxVersionString == null
|| !firefoxVersionString.startsWith(MOZILLA_FIREFOX_VERSION_STRING_PREFIX)) {
return 0;
}
firefoxVersionString = firefoxVersionString.substring(MOZILLA_FIREFOX_VERSION_STRING_PREFIX.length())
.trim();
String firefoxVersionMajor = firefoxVersionString.split(VERSION_SEPARATOR_REGEX)[0];
Number firefoxVersion = NumberUtils.createNumber(firefoxVersionMajor);
return firefoxVersion.intValue();
} catch (IOException | InterruptedException | NumberFormatException e) {
// Exception happened, ignore
}
return 0;
}
private static String getFirefoxBinary(DesiredCapabilities desiredCapabilities) {
if (desiredCapabilities == null || desiredCapabilities.getCapability(FirefoxDriver.BINARY) == null) {
return null;
}
Object raw = desiredCapabilities.getCapability(FirefoxDriver.BINARY);
if (raw instanceof String) {
return (String) raw;
}
return null;
}
public static File getFirefoxBinaryFile(String userSpecifiedBinaryPath) throws WebDriverException {
if (userSpecifiedBinaryPath != null) {
File userSpecifiedBinaryFile = new File(userSpecifiedBinaryPath);
// It should exist and be a file.
if (userSpecifiedBinaryFile.exists() && userSpecifiedBinaryFile.isFile()) {
return userSpecifiedBinaryFile;
}
throw new WebDriverException("Specified firefox binary location does not exist or is not a real file: "
+ userSpecifiedBinaryPath);
}
if (SYSTEM_BINARY != null && SYSTEM_BINARY.exists()) {
return SYSTEM_BINARY;
}
if (PLATFORM_BINARY != null && PLATFORM_BINARY.exists()) {
return PLATFORM_BINARY;
}
throw new WebDriverException("Cannot find firefox binary in PATH. "
+ "Make sure firefox is installed. OS appears to be: " + Platform.getCurrent());
}
private static File locateFirefoxBinaryFromSystemProperty() {
String binaryName = System.getProperty(FirefoxDriver.SystemProperty.BROWSER_BINARY);
if (binaryName == null)
return null;
File binary = new File(binaryName);
if (binary.exists())
return binary;
Platform current = Platform.getCurrent();
if (current.is(WINDOWS)) {
if (!binaryName.endsWith(".exe"))
binaryName += ".exe";
} else if (current.is(MAC)) {
if (!binaryName.endsWith(".app"))
binaryName += ".app";
binaryName += "/Contents/MacOS/firefox-bin";
}
binary = new File(binaryName);
if (binary.exists())
return binary;
throw new WebDriverException(String.format("'%s' property set, but unable to locate the requested binary: %s",
FirefoxDriver.SystemProperty.BROWSER_BINARY, binaryName));
}
/**
* Locates the firefox binary by platform.
*/
@SuppressWarnings("deprecation")
private static File locateFirefoxBinaryFromPlatform() {
File binary = null;
Platform current = Platform.getCurrent();
if (current.is(WINDOWS)) {
binary = findExistingBinary(WindowsUtils.getPathsInProgramFiles("Mozilla Firefox\\firefox.exe"));
} else if (current.is(MAC)) {
binary = new File("/Applications/Firefox.app/Contents/MacOS/firefox-bin");
// fall back to homebrew install location if default is not found
if (!binary.exists()) {
binary = new File(System.getProperty("user.home") + binary.getAbsolutePath());
}
}
if (binary != null && binary.exists()) {
return binary;
}
ExecutableFinder binaryFinder = new ExecutableFinder();
if (current.is(UNIX)) {
String systemFirefox = binaryFinder.find("firefox-bin");
if (systemFirefox != null) {
return new File(systemFirefox);
}
}
String systemFirefox = binaryFinder.find("firefox");
if (systemFirefox != null) {
return new File(systemFirefox);
}
return null;
}
private static File findExistingBinary(final ImmutableList<String> paths) {
for (String path : paths) {
File file = new File(path);
if (file.exists()) {
return file;
}
}
return null;
}
}
package com.upgrade.ui.driver;
import com.google.common.base.Preconditions;
import com.upgrade.ui.helpers.AbstractUITest;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.os.ExecutableFinder;
import java.io.File;
import java.net.URL;
public abstract class DriverManager {
protected WebDriver driver;
private ThreadLocal<WebDriver> driverThreads;
protected abstract void createDriver(AbstractUITest ab);
protected DriverManager() {
driverThreads = new ThreadLocal<>();
}
public void quitDriver() {
if (driverThreads.get() != null) {
driverThreads.get().quit();
driverThreads.set(null);
}
}
public WebDriver getDriver(AbstractUITest ab) {
if (driverThreads.get() == null) {
createDriver(ab);
}
driverThreads.set(driver);
return driverThreads.get();
}
protected File getExecutable(String executableName) {
File file;
Preconditions.checkNotNull(executableName);
if (Platform.getCurrent().is(Platform.WINDOWS)) {
file = new File(DriverManager.class.getResource("/" + executableName + ".exe").getFile());
if (canExecute(file)) {
return file;
}
} else if(Platform.getCurrent().is(Platform.MAC)) {
URL res = getClass().getClassLoader().getResource("/macDrivers/chromeDriver.exe");
file = new File(DriverManager.class.getResource(("/macDrivers/" + executableName)).getFile());
return file;
}
ExecutableFinder executableFinder = new ExecutableFinder();
return new File(executableFinder.find(executableName +".exe"));
}
private static boolean canExecute(File file) {
return file.exists() && !file.isDirectory();
}
}
public static File checkAndGetFromPATHEnvVar(final String matchesExecutable) {
String[] pathParts = System.getenv("PATH").split(File.pathSeparator);
for (String pathPart : pathParts) {
File pathFile = new File(pathPart);
if (pathFile.isFile() && pathFile.getName().toLowerCase().contains(matchesExecutable)) {
return pathFile;
} else if (pathFile.isDirectory()) {
File[] matchedFiles = pathFile.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return FileUtil.getFileNameWithoutExtension(pathname).toLowerCase().equals(matchesExecutable);
}
});
if (matchedFiles != null) {
for (File matchedFile : matchedFiles) {
if (FileUtil.canRunCmd(new String[]{matchedFile.getAbsolutePath()})) {
return matchedFile;
}
}
}
}
}
return null;
}
public static String getFileNameWithoutExtension(File file) {
String fileName = file.getName();
int pos = fileName.lastIndexOf(".");
if (pos > 0) {
fileName = fileName.substring(0, pos);
}
return fileName;
}
public static boolean canRunCmd(String[] cmd) {
try {
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.redirectErrorStream(true);
Process process = pb.start();
try (BufferedReader inStreamReader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
while ((inStreamReader.readLine()) != null) {
}
}
process.waitFor();
} catch (Exception e) {
return false;
}
return true;
}
private static final String ENVIRONMENT_VARIABLES_TEXT = System.getenv("PATH");
private static boolean isCommandAvailable(String executableFileName)
{
String[] environmentVariables = ENVIRONMENT_VARIABLES_TEXT.split(File.pathSeparator);
for (String environmentVariable : environmentVariables)
{
try
{
Path environmentVariablePath = Paths.get(environmentVariable);
if (Files.exists(environmentVariablePath))
{
Path resolvedEnvironmentVariableFilePath = environmentVariablePath.resolve(executableFileName);
if (Files.isExecutable(resolvedEnvironmentVariableFilePath))
{
return true;
}
}
} catch (InvalidPathException exception)
{
exception.printStackTrace();
}
}
return false;
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.logging.Logger;
public class SimulationUtils
{
private final static Logger LOGGER = Logger.getLogger(SimulationUtils.class.getName());
public static Path lookForProgramInPath(String desiredProgram) {
ProcessBuilder pb = new ProcessBuilder(isWindows() ? "where" : "which", desiredProgram);
Path foundProgram = null;
try {
Process proc = pb.start();
int errCode = proc.waitFor();
if (errCode == 0) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()))) {
foundProgram = Paths.get(reader.readLine());
}
LOGGER.info(desiredProgram + " has been found at : " + foundProgram);
} else {
LOGGER.warning(desiredProgram + " not in PATH");
}
} catch (IOException | InterruptedException ex) {
LOGGER.warning("Something went wrong while searching for " + desiredProgram);
}
return foundProgram;
}
private static boolean isWindows() {
return System.getProperty("os.name").toLowerCase().contains("windows");
}
}
System.out.println(SimulationUtils.lookForProgramInPath("notepad"));
System.out.println(SimulationUtils.lookForProgramInPath("psql"));
SimulationUtils.lookForProgramInPath("gnuplot")
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("svn help");
int exitVal = proc.exitValue();
String exec = <executable name>;
boolean existsInPath = Stream.of(System.getenv("PATH").split(Pattern.quote(File.pathSeparator)))
.map(Paths::get)
.anyMatch(path -> Files.exists(path.resolve(exec)));
import java.io.File;
import java.nio.file.Paths;
import java.util.stream.Stream;
import static java.io.File.pathSeparator;
import static java.nio.file.Files.isExecutable;
import static java.lang.System.getenv;
import static java.util.regex.Pattern.quote;
public static boolean canExecute( final String exe ) {
final var paths = getenv( "PATH" ).split( quote( pathSeparator ) );
return Stream.of( paths ).map( Paths::get ).anyMatch(
path -> {
final var p = path.resolve( exe );
var found = false;
for( final var extension : EXTENSIONS ) {
if( isExecutable( Path.of( p.toString() + extension ) ) ) {
found = true;
break;
}
}
return found;
}
);
}
WebDriver driver = new FirefoxDriver();
/**
*
* @param exeName Name of the executable file to look for in PATH
* @param exeProperty Name of a system property that specifies the path to the executable file
* @param exeDocs The link to the driver documentation page
* @param exeDownload The link to the driver download page
*
* @return The driver executable as a {@link File} object
* @throws IllegalStateException If the executable not found or cannot be executed
*/
protected static File findExecutable(
String exeName,
String exeProperty,
String exeDocs,
String exeDownload) {
String defaultPath = new ExecutableFinder().find(exeName);
String exePath = System.getProperty(exeProperty, defaultPath);
checkState(exePath != null,
"The path to the driver executable must be set by the %s system property;"
+ " for more information, see %s. "
+ "The latest version can be downloaded from %s",
exeProperty, exeDocs, exeDownload);
File exe = new File(exePath);
checkExecutable(exe);
return exe;
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* <p>See {@link #checkState(boolean, String, Object...)} for details.
*/
public static void checkState(
boolean b,
@Nullable String errorMessageTemplate,
@Nullable Object p1,
@Nullable Object p2,
@Nullable Object p3) {
if (!b) {
throw new IllegalStateException(format(errorMessageTemplate, p1, p2, p3));
}
}
System.setProperty("webdriver.gecko.driver", "./libs/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
@Override
protected File findDefaultExecutable() {
return findExecutable(
"geckodriver", GECKO_DRIVER_EXE_PROPERTY,
"https://github.com/mozilla/geckodriver",
"https://github.com/mozilla/geckodriver/releases");
}
@Override
protected File findDefaultExecutable() {
return findExecutable("chromedriver", CHROME_DRIVER_EXE_PROPERTY,
"https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver",
"http://chromedriver.storage.googleapis.com/index.html");
}
System.setProperty("webdriver.gecko.driver","c:/your/path/to/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
...
<match target="font">
<edit mode="assign" name="antialias">
<bool>false</bool>
</edit>
</match>
public class MyPhantomDriverService {
public static PhantomJSDriverService createDefaultService(Capabilities desiredCapabilities, Map<String, String> env) {
Proxy proxy = null;
if (desiredCapabilities != null) {
proxy = Proxy.extractFrom(desiredCapabilities);
}
File phantomjsfile = findPhantomJS(desiredCapabilities, "https://github.com/ariya/phantomjs/wiki", "http://phantomjs.org/download.html");
File ghostDriverfile = findGhostDriver(desiredCapabilities, "https://github.com/detro/ghostdriver/blob/master/README.md", "https://github.com/detro/ghostdriver/downloads");
Builder builder = new Builder();
builder.usingPhantomJSExecutable(phantomjsfile)
.usingGhostDriver(ghostDriverfile)
.usingAnyFreePort()
.withProxy(proxy)
.withLogFile(new File("phantomjsdriver.log"))
.usingCommandLineArguments(findCLIArgumentsFromCaps(desiredCapabilities, "phantomjs.cli.args"))
.usingGhostDriverCommandLineArguments(findCLIArgumentsFromCaps(desiredCapabilities, "phantomjs.ghostdriver.cli.args"));
if(null != env)
builder.withEnvironment(env);
return builder.build();
}
public static File findPhantomJS(Capabilities desiredCapabilities, String docsLink, String downloadLink) {
String phantomjspath;
if (desiredCapabilities != null && desiredCapabilities.getCapability("phantomjs.binary.path") != null) {
phantomjspath = (String)desiredCapabilities.getCapability("phantomjs.binary.path");
} else {
phantomjspath = (new ExecutableFinder()).find("phantomjs");
phantomjspath = System.getProperty("phantomjs.binary.path", phantomjspath);
}
Preconditions.checkState(phantomjspath != null, "The path to the driver executable must be set by the %s capability/system property/PATH variable; for more information, see %s. The latest version can be downloaded from %s", "phantomjs.binary.path", docsLink, downloadLink);
File phantomjs = new File(phantomjspath);
checkExecutable(phantomjs);
return phantomjs;
}
protected static File findGhostDriver(Capabilities desiredCapabilities, String docsLink, String downloadLink) {
String ghostdriverpath;
if (desiredCapabilities != null && desiredCapabilities.getCapability("phantomjs.ghostdriver.path") != null) {
ghostdriverpath = (String)desiredCapabilities.getCapability("phantomjs.ghostdriver.path");
} else {
ghostdriverpath = System.getProperty("phantomjs.ghostdriver.path");
}
if (ghostdriverpath != null) {
File ghostdriver = new File(ghostdriverpath);
Preconditions.checkState(ghostdriver.exists(), "The GhostDriver does not exist: %s", ghostdriver.getAbsolutePath());
Preconditions.checkState(ghostdriver.isFile(), "The GhostDriver is a directory: %s", ghostdriver.getAbsolutePath());
Preconditions.checkState(ghostdriver.canRead(), "The GhostDriver is not a readable file: %s", ghostdriver.getAbsolutePath());
return ghostdriver;
} else {
return null;
}
}
protected static void checkExecutable(File exe) {
Preconditions.checkState(exe.exists(), "The driver executable does not exist: %s", exe.getAbsolutePath());
Preconditions.checkState(!exe.isDirectory(), "The driver executable is a directory: %s", exe.getAbsolutePath());
Preconditions.checkState(exe.canExecute(), "The driver is not executable: %s", exe.getAbsolutePath());
}
private static String[] findCLIArgumentsFromCaps(Capabilities desiredCapabilities, String capabilityName) {
if (desiredCapabilities != null) {
Object cap = desiredCapabilities.getCapability(capabilityName);
if (cap != null) {
if (cap instanceof String[]) {
return (String[])((String[])cap);
}
if (cap instanceof Collection) {
try {
Collection<String> capCollection = (Collection<String>)cap;
return (String[])capCollection.toArray(new String[capCollection.size()]);
} catch (Exception var4) {
System.err.println(String.format("Unable to set Capability '%s' as it was neither a String[] or a Collection<String>", capabilityName));
}
}
}
}
return new String[0];
}
}
//-- 1. Make a temp directory which will contain our fonts.conf
String tmp = System.getProperty("java.io.tmpdir");
if(tmp == null) {
tmp = "/tmp";
}
File dir = new File(tmp + File.separator + "/_phantomjs-config/fontconfig");
dir.mkdirs();
if(! dir.exists()) {
throw new IOException("Can't create fontconfig directory to override phantomjs font settings at " + dir);
}
File conf = new File(dir, "fonts.conf");
String text = "<match target=\"font\">\n"
+ "<edit mode=\"assign\" name=\"antialias\">\n"
+ "<bool>false</bool>\n"
+ "</edit>\n"
+ "</match>";
try(FileOutputStream fos = new FileOutputStream(conf)) {
fos.write(text.getBytes("UTF-8"));
}
//-- Set the XDG_CONFIG_HOME envvar; this is used by fontconfig as one of its locations
Map<String, String> env = new HashMap<>();
env.put("XDG_CONFIG_HOME", dir.getParentFile().getAbsolutePath());
PhantomJSDriverService service = MyPhantomDriverService.createDefaultService(capabilities, env);
wd = new PhantomJSDriver(service, capabilities);
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeDriverService.Builder;
...
Map<String, String> env = new HashMap<>();
env.put("XDG_CONFIG_HOME", dir.getParentFile().getAbsolutePath());
Builder builder = new Builder();
builder.usingAnyFreePort();
builder.withEnvironment(env);
ChromeDriverService service = builder.build();
return new ChromeDriver(service, dc);
Accelerate Your Automation Test Cycles With LambdaTest
Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.