selenium grid connction with autoit not working? - selenium

selenium grid connection with auto it not working ?
#daluudaluu/PartialSeleniumGridIntegrationWithAutoItExample.java
Last active a year ago
Embed
Download ZIP
Code Revisions 2 Forks 1
Partial Selenium Grid integration support with tools like AutoIt, Sikuli, etc.
Raw
PartialSeleniumGridIntegrationWithAutoItExample.java
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.remote.*;
import java.net.URL;
public class DemoTest {
public WebDriver driver;
public DesiredCapabilities capabilities;
#Before
public void setUp() throws Exception {
capabilities = DesiredCapabilities.firefox();
driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub" ), capabilities);
}
#After
public void tearDown() throws Exception {
driver.quit();
}
#Test
public void test() throws Exception {
// Use RemoteWebDriver, grab actual node host info
driver.get("http://www.google.com");
String sessionId = ((RemoteWebDriver) driver).getSessionId().toString();
//grid info extractor from: https://gist.github.com/krmahadevan/1766772
String nodeHost = GridInfoExtracter.getHostNameAndPort("localhost", 4444, sessionId)[0];
System.out.println("Extracted hostname: "+nodeHost);
// Now use node host info to handle running AutoIt on that specific node, assuming all needed files deployed to all nodes
// Case 1 - PSExec.exe from Windows host (that is executing this Selenium code) to Selenium node that is Windows host
//String psexecCmd = "C:\\LocalMachinePathTo\\psexec.exe \\\\%s -u %s -p %s -i C:\\GridNodeMachinePathTo\\autoitCompiledScript.exe";
//Process p = Runtime.getRuntime().exec(String.format(psexecCmd,nodeHost,"jdoe","hisPassword"));
//p.waitFor();
// Case 2 - winexe from *nix host (that is executing this Selenium code) to Selenium node that is Windows host
// Example reference: http://secpod.org/blog/?p=661
//String winexeCmd = "/LocalMachinePathTo/winexe -U domainName/jdoe%hisPassword //"+nodeHost+" C:\\GridNodeMachinePathTo\\autoitCompiledScript.exe";
//Process p = Runtime.getRuntime().exec(winexeCmd);
//p.waitFor();
// Case 3 - have SSH installed on Windows-based Selenium nodes, now just connect to node host via SSH to run a command, i.e. execute AutoIt script binary
// no sample code given for Java, but maybe this gives you ideas on Java SSH connection:
// http://stackoverflow.com/questions/995944/ssh-library-for-java
// Case 4 - if you have implemented a custom web service (XML-RPC/SOAP/REST) for AutoIt that listens for requests/commands
// just connect to it via (Java) HTTP library to "http://"+nodeHost+"/someWebServicePath/someCommand" (via GET or POST)
// details not covered, this is just an example. Most people won't be taking this route due to customization & complexity in
// building the web service first
// Case 5 - using AutoItDriverServer that is also running on Selenium nodes
//DesiredCapabilities autoitCapabilities = new DesiredCapabilities();
//autoitCapabilities.setCapability("browserName", "AutoIt");
//WebDriver autoitDriver = new RemoteWebDriver(new URL("http://"+nodeHost+":4723/wd/hub"), autoitCapabilities);
//autoitDriver.findElement(By.id("133")).click();
//and whatever other AutoItX commands to call that you normally have in the AutoIt script that you compile into binary
//for more ideas on AutoIt commands issued as WebDriver commands with respect to Selenium integration, see:
//https://github.com/daluu/AutoItDriverServer/blob/master/sample-code/SeleniumIntegrationWithAutoItDriver.py
//or if you are old school, and want to do that same approach even with AutoItDriverServer,
// assuming you have first set AutoItScriptExecuteScriptAsCompiledBinary to True in autoit_options.cfg file before starting AutoItDriverServer:
//((JavascriptExecutor) autoitDriver).executeScript("C:\\GridNodeMachinePathTo\\autoitCompiledScript.exe");
// Case for Sikuli integration, using https://github.com/enix12enix/sikuli-remote-control
//RemoteScreen rs = new RemoteScreen(nodeHost);
//rs.setMinSimilarity(0.9);
//rs.click("D://test.png");
}
}

Related

Selenium JUnit tests not running org.openqa.selenium.NoSuchSessionException: Session ID is null. Using WebDriver after calling quit()?

