Thursday, 8 December 2016

selenium quick tutorial

Tool Selection:
Before finalizing automation tool we should consider below points
Ease of usage
Quick Support
Technology support
Cost
Compatible with different browsers and operating systems

Selenium is open source WEB automation testing tool.
Technologies: java , c#, Ruby, Python, PHP
Browsers: ie, chrome, Firefox, opera, safari
OS: win, max, Linux, Unix

Selenium components:
IDE, RC, WebDriver 2.0, Web Driver 3.0, Grid
IDE: add-on Firefox browser. For record and play back only. With the help of user extensions, we can improve functionality. Supports conditional, iterative, regex. Tests can be parameterized using IDE
RC: (1.0 ), supports multiple browsers, supports most of the programming languages
WD: (2.0, 3.0) : eliminated drawbacks in RC ( by eliminating server ). We can make direct calls to the browser using various drivers available. Supports mobile testing
GRID: to run tests parallel on different machines at a time

Advantages:
Free and open source
Multi browser and OS support
Parallel execution
Mobile testing
IDE – record and play back for quick automation evaluation
Continuous integration support
Easy framework development (data, keyword, hybrid, POM, PF )
Support for testing, junit etc

Capabilities:
Capabilities are options that you can use to customize and configure a Browser Driver session. 

Chrome:


DesiredCapabilities capabilities = DesiredCapabilities.chrome();
// Add the WebDriver proxy capability.
Proxy proxy = new Proxy();
proxy.setHttpProxy("myhttpproxy:3337");
capabilities.setCapability("proxy", proxy);

// Add ChromeDriver-specific capabilities through ChromeOptions.
ChromeOptions options = new ChromeOptions();

options.addExtensions(new File("/path/to/extension.crx"));//browser extensions
options.addArguments("start-maximized");//start chrome maximised
options.setBinary("/path/to/other/chrome/binary");// chrome.exe file path, if multiple verions available
options.addArguments("user-data-dir=/path/to/your/custom/profile");//By default, ChromeDriver will create a new //temporary profile for each session. At times you may want to set special preferences or just use a custom //profile altogether

capabilities.setCapability(ChromeOptions.CAPABILITY, options);
ChromeDriver driver = new ChromeDriver(capabilities);
--OR--
RemoteWebDriver driver = new RemoteWebDriver(
     new URL("http://localhost:4444/wd/hub"), capabilities);


Internet Explorer:
Set below browser options



DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
 
capabilities.setCapability(CapabilityType.BROWSER_NAME, "IE");
capabilities.setCapability(InternetExplorerDriver.
  INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);

capabilities.setCapability(InternetExplorerDriver.INITIAL_BROWSER_URL, "https://testvmm6.partnersonline.com/vmm");
capabilities.internetExplorer().setCapability("ignoreProtectedModeSettings", true);

capcapabilities.setCapability("IE.binary", "C:/Program Files (x86)/Internet Explorer/iexplore.exe");
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
capabilities.setJavascriptEnabled(true);
capabilities.setCapability("requireWindowFocus", true);
capabilities.setCapability("enablePersistentHover", false);

System.setProperty("webdriver.ie.driver", "C:\\IEDriverServer.exe");//32 bit driver is good

WebDriver driver = newInternetExplorerDriver(capabilities);


Navigation methods:
Driver.get(“url”)
Driver.getTitle()
Driver.getCurrentURl()
Driver.getPageSource()
Driver.close()//closes current browser
Driver.quit()//closes all browsers under the driver
Driver.navigate().to(“url”)
Driver.navigate().forward()
Driver.navigate().back()
Driver.navigate().refresh()

Locators:
Common web elements are TextBox, Button, DropDown, Anchor Tag, ChecBox, Radio Button.
We can locate elements using ID, class name, Name, link text, xpath, css selector ( id, class, attribute, substring, Innter text )

<input id=”myId” name=”name1” class=”class1” title=”sample toot tip”/>
<a>help</a>

