Saturday 18 November 2017

Selenium grid parallel run with different browser in distributed system.


pre requisites: jdk,  eclipse with testng.


1. Download selenium server standalone jar
2. open command prompt and cd to the folder - where you have "selenium server standalone jar" available
ex:
cd E:\Selenium

3. start the hub from command prompt:
java -jar selenium-server-standalone.jar -role hub

4. run two nodes in diff vm or diff system (Replace localhost with hub system IP)
java -jar selenium-server-standalone.jar -role node -hub http://localhost:4444

5.verify your grid setup in below url.
http://localhost:4444/grid/console

5. Create one java project and convert into testng project.add selenium jar to buildpath

6. Update your testng.xml file with below code

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="methods">

  <test name="Democart">
    <classes>
       <class name="testng.GridParreleltests"/>
    </classes>
  </test>
</suite>

7. Crate one testng class(GridParreleltests) under grid package and write below codes.     note:- replace localhost with hub system IP.

package grid;

import java.net.MalformedURLException;
import java.net.URL;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.Test;

public class GridParreleltests {

public static WebDriver driver;

@Test
  public void test1() throws MalformedURLException {

String hubUrl="http://localhost:4444/wd/hub";
DesiredCapabilities cap=  DesiredCapabilities.firefox();
  //cap.setPlatform(Platform.WINDOWS);
// cap.setVersion);
  cap.setBrowserName("firefox");
  System.out.println("before launch");
  driver =new RemoteWebDriver(new URL(hubUrl),cap);
  driver.get("http://www.google.com");
  System.out.println("after launch");

  }

@Test
public void test2() throws MalformedURLException {
String hubUrl="http://localhost:4444/wd/hub";
DesiredCapabilities cap=  DesiredCapabilities.chrome();
  //cap.setPlatform(Platform.WINDOWS);
// cap.setVersion);
  cap.setBrowserName("chrome");
  System.out.println("before launch");
  driver =new RemoteWebDriver(new URL(hubUrl),cap);
  driver.get("http://www.yahoo.com");
  System.out.println("after launch");
}
}

8. Right click on testng.xml and run as testng suite.

Webtable data fetch and verification selenium webdriver-java

//sample html content

<table name="t1" border="5">
<thead>
<tr>
<th>ID</th><th>Name</th><th>Dept</th>
</tr>
</thead>
<tbody>
<tr>
<td>123</td><td>Mohan</td><td>Admin</td>
</tr>
<tr>
<td>432</td><td>Sohan</td><td>Hr</td>
</tr>
<tr>
<td>543</td><td>Hanuman</td><td>Finance</td>
</tr>
<tr>
<td>765</td><td>Dinesh</td><td>It</td>
</tr>
</tbody>
</table>




//codes to fetch name and dept based on ID no

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class WebTable {
public static WebDriver driver;

  @Test
  public void test1() {
  driver=new FirefoxDriver();
  driver.get("file:///E:/Selenium/docs/sample.html");
  driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
  List row=driver.findElements(By.xpath("//table[@name='t1']/tbody/tr"));
  System.out.println(row.size());
 
  List col=driver.findElements(By.xpath("//table[@name='t1']/tbody/tr[1]/td"));
  System.out.println(col.size());
  for(int i=1;i<=row.size();i++)
  {
  for(int j=1;j<=col.size();j++)
  {
String sData= driver.findElement(By.xpath("//table[@name='t1']/tbody/tr["+i+"]/td["+j+"]")).getText();

System.out.println(sData);
if(sData.equals("543"))
{
System.out.println(driver.findElement(By.xpath("//table[@name='t1']/tbody/tr["+i+"]/td["+j+1+"]")).getText());
System.out.println(driver.findElement(By.xpath("//table[@name='t1']/tbody/tr["+i+"]/td["+j+2+"]")).getText());
}
  }
  }
 
  }
}

Sikuli integration with Selenium webdriver-Java for upload functionality

Steps:

1. Capture 3 snapshot(Try it,Browse,Open) for below url using sikuli ide or snipping tool or  copy paste below images  in mentioned folder

https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_fileupload_create





2. Create a file test.txt in your default window folder (for me - desktop)

3. Add Sikulix jar and selenium jar in your project build path
4. create a testng class - SikuliProj in your project and run the test.

//Codes


import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.sikuli.script.FindFailed;
import org.sikuli.script.Pattern;
import org.sikuli.script.Screen;
import org.testng.annotations.Test;