I have created a java/selenium/cucumber automation framework with 4 feature files each testing different functional area's.
I can run each of these within Eclipse as feature files and they all run fine.
However I am trying to figure out how I can run them all as a JUnit test so that I can generate the extent reports.
I run the mainRunner class as a Junit test like ..
The first feature runs fine but then the next three do not. A chrome browser is opened for each of these but
the site is not navigated to. The error
'org.openqa.selenium.NoSuchSessionException: Session ID is null. Using WebDriver after calling quit()?'
is shown in the console logs.
So is this issue to do with how I have set my feature files up to use the startBrowser, initBrowser and closeBrowser methods. Which are
defined in a seperate class 'BrowserInitTearDownStepDefinitions'?
All my feature files look like ..
Feature: Update a Computer in Database
-- left out details
#StartBrowser
Scenario: Start browser session
When I initialize driver
Then open browser
#MyTest4
Scenario Outline: Update a computer
-- left our details
Examples:
-- left out details
#CloseBrowser
Scenario: Close the browser
Then close browser
I have had a look at the other posts related to this message that reference the same error, but can't see a clear cut solution.
As the error would indicate I seem to be quitting the driver but then not reinitialising it for the next test. Although Im not sure why this
would be the case given that each feature file has the #StartBrowser and #CloseBrowser tags which should execute these methods. Below is my BrowserInitTearDownStepDefinitions class.
public class BrowserInitTearDownStepDefinitions {
//Initialises Chrome browser
#When("^I initialize driver$")
public void initializeDriver() {
System.out.println("initializeDriver runs");
System.setProperty("webdriver.chrome.driver","C:\\xxxx\\CucumberAutomationFramework\\src\\test\\java\\cucumberAutomationFramework\\resources\\chromedriver.exe");
WebDriverUtils.setDriver(new ChromeDriver());
}
//Opens Chrome browser and clicks in search input box
#Then("^open browser$")
public void openBrowser() {
System.out.println("Open Browser runs");
WebDriver driver = WebDriverUtils.getDriver();
driver.manage().window().maximize();
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
driver.manage().timeouts().setScriptTimeout(60, TimeUnit.SECONDS);
driver.get("https://computer-database.gatling.io/computers");
}
//Closes browser after all scenarios run and deletes cookies
#Then("^close browser$")
public void closeBrowser() {
System.out.println("Close Browser runs");
WebDriver driver = WebDriverUtils.getDriver();
driver.manage().deleteAllCookies();
driver.quit();
driver =null;
}
}
I create a new instance of the webdriver within my stepDefs file with ..
WebDriver driver = WebDriverUtils.getDriver()
The webdriver utils class code is ..
package cucumberAutomationFramework.utilityClasses;
import org.openqa.selenium.WebDriver;
public class WebDriverUtils {
private static WebDriver driver;
public static void setDriver(WebDriver webDdriver) {
if (driver == null) {
driver = webDdriver;
}
}
public static WebDriver getDriver() {
if (driver == null) {
throw new AssertionError("Driver is null. Initialize driver before calling this method.");
}
return driver;
}
}
Any advice would be much appreciated. Thanks.

Kill GeckoDriver by PID Process [Java]

