Monday, 4 March 2019

selenium basics for beginners


 Selenium Introduction

 l  Selenium is an open source tool (no cost involved – free to download from Seleniumhq) “https://docs.seleniumhq.org/download/”
l  Selenium supports language like HTML, Java, PHP, purl, Python, Ruby and C# .
l  Selenium supports multiple web browsers like, IE, Firefox, Chrome, Opera
l  Selenium supports multiple Operating systems like Windows, Linux, Mac
l  Selenium Components


Selenium IDE


l  Firefox extension
l  Easy record and replay
l  Debug and set breakpoints
l  Save tests in HTML, WebDriver
and other formats.
l  Selenium saves all information
  in an HTML table format
l  Each record consists of:
Command – tells Selenium what to do (e.g. “open”, “type”, “click”, “verifyText”)
Target – tells Selenium which HTML element a command refers to (e.g. textbox, header, table)
Value – used for any command that might need a value of some kind (e.g. type something into a textbox)



Selenium IDE Commands and Assertion


Command
Number of Parameters
Description
open
0 - 2
Opens a page using a URL.
click/clickAndWait
1
Clicks on a specified element.
type/typeKeys
2
Types a sequence of characters.
verifyTitle/assertTitle
1
Compares the actual page title with an expected value.
verifyTextPresent
1
Checks if a certain text is found within the page.
verifyElementPresent
1
Checks the presence of a certain element.
verifyTable
2
Compares the contents of a table with expected values.
waitForPageToLoad
1
Pauses execution until the page is loaded completely.
waitForElementPresent
1
Pauses execution until the specified element becomes present.

Selenium IDE Assertion


There are 3 Types of Assertions
l  Assert. When an "assert" command fails, the test is stopped immediately.
l  Verify. When a "verify" command fails, Selenium IDE logs this failure and continues with the test execution.
l  WaitFor. Before proceeding to the next command, "waitFor" commands will first wait for a certain condition to become true

Selenium Webdriver


l  It is an API that’s easy to explore and understand, which help us to make our tests easier to read and maintain
l  Supports dynamic web pages where element of a Page may change without the Page itself being reloaded
l  Web Driver is a compact Object Oriented API which can directly interacts with the Application under tests.
l  WebDriver utilizes the browser native compatibility to automation without using any peripheral entity.
l  Selenium-WebDriver supports multiple browsers in multiple platforms
        Google Chrome 12.0.712.0+
        Internet Explorer 6+
        Firefox 3.0+
        Opera 11.5+
        Android – 2.3+ for phones and tablets
        iOS 3+ for phones
        iOS 3.2+ for tablets

Selenium WebDriver 3.0 Architecture Diagram



Instantiating Selenium WebDriver object in Java\C#