public class SikuliProj {

@Test
public void functionName() throws FindFailed, InterruptedException {


// Create a new instance of the Firefox driver

WebDriver driver = new FirefoxDriver();

//navigate to websie
driver.get("https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_fileupload_create");

Screen sc=new Screen();

//Create object for all 3 captured images
Pattern image1 = new Pattern("E:\\test\\tryit.png");
Pattern image2 = new Pattern("E:\\test\\browse.png");
Pattern image3 = new Pattern("E:\\test\\open.png");

//Perform action using sikuli
sc.wait(image1,10);
sc.click(image1);
sc.wait(image2,5);
sc.click(image2);
Thread.sleep(5000);
sc.type("test.txt");
sc.wait(image3,5);
sc.click(image3);

  }

}


Monday 5 September 2016

Selenium Webdriver - C# with NUNIT 3 using visual studio

Step1:  Open Visual studio
Step2: Choose Extension and updates from Tools Menu
Step3: Install 'NUnit 3 Test Adapter' and 'NUnit Template fro Visual Studio' - Follow below screen:

Step4: Create new Project from File-> New Project -> Test -> NUnit 3 Unit test Project:  Follow below screen

Step5: Double Click on CS File from View- > Solution Exploer

Step6: Install Selenium Webdriver, Webdriver support and chromedriver dlls by right clicking on Solution and choosing manage Nuget Package
Step 7: Install above DLLS , please follow below screen:

Step8:  Replace the code of CS file with below codes .

using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace NUnit.Tests
{
    [TestFixture]
    public class TestClass
    {
        public static IWebDriver driver;

        [Test]
        public void TestMethod()
        {
            //To Launch Firefox
            driver = new FirefoxDriver();

            //To Navigate Given URL
            driver.Navigate().GoToUrl("http://newtours.demoaut.com");

            //Implicitly wait for 30 seconds
            driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(30));
            //Enter credentials and login
            driver.FindElement(By.Name("userName")).SendKeys("mercury");
            driver.FindElement(By.Name("password")).SendKeys("mercury");
            driver.FindElement(By.Name("login")).Click();
        }
    }
}


Step8: Run Test from  Test -> Run-> All Tests menu

Friday 18 September 2015

TestNG + Selenium WebDriver configuration and execution


Install TestNG
1.        Launch the Eclipse IDE
2.       Navigate to Help->Install new software
3.       In Install dialog window, click “Add” button.
4.       Type name as you wish, for example :- “TestNG
5.       Type “http://beust.com/eclipse/” as location.
6.       Click OK.
7.        Just Click TestNG checkbox
8.       Press “Next” button.
9.       Click “I accept the terms of the license agreement
10.   Click Finish.
11.   Restart Eclipse

Create testng Class
1.       Right click on your package ( for this example package is p1)
2.       Select New-> Others->testing class
3.       Enter name of the class ( for this example name is testng1)
4.       Click OK
5.       Copy paste below code in the opened class

package p1;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.Assert;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class testng1 {
      
       WebDriver driver;
      
  @Test(groups = {"Regression"},priority = 2)
  @Parameters({"Browser1","url1"})
  public void test1(String sBrowser,String url) {
        
         if (sBrowser.equalsIgnoreCase("firefox"))
         {
                driver=new FirefoxDriver();
         }
         else if (sBrowser.equalsIgnoreCase("ie"))
         {
                System.setProperty("webdriver.ie.driver", "C:/imp/software/IEDriverServer.exe");
                driver=new InternetExplorerDriver();
         }
        
         else
         {
                System.out.println("Invalid browser");
                System.exit(0);
         }
        
         driver.get(url);
         String sTitle=driver.getTitle();
         System.out.println("Title is "+ sTitle);
         Assert.assertEquals("idojfioe", sTitle);
         driver.close();
  }
 
  @Test(groups = {"Smoketest"},priority = 1)
  @Parameters({"Browser2","url2"})
  public void test2(String sBrowser,String url) {
        
         if (sBrowser.equalsIgnoreCase("firefox"))
         {
                driver=new FirefoxDriver();
         }
         else if (sBrowser.equalsIgnoreCase("ie"))
         {
                System.setProperty("webdriver.ie.driver", "C:/imp/software/IEDriverServer.exe");
                driver=new InternetExplorerDriver();
         }
        
         else
         {
                System.out.println("Invalid browser");
                System.exit(0);
         }
        
         driver.get(url);
         String sTitle=driver.getTitle();
         System.out.println("Title is "+ sTitle);
         driver.close();
  }
}

Create TestNG xml file
1.       Right click on your Project
2.       Select New-> File
3.       Enter name of the file ( for this example name is testing.xml)
4.       Click OK
5.       Copy paste below code in xml file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">

