Thursday 30 January 2014

Selenium Webdriver - Example with different cases


 

Browser Back and Forward (NAVIGATION)


Follow the below steps for backward and forward navigation:

WebDriver driver =new FirefoxDriver();
driver.get("http://seleniumhq.org/");
driver.findElement(By.linkText("Download")).click();
Thread.sleep(3000);            //delay for 3 second
driver.navigate().back();
driver.navigate().forward();

Handling Drag and Drop 

Actions act = new Actions(driver);
WebElement src = driver.findElement(By.xpath("//div[@id='items']/div[1]"));
WebElement tar = driver.findElement(By.id("trash"));

act.clickAndHold(src).build().perform();                //For each action we need to build and Perform
act.moveToElement(tar).build().perform();
act.release(tar).build().perform();

Handling Frame

driver.get("http://timesofindia.indiatimes.com/");
driver.manage().timeouts().implicitlyWait(30,TimeUnit.Seconds);
List frms= driver.findElements(By.tagName("iframe"));  //Frame List
System.out.println(frms.size());
for(int i=0;i
{
System.out.println(frms.get(i).getAttribute("src"));
}

 Perform Action in Frame 

WebElement iframe = driver.findElement(By.xpath("//iframe[@src='/poll.cms']"));
driver.switchTo().frame(iframe);                                     //Switch to iFrame
driver.findElement(By.id("basantd")).sendKeys("21");  //Perform Action in iFrame

 

Tab and New Window 

Set windowHandles = driver.getWindowHandles();
Iterator it = windowHandles.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}

 Count link in  a page

List allLinks= driver.findElements(By.xpath("//a"));
//display the count of links in the page
System.out.println(allLinks.size());
//display the text for each link on the page
for(int i=0;;i)
{
        //display href for each link
System.out.println(allLinks.get(i).getAttribute("href"));
//display text for each link
System.out.println(allLinks.get(i).getText());
//perform click action
allLinks.get(i).click();

}
 

Selenium Webdriver Questions and Answers Part - 2


       1.   What is webdriver?
 WebDriver is a simpler, more concise programming interface in addition to addressing some limitations in  the Selenium-RC API. Selenium-WebDriver was developed to better support dynamic web page where elements of a page may change without the page itself being reloaded. WebDriver’s goal is to supply a well-designed object-oriented API that provides improved support for modern advanced web-app testing problems.
2.  What are the advantages of selenium2.0/webdriver?
  •         Need no server to start
  •         Easy to code
  •         Has sophisticated API to support wide verity of browsers.
  •         Supports to test dynamic UI web page.

3.      Difference between the selenium1.0 and selenium 2.0?
Selenium 1.0
Selenium 2.0/Webdriver
1.   It ‘injected’ javascript functions into the browser when the browser was loaded and then used its javascript to drive the AUT within the browser. 
2.  Selenium server need to start to run tests
3.   Has some loop-holes in supporting complex UI apps,Javascript security
4.  No support for headless broswers
1.   WebDriver makes direct calls to the browser using each browser’s native support for automation


     2.   Not needed unless tests are run
           on local machine.
3. Supports even drag and drop features and no security loop-holes
4.  Supports htmlunit driver –headless browser runs fast


4.      What are the Locators are there in selenium 2.0?
It supports locators based on Id,name,xpath,dom,css,class,tagname
5.      How to handle the Ajax Applications in Web driver?
There are 2 types of waits webdriver supports to handle ajax applications to make webdrive sync to execution:
Implicit wait :
driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
Explicit wait:   WebDriverWait, FluentWait
WebElement strr = (new WebDriverWait(driver,30)).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[starts-with(@id,'yui_3_4_0_1_137509')]/ul/li[2]/a")));
This link explains better about handling ajax in webdriver.

5.      How to handle the multiple windows in web driver?
            driver.switchTo().window(Window ID);

6.      Difference between findelement() and findelements()?
     findELement will find the first matching element.
     findELements will all the matching elements. You'll probably need to loop through all the elements  returned.
7.      How to handle the alerts in web driver?
    driver.switchTo().alert().accept();
 
8.      How to take the screen shots in seelnium2.0?
            File src2 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
            FileUtils.copyFile(src2,new File("d:\\sc2.jpeg"));