ID: Driver.findElement(By.id(“myId”))
Name: Driver.findElement(By.name(“name1”))
Class: Driver.findElement(By.class(“class1”))
linkText: Driver.findElement(By.LinkText(“Help”))
Xpath: Driver.findElement(By.xpath(“//intput[@title=’sample tool tip’]”)
Tagname: Driver.findElement(By.tagName(“input”))
cssSelector: driver.findElement(By.css(‘#myId’))

FindElement vs FindElements
WebElement ele = Drive.findElement(By.id(“#myId”)) // returns only one element
List<WebElemen> list = Driver.findElements(By.tagName(“input”))// returns list of elements

Events:
Common web element interactions are
Click(), clear(), sendKeys(“”), isDispalyed(), isSelected() ( applicable for check box and Radio button ) ,getText().getAttribute(“attr”), getSize(), getLocation() ( returns X and Y co-ordinate )

Synchronization ( webDriver waits):
Implicit wait: wait is applicable for all the elements under the driver object.
Wait for all the elements maximum 10 seconds if not available by default.
If element found, skips the wait time.
Driver.manage().timeouts.implicitWait(10,TimeUnits.SECONDS)
Explicit Wait : wait is applicable for only one element under the driver object.
We can specify explicit waiting conditions for any element so that our test should pass.
Ex: wait for this element until this element is clickable , upto maximum 55 seconds.
If element found, skips the wait time.
Few expected conditions are below:
elementToBeClickable()
textToBePresentInElement()
alertsPresent()
Titles()
framToBeAvaialbeAndSwitchToIt()

Actions Class:
Helps to handle keyboard and mouse events ( ex: drag and drop, selecting items holding Control key or alt key etc )


Actions builder=new Actions(driver);
        builder.moveToElement(username,150,22);
        builder.sendKeys("Mahesh");
        builder.perform();

Action seriesofactions=builder.moveToElement(username).click().keyDown(username,Keys.SHIFT).sendKeys(username,"hell").keyUp(username,Keys.SHIFT).doubleClick(username).contextClick(username).build();
       seriesofactions.perform();

clickAndHold()
release()
contextClick()
doubleClick()
dragAndDrop(source,target)
dragAndDropBy(source,x-offset,y-offset)
keyDown(modifier_key)
keyUp(modifier_key)
moveByOffset(x-offset, y-offset)
moveToElement(toElement)
sendKeys(onElement, charSequence)


Screen capture:
If we wanted to take screen shot of current browser, here is the way

WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy somewhere
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));

Switch to :
Here is the code to switch to new browser and and close it and switch back to original browser.
// Store the current window handle
String winHandleBefore = driver.getWindowHandle();
// Perform the click operation that opens new window
// Switch to new window opened
for(String winHandle : driver.getWindowHandles()){
    driver.switchTo().window(winHandle);
}
// Perform the actions on new window
// Close the new window, if that window no more required
driver.close();
// Switch back to original browser (first window)
driver.switchTo().window(winHandleBefore);
// Continue with original browser (first window)

Alerts:
Below is the code for accepting alert box and getting alert text

String alertText = "";
WebDriverWait wait = new WebDriverWait(driver, 5);
// This will wait for a maximum of 5 seconds, everytime wait is used

driver.findElement(By.xpath("//button[text() = \"Edit\"]")).click();//causes page to alert() something

wait.until(ExpectedConditions.alertIsPresent());
// Before you try to switch to the so given alert, he needs to be present.

Alert alert = driver.switchTo().alert();
alertText = alert.getText();
alert.accept();

return alertText;


Wednesday, 7 December 2016

Setting up Jenkins in local Machine

Jenkins is a famous continuous integration tool which is used in the industry.

Step 1:  Lets create a simple maven project.

a.       Set maven and java paths in environment variables
JAVA_HOME=C:\Program Files\Java\jdk1.8.0_111
M2_HOME=D:\Personnel\Softwares\apache-maven-3.3.9
path=%M2_HOME%\bin;%JAVA_HOME%\bin;

Step 2: Create a maven project.
                Install eclipse and create a maven project
              

Pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
       <modelVersion>4.0.0</modelVersion>

       <groupId>com.google.com</groupId>
       <artifactId>google-test</artifactId>
       <version>0.0.1-SNAPSHOT</version>
       <packaging>jar</packaging>

       <name>google-test</name>
       <url>http://maven.apache.org</url>

       <properties>
              <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jre.level>1.8</jre.level>

<jdk.level>1.8</jdk.level>
       </properties>

       <dependencies>
              <!-- https://mvnrepository.com/artifact/org.testng/testng -->
              <dependency>
                     <groupId>org.testng</groupId>
                     <artifactId>testng</artifactId>
                     <version>6.9.13.6</version>
              </dependency>

       </dependencies>
<build>
<plugins>
<!-- Compiler plug-in -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${jdk.level}</source>
<target>${jdk.level}</target>
</configuration>
</plugin>
<!-- Below plug-in is used to execute tests -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<suiteXmlFiles>
<!-- TestNG suite XML files -->
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>

</build>
</project>


TestNg.xml

<suite name="Test">
       <test name="Test">
              <classes>
                     <class name="com.google.com.google_test.NewTest"></class>
              </classes>
       </test>
</suite>





Setup Jenkins:

1.       Download Jenkins war file  from https://jenkins.io/
2.       Strat Jenkins server; cmd>java –jar Jenkins.war
a.       Takes some time to deploy Jenkins in the local system
3.       Browse: localhost:8080
a.       Asks for admin password
b.       You can get it at c:\users\accoutnname\.jenkins\secrets\invalidAdminPassword
4.       Customize Jenkins
a.       Install Suggested plugins
5.       Now create Admin user
a.       Uname
b.       Password
c.       Confirm password
d.       Name
e.       Email


Create a new job in Jenkins:

Job name: First Job
Choose Freestyle project and say ok


Tab: General
Click on advanced, click on ‘use custom workspace’  and enter project directory

Tab: Build
Choose ‘execute windows batch command’

set JAVA_HOME=C:\Program Files\Java\jdk1.8.0_111
set M2_HOME=D:\Personnel\Softwares\apache-maven-3.3.9
set path=%M2_HOME%\bin;%JAVA_HOME%\bin;%path%
mvn clean test



save it.

This is how it looks like.



Just run it. ( click on build now)