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)



Thursday 27 October 2016

Http get with authenticaion using C# dot net

 protected void Page_Load(object sender, EventArgs e)
        {
            string url = "http://jira.company.com/rest/api/latest/issue/REL-461.json";
            WebClient client = new WebClient();
            String userName = "email@Comp.com";
            String passWord = "PWD";

            client.Credentials = new System.Net.NetworkCredential(userName, passWord);

            var result = client.DownloadString(url);

            Response.Write(result);
        }

Friday 5 August 2016

First Gradle project | IntellJ

Gradle is one more tool for build management besides ANT, Maven etc.

Below are the steps to configure for the first time.


Download and Configuration:

Gradle is downloadable as a zip file at http://www.gradle.org/downloads.

Only the binaries are required, so look for the link to gradle-version-bin.zip.

Unzip the file to your computer, and add the bin folder to your path.



Testing:

From the command-line:

> gradle

You will get ‘BUILD SUCCESSFUL’

If you are still not able to see ‘Gradle’ option in Intellij


Run below command.

>gardle init




First Gradle project:

Open IntelliJ idea – File – New – Project



Choose Gradle from left panel and select Java Checkbox.

Key in GroupId and ArtifactID.



Select below 3 options for easy configuration:

-          -Use Auto Import
-         - Create Directories for empty content roots automatically
-         - Use local gradle distribution




Choose appropriate project name and location.

Click on FINISH button.

Takes few minutes to create initial gradle project.







If you see any issues reg importing gradle dependencies,

File - settings - Build,Execution,Deployment - Gradle - Uncheck 'offline work'



Thats all.





Thursday 21 July 2016

Acceptance testing Framework: concordion


Acceptance testing Framework: concordion

“Next gen BDD”

Concordion lets you write tests in normal language use in paragraphs , tables and proper punctuations.

Tests are written in html and then instrumented with special attributes that concordion interprets to execute the test

Intro:
Concordion is a Java library that allows to bind an HTML document to methods in a Fixture - a Java class that does various binding work. When you execute that specification, it generates an HTML output of what has been tested, with errors in red and ‘test ok’ in green.

Sample Project:

https://github.com/kasthurikranthikumar/concordion.git





Tuesday 19 July 2016

Selenium to Selenide Transition



1. Create a browser

Selenium WebDriver:
DesiredCapabilities desiredCapabilities = DesiredCapabilities.htmlUnit();
desiredCapabilities.setCapability(HtmlUnitDriver.INVALIDSELECTIONERROR, true);
desiredCapabilities.setCapability(HtmlUnitDriver.INVALIDXPATHERROR, false);
desiredCapabilities.setJavascriptEnabled(true);
WebDriver driver = new HtmlUnitDriver(desiredCapabilities);

Selenide:
open("/my-application/login");
// And run tests with option -Dbrowser=htmlunit (or "chrome" or "ie", default value is "firefox")


2. Shutdown a browser
Selenium WebDriver:
if (driver != null) {
    driver.close();
}
Selenide:
// Do not care! Selenide closes the browser automatically.

3. Find element by id
Selenium WebDriver:
WebElement customer = driver.findElement(By.id("customerContainer"));
Selenide:
WebElement customer = $("#customerContainer");
or a longer conservative option:
WebElement customer = $(By.id("customerContainer"));

4. Assert that element has a correct text
Selenium WebDriver:
assertEquals("Customer profile", driver.findElement(By.id("customerContainer")).getText());

Selenide:
$("#customerContainer").shouldHave(text("Customer profile"));

5. Ajax support (waiting for some event to happen)
Selenium WebDriver (OMG!):
FluentWait<By> fluentWait = new FluentWait<By>(By.tagName("TEXTAREA"));
fluentWait.pollingEvery(100, TimeUnit.MILLISECONDS);
fluentWait.withTimeout(1000, TimeUnit.MILLISECONDS);
fluentWait.until(new Predicate<By>() {
    public boolean apply(By by) {
        try {
            return browser.findElement(by).isDisplayed();
        } catch (NoSuchElementException ex) {
            return false;
        }
    }
});
assertEquals("John", browser.findElement(By.tagName("TEXTAREA")).getAttribute("value"));
Selenide:
$("TEXTAREA").shouldHave(value("John"));
This command automatically waits until element gets visible AND gets expected value.
Default timeout is 4 seconds and it's configurable.

