how would I run Selenium test through the GRID using C# - selenium

i have just set-up the selenium grid on my local machine and everything seems to be up and running.
my question is, is there a way I can run the test case from selenium grid node (command prompt)?
I am using WebDriver for creating my testcase using .Net

Sample code from here
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
// Requires reference to WebDriver.Support.dll
using OpenQA.Selenium.Support.UI;
class GoogleSuggest
{
static void Main(string[] args)
{
// Create a new instance of the Firefox driver.
// Notice that the remainder of the code relies on the interface,
// not the implementation.
// Further note that other drivers (InternetExplorerDriver,
// ChromeDriver, etc.) will require further configuration
// before this example will work. See the wiki pages for the
// individual drivers at http://code.google.com/p/selenium/wiki
// for further information.
WebDriver driver = new RemoteWebDriver(new Uri("http://127.0.0.1:4444/wd/hub"),
DesiredCapabilities.FirefoxDriver());
//Notice navigation is slightly different than the Java version
//This is because 'get' is a keyword in C#
driver.Navigate().GoToUrl("http://www.google.com/");
// Find the text input element by its name
IWebElement query = driver.FindElement(By.Name("q"));
// Enter something to search for
query.SendKeys("Cheese");
// Now submit the form. WebDriver will find the form for us from the element
query.Submit();
// Google's search is rendered dynamically with JavaScript.
// Wait for the page to load, timeout after 10 seconds
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until((d) => { return d.Title.ToLower().StartsWith("cheese"); });
// Should see: "Cheese - Google Search"
System.Console.WriteLine("Page title is: " + driver.Title);
//Close the browser
driver.Quit();
}
}

WebDriver driver = new RemoteWebDriver(new Uri("http://127.0.0.1:4444/wd/hub"),
DesiredCapabilities.FirefoxDriver());
OR in c#
IWebDriver driver;
DesiredCapabilities capability = new DesiredCapabilities();
driver = new RemoteWebDriver(
new Uri("http://hub-cloud.com/wd/hub/"), capability);
driver.Navigate().GoToUrl("http://www.google.com");

Related

getWindowHandles in selenium is always returning size as 1 even though multiple instances of chrome are open

I have multiple chrome windows open, but getWindowHandles in selenium is always returning size as 1 even though multiple instances of chrome are open.
here is the code:
System.setProperty("webdriver.chrome.driver", "C:/Downloads/New folder/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com/");
driver = new ChromeDriver();
driver.get("https://www.rediffmail.com/");
driver = new ChromeDriver();
driver.get("https://www.facebook.com/");
Set<String> ids = driver.getWindowHandles();
System.out.println(ids.size());
System.out.println(ids);
and here is the output:
1
[CDwindow-DBDAD89956F46A4DE6DC3F16E70D79A6]
any idea as to why this is happening?
or perhaps maybe im doing something incorrectly.
Im using Selenium-Java "selenium-java-3.13.0"
JDK "10.0.2"
Chrome "Version 68.0.3440.75 (Official Build) (64-bit)"
getWindowHandles() method will return the set of window handles of the current WebDriver instance.
Here you are creating different instance of each url and trying to get the WindowHandles. So, it is returning the size as 1.
Instance 1:
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com/")
Instance 2:
driver = new ChromeDriver();
driver.get("https://www.rediffmail.com/");
Instance 3:
driver = new ChromeDriver();
driver.get("https://www.facebook.com/");
you are finding the windowhandles after creating the instance 3. So, the driver object will hold the instance 3 and hence driver.getWindowHandles(); is returning as 1 .
You can try by opening multiple different tab using the same driver object and then check the size of the WindowHandles.
For the understanding purpose, Please add the below steps after the instance 3 and you can observe the getWindowHandles size.
//Latest driver instance is passed
JavascriptExecutor js=(JavascriptExecutor)driver;
String url1="https://www.rediffmail.com/";
String url2="https://www.google.com/";
js.executeScript("window.open(arguments[0])",url1); //New Tab will be opened
js.executeScript("window.open(arguments[0])",url2); //New Tab will be opened
Set<String> ids = driver.getWindowHandles();
System.out.println(ids.size());
System.out.println(ids);
Output:
3
First of all we required to find how many windows are open for this required to store getWindowHandles in String as below and hope below code will helps.
Try below code
Set<String> allWindowHandles = driver.getWindowHandles();
int count = allWindowHandles.size();
System.out.println("Number of browser windows opened on the system is : "+ count);
for (String windowHandle : allWindowHandles) {
//switch to each browser window
driver.switchTo().window(windowHandle);
String title = driver.getTitle();
//print the window handle id of each browser window
System.out.println("Window handle id of page -->"+ title +" --> is : "+windowHandle);
}