My question is very similar to this question. I launch many instances of WebDriver and some of them don't respond to driver.quit(). As described in this response I am able to kill browser instance by retrieving PID directly from capabilities object via the following code:
Code Block:
import java.io.IOException;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
public class Kill_Firefox_PID {
public static void main(String[] args) throws IOException {
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
Capabilities cap = ((RemoteWebDriver) driver).getCapabilities();
System.out.println("moz:processID value is : "+cap.getCapability("moz:processID"));
Runtime.getRuntime().exec("taskkill /PID "+cap.getCapability("moz:processID"));
}
}
Console Output:
moz:processID value is : 8492
While this works excellently to kill browser itself I still see instances of Geckodriver when I open task manager. As stated in the other thread I am unable to indiscriminately kill all Geckdriver instances via taskkill /f /im geckodriver.exe as there are some instances that are needed.
In short, I want to be able to retrieve PID of Geckodriver via capabilities and destroy those instances of Geckodriver (via PID) in a similar way that we are able to retrieve PID of Firefox WebDriver as outlined in response to this question.
Is this possible?
Thanks!
A new set of GeckoDriver and Firefox Browser are initiated when you invoke:
WebDriver driver = new FirefoxDriver();
You can find a detailed discussion in Is this correct - FirefoxDriver driver = new FirefoxDriver();?
The life span of GeckoDriver / Firefox Browser ceases to exist when you invoke:
driver.quit()
You can find a detailed discussion in PhantomJS web driver stays in memory
Solution
So a generic solution would be, instead of keeping the keeping/preserving the stale instances of geckodriver invoke close() or quit() as per the flow of your test execution which will relieve you from indiscriminately killing all the GeckoDriver instances.
However at the end of your Test Execution if you want to kill all the GeckoDriver instances, you can use the following solution:
public class Killing_GeckoDriver_PID {
public static void main(String[] args) throws IOException {
String line;
String pidInfo ="";
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
Process p =Runtime.getRuntime().exec(System.getenv("windir") +"\\system32\\"+"tasklist.exe");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
pidInfo+=line;
}
input.close();
if(pidInfo.contains("geckodriver.exe"))
{
Runtime.getRuntime().exec("taskkill /F /IM geckodriver.exe");
}
System.out.println("Killed all the instances of GeckoDriver");
}
}
You can find a alternative approach within the discussion Selenium : How to stop geckodriver process impacting PC memory, without calling driver.quit()?

Take multiple browser snapshots

I am an ASP.NET web developer and need to submit artifacts of the developed page, to the testers.
These include:
Snapshots of the page when opened in different browsers.
Same thing, with different versions of the browsers.
I do this manually (one by one) and also from different systems.(because IE8 is available only at a particular system...so on..). Yes of course time consuming.
Is there a way that could simplify my life in this.(something like browserstack.com)
I am looking at Selenium grid. But this requires some coding too and using eclipse etc. Not sure yet if taking screenshots is possible too and I have no knowledge of selenium.
Appreciate any help in this. Thank you
Create a config file for the Selenium Hub
The file name should be for example hubConfig.json and save it in the same folder where you will start the Hub. The host contains the IP of the HUB and the port contains the port number ... :)
{
"host": "127.0.0.1",
"port": 4444
}
Run your Selenium Hub, and load the configuration file too
Create a new file with the following name: startSeleniumHub.cmd and add the following command in it:
java -jar selenium-server-standalone.jar -role hub -hubConfig hubconfig.json
You can download the latest version Selenium Server Standalone on the Selenium HQ website:
http://www.seleniumhq.org/download/
Create a config file for the Node
The file name should be for example nodeConfig.json and save it in the same folder on the same PC where you will start the Node.
{
"capabilities":[
{
"platform":"WINDOWS",
"browserName":"firefox",
"firefox_binary":"C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe",
"maxInstances":5,
"seleniumProtocol":"WebDriver"
},
{
"platform":"WINDOWS",
"browserName":"chrome",
"maxInstances":5,
"seleniumProtocol":"WebDriver"
},
{
"platform":"WINDOWS",
"browserName":"internet explorer",
"maxInstances":5,
"version":11,
"seleniumProtocol":"WebDriver"
}
],
"configuration":{
"port":5555,
"host":"IP_OF_THE_NODE_PC",
"register":true,
"hubHost":"IP_OF_THE_HUB",
"hubPort": 4444,
"maxSession":1
}
}
If something is not understandable for you in this config, you can read more details about it on the following page:
https://code.google.com/p/selenium/wiki/Grid2
If you want, you can add more browsers like Edge, Safari, Opera, etc...
Connect your PCs to the Selenium Hub as a Node with the configuration file and with the WebDrivers as well
Create a new file with the following name: startSeleniumNode.cmd and add the following command in it:
java -jar "selenium-server-standalone-X.XX.X.jar" -role node -nodeConfig "nodeConfig.json" -Dwebdriver.chrome.driver="chromedriver.exe" -Dwebdriver.ie.driver="IEDriverServer.exe"
You can download the latest Chrome and IE WebDriver on the same page where you downloaded the Selenium Server Standalone:
http://www.seleniumhq.org/download/
Write some JAVA code :)
It is just an example, I'm sure that there are better solutions. For example you can use TestNG to create different tests, add parameters to your tests, or run your tests in parallel, etc... You can find more information on the TestNG site: http://testng.org/doc/index.html
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Platform;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class ScreenshotMakerTest
{
public static void main(String [] args) throws IOException
{
// Init a new DesiredCapabilites which will setup the WebDriver to open a specific browser.
DesiredCapabilities dc = new DesiredCapabilities();
// Set the browser. If you want to open a Chrome, you can modify it to: DesiredCapabilites.chrome(); etc...
dc = DesiredCapabilities.internetExplorer();
// Set the Platform. It must be the same what you defined in the nodeConfig.json.
dc.setPlatform(Platform.WINDOWS);
// Set the version of the browser. If you didn't set any version in the nodeConfig.json, you can skip this line.
dc.setVersion("11");
// Create the WebDriver which will open the given browser on a Node
WebDriver driver = new RemoteWebDriver(new URL("IP_OF_THE_HUB:4444/wd/hub"), dc);
// Open a page
driver.get("http://google.com");
// Create screenshot about the current page
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Save the screenshot into a file
FileUtils.copyFile(scrFile, new File("c:\\screenshots\\screenshot.png"));
// Close the browser
driver.quit();
}
}
In this example, your code will open an Internet Explorer 11 on a Windows Node, open the http://google.com url and create a screenshot about it, and save it to c:/screenshots/screenshot.png.
Hope it helps.