Firefox Browser
IWebDriver driver = new  FirefoxDriver(@"C:\Path for geckodriver exe\");
Chrome Browser
IWebDriver driver = new ChromeDriver(@"C:\Path for chrome exe\");
Internet Browser
IWebDriver driver = new InternetExplorerDriver(@"C:\Path for IE exe\");
Not the Selenium executable for above drivers are available in seleniumhq website mentioned in next slide. Download the executable and unzip it.  

Downloading Browser executable


Download browse's executable from below link for Firefox, Chrome, IE:

WebDriver methods to –


Launching a Page e.g. driver.Url = "http://www.google.co.in";
       Locating UI Elements (WebElements)
        FindElement(By arg)
        FineElements(By arg)
        Both methods of WebDriver object are passing By object as parameter
        FindElement return single WebElement and FindElements return list of WebElement
        Example
WebDriver driver = new FirefoxDriver();
WebElement field = driver.FindElement(By.Id(“abc”));
List<WebElement> fields = driver.FindElements(By.TagName(“abc”));

How to locate an element using By class


By Id
         HTML:  <div id="coolestWidgetEvah">...</div>
WebDriver:
   driver.FindElement( By.Id("coolestWidgetEvah") );
By Name
       HTML: <input name="cheese" type="text"/>
WebDriver: driver.FindElement( By.Name("cheese") );
By.LinkText finds a link element by the exact text it displays
      driver.FindElement(By.LinkText("REGISTRATION"))  
By.ClassName finds elements based on the value of the "class" attribute
     driver.FindElement(By.ClassName("someClassName"))
By.TagName locates elements by their tag name
     driver.FindElement(By.TagName("div")) 
By.PartialLinkText locates elements that contain the given link text
     driver.FindElement(By.PartialLinkText("REG"))
By Xpath
HTML
                <html>
      <input type="text" name="example" />
      <input type="text" name="other" />
  </html>
WebDriver: 
      driver.FindElements( By.Xpath("//input") );
There are plug-ins for firefox/chrome to automatically display the Xpath
Syntax for Xpath : Xpath=//tagname[@attribute='value']
By.CssSelector finds elements based on the driver's underlying CSS Selector engine
      driver.FindElement(By.CssSelector("input#email"))

 

Sample Application

Selenium-WebDriver Test Script
       Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.IE;
namespace SeleniumTesting
{
    [TestFixture]
    class SeleniumIE
    {
        IWebDriver driver;
       
        [SetUp]
        public void StartBrowser()
        {
            driver = new InternetExplorerDriver(@"C:\Users\Hunza\SeleniumCsharp\SeleniumAutomation\");
        }
        [Test]
        public void Test()
        {
            driver.Manage().Window.Maximize();
            driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(25);
            driver.Url = "http://www.google.co.in";
            IWebElement field= driver.FindElement(By.Id("lst-ib"));
            field.Clear();
            field.SendKeys("Seleniumhq");
            IWebElement fieldButton = driver.FindElement(By.Name("btnK"));
            fieldButton.Click();
        }
        [TearDown]
        public void CloseBrowser()
        {
            driver.Close();
        }
    }
}


Selenium-WebDriver methods – control browser


l  Close() - close the browser window which the driver has focused
Syntax:                
driver.Close();
l  Quit() - close all the browser windows open by driver.
Syntax:                                
driver.Quit();
l  Url() retrun type String
Syntax:                                
String strurl = driver.Url();
l  Title() retrun type String
Syntax:
String strTitle =driver.Title();
l  CurrentWindowHandle()  return the web browser driver's reference ID
  Syntax:
  String strDriverReference = driver.CurrentWindowHandle();
l  WindowHandles()  return the reference ID of all the browser's window open by the driver.
  Syntax:
  List<String> strDriverReference = driver.WindowHandles();
l  Manage(): There below supporting methos used by the driver
l  driver.Manage().Cookies.AddCookie()
l  driver.Manage().Window.Maximize();
l  driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(25);
l  driver.Manage().Window.FullScreen();
l  Point point= driver.Manage().Window.Position;

       Navigate() is instance variable of Navigation interface
        driver.Navigate().Back();
         driver.Navigate().Forward();
        driver.Navigate().GoToUrl("");
SwitchTo() is instance variable of TargetLocator interface
        driver.SwitchTo().Window("windowRefrence");
        driver.SwitchTo().Alert().Accept();
        driver.SwitchTo().Alert().Dismiss();
        driver.SwitchTo().Alert().SendKeys("values");
        driver.SwitchTo().Frame(i);
        driver.SwitchTo().Frame(“frameName”);
        driver.SwitchTo().ParentFrame();
l  Text () - to read html tag value.
                driver.FindElement(By.Id("disp")).Text();
l  SendKeys (String values) - input value in text box
                driver.FindElement(By.id("inp1")).SendKeys("50000");
l  Click() - click a button or webElement
                driver.FindElement(By.TagName("button")).Click()
l  GetAttribut(String attributname) – get the html tag's attribute value       
                                driver.FindElement(By.TagName("button")).GetAttribute("class")
l  TagName() - get the html tag name (input/button/select)
                                driver.FindElement(By.Id("inp1")).TagName()
l  Displayed()/ Enabled()/ Selected() - verify the displayed/enabled/selected status of html tags

Example One (Loan Calculator)

using System;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
namespace SeleniumTesting
{
    [TestFixture]
    class SeleniumTestOne
    {
        IWebDriver driver;
        [SetUp]
        public void StartBrowser()
        {
            driver = new ChromeDriver(@"C:\Users\Hunza\SeleniumCsharp\SeleniumAutomation\");
            driver.Manage().Window.Maximize();
            driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(25);
        }
        [Test]
        public void Test()
        {
            driver.Url = "file:///C:/Users/Hunza/KM/Selenium/Application/SeleniumExampleSite.html";
            IWebElement listOfCars = driver.FindElement(By.Id("cars"));
            SelectElement selectObject = new SelectElement(listOfCars);
            selectObject.SelectByText("Santro");
            driver.FindElement(By.Id("inp1")).SendKeys("50000");
            driver.FindElement(By.Id("inp2")).SendKeys("10");
            driver.FindElement(By.Id("inp3")).SendKeys("10");
            driver.FindElement(By.TagName("button")).Click();
            String strValue = driver.FindElement(By.Id("disp")).Text;
            String strValue2 = selectObject.SelectedOption.Text;
            Assert.AreEqual("5000", strValue);
            Assert.AreEqual("Santro", strValue2);
        }
        [TearDown]
        public void CloseBrowser()
        {
            driver.Close();
        }
    }
}


How to handle Alert in Selenium WebDrive

Alert interface provides the below few methods which are widely used in Selenium Webdriver.
1) void Dismiss() // To click on the 'Cancel' button of the alert.
driver.SwitchTo().Alert().Dismiss();
2) void Accept() // To click on the 'OK' button of the alert.
driver.SwitchTo().Alert().Accept();
3) String Text() // To capture the alert message.
String strText= driver.SwitchTo().Alert().Text;
4) void SendKeys(String stringToSend) // To send some data to alert box.
driver.SwitchTo().Alert().SendKeys("Text");
5) void SetAuthenticationCredentials(String user, String password) // To send used id and password to alert box.
driver.SwitchTo().Alert().SetAuthenticationCredentials("Ali", "123456");