9.  What is the limitations of web driver?
  • Can not automate desktop applications, supports only web application.
  •  No inbuilt commands to generate good reports
  • Cannot support readily for new browsers

Selenium Questions and Answers - Part -1



1.      What are the advantages and disadvantages of Selenium IDE?
Advantages:
1.      It is Opensource
2.      Can generate code in any format like java,python,html,php etc.
3.      Easy to record and play
4.      Can extend the code of IDE using user-extensions
5.      Can increase and decrease the speed of execution
6.      Can run multiple tests at a time
7.      Breakpoint insertion is possible
Disadvantages:
1.      Supports only in Mozilla as add-on,but not for IE,chrome etc
2.      Doesn’t support flow control,data driven testing unless we use third party user-extensions.
3.      Not efficient in running large number of scripts,complex to manage suites.
4.      Detailed results are not available
5.      Supports only web based apps

2.      What is the Difference between id and name?
name as used on the form controls (input, textarea, select, button elements) is radically different from the id attribute on named elements. In this case, the name attribute relates to how data is labeled when sent to server, and multiple elements may share the same name. The id attribute on the other hand is for identifying one unique element for the purposes of scripting, styling, or addressing.
id and name are the two different attributes of web elements.These are used to locate the element on webpage while automating,most of the times id is used, if two elements has same id’s then we can also look for name attribute to locate exact one.
Ex:       //input[@id =”xxx” and @name =”yyy”]
//input[@id=”xxx”]
//input[@name=”yyy”]


3.      What is the difference between Xpath and dom?
DOM: The Document Object Model (DOM) is a cross-platform and language-independent convention for representing and interacting with objects in HTMLXHTML and XML documents. Objects in the DOM tree may be addressed and manipulated by using methods on the objects
Ex: var element=document.getElementById("intro");

XPTAH: XPath, the XML Path Language, is a query language for selecting nodes from an XML document. In addition, XPath may be used to compute values (e.g., strings, numbers, or Boolean values) from the content of an XML document.
Ex: //input[@id=”xxx”]

4.      What is the difference between assert and verify command?
Assert : If you use this, the test will be terminated at the point where check fails. The main plus point of this is you can immediately see if the test passed or failed. However, the disadvantage of doing this is the remaining checks and verification that will never be performed and you can not track that.
Verify : This is in contrast, will not terminate the whole test. If you only used Verify commands in your tests, all tests are going to run guaranteed even if any of the checks fails when test is running. However, there is a bit of work in order to find out your results in details

5.      What type of testing we can do by using Selenium?
    • Functional automation testing of web applications(Android also)
    •  Load Testing

Monday 27 January 2014

Calender pick Date and select drop down items using C #.


Enter / Select date from the calender

 Date Set using Java Script.. In calender. 

  String FutureDate = "28/02/2014";
  String javaStringToSetDate = "var x=document.getElementsByName('flight_depart_date);  
  x[0].value=" + "'" + FutureDate + "';";
  js.executeScript(javaStringToSetDate);

  Date selection using JavaScript in a calender (50 Days + from current Date). 

  now = Calendar.getInstance();
  now.add(Calendar.DATE, +50);
  String FromDate =(now.get(Calendar.MONTH) + 1) + "/" + now.get(Calendar.DATE) + "/" +     
  now.get(Calendar.YEAR);

You can use this using JavaScript Executor code below u can send it to the Element.

((JavascriptExecutor)driver).executeScript("arguments[0].value=arguments[1]",  driver.findElement(By.id(OR.getProperty("txtSSTODate_ID"))), ToDate);


Another Option to select date : 

 public void DateSelection()
        {
            var selectDate = (DateTime.Now.AddDays(50)).ToString("dd'/'MM'/'yyyy");

            IJavaScriptExecutor js = driver as IJavaScriptExecutor;
            js.ExecuteScript("window.document.getElementById('textboxDepDate').setAttribute('value',    '" + selectDate + "')");
        }

Select items from Drop Down List

  var List = driver.FindElement(By.Name("DropdownElement"));
       var listElement = new SelectElement(List);  //create select element object 
       listElement.SelectByValue("Mumbai");   //select by value


Create Database Connection using c-sharp in selenium webdriver.


 
Test Scanerio :  Login Page.

Find below statement : 


driver.Navigate().GoToUrl(baseURL + "/");