6. Assert that element has a correct CSS class
Selenium WebDriver:
assertTrue(driver.findElement(By.id("customerContainer")).getAttribute("class").indexOf("errorField") > -1);
Selenide:
$("#customerContainer").shouldHave(cssClass("errorField"));

7. Find element by text
Selenium WebDriver:
No way (except XPath)
Selenide:
WebElement customer = $(byText("Customer profile"));

8. Assert that element text matches a regular expression
Selenium WebDriver:
WebElement element = driver.findElement(By.id("customerContainer"));
assertTrue(Pattern.compile(".*profile.*", DOTALL).matcher(element.getText()).matches());

Selenide:
$("#customerContainer").should(matchText("profile"));

9. Assert that element does not exist
Selenium WebDriver:
try {
    WebElement element = driver.findElement(By.id("customerContainer"));
    fail("Element should not exist: " + element);
}
catch (WebDriverException itsOk) {}
Selenide:
$("#customerContainer").shouldNot(exist);

10. Looking for element inside parent element
Selenium WebDriver:
WebElement parent = driver.findElement(By.id("customerContainer"));
WebElement element = parent.findElement(By.className("user_name"));
Selenide:
$("#customerContainer").find(".user_name");

11. Looking for Nth element
Selenium WebDriver:
WebElement element = driver.findElements(By.tagName("li")).get(5);
Selenide:
$("li", 5);

12. Click "Ok" in alert dialog
Selenium WebDriver:
    try {
      Alert alert = checkAlertMessage(expectedConfirmationText);
      alert.accept();
    } catch (UnsupportedOperationException alertIsNotSupportedInHtmlUnit) {
      return;
    }
    Thread.sleep(200); // sometimes it will fail
Selenide:
    confirm("Are you sure to delete your profile?");
or
    dismiss("Are you sure to delete your profile?");
13. Debugging info for elements
Selenium WebDriver:
    WebElement element = driver.findElement(By.id("customerContainer"));
    System.out.println("tag: " + element.getTag());
    System.out.println("text: " + element.getText());
    System.out.println("id: " + element.getAttribute("id"));
    System.out.println("name: " + element.getAttribute("name"));
    System.out.println("class: " + element.getAttribute("class"));
    System.out.println("value: " + element.getAttribute("value"));
    System.out.println("visible: " + element.isDisplayed());
    // etc.
Selenide:
    System.out.println($("#customerContainer"));
    // output looks like this: "<option value=livemail.ru checked=true selected:true>@livemail.ru</option>"

14. Take a screenshot
Selenium WebDriver:
    if (driver instanceof TakesScreenshot) {
      File scrFile = ((TakesScreenshot) webdriver).getScreenshotAs(OutputType.FILE);
      File targetFile = new File("c:\temp\" + fileName + ".png");
      FileUtils.copyFile(scrFile, targetFile);
    }
Selenide:
    takeScreenShot("my-test-case");
For JUnit users it's even more simpler:
    public class MyTest {
      @Rule // automatically takes screenshot of every failed test
      public ScreenShooter makeScreenshotOnFailure = ScreenShooter.failedTests();    }
15. Select a radio button
Selenium WebDriver:
    for (WebElement radio : driver.findElements(By.name("sex"))) {
      if ("woman".equals(radio.getAttribute("value"))) {
        radio.click();
      }
    }
    throw new NoSuchElementException("'sex' radio field has no value 'woman'");
Selenide:
    selectRadio(By.name("sex"), "woman");

16. Reload current page
Selenium WebDriver:
    webdriver.navigate().to(webdriver.getCurrentUrl());
Selenide:
    refresh();

17. Get the current page URL, title or source
Selenium WebDriver:
    webdriver.getCurrentUrl();
    webdriver.getTitle();
    webdriver.getPageSource();
Selenide:
    url();
    title();

    source();

My first program with Selenide:


Create a Maven project.

Add selenium-java client dependencies in pom.xml

Add TestNG or JUnit dependencies in pom.xml

And finally Selenide dependencies

<dependency>
    <groupId>com.codeborne</groupId>
    <artifactId>selenide</artifactId>
    <version>3.7</version>
    <scope>test</scope>
</dependency>


Add a simple TestNG/ Junit class

import static com.codeborne.selenide.Selenide.*;
import static com.codeborne.selenide.Condition.*;
public class Test
{
@Test
public void userCanLoginByUsername() {
  open("/login");
  $(By.name("user.name")).setValue("johny");
  $("#submit").click();
  $(".loading_progress").should(disappear); 
  $("#username").shouldHave(text("Hello, Johny!")); 
}
}
 


Just Run it.