Example Three (Verify Alert message)

using System;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Remote;
namespace SeleniumTesting
{
    [TestFixture]
    class SeleniumTestThree
    {
        IWebDriver driver;
        IAlert alert;
        [SetUp]
        public void StartBrowser()
        {
            driver = new InternetExplorerDriver(@"C:\Users\Hunza\SeleniumCsharp\SeleniumAutomation\");
            driver.Manage().Window.Maximize();
            driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(25);
        }

        [Test]
        public void Test()
        {
            driver.Url = "file:///C:/Users/Hunza/KM/Selenium/Application/SeleniumExampleSite.html";
            driver.FindElement(By.Id("bt2")).Click();
            alert = driver.SwitchTo().Alert();
            alert.Accept();
            String message = driver.FindElement(By.Id("demo")).Text;
            Assert.AreEqual("Hello Harry Potter! How are you today?", message);
            driver.FindElement(By.Id("bt2")).Click();
            alert = driver.SwitchTo().Alert();
            alert.Dismiss();
            message = driver.FindElement(By.Id("demo")).Text;
            Assert.AreEqual("User cancelled the prompt.", message);
        }
        [TearDown]
        public void CloseBrowser()
        {
            driver.Close();
        }
    }
}


Locating Object using Xpath:


Xpath: XPath is defined as XML path. XPath is used to find the location of any element on a webpage using HTML DOM structure.

      