When I execute selenium script, following it browser is being closed Automatically?

I am writing selenium script and It's working perfect but when code is running then my browser is automatically closed?
public static void main(String args[])
{
System.setProperty("webdriver.chrome.driver",
"./chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("URL");
String email = "EMAil";
String password = "123";
int ELEMENT_WAIT_TIME_SEC = 60;
WebDriverWait explicitWait = new WebDriverWait(driver, ELEMENT_WAIT_TIME_SEC);
String locator = "//input[#type='email'][#aria-label='Email']";
By findBy = By.xpath(locator);
WebElement Login = explicitWait.until(ExpectedConditions.elementToBeClickable(findBy));
Login.click();
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("arguments[0].setAttribute('aria-invalid',true);", Login);
Login.sendKeys(email);
String plocator = "//input[#type='password'][#aria-label='Password']";
By findByp = By.xpath(plocator);
WebElement Password = explicitWait.until(ExpectedConditions.elementToBeClickable(findByp));
Password.click();
jse.executeScript("arguments[0].setAttribute('aria-invalid',true);", Password);
Password.sendKeys(password);
}
Check your code. May be you used driver.close() method to close the browser.
Just comment or delete that code and the browser will not close automatically.
I got over this error by using the Code Runner extension of VS Code instead of manually running node file-path.
Works well.
This is a case of browser version compatibility issue with chrome. so update your chromedriver.exe in sync with current version of Chrome browser.

Selenium tests do not work on IE8

To test some of the legacy pages I need to execute few test cases against IE8. These same testcases run efficiently against IE10/11, FF, Chrome without any issue.
public void TypePassword(string password)
{
var element = new WebDriverWait(Driver, TimeSpan.FromSeconds(10)).Until(
ExpectedConditions.ElementIsVisible(By.XPath("//input[#id='txtPassword']")));
//I also tried with just id and cssselector
element.Clear();
element.SendKeys(password);
}
I also tried
public void TypePassword(string password)
{
Password.Clear();
Password.SendKeys(password);
}
Interestingly,
public void TypeUsername(string username)
{
Username.Clear();
Username.SendKeys(username);
}
always work without any issue.
The IE driver configuration
var options = new InternetExplorerOptions { EnableNativeEvents = false};
options.AddAdditionalCapability("EnsureCleanSession", true);
Driver = new InternetExplorerDriver(options);
Seems like I am missing some configuration which is specific to IE8.
Also, confirmed zoom level and protected mode set up
Have you tried JavascriptExecutor ?
var element = new WebDriverWait(Driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementIsVisible(By.XPath("//input[#id='txtPassword']")));
((JavascriptExecutor)Driver).executeScript("arguments[0].value='"+password+"'", element);
It is difficult to find the element exists,
so u can go for the element count >1 using do while loop,
do
{
Thread.Sleep(500);
}while(driver.FindElements(By.Id("IDNAME")).Count>0);
Unless until, the count of the element gets, this do loop will execute and wait for the element to visible also

Setting separate profiles for Parallel Selenium Tests

I am researching how to set an individual profile using RemoteWebDriver. I have been reading about it on the following thread.
http://stackoverflow.com/questions/12961037/parallel-execution-of-firefoxdriver-tests-with-profile-share-same-profile-copy
I am trying to tackle it as following:
public static RemoteWebDriver getDriver(String methodName) throws MalformedURLException {
String SELENIUM_HUB_URL = "http://localhost:4444/wd/hub";
ThreadLocal<RemoteWebDriver> remoteWebDriver = null;
File currentProfileFile = new File(methodName);
//This is where it gives the error
FirefoxProfile currentFireFoxProfile = new FirefoxProfile(currentProfileFile);
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
capabilities.setCapability(FirefoxDriver.PROFILE, currentFireFoxProfile);
String proxy = System.getProperty("proxy");
try {
remoteWebDriver = new ThreadLocal<RemoteWebDriver>();
remoteWebDriver.set(new RemoteWebDriver(new URL(SELENIUM_HUB_URL),
capabilities));
} catch (MalformedURLException e) {
System.out.println("Please fix the RemoteDriverSetup.class");
}
remoteWebDriver.get().manage().window()
.setSize(new Dimension(2880, 1524));
remoteWebDriver.get().manage().timeouts()
.pageLoadTimeout(10, TimeUnit.SECONDS);
remoteWebDriver.get().manage().timeouts()
.implicitlyWait(10, TimeUnit.SECONDS);
return remoteWebDriver.get(); // Will return a thread-safe instance of the WebDriver
}
I am getting the following error :
Time elapsed: 1.044 sec <<< FAILURE!
org.openqa.selenium.firefox.UnableToCreateProfileException: Given model profile directory does
not exist: TEST001
Update : I am injecting method name in the BaseTest class below
#BeforeMethod
public void startTest(Method testMethod) {
LOG.info("Starting test: " + testMethod.getName());
this.driver = WebDriverSetup.getDriver(testMethod.getName());
}
If you don't want to customize anything on your Firefox profile, better to create Firefox webdriver instance by NOT providing any profile details (as mentioned by Nguyen).
If you really want to create separate profiles (may be required to install some plug-ins like Firebug), in that case, you can do that by without passing any file name as below:
FirefoxProfile currentFireFoxProfile = new FirefoxProfile();
//Do some customization - add extension
currentFireFoxProfile.addExtension(pathOfextensionToInstall);
//or Setup some Firefox config. switch values
currentFireFoxProfile.setPreference("browser.download.manager.showWhenStarting", false);

Facebook Logout Script

Can you please let me know how we can logout in chrome browser by using selenium?
e.g
public class AJ {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://facebook.com");
WebElement element=driver.findElement(By.name("email"));
element.sendKeys("user#example.com");
element=driver.findElement(By.name("pass"));
element.sendKeys("password");
element.submit();
The following code should help you.
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("http://facebook.com");
WebElement element=driver.findElement(By.name("email"));
element.sendKeys("user#example.com");
element=driver.findElement(By.name("pass"));
element.sendKeys("password");
element.submit();
//Click on dropdown menu then logout button
driver.findElement(By.id("userNavigationLabel")).click();
driver.findElement(By.id("logout_form")).click();
//Check to see if email login box is available
//therefore confirming user has logged out
driver.findElement(By.name("email"));
}
I recommend using the Chrome Developer tools to help you find unique attributes of a page for Selenium to find.
I hope this helps!
In python the same is done using this line of code. It uses the same module i.e, Selenium.
So just change the element using css selector by using the argument passed below.
logout1 = driver.find_element_by_css_selector("._w0d[action='https://www.facebook.com/logout.php?button_name=logout&button_location=settings']").submit()
Hope it works.
I am able to successfully logout from Facebook.
Here is the Java code
String url = "http://facebook.com";
String email = "email";
String password = "password";
System.setProperty("webdriver.chrome.driver", "src/chromedriver 3");
WebDriver driver = new ChromeDriver();
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-notifications");
driver = new ChromeDriver(options);
driver.get(url);
driver.manage().window().maximize();
driver.findElement(By.id("email")).sendKeys("Your email here");
driver.findElement(By.id("pass")).sendKeys("Your password here" + Keys.ENTER);
driver.findElement(By.id("logoutMenu")).click();
Thread.sleep(2000);
driver.findElement(By.xpath("//form[contains(#id,'show_me_how_logout')]/../../../..")).click();