Friday, September 1, 2017

Selenium Python Object Repository - Using Lambda

in the last post I discussed how to create object repository using decorator. if you haven't read the post, please read it here

I am going to take the same example to demonstrate how to use lambda (anonymous function).

from selenium import webdriver
from selenium.webdriver.common.by import By


class TestGoogle(object):
    
    search_input = lambda self: self.find_element(By.NAME, "q")

    def test_search(self):
        self.driver = webdriver.Firefox()
        self.driver.get("https://google.com")
        self.search_input().send_keys("selenium python")
Pros of Using
  • all the elements are in one place in the file (class), so if any element change it's easy and fast
  • it's a function, so every time a object would be created, you should never get StaleElementRefereceException
Cons of Using
  • You will have to keep in mind it's a function not a variable
  • Every time a new object would be created, so it could be a overhead.

Thursday, August 24, 2017

Selenium Python Object Repository - Using decorator

In the series of posts I will try to explain how to create the object repository when you are writing selenium tests using python. There are different ways, few more simple than others but finally it's upto you which to use and how to use it.

Java has PageFactory which allows a nicer, cleaner way to create WebElement object repository.  It doesn't actually creates the object it's just do the lazy initialization. which means the first time you do some action on this object and it's actually created.

I wanted to something like this Python, I searched it but didn't find any satisfactory answer. and So I write my own code.  It look similar to how you initialize the object in Java, however, it's different in few aspects. For one it doesn't actually do the lazy initialization, however it creates the new object every time you do some action on it.  However, it has advantages as well.

Remember,  StaleElemementReferenceException, it's very less likely you will get this as it creates new object every time.

For this I am using Decorator, if don't know what is decorator, it's simply a function which takes a function as a input and returns you a brand new function. However, I would advice you to read more about this.

Now let's just to code.


Without Object Repository


class TestGoogle(object):

    def test_search(self):
        self.driver = webdriver.Firefox()
        self.driver.get("https://google.com")
        self.driver.find_element_by_name("q").send_keys("selenium")

And now, with Object Repository
class TestGoogle(object):

    @FindBy(By.NAME, "q")
    def search_input(self): pass

    def test_search(self):
        self.driver = webdriver.Firefox()
        self.driver.get("https://google.com")
        self.search_input().send_keys("selenium python")

If you have noticed, search_input is a function and not a variable. The reason for this is, Python don't have a decorator for variable, at least yet.  And so you need to call the function which will give you a WebElement object on which you can do multiple actions. 

Tuesday, February 21, 2017

PyTest with Selenium - HTML report with Screenshot

recently I was working with Py.Test with selenium. It's really powerful tool with awesome fixtures. It generates JUnit XML report as well which is good to be consumed by Jenkins. However, I needed an HTML report as well with embedded screenshot for the ease of identifying the issue. And this is how I did it finally after doing some googling.

Generate HTML Report of PyTest 

Pytest-html plugin is available which you can use to generate the beautiful Report. The all you have to do is install the plugin and run your test case with this plugin. 

Embede ScreenShot When Test Case Fails

PyTest-html plugin allows you to extend the plugin and that's the best thing about this plugin. 
conftest.py

from selenium import webdriver
import pytest
driver = None


@pytest.mark.hookwrapper
def pytest_runtest_makereport(item):
    """
    Extends the PyTest Plugin to take and embed screenshot in html report, whenever test fails.
    :param item:
    """
    pytest_html = item.config.pluginmanager.getplugin('html')
    outcome = yield
    report = outcome.get_result()
    extra = getattr(report, 'extra', [])

    if report.when == 'call' or report.when == "setup":
        xfail = hasattr(report, 'wasxfail')
        if (report.skipped and xfail) or (report.failed and not xfail):
            file_name = report.nodeid.replace("::", "_")+".png"
            _capture_screenshot(file_name)
            if file_name:
                html = '<div><img src="%s" alt="screenshot" style="width:304px;height:228px;" ' \
                       'onclick="window.open(this.src)" align="right"/></div>' % file_name
                extra.append(pytest_html.extras.html(html))
        report.extra = extra


def _capture_screenshot(name):
    driver.get_screenshot_as_file(name)


@pytest.fixture(scope='session', autouse=True)
def browser():
    global driver
    if driver is None:
        driver = webdriver.Firefox()
    return driver
test_screenshot.py
def test_screenshot_on_test_failure(browser):
    # driver = webdriver.Firefox()
    browser.get("https://google.com")
    assert False

Tuesday, March 29, 2016

linux java shows older version after upgrade

While working with Linux today I stumbled upon a weird problem, even after upgrading java to 1.8 it was showing 1.7 only.