  (*) is default tagName in Xpath = //div[1]/*[@id='bt1']
 TagName can be any html tag like button, input, select, div, p etc.
 attributes like id , name, classname, class, type, tooltip, value etc
       

Locating Object using Xpath:


Xpath functions:
1. contains(): to find element with partial text. It used when value changed dynamically.   xpath=//*[contains(@type,'sub')]
                                                                                example: //*[contains(@id, 'bt')]
2. type(): to find element with exact text match. It used when value is fixed
                                                                xpath=//tabName[text()='value'],
                                                                example: //*[text()='Click for Alert']
3. start-with(): to find element matching with starting characters
                                                                xpath=//tabName[starts-with(@attribut,'start value')]
                                                                example:  //*[starts-with(text(),'Loan')]
4. AND & OR operators
                                                                xpath=//tabName[@attribut1='value1' AND @attribut2='value2']
                                                                xpath=//tabName[@attribut1='value1' OR @attribut2='value2']
5. following: Selects all the elements in the document following current node
                                                                xpath=//tabName1[@attribut='value']//following::tabName2
                                                                //*[@type='textbox']//following::button
                                                                //*[@type='textbox']//following::button[2]
6. preceding: Selects all the elements in the document preceding current node
                                                                xpath=//tabName1[@attribut='value']//preceding::tabName2
7. ancestor: selects all ancestors element (grandparent, parent, etc.) of the current node
                                                                xpath=//tabName1[@attribut='value']//ancestor::tabName2
8. descendant: selects all descendant elementsof the current node
                                                                xpath=//tabName1[@attribut='value']//descendant::tabName2
9. child: selects all child element of the current node
                                                                xpath=//tabName1[@attribut='value']//child::tabName2
                                                                //select//child::*

Locating Object using cssSelector:


cssSelector: CSS Selectors are string patterns used to identify an element based on a combination of HTML tag, id, class, and attributes.
  1. Tag and ID: syntax -  tag#id
  2. Tag and Class: syntax - tag.class
  3. Tag and Attribute: syntax - tag[attribute=value]
  4. Tag, class, and attribute: - tag.class[attribute=value]
  5.  Inner text: - tag:contains("inner text")

Wait in Selenium

Why do we required wait in Selenium?
 Most of the web applications are developed using Ajax and Javascript. When a page is loaded by the browser the elements which we want to interact with may load at different time intervals.
  It makes difficult to identify the element on web page, also it will throw an "ElementNotVisibleException" exception during the automation script execution which result in fail the script. To resolve the issue we use following types of wait in selenium.
l  Implicit Wait
l  Explicit Wait

Implicit wait
Implicit wait – An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.
     Webdriver wait for specified amount of time before it throws exception “NoSuchElementFoundException”
    driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(25);
    driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(25);
The TimeSpan can be in FROMMICROSECONDS, FROMMINISECONDS, SECONDS, FROMMINUTES, FROMHOURS or FROMDAY 

Explicit Wait
Explicit wait – WebDriver wait for certain condition to occur before proceeding further in combination of WebDriverWait and .Until(Your Condition) method became true.
There are some convenience methods provided that help you write code that will wait only as long as required.
WebDriver driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(25));
            Func<IWebDriver, bool> waitForElement = new Func<IWebDriver, bool>((IWebDriver Web) =>
            {
              Console.WriteLine(Web.FindElement(By.Id("target")).GetAttribute("innerHTML"));
                return true;
            });
wait.Until(waitForElement);

Keyboard & Mouse event using Action Class


Selenium has provided Action interface and Actions class to perform complex mouse and  keyboard events. The following are the most commonly used keyboard and mouse events provided by the Actions class
API Reference:                 OpenQA.Selenium.Interactions.Action;
OpenQA.Selenium.Interactions.Actions;
Method
Description
ClickAndHold()
Clicks (without releasing) at the current mouse location
MoveToElement(toElement)
Moves the mouse to the middle of the element
MoveByOffset(x-offset, y-offset)
Moves the mouse from its current position (or 0,0) by the given offset.
DragAndDrop(source, target)
Performs click-and-hold at the location of the source element, moves to the location of the target element, then releases the mouse.
ContextClick()
Performs a context-click at the current mouse location.
DoubleClick()
Performs a double-click at the current mouse location
Release()
Releases the depressed left mouse button at the current mouse location
Build()
Generates a composite action containing all actions so far, ready to be performed 
Perform()
A convenience method for performing the actions without calling build() first.
KeyDown() & KeyUp()

Example 1:
                WebDriver  driver = new FirefoxDriver();
                driver.get(“www.google.com”)
                 WebElement field=driver.findElement(By.id(“lst-ib”));
                Actions action = new Actions(driver);
                Action act=         action.moveToElement(field).build();
                act.perform()
                                                Or
                action.moveToElement(field).build().perform;
                                                Or
                action.moveToElement(field).perform;