selenium firefox path setting problems

no matter what I do selenium doesn't accept my firefox path in the console where I launch it from. Keep getting the same error.
I also set the path as an environment variable in win 7 64.
I'm pretty much a virgin when it comes to selenium. Trying to run my first JUNIT test.
Here is the message from selenium.
21:46:43.481 INFO - Command request: getNewBrowserSession[*chrome, http://compendiumdev.co.uk/, ] on session null
21:46:43.497 INFO - creating new remote session
21:46:43.544 INFO - Got result: Failed to start new browser session: java.lang.RuntimeException: java.lang.RuntimeException: Firefox could not be found in the path!
Please add the directory containing ''firefox.exe'' to your PATH environment
variable, or explicitly specify a path to Firefox like this:
*firefox c:\blah\firefox.exe on session null
Below is my java code
package com.eviltester.seleniumtutorials;
import com.thoughtworks.selenium.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class MyFirstSeleniumTests {
Selenium selenium=null;
#Before
public void setUp() throws Exception {
selenium = new DefaultSelenium("localhost", 4444, "*chrome",
http://compendiumdev.co.uk/");
selenium.start();
}
#Test
public void testExported() throws Exception {
selenium.open("/selenium/search.php");
selenium.type("q", "Selenium-RC");
selenium.click("name=btnG");
}
#After
public void tearDown() throws Exception {
selenium.stop();
}
}
Thank you for the help.

How to run Selenium WebDriver test cases in Chrome

I tried this
WebDriver driver = new ChromeDriver();
But I'm getting the error as
Failed tests: setUp(com.TEST): The path to the driver executable must be set by the webdriver.chrome.driver system property; for more information, see code here . The latest version can be downloaded from this link
How can I make Chrome test the Selenium WebDriver test cases?
You need to download the executable driver from:
ChromeDriver Download
Then use the following before creating the driver object (already shown in the correct order):
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
WebDriver driver = new ChromeDriver();
This was extracted from the most useful guide from the ChromeDriver Documentation.
Download the updated version of the Google Chrome driver from Chrome Driver.
Please read the release note as well here.
If the Chrome browser is updated, then you need to download the new Chrome driver from the above link, because it would be compatible with the new browser version.
public class chrome
{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com");
}
}
You should download the chromeDriver in a folder, and add this folder in your PATH environment variable.
You'll have to restart your console to make it work.
If you're using Homebrew on a macOS machine, you can use the command:
brew tap homebrew/cask && brew cask install chromedriver
It should work fine after that with no other configuration.
You need to install the Chrome driver. You can install this package using NuGet as shown below:
You can use the below code to run test cases in Chrome using Selenium WebDriver:
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ChromeTest {
/**
* #param args
* #throws InterruptedException
* #throws IOException
*/
public static void main(String[] args) throws InterruptedException, IOException {
// Telling the system where to find the Chrome driver
System.setProperty(
"webdriver.chrome.driver",
"E:/chromedriver_win32/chromedriver.exe");
WebDriver webDriver = new ChromeDriver();
// Open google.com
webDriver.navigate().to("http://www.google.com");
String html = webDriver.getPageSource();
// Printing result here.
System.out.println(html);
webDriver.close();
webDriver.quit();
}
}
Find the latest version of chromedriver here.
Once downloaded, unzip it at the root of your Python installation, e.g., C:/Program Files/Python-3.5, and that's it.
You don't even need to specify the path anywhere and/or add chromedriver to your path or the like.
I just did it on a clean Python installation and that works.
Download the latest version of the Chrome driver and use this code:
System.setProperty("webdriver.chrome.driver", "path of chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
Thread.sleep(10000);
driver.get("http://stackoverflow.com");
On Ubuntu, you can simply install the chromium-chromedriver package:
apt install chromium-chromedriver
Be aware that this also installs an outdated Selenium version. To install the latest Selenium:
pip install selenium
All the previous answers are correct. Following is the little deep dive into the problem and solution.
The driver constructor in Selenium for example
WebDriver driver = new ChromeDriver();
searches for the driver executable, in this case the Google Chrome driver searches for a Chrome driver executable. In case the service is unable to find the executable, the exception is thrown.
This is where the exception comes from (note the check state method)
/**
*
* #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;
}
The following is the check state method which throws the exception:
/**
* 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));
}
}
SOLUTION: set the system property before creating driver object as follows.
System.setProperty("webdriver.gecko.driver", "path/to/chromedriver.exe");
WebDriver driver = new ChromeDriver();
The following is the code snippet (for Chrome and Firefox) where the driver service searches for the driver executable:
Chrome:
#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");
}
Firefox:
#Override
protected File findDefaultExecutable() {
return findExecutable(
"geckodriver", GECKO_DRIVER_EXE_PROPERTY,
"https://github.com/mozilla/geckodriver",
"https://github.com/mozilla/geckodriver/releases");
}
where CHROME_DRIVER_EXE_PROPERTY = "webdriver.chrome.driver"
and GECKO_DRIVER_EXE_PROPERTY = "webdriver.gecko.driver"
Similar is the case for other browsers, and the following is the snapshot of the list of the available browser implementation:
To run Selenium WebDriver test cases in Chrome, follow these steps:
First of all, set the property and Chrome driver path:
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
Initialize the Chrome Driver's object:
WebDriver driver = new ChromeDriver();
Pass the URL into the get method of WebDriver:
driver.get("http://www.google.com");
I included the binary into my projects resources directory like so:
src\main\resources\chrome\chromedriver_win32.zip
src\main\resources\chrome\chromedriver_mac64.zip
src\main\resources\chrome\chromedriver_linux64.zip
Code:
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.SystemUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.*;
import java.nio.file.Files;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public WebDriver getWebDriver() throws IOException {
File tempDir = Files.createTempDirectory("chromedriver").toFile();
tempDir.deleteOnExit();
File chromeDriverExecutable;
final String zipResource;
if (SystemUtils.IS_OS_WINDOWS) {
zipResource = "chromedriver_win32.zip";
} else if (SystemUtils.IS_OS_LINUX) {
zipResource = "chromedriver_linux64.zip";
} else if (SystemUtils.IS_OS_MAC) {
zipResource = "chrome/chromedriver_mac64.zip";
} else {
throw new RuntimeException("Unsuppoerted OS");
}
try (InputStream is = getClass().getResourceAsStream("/chrome/" + zipResource)) {
try (ZipInputStream zis = new ZipInputStream(is)) {
ZipEntry entry;
entry = zis.getNextEntry();
chromeDriverExecutable = new File(tempDir, entry.getName());
chromeDriverExecutable.deleteOnExit();
try (OutputStream out = new FileOutputStream(chromeDriverExecutable)) {
IOUtils.copy(zis, out);
}
}
}
System.setProperty("webdriver.chrome.driver", chromeDriverExecutable.getAbsolutePath());
return new ChromeDriver();
}
Download the EXE file of chromedriver and extract it in the current project location.
Here is the link, where we can download the latest version of chromedriver:
https://sites.google.com/a/chromium.org/chromedriver/
Here is the simple code for the launch browser and navigate to a URL.
System.setProperty("webdriver.chrome.driver", "path of chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://any_url.com");