And when I tried to install it again, it showed me following message.
sudo yum install java-1.8.0-openjdk.x86_64

Package 1:java-1.8.0-openjdk-1.8.0.71-2.b15.8.amzn1.x86_64 already installed and latest version

Nothing to do
Following command help me to figure out what's going wrong. 

Following command will show you all the java versions currently installed on your system, it will also show you which one is currently active.  If you need to change just provide the number and that would be activated. 

Command:
sudo update-alternatives --config java

Output:
There are 2 programs which provide 'java'.

  Selection    Command
-----------------------------------------------
 + 1           /usr/lib/jvm/jre-1.8.0-openjdk.x86_64/bin/java
*  2           /usr/lib/jvm/jre-1.7.0-openjdk.x86_64/bin/java

Enter to keep the current selection[+], or type selection number:

Friday, December 18, 2015

JVM Cucumber Hooks Part 1

As the name itself suggests hooks are used to hook any feature or scenario. In a simpler terms you can create a function and then hook that into any feature or scenario.

There are two types of hooks you can create.  Please not there ain't such categories, I have just divided them into following categories for better understanding.
  • Generic Hooks:  Hooks that executes before or after each and every scenario.
  • Specific Hooks: Hooks that executes before or after every specific(mentioned) scenario or feature. 

Now let's see how to implement this, for this I am going to use the same example I used in the last blog post. if you haven't read that yet, please visit it here. 

Generic Hooks

if you will check the code of the previous post, we were creating the driver object, in the class file as we had only one test case(scenario).  if we have multiple scenarios and we want to open new browser before each and every scenario and want to close after each and every scenario we can utilize the hooks.

In the following example, I am going to create a hook (setUp method) that will be called before each and every scenario. this method will open a firefox browser and will navigate to site home page. I will also create an another hook (tearDown method) which will be called after each and every scenario. This method will close the browser after each and every scenario.

Hooks.java
public class Hooks extends WebDriverManager{

    @Before
    public void setUp(){
        driver = new FirefoxDriver();
        wait = new WebDriverWait(driver, 30);
        driver.get("https://en.wikipedia.org");
        driver.manage().window().maximize();
    }

    @After
    public void tearDown(){
        driver.quit();
    }
}

WebDriverManager.java
public class WebDriverManager {
    public static WebDriver driver;
    public static WebDriverWait wait;
}

HomePage.java
public class HomePage extends WebDriverManager{
 
    @When("^I search \"(.*?)\"$")
    public void i_search(String arg1) throws Throwable {
        WebElement search_box = driver.findElement(By.id("searchInput"));
        search_box.sendKeys(arg1);
        search_box.submit();
    }

    @Then("^I should get \"(.*?)\" on page$")
    public void i_should_get_on_page(String arg1) throws Throwable {
        Assert.assertTrue(driver.findElement(By.xpath("//body")).getText().contains(arg1));
    }
}

wkipedia_search.feature
@Search
Feature: Verify WikiPedia Search

  @Regression @Functional
  Scenario: Verify Wikipdia for indirect posts-BDD
  When I search "BDD"
  Then I should get "Behavior-driven development" on page

  @Regression
  Scenario: Verify Wikipdia for indirect posts-TDD
  When I search "TDD"
  Then I should get "Test-driven development" on page

Tuesday, May 5, 2015

BDD (Cucumber) with Selenium Webdriver

In the following post I am going to explain how to setup cucumber on Java with selenium to use for Behavior Driven Development.

I am going to use IntelliJ for writing this test cases, however you can choose eclipse or any other IDE as well.

How to create project.

I have also hosted the demo project on GitHub you can access that using following link 


  • Go to File >> New >> Project and select Maven as shown in the screenshot
  • Provide GroupId and ArtifactID
  • Provide the Project Name, After this step, IntelliJ will create new project for you. 

  • Add Maven Dependencies.

    We need to add Cucumber, Selenium and JUnit dependencies to pom.xml. Open pom.xml and add the following code to it.

    <dependencies>
     <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>2.40.0</version>
     </dependency>
    
     <dependency>
      <groupId>info.cukes</groupId>
      <artifactId>cucumber-java</artifactId>
      <version>1.2.2</version>
     </dependency>
    
     <dependency>
      <groupId>info.cukes</groupId>
      <artifactId>cucumber-junit</artifactId>
      <version>1.2.2</version>
     </dependency>
    
     <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
    
     </dependency>
    </dependencies>
    

    Automating Your First Test case


    I am going to automate following test case for this BDD (Cucumber) demo
    1. Open wikipedia.com website 
    2. Search for BDD 
    3. Result page should contain Behavior-driven development text. 
    Now before we begin writing test cases, let's create proper packages. I have created the packages in following, however you can create the way you like. 

    Just make sure that all your code (directly or indirectly) is under test package. 

    The first thing we need to do, to write cucumber tests, is to convert existing test case into Gherkin Syntax.  In the resources folder create one package and inside this package create one feature file, mine is called wikipedia_search.feature however you can give the name you want. 

    Feature: Verify WikiPedia Search
    
      Scenario: Verify Wikipdia for indirect posts
      When I search "BDD"
      Then I should get "Behavior-driven development" on page
    

    Feature:, is a keyword through which you can specify which feature you are testing
    Scenario:, is a keyword though which you can specify of which scenario following test cases belong to
    Your test cases start after the scenario line. When specifies the step we need to perform and Then specifies the part we need to verify.

    Now the next thing we need to do is, implement this test cases and write selenium code for it. however before that you need to write a Java class which runs your test cases. Create a java class under test\java\com.gaurang package and paste the following code.

    Please create one file with following code
    @RunWith(Cucumber.class)
    @CucumberOptions(plugin={"pretty", "html:target/cucumber-html-report"})
    public class RunAllTests {
    
    }
    

    Now everything is in place, let's write the selenium code for Gherkin statement we wrote above. There are actually two way to do it.

    1. Run the file created in above step, and on the console you will be able to see something like below. copy this code and paste into the class file. 
    2. You can open the feature file and press ALT+Enter key combination, this will ask you to choose the file name and then it will create the empty implementation of all the steps in that file. 
    Once this is done, the only thing remain is to write corresponding selenium code. 

    Report: 

    Cucmber generates it's own HTML report, which look like this. 

    Cucumber HTML Report

    Tuesday, March 17, 2015

    Selenium WebDriver with Python

    In the following blog I will show you how to setup and write your first test case using Webdriver in Python Language.

    Install Python:

    If you are using Linux or Mac you need not do this as Python comes pre-installed on these OS. however if you are using windows (most of us do), Please follow the steps mentioned blow to install python on windows platform.
    • Download the Python from following location for your windows OS and install it.
      https://www.python.org/downloads/windows/
    • Once installed you need to set the following paths in your system PATH variable. (Python folder name may be depends on the version of the Python you have installed)
      • C:\Python27
      • C:\Python27\Scripts
    • Now, let's test if Python has installed or not. Open command prompt (CMD) and enter following command, if it shows you version number then python has successfully installed.
      python --version

    Now let's Install WebDriver for Python

    Installing WebDriver in python is different than installing in Java, actually Installing webdriver for Python is pretty simple.  To install WebDriver, Just open command prompt (CMD) and enter following command. 
    • pip install selenium

    First WebDriver Test in Python.

    test_google.py
    from selenium import webdriver
    import unittest
    
    class TestGoogle(unittest.TestCase):
    
        def setUp(self):
            self.driver = webdriver.Firefox()
            self.driver.get("https://google.com")
    
        def tearDown(self):
            self.driver.quit()
    
        def test_search(self):
            search_edit_box = self.driver.find_element_by_name("q")
            search_edit_box.send_keys("webdriver with python")
            search_edit_box.submit()
    
    if __name__ == '__main__':
        unittest.main()

    Now let's see How to run Above Webdrive Test

    • First of all copy above file and paste it in any file and save as test_google.py
    • Open command prompt (CMD) and navigate to folder where you have stored this file. 
    • Now run the following command
      python test_google.py


    Friday, October 3, 2014

    Alternative to Setup and TearDown - Python Decorators

    I recently designed a Automation Framework using Selenium Webdriver and Python. Everything was working fine until few days back when we realized that we have some test cases which verifies back-end and doesn't require browser to be opened. I never knew this while I was designing the framework, and so I  wrote one common Setup and Teardown, now problem is it opens the browser and does so many other stuffs even for the test cases which doesn't require it.

    So, I came up with solution, I wrote down two decorators, one for UI test cases and one for backend test cases.

    Following is the code.

    import traceback
    import unittest
    from selenium import webdriver
    
    
    class AppManager(unittest.TestCase):
    
        def setup_func(self, url):
            self.driver = webdriver.Firefox()
            self.driver.maximize_window()
            if url is not None:
                self.driver.get("http://google.com")
    
        def teardown_func(self):
            self.driver.close()
    
        @staticmethod
        def gui_test(url=None):
            def wrapper(func):
                def deco_func(self):
                        #Setup
                        self.setup_func(url)
                        #Your Test case
                        try:
                            func(self)
                        except Exception as e:
                            print traceback.print_exc()
                            self.teardown_func()
    
                        self.teardown_func()
                        #TearDown
                return deco_func
            return wrapper
    
        @staticmethod
        def backend_test(func):
            def deco_func(self):
    
                #Setup
                #TODO add setup stpes
    
                #Your Test case
                func(self)
    
                #TearDown
                #TODO Add teardown steps
            return deco_func

    How to use this decorator


    class Demo(AppManager):
        
        @AppManager.gui_test(url="http://www.google.com")
        def test_setup(self):
            #self.driver.get("http://google.com")
            search_editbox =self.driver.find_element_by_name("q").submit()
            search_editbox.send_keys("gaurang")
            search_editbox.submit()

    Sunday, July 27, 2014

    WebDriver with Python using Splinter and Nose

    Till now I have been writing all my post in java, However after spending almost an year in python, Why not I write post in python. So here is my first post about how to use WebDriver in Python. If you are reading this please don't forget to put the comment.

    I have used two frameworks for writing Webdriver tests in Python

    Splinter:
    Splinter is basically a wrapper around the Webdriver API, which ease you to write code as compared to webdriver.

    For example if you have to fill a form with web driver, your code might look
    elem = browser.find_element.by_name('username')
    elem.send_keys('janedoe')

    However, if you use splinter, it will look like this
    browser.fill('username', 'janedoe')

    Better, Aint't it ?

    Nose:
    Nose is an unit testing framework extended from python unittest. As I told you it's extended from unittest which mean it provides all the features provided by unittest plus few more

    Enough of theory, let's see the code.


    from nose.tools import assert_true
    
    __author__ = 'Gaurang_Shah1'
    
    
    import unittest
    import splinter
    
    
    class GoogleTest(unittest.TestCase):
    
        def setUp(self):
            self.browser = splinter.Browser()
    
        def tearDown(self):
            self.browser.quit()
    
        def test_google_search(self):
            google = GooglePage(self.browser)
            google.search('splinter - python acceptance testing for web applications').verify_text_on_page(''splinter.cobrateam.info')
    
    
    class GooglePage(object):
    
        def __init__(self, browser):
            self.browser = browser
            self.browser.visit("http://google.co.in")
    
        def search(self, keyword):
            self.browser.fill('q', keyword)
            self.browser.find_by_name('btnG').click()
            return self
    
        def verify_text_on_page(self, text):
            assert_true(self.browser.is_text_present('splinter.cobrateam.info'))
    
    
    

    Thursday, June 26, 2014

    REST API Testing using REST-assured

    This is my second post about doing Automation of REST API Testing, few days back I write the post to do REST API Testing using Frisby.js ( a Javascript tool), today i will post about how to do this in JAVA using REST-assured API.

    Installation
    Please down and put following JAR files in your build path. 
    rest-assured
    json-schema-validator

    Test Case. 
    For this demo purpose, I am going to use freegeoip.net site which return simple JSON response. 
    steps: 
    1. visit http://freegeoip.net:80/json/yahoo.com site 

    verification:
    1. verify that it returns 200 OK 
    2. verify it return correct JSON 

    Test Script. 
    /**
     * @author Gaurang_Shah
     *
     */
    
    //import com.jayway.restassured.RestAssured;
    import static com.jayway.restassured.RestAssured.baseURI;
    import static com.jayway.restassured.RestAssured.given;
    import static com.jayway.restassured.RestAssured.useRelaxedHTTPSValidation;
    import static com.jayway.restassured.RestAssured.when;
    import static org.hamcrest.Matchers.equalTo;
    
    import org.junit.Test;
    
    import com.jayway.restassured.authentication.FormAuthConfig;
    
    public class TestATP {
    
     
     @Test
     public void testDemo(){
      baseURI="http://freegeoip.net:80/";
      when().
        get("/json/yahoo.com"). 
      then().
        assertThat().statusCode(200).
        log().all().
        body("country_code",equalTo("US"),
          "country_name",equalTo("United States"),
          "region_code",equalTo("CA"),
          "region_name",equalTo("California"),
          "city",equalTo("Sunnyvale")
          
         );
     
     }
    }
    

    Friday, May 30, 2014

    REST API Testing using Frisby.js

    Couple of days back I was searching ways to Automate REST API, I was searching for tool which is open source, free and has good support. The first thing which I came across is Frisby.js

    Frisby.Js  is a framework for testing REST API built on node.js. (Yes, that means you will have use javascript)

    Pros:
    • It's fast and easy to use. 
    • It generated JUnit XML report.
    Cons
    • Doesn't have much facilities
    • very limited support group. 
    However't that's what I feel, you can explore this and can comment if feels other wise. Now let me show you how to install it. 

    Installation 

    • First install the node.js from following location
      http://nodejs.org/download/
    • Now go the command line and install the frisby.js using npm (node package manager)
      npm install -g frisby
    • You will also require to install jasmine as it is being used by frisby.js, Goto the command line and install jasmine using following command.
      npm install -g jasmine-node
    • Now all is set, you can go ahead and create the test case. 

    Write Test Cases

    • Now firsby.js is using jasmine, name of the test case file must end with spec.js.
    • You also need to create the folder named spec and then folder names api inside that. 
    • Now copy the following file in spec/api.
    • Please not that, the first line is the location of the code may change depends where frisby module is located on your local machine. 
    getHostDetails_specs.js.

    In following test cases, we will get the details for yahoo.com site using freegeoip.com and then verify the JSON reponse. 
    var frisby = require('C:/Users/gaurang_shah/AppData/Roaming/npm/node_modules/frisby');
    
    frisby.create('Get IP From Host Name')
      .get('http://freegeoip.net/json/yahoo.com')
      .expectStatus(200)
      .expectHeaderContains('content-type', 'application/json')
      .inspectJSON()
      .expectJSON({
      country_code:"US",
      country_name:"United States",
      region_code: 'CA',
      region_name: 'Californ',
      city: 'Sunnyvale',
      zipcode: '94089',
      latitude: 37.4249,
      longitude: -122.0074,
      metro_code: '807',
      area_code: '408' 
      })
     .toss();
    

    Run the Test Cases

    • open the command prompt and make sure you are in the parent directory of spec/api folder. 
    • Enter the following command
      jasmine-node spec\api\getHostDetails_spec.js
    • If you have multiple spec file and if you want to run all, then you can run using following command
      jasmine-node spec/api

    Results & Reports 

    • Above test case will fail, as we are expecting region_name to be Californ and actual is California.
    • To Generate the Junit report, you just need to run the test cases using following command
      jasmine
      -node spec/api/ --junitreport

    Monday, January 20, 2014

    WebDriver: Verify If JavaScript Alert is Present or Not

    WebDriver has provided decent API to handle JavaScript Alert, however there isn't any API present which lets you know if JavaScript Alert is present on page or not. And sometime we are not sure if Alert is present or not, if it is present then we need to cancel it.

    Implementation of isAlertPresent is very simple, Following code shows how to check if alert is present or not and if present cancel it.


    /**
     * If Javascript Alert is present on the page cancels it. 
     */
    public void handleAlert(){
     if(isAlertPresent()){
      Alert alert = driver.switchTo().alert();
      System.out.println(alert.getText());
      alert.accept();
     }
    }
    
    /**
     * 
     * @return True if JavaScript Alert is present on the page otherwise false
     */
    public boolean isAlertPresent(){
     try{
      driver.switchTo().alert();
      return true;
     }catch(NoAlertPresentException ex){
      return false;
     }
    }

    Thursday, October 17, 2013

    Speedup Your Selenium Test with PhantomJS

    I was searching some way to speedup my WebDriver tests and this is what I came across, PhantomJS. It took awhile to understand how it works but it's worth spending time as I can say it's more than 50% faster when your run your test with PhantomJS. So,

    What is PhantomJS?

    PhantomJS is a headless WebKit scriptable with a JavaScript API. It's okay if you didn't understand it by this single line. Let me explain it to you.
    Webkit is a browser engine which allows web browser to render pages, and it is used by many streamline browser (I guess Firefox and Google chrome both uses this). Now what is this headless then? Headless mean you won't be able to see any GUI component of the browser.

    So Why PhantomJS is faster ?

    This is the second question you might come up with. That if it is the same engine that many browser uses then how my test cases will execute faster if I will run them on PhantomJS.
    The reason is, it just process data (request and response) it doesn't draw canvas.

    We have had enough talk, now let's compare the result.

    import java.util.List;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.phantomjs.PhantomJSDriver;
    import org.testng.annotations.Test;
    
    public class TestPhantoJS {
    
     /**
      * @author Gaurang_Shah
      * Following test will search the keyword on google 
      * and will print all websites on first page.
      */
     @Test
     public void GoogleSearch(){
      WebDriver driver = new PhantomJSDriver();
    //  WebDriver driver = new FirefoxDriver();
      driver.get("http://google.com");
      driver.findElement(By.name("q")).sendKeys("phantomjs");
      driver.findElement(By.name("q")).submit();
      List<WebElement> sites = driver.findElements(By.xpath("//cite"));
      System.out.println(driver.getTitle());
      int index=1;
      for(WebElement site: sites){
       String siteName=site.getText();
       if(!siteName.equalsIgnoreCase(""))
        System.out.println(index+++":--"+site.getText());
      }
      driver.close();
     }
    }
    On my machine when I am running above test with PhantomJSdriver and FirefoxDriver following is the result.
    FirefoxDriver - ~28 seconds
    PhantomJSDriver - ~13 seconds
    Pretty Fast. Right ??

    Let Me Move My all Tests to PhantomJSDriver 

    this is the first thought that my come up in your mind after this result. Right ???, however I wouldn't advice you to do that. And there are reason to this as well as mention below.
    PhantomJS is just a headless WebKit which uses JavaScript, however it uses GhostDriver to run your test cases used webdriver. And it's in intermediate stage and you might feel bit trouble with someone the WebDriver API.

    What is GhostDriver?? 

    I am sure you must have this question in mind. Let me try to explain it to you. It's a Webdriver wire protocol in simple javascript for PhantomJS. (what the hell ??? ) ohh. let me make it more simple. GhostDriver is not but some kind of communicator between your Webdriver Bidning and PhantomJS. PhantomJS comes with the GhostDriver inbuilt, however it's available separately as well.

    Tuesday, October 8, 2013

    Webdriver: RobotFramework with Java - Part 1

    There are so many posts available which states how to install/setup and configure robotframwork in python, however i didn't find any good posts which states how to configure robotframework in Java. So decided to write a blog.

    Install/Setup Robot Framework 

    To run webdriver test with RoboFramework in java you require following two jar files. 

    Download the above two files and put that into some directory. 

    Sample Test Case

    Create the testcase.txt as mention below into the same directory in which you downloaded JARs
    ***Setting***
    Library    Selenium2Library
    
    *** Test Cases ***
    Get Current Browser Test
        Open Browser  http://google.com

    Run Test Case

    To run the RobotFramework test case you need to set the CLASSPATH. Please add above jar files into your classapth and run the following command 
    java org.robotframework.RobotFramework run testcase.txt

    Verify Results

    Results will be located into same directory in which you have created test case. 

    Tuesday, October 1, 2013

    WebDriver: TestNG with ANT

    Few posts back I explained how to use Maven with Webdriver and TestNG. Now let's see how to use ANT with WebDriver and TestNG.
    <project name="WebDriverAntTestNG" default="run" basedir=".">
     
     <path id="libs">
      <!-- Include all the external Jar files -->
      <fileset dir="${basedir}\src\jars">
       <include name="*.jar"/>
      </fileset>
      <!-- Include all the compile classes -->
      <fileset dir="bin">
       <include name = "**/*.class"/>
      </fileset>
      <pathelement path="${basedir}\bin"/>
      </path>
     
     <target name="run">
        <antcall target="init"/>
        <antcall target="compile"/>
        <antcall target="runTests"/>
      </target>
     
       <!-- Delete old data and create new directories -->
      <target name="init" >
       <echo>Initlizing...</echo>
       <delete dir="bin" />
        <mkdir dir="bin"/>
        <delete dir="report" />
        <mkdir dir="report"/>
        
      </target>
     
     <!-- Complies the java files -->
     <target name="compile">
        <echo>Compiling...</echo>
        <javac includeantruntime="false" debug="true" srcdir="src" destdir="bin"   classpathref="libs" />
      </target>
    
     <!-- Runs the file and generates Reportng report -->
     <target name="runTests" description="Running tests" >
      <echo>Running Tests...</echo>
        <taskdef resource="testngtasks" classpathref="libs"/>
        <testng outputDir="report"
        haltonfailure="true"
        classpathref="libs"
          >
       <classfileset dir="bin" includes="**/*.class" />
        </testng>
      </target>
    
    </project>

    Targets Explained:


    Run: This is main target, which will call all the below target in order.
    Init: This target will delete the Bin an Report directory and will crate again in order to clean. 
    Compile: This target will compile all the java classes. 
    runTests: This target contain the TestNGTask which will all the testng tests. 


    Tuesday, September 3, 2013

    Jenkins: Static Analysis with CheckStyle

    In the last post I mention how to configure your Maven Webdriver project on Jenkins, today let's see how to configure checkStyle plugin for static analysis with jenkins.

    Configure Check Style with Maven

    Mention the following plugin in pom.xml, make sure you mention it inside build block 
    pom.xml

    <plugin>
     <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-checkstyle-plugin</artifactId>
     <version>2.10</version>
     <configuration>
      <sourceDirectory>src</sourceDirectory>
     </configuration>
    </plugin>

    Configure Check Style with Jenkins
    follow the steps mention below to configure and generate checkStyle Report in jenkins
    Install checkStyle plugin Navigate to Manage Jenkins->Manage Plugin and install checkStyle plugin and then restart the jenkins 

    Configure checkStyle for project
     Following is how to configure checkStyle for Maven project, it might vary if you are using ANT. 
    • Append checkstyle:checkstyle to your build goal
    • check Publish Checkstyle analysis results
      Configure Checkstyle for project
      Configure checkStyle for Project
    Configure checkStyle Reports
     Now you need to configure which reports you want to see for this project, follow the steps to configure reports
    • Navigate to Jenkins home page and create new view
      Add New Dashboard for checkStyle
      Add new dashboard for checkstyle
    • Select the project you want to include for checkStyle Report
      Add Projects for checkStyle Report
      choose jenkins jobs for checkstyle
    • Include the graphs/reports you want
      Select Graphs for checkStyle report
      configure checkstyle report in jenkins

    Monday, September 2, 2013

    WebDriver with Jenkins

    In the last post we see how to create Maven Project for WebDriver from eclipse. Now let's configure same Webdriver Maven Project on Jenkins.

    Setup Jenkins on Windows 

    download the jenkins from following location
    http://jenkins-ci.org/
    Running Jenkins as War file 
    You can run jenkins using war file, if you are doing it you don't need any slave to start on machine. Running Jenkins as Windows Service 
    If you have installed Jenkins as Windows Services then you need to Start Slave and Bind you project to that slave.

    Create/Run Slave Node 

    If Jenkins is installed as Windows Services you need to start the JNLP slave node on machine where you need to execute your test cases. Follow the process to create node.
    • Go to Manage Jenkins->Manage Nodes and Click on New Node
    • Enter the Node Name and choose Dumb Slave
      Create Jenkins Slave node for WebDriver Execution
      Create Jenkins Slave node for WebDriver Execution


    • Enter the information as mention in the screenshot
      Configure Node for WebDriver
      Configure Node for WebDriver
    • After saving node will be listed under Nodes 
      All Available Nodes in Jenkins
      All Available Nodes in Jenkins
    • Start the node by Running displayed command in CMD
      Start JNLP node in Jenkins
      Starting JNLP Node in Jenkins
    • if everything has been done correctly if you will able to see small java program running
      Connected JNLP Node
      Connected JNLP Node


    Configure Maven in Jenkins

    Before you create a new Job for Maven WebDriver Project, let's configure Maven in jenkins
    Go to Manage Jenkins->Configure System and Provide Installation directory for JDK and Maven as mention in screenshot below
    Configure JDK and Maven in Jenkins
    Configure JDK and Maven in Jenkins

    Create New Job on Jenkins

    Now let's create the new Job for Project
    • Go to Home page and click on New Job
      Create Jenkins Job for Maven WebDriver Project
      Create Jenkins Job for Maven WebDriver Project
    • Restrict the job to run on the Slave Node we created
      Configure WebDriver Project to run on Specific Node
      Configure WebDriver Project to run on Specific Node
    • Click on Use custom workspace and Mention your workspace location und Directory
    • Provide the path of pom.xml in Root POM and provide Test in Goals and Options
      Provide Maven in Goal in Jenkins
      Provide Maven Goal in Jenkins

    Sunday, September 1, 2013

    WebDriver with Maven

    Maven is a build Automation Tool somewhat like ANT. Having use ANT for the previous project wanted to try Maven this time. I thought it would be easy as I know ANT, however it took a while for me to figure out as i didn't find any proper tutorial on net. And this is the reason I am writing new Blogpost.

    I have just started, So if someone knows the better way to do few things mention here please let me know in comment.

    Now let's try setting up new Maven Project for Webdriver using Eclipse. However before you do, you need to download and setup Maven on you local machine.

    Setup up Maven
    • download the appropriate maven from the following site.
      http://maven.apache.org/download.cgi Extract it to some location and setup the PATH variable. 
    • If you have done everything correctly, Following command on CMD will let you know the Maven Version.
      mvn --version 


    Install Maven Plug-in in Eclipse 
    Install the m2Eclipse plugin in you eclipse

    Setup Maven Project for WebDriver.

    • In Eclipse choose New Maven Project and check the "Create Simple Project" 
    • Fill the Group id and Artifact id 
    • Create New Class named "GoogleTest" under "src/test/java" Copy Following code in it.
    • GoogleTest.java 

      import org.openqa.selenium.WebDriver;
      import org.openqa.selenium.firefox.FirefoxDriver;
      import org.testng.annotations.Test;
      
      /**
       * @author Gaurang_Shah
       */
      public class GoogleTest {
       private WebDriver driver;
      
       @Test
       public void verifySearch() {
        driver = new FirefoxDriver();
        driver.get("http://www.google.com/");
        driver.quit();
       }
      }


  • It will show you some compile time error as we haven't added the dependencies yet.
  • Maven mention all the dependencies in pom.xml file. Please copy and replace the following pom.xml with your project pom.xml file.
    <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>MavenWebDriverDemo</groupId>
     <artifactId>MavenWebDriverDemo</artifactId>
     <version>0.0.1-SNAPSHOT</version>
    
     <dependencies>
      <dependency>
       <groupId>org.seleniumhq.selenium</groupId>
       <artifactId>selenium-java</artifactId>
       <version>2.33.0</version>
      </dependency>
      <dependency>
       <groupId>org.seleniumhq.selenium</groupId>
       <artifactId>selenium-server</artifactId>
       <version>2.33.0</version>
      </dependency>
      <dependency>
       <groupId>org.testng</groupId>
       <artifactId>testng</artifactId>
       <version>6.8.5</version>
      </dependency>
     </dependencies>
    </project>
  • Running Project
    • To run from Eclipse, Right click on pom.xml and choose Run as --> Maven Test 
    • To run from command line, Go to project directory and enter following command
       mvn test

    Monday, July 22, 2013

    webdriver - handle untrusted ssl certificate

    While doing automation of https site there are chances when you get the following error.
    This Connection is Untrusted. 



    Reason: This certificate is not issued by some valid authority, it's a self signed certificate.

    Solution:

    • Create a new profile and add this certificate in that profile by using following steps.
    • Make sure you are accessing site though the domain for which certificate has issued.
    •  If you get the above screen after accessible the site, You need to add certificate in Exception so next time it doesn't give you error.
    • However while adding certificate make sure "Permanently store this exception" check box is selected. 
    • If  "Permanently store this exception" is enable the history.

    • Now you need to give path of this newly created profile while creating the object of WebDriver.

    Wednesday, July 17, 2013

    PyTest - Quick Reference

    What is PyTest?
    PyTest is just like any other unit test framework for Python. It generates JUnit XML report as well which makes easy to integrate it's report with Jenkins

    How to Install PyTest: 
    pip install -U pytest or
    easy_install pytest

    How it Identifies: 
    Every unit testing framework has some pattern though which identifies which is Test Class, which is Test Method, Which is Setup and TearDown method and so do PyTest.
    Test Class - Any Class name which starts with Test is indentified as Test Class (i.e. TestMathFunc) Test- Any function which starts with test_ is identified as test method (i.e. test_devision)
    Apart from this there are few setup and teardown methods as well, as mention below
    setup_module:- Called before the first test of the module
    teardown_module:- Called after the last test of the module
    setup_class:- Called before the first test of the class
    teardown_class:- Called after the last test of the class 
    setup_method:- Called before each and every test inside class
    teardown_method:- Called after each and every test inside class
    setup_function:- Called before each and every test outside class 
    teardown_function:- Called after each and every test outside class 

    Sample Code:
    PyTestDemo.py
    class TestPyTestDemo():
        """
        This class demonstrates who to write simple test using pytest framework
        @author: Gaurang Shah
        @contact: gaurangnshah@gmail.com
        
        """
        def add(self,arg1,arg2):
            return arg1+arg2
    
        def test_pass(self):
            print "test_pass"
            assert self.add(2, 3) == 5
            
        def test_fail(self):
            print "test_fail"
            assert self.add(0, 2) == 1
    
        def setup_method(self,method):
            "This method will be called before each and every method inside class"
            print "setup_method"
            
        def teardown_method(self,method):
            "This method will be called after each and every method inside class"
            print "teardown_method" 
                    
        @classmethod
        def setup_class(cls):
            "This method will be called before first method of classe"
            print "setup_class"
             
        @classmethod
        def teardown_class(cls):
            "This method will be called after last method of class"
            print "teardown_class"
    
    def setup_module(module):
        "This method will be called before first method of module"
        print "setup_module"
    
    def teardown_module(module):
        "This method will be called after last method of module"
        print "teardown_module"  
       
    def setup_function(function):
        "This method will be called before each and every function outside class"
        print "setup function"
        
    def teardown_function(function):
        "This method will be called before each and every function outside class"
        print "teardown function"
        
    def test_function():
        print "test_function"
    How to Execute :
    py.test PyTestDemo.py