driver.FindElement(By.Id("Login")).Click();        //Open Login Page



driver.FindElement(By.Id("UserID")).SendKeys("UserName");

driver.FindElement(By.Id("Password")).SendKeys("Password");
driver.FindElement(By.Id("btnSubmit")).Click();   // Successfully Login.

Above statement was for hardcoded value.

Just few modification required for database connection using c#.

driver.Navigate().GoToUrl(baseURL + "/login.aspx");
Assert.AreEqual("Welcome", driver.Title); // Page title checkpoint
// DB connection Command                
SqlCommand comm = new SqlCommand();
comm.Connection = new SqlConnection("Server=192.168.02.1;Initial Catalog=BasantDB; uid=sa;pwd=basant123"); //Windows Authentication
string sqluserid = @"select userid, dbo.decrypt(password) as password from memberlogin";
          
            comm.CommandText = sqluserid;
            comm.Connection.Open();
            SqlDataReader cursor = comm.ExecuteReader();
            while (cursor.Read())
            {
               
                string username = cursor["UserId"].ToString();
                string password = cursor["Password"].ToString();
                driver.FindElement(By.Id("header1_hreflogin")).Click();
                driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(30));
                driver.FindElement(By.Id("UserId")).Clear();
                driver.FindElement(By.Id("UserId")).SendKeys(username);
                driver.FindElement(By.Id("Password")).Clear();
                driver.FindElement(By.Id("Password")).SendKeys(password);
                driver.FindElement(By.Id("btnSubmit")).Click();
                WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(40));

                driver.FindElement(By.Id("header1_hrfLogout")).Click();

                driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(30));      
             
            }
            comm.Connection.Close();

        }





Friday 24 January 2014

Selenium Beginner



Need knowledge of some basic information -
1. HTML
2. XML
3. JavaScript
4. DOM (Document Object Model)
5. Basic Conditional Statement - like core programming with oops concept.
Here  we are learning about selenium with c-sharp.

Selenium :
Selenium is an open source web based automation functional and regression tools. which support 
multiple browser and programming language.

Component available in Selenium :
There are four component available in selenium -
              Selenium Integrated Development Environment  (IDE)
              Selenium Remote Control (RC) Selenium 1.0
              Selenium Webdriver / Selenium 2.0
              Selenium Grid
Prior to IDE, Selenium Core was another tools. It is not used in isolation.

Selenium difference from another functional automation testing tools :
As you see, selenium are different component - where different different limitation and
advantages presents. Its support multiple browser, multiple programming language. After 
test execution, can not find test report. We have to generate test execution report 
by using prefer programming language.  Its open source and no license required for accessing
the tools.

Selenium IDE - its firefox plug-in and record play option for preparing test script.

Selenium RC - its launch the browser and kill the browser after completing test execution. There are two component ; client library and selenium server.

Selenium Webdriver : its upgrade version of selenium RC, better API, and can test mobile apps driver.
Selenium Grid : with the help of these tool, we can test our application with multiple machine and 
multiple operating systems.

These such features are not available in some another automation testing tools. 

Selenium supporting browsers :
As you can see, Selenium supporting multiple browsers but there are some specific browser specified as selenium components - 

Selenium IDE - It is plug-in in Mozila Firefox browser. So only supporting MF browser only. 
                We can not execute our test script directly from Selenium IDE in another browser. 
               But we can execute our test script in another browser with the help of Selenium RC.

Selenium RC -  This Component supporting and can execute test script in multiple browsers ; i.e. 
                         Mozila Firefox, Internet Explorer, Google Chrome, Opera, Safari, Mac.

Selenium Webdriver -  It supports some another browser including selenium RC. 
                                    HtmlUnit,  Andriod for Phone and tablets, iOS for Phone and Tablet.

Supporting Operating System :
Its supporting different different operating system depends upon browser specification - 

Windows - All browsers.

Linux and Unix - Excluding Internet Explorer.

Mac - Excluding Internet Explorer. 

Solaris - All Browser. 

Flexibility and Extensibility : 
Selenium is highly flexible. There are many ways you can add functionality to both Selenium test scripts and Selenium’s framework to customize your test automation. This is perhaps Selenium’s greatest strength when compared with other automation tools. These customizations are described in various places throughout this document. In addition, since Selenium is Open Source, the sourcecode can always be downloaded and modified.