<suite name="Suite" parallel="false">
                <parameter name="Browser1" value="firefox"/>
                <parameter name="Browser2" value="ie" />
                <parameter name="url1" value="http://www.google.com"/>
                <parameter name="url2" value="http://newtours.demoaut.com" />
                <test name="Selenium-AutomationSuite">
                                <groups>
                                                <run>
                                                                  <include name="Smoketest" />
                                  <include name="Regression" />
                                                </run>
                                </groups>
                                <classes>
                                                 <class name="p1.testng1"/>
                                                 
                                                 
                                               
                                </classes>
                </test>
</suite>

Run the Suite
1.       Right click on xml file(testing.xml)
2.       Navigate to Run as-> TestNG Suite



Friday 17 July 2015

Selenium Web driver integration with HP-ALM

As selenium is open source and not having any inbuilt integration with any test management tool. It is very important and handy to integrate selenium with well-established test management tool (HP-ALM)

Steps:

     1. Register 'OTAClient.dll' with registry
a.     open command prompt by typing cmd in run command
b.     copy below command and press enter

         regsvr32  ” complete path of OTAClient.dll file in your local system”
           ex:  regsvr32  "C:\Users\user1\AppData\Local\HP\ALM-Client\10\OTAClient.dll"

2.   Convert the DLL file into Jar
c.      Download ‘com4j.jar file’, downloaded file will be in zip format, extract the zip file in some folder.
d.     Navigate to extracted folder in command prompt
e.     Enter the below command
java -jar tlbimp.jar -o alm -p com.qc ” complete path of OTAClient.dll file in your local system”
f.       All java files will be available in alm folder under parent folder( where you extracted the zip file)

3.   Export these java files as jar filefrom eclipse.
g.     Copy com folder ,created under  alm folder , and copy it in src folder of eclipse
h.     You will get com.qc and com.qc.events folder in created under src folder in eclipse
i.        Select the folder and export as jar file, save as ‘otaclient.jar’
Add these two jar files (‘com4j.jar’ and ‘otaclient.jar’) and you are good to go with ALM-integrated selenium run.

Tuesday 10 March 2015

Selecting item from ListBox and check which value is selected

import org.openqa.selenium.*;

import org.openqa.selenium.firefox.*;
import org.openqa.selenium.support.ui.Select;


// - Selecting Existing list of values from ListBox
// and check which value is selected
public class WebDriver19 {

/**
* @param args
*/
public static WebDriver oBrowser;
public static String sUrl = "http://www.goibibo.com";
public static void main(String[] args)
{
boolean bIsBrowserOpened;

bIsBrowserOpened = OpenBrowser();

if (bIsBrowserOpened)
{
Set_ListBox_Item_Method3();
//Set_ListBox_Item_Method2_Valid();
//Set_ListBox_Item_Method2_InValid();
CloseBrowser();
}


}

public static boolean OpenBrowser()
{
try
{
oBrowser = new FirefoxDriver();
oBrowser.get(sUrl);
try
{
Thread.sleep(5000L);
}
catch (Exception e)
{
e.printStackTrace();
}
}
catch (Exception e)
{
System.err.println(e.getMessage());
return false;
}
return true;

}



public static void CloseBrowser()
{
oBrowser.close();
}

public static void Set_ListBox_Item_Method1()
{
WebElement oListBox;


oListBox = oBrowser.findElement(By.id("gi_source"));
oListBox.sendKeys("Hyderabad");

}

//For throwing not found exception
public static void Set_ListBox_Item_Method2_Valid()
{
WebElement oListBox;


oListBox = oBrowser.findElement(By.id("gi_source"));
//oListBox.sendKeys("Hyderabad");
try
{


oListBox.findElement(By.xpath("//option[@value='HYD']")).click();

}
catch(NoSuchElementException e)
{
System.out.println("Specified Item Not Found");
}
catch(Exception e)
{
e.printStackTrace();
}
}

public static void Set_ListBox_Item_Method2_InValid()
{
WebElement oListBox;

oListBox = oBrowser.findElement(By.id("gi_source"));

//oListBox.sendKeys("Hyderabad");
try
{


oListBox.findElement(By.xpath("//option[@value='HYD123']")).click();

}
catch(NoSuchElementException e)
{
System.out.println("Specified Item Not Found");
}
catch(Exception e)
{
e.printStackTrace();
}
}

public static void Set_ListBox_Item_Method3()
{ //using select class
WebElement oListBox;
Select ListSelect;
oListBox = oBrowser.findElement(By.id("gi_source"));
ListSelect=new Select(oListBox);
ListSelect.selectByValue("HYD");
System.out.println("Selected:= "+ListSelect.getAllSelectedOptions().get(0).getText());
ListSelect.selectByVisibleText("Pune");
System.out.println("Selected:= "+ListSelect.getAllSelectedOptions().get(0).getText());

}

}

Monday 28 October 2013

Getting count of Different Web Element displayed in the page using WebDriver

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;

//Getting count of Different Web Element  displayed
public class WebDriverElementCount {

public static WebDriver oBrowser;
public static String sUrl="http://in.yahoo.com";
public static void main(String[] args)
{
boolean bIsBrowserOpened;

bIsBrowserOpened=OpenBrowser();
if(bIsBrowserOpened)
{

Display_Element_Count();
CloseBrowser();
}

}
public static boolean OpenBrowser()
{
try
{
oBrowser=new FirefoxDriver();
oBrowser.get(sUrl);
try
{
Thread.sleep(5000L);
}
catch(Exception e)
{
e.printStackTrace();
}
return true;
}
catch(Exception e)
{
System.err.println(e.getMessage());
return false;
}
}

public static void Display_Element_Count()
{
Get_Element_Count("Link","//a");
Get_Element_Count("Image","//img");
Get_Element_Count("TextBox","//input[@type='text']");
Get_Element_Count("Form Submit Button","//input[@type='submit' or @type='clear']");
Get_Element_Count("HTML 4/5 button","//button");
Get_Element_Count("Radio Button","//input[@type='radio']");
Get_Element_Count("CheckBox","//input[@type='checkbox']");
Get_Element_Count("List Box","//select");
Get_Element_Count("Activex Button","//object");
Get_Element_Count("Text Area","//textarea");
}
public static void Get_Element_Count( String sElementName,String sXpath_of_Element)
{
int iCount;
if(!sXpath_of_Element.isEmpty())
{
iCount=oBrowser.findElements(By.xpath(sXpath_of_Element)).size();
System.out.printf("\n No of (%s)  Element= %d" ,
sElementName,iCount);
}
}
public static void CloseBrowser()
{
oBrowser.close();
}

}


Reading Existing list of values from ListBox Using WebDriver

import java.util.List;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.*;

// - Reading Existing list of values from ListBox
public class WebDriver18 {
/**
* @param args
*/
public static WebDriver oBrowser;
public static String sUrl = "http://www.goibibo.com";
public static void main(String[] args)
{
boolean bIsBrowserOpened;
bIsBrowserOpened = OpenBrowser();
if (bIsBrowserOpened)
{
Get_ListBox_Items();
CloseBrowser();
}
}
public static boolean OpenBrowser()
{
try
{
oBrowser = new FirefoxDriver();
oBrowser.get(sUrl);
try
{
Thread.sleep(5000L);
}
catch (Exception e)
{
e.printStackTrace();
}
}
catch (Exception e)
{
System.err.println(e.getMessage());
return false;
}
return true;
}

public static void CloseBrowser()
{
oBrowser.close();
}
public static void Get_ListBox_Items()
{
WebElement oListBox;
int iElement, iCount;
List<WebElement> oAllListValues;
oListBox = oBrowser.findElement(By.id("gi_source"));
oAllListValues = oListBox.findElements(By.tagName("option"));
iCount = oAllListValues.size();
System.out.println("No of Items found in list box ="+String.valueOf(iCount));
System.out.println("*********************************");
for (iElement=0; iElement<iCount; iElement++)
{
System.out.printf("\n Item (%d/%d) = %s",
iElement+1,iCount,
oAllListValues.get(iElement).getText());
}

}

}

Wednesday 6 February 2013

WebDriver with JUNIT


import java.util.concurrent.TimeUnit;

import junit.framework.Assert;

import  org.junit.Assert.*;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;


public class WebDriverJunit {

public static WebDriver oBrowser;

@BeforeClass
public static void Selenium_init()
{
oBrowser=new FirefoxDriver();
oBrowser.manage().window().maximize();
oBrowser.manage().timeouts().pageLoadTimeout(15, TimeUnit.SECONDS);
oBrowser.get("http://www.bing.com");
}

@AfterClass
public static void Selenium_End()
{
oBrowser.quit();
}

@Test
public void Validate_Edit()
{
WebElement oEdit;

try
{
oEdit=oBrowser.findElement(By.id("sb_form_q"));
Assert.assertEquals("", oEdit.getText());
}
catch(Exception e)
{
Assert.fail(e.getMessage());
}
}

@Test
public void Search()
{
WebElement oEdit,oButton;
String sPageSource;

try
{
oEdit=oBrowser.findElement(By.id("sb_form_q"));
oButton=oBrowser.findElement(By.id("sb_form_go"));
oEdit.sendKeys("Selenium");
oButton.click();
sPageSource=oBrowser.getPageSource();
oBrowser.navigate().back();
if (sPageSource.lastIndexOf("Selenium")<100)
{
Assert.fail("No Proper result");
}
}
catch(Exception e)
{
Assert.fail(e.getMessage());
}
}
}