Handling Ajax call in Selenium

AJAX stands for Asynchronous JavaScript & XML, and it allows the Web page to retrieve small amounts of data from the server without reloading the entire page.
To test Ajax application, different wait methods should be applied
       ThreadSleep
       Implicit Wait
       Explicit Wait

Taking Screen shots

API: org.openqa.selenium.TakesScreenshot;
Taking Screenshot in Selenium is a 3 Step process
Step 1) Convert web driver object to TakeScreenshot
                                TakesScreenshot scrShot =((TakesScreenshot)webdriver);
Step 2) Call getScreenshotAs method to create image file
                                File SrcFile=scrShot.getScreenshotAs(OutputType.FILE);
Step 3) Copy file to Desired Location
                                File DestFile=new File(fileWithPath);
                                FileUtils.copyFile(SrcFile, DestFile);

Dynamic Web Table

Static Table: Where the number of rows and columns are fixed
Dynamic Table: Where the number of rows or columns are not fixed
Example Link:
Reading number of columns:
List<WebElement> cols = driver.findElements(By.xpath("//*[@id="leftcontainer"]/table/thead/tr/th“));
cols.size();
Reading number of rows:
List<WebElement> rows= driver.findElements(By.xpath("//*[@id="leftcontainer"]/table/tbody/tr/td[1]“));
rows.size();

 

Nunit Suite

l  [Suite]
l  The Suite Attribute is used to define subsets of suites based on user preference.
l  Example:
namespace NUnit.Tests
{
  using System;
  using NUnit.Framework;
  public class AllTests
  {
    [Suite]
    public static TestSuite Suite
    {
      get
      {
        TestSuite suite = new TestSuite("All Tests");
        suite.Add(new OneTestCase());
        suite.Add(new Assemblies.AssemblyTests());
        suite.Add(new AssertionTest());
        return suite;
      }
    }
  }
}





Order Attribute in Nunit

       The OrderAttribute may be placed on a test method or fixture to specify the order in which tests are run. Ordering is given by the required order argument to the attribute, an int.
public class MyFixture
{
    [Test, Order(1)]
    public void TestA() { ... }
    [Test, Order(2)]
    public void TestB() { ... }
    [Test]
    public void TestC() { ... }
}
l  Tests with an OrderAttribute argument are started before any tests without the attribute.
l  Ordered tests are started in ascending order of the order argument.
l  Among tests with the same order value or without the attribute, execution order is indeterminate.
l  Tests do not wait for prior tests to finish. If multiple threads are in use, a test may be started while some earlier tests are still being run.

Desired Capabilities

Desired capability is a series of value or key pairs that stores the web browser properties such as browser name, browser version, the path of the browser in the system etc which will help to determine the behavior of the browser at run time.
Different types of Desired Capabilities Methods:
l  getBrowserName()
l  setBrowserName()
l  getVersion()
l  setVersion()
l  getPlatform()
l  setPlatform()
l  getCapability
l  SetCapability
The setCapability() method of the Desired Capabilities class can be used to set the device name, platform version, platform name, absolute path of the app under test
Import org.openqa.selenium.WebDriver;
Import org.openqa.selenium.ie.InternetExplorerDriver;
Import org.openqa.selenium.remote.DesiredCapabilities;
public class IEtestforDesiredCapabilities {
 
public static void main(String[] args) {
//it is used to define IE capability
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
 
capabilities.setCapability(CapabilityType.BROWSER_NAME, "IE");
capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
System.setProperty("webdriver.ie.driver", "C:\\IEDriverServer.exe");
 
 //it is used to initialize the IE driver
 WebDriver driver = new InternetExplorerDriver(capabilities);
 
 driver.manage().window().maximize();
 driver.get("http://gmail.com");
 
 driver.quit();
 }
 
}


C# Introduction

       C# is object oriented programming language. It provides a lot of features that are given below.


C# program window










No comments:

Post a Comment