Monday, 10 April 2017

Select dropdown in Ruby | Selenium


Note| 
 
Text in Blue [#PYTHON], Red [#RUBY], and Orange [#JAVA] can be edited or mentioned important for the entire blog. All the posts are practically done by me.


Select dropdown


Add below snippet in the step definition file,

When(/^I select using "([^"]*)" with data "([^"]*)" from "([^"]*)" on the xyz page$/) do |event, value, dropdown|
  yourpage_data = PageName.new(@driver)
  case event
    when "position"
      yourpage_data.select_by_position(value, dropdown)
    when "value"
      yourpage_data.select_by_value(value, dropdown)
    else
      raise ArgumentError, "can't find the event #{event}"
  end
end

Select by position

Make sure you create cucumber steps before step definitions; say,

And I select using "position" with data "1" from "your_locator" on the xyz page


Add the following snippets inside the page file,

your_locator_dropdown = @driver.find_element(:css => "your_css_locator")
your_locator = @driver.find_elements(:css => "your_css_locator")

def select_by_position(value, dropdown)
  __send__("#{dropdown}_dropdown").click
  __send__("#{dropdown}").each_with_index do |elem, index|
    if index == value
      elem.click
      break
    end
  end
end



Select by value

Make sure you create cucumber steps before step definitions; say,

And I select using "value" with data "demo_value" from "your_locator" on the xyz page


Add the following snippets inside the page file,

your_locator_dropdown = @driver.find_element(:css => "your_css_locator")
your_locator = @driver.find_elements(:css => "your_css_locator")

def select_by_value(value, dropdown)
  __send__("#{dropdown}_dropdown").click
  __send__("#{dropdown}").each do |elem|
    if elem.attribute("value").to_s == value.to_s
      elem.click
      break
    end
  end
end


Select by last value

Make sure you create cucumber steps before step definitions; say,

And I select using "last_value" with data "" from "your_locator" on the xyz page


Add the following snippets inside the page file,

your_locator_dropdown = @driver.find_element(:css => "your_css_locator")
your_locator = @driver.find_elements(:css => "your_css_locator")

def select_by_last_value(dropdown)
  __send__("#{dropdown}_dropdown").click
  (__send__("#{dropdown}").last).click
end


Select by text

Make sure you create cucumber steps before step definitions; say,

And I select using "text" with data "demo_text" from "your_locator" on the xyz page


Add the following snippets inside the page file,

your_locator_dropdown = @driver.find_element(:css => "your_css_locator")
your_locator = @driver.find_elements(:css => "your_css_locator")

def select_by_text(value, dropdown)
  __send__("#{dropdown}_dropdown").click
  __send__("#{dropdown}").each do |elem|
    if elem.text.to_s == value.to_s
      elem.click
      break
    else
      puts "#{elem.text} not matching #{value}"
    end
  end
end

Tuesday, 4 April 2017

How to use JSON file as Object Repository in Ruby ?


Note| 
 
Text in Blue [#PYTHON], Red [#RUBY], and Orange [#JAVA] can be edited or mentioned important for the entire blog. All the posts are practically done by me.


JSON as Object Repository in Ruby


Create a JSON formatted object repository file; say, or.json

{
  "login_id": {
    "selector": ":css",
    "value": "#login"
  }
}

Now, create a module; say, utilities.rb

module Modulename
def loc(element)
  file = File.read(File.dirname(__FILE__) + "/../helpers/or.json")
  @driver.find_element(eval(JSON.parse(file)["#{element}"]['selector']), JSON.parse(file)["#{element}"]['value'])
end
end

Add the path in your env.rb

require File.dirname(__FILE__) + "/../helpers/utilities"
include Modulename

Finally call the loc() method in a page file as shown below,

loc("login_id").click

Saturday, 23 July 2016

CSS Locators


Note| 
 
Text in Blue [#PYTHON], Rose [#PROTRACTOR], Red [#RUBY] and Orange [#JAVA] can be edited or mentioned important for the entire blog. All the posts are practically done by me.


Experimental CSS Locators in automation aspects

CSS locators are comparatively faster than Xpath and readable; it uses JQuery's way to locate elements.

Note: This post is fully experimented on https://www.python.org/


General
     ID
               #id-search-field

     The same can be achieved through,
               *#id-search-field
               input#id-search-field

     Class
               .search-field
               .search-field.placeholder
               
     The same can be achieved through,
               *.search-field
               input.search-field

     Direct Child | absolute css
     '>' operator matches the immediate child of an element
               .python.home > #touchnav-wrapper > #nojs > p > strong:contains(Notice:)

     Sub Child | relative css
     a space between two instance matches any descendant of a parent/grand-parent elements
               .python.home strong:contains(Notice:)

     contains | text
     locates elements with text
               button:contains(GO)

     not contains | text
     skips elements with specific text
               a:not(:contains(notinthispage))









Attrribute
     CSS locates elements using properties
               input[name='q']
               input[id='id-search-field']
               input[class='search-field placeholder']
               input[class='search-field placeholder'][id='id-search-field']

     not contains | attribute
     locates all the elements that doesn't contain specific property, text, etc., 
               .tier-2:contains(Group):not(.element-4)
               .tier-2:contains(Group):not([class*='element-4'])



Advanced attrribute css selectors
     CSS locates dynamic elements using the following operators
               = operator
               ~= operator
               ^= operator
               $= operator
               *= operator
               |= operator

     Equal
     = operator lets you find elements that matches attribute with the exact specified value
               *[class='python home']

     space-separated values
     ~= operator lets you find elements that matches attribute with space-separated values
               *[class~='menu']

     prefix [begins-with]
     ^= operator lets you find elements that matches attribute starting with the specified value
               *[class^='main']

     suffix [ends-with]
     $= operator lets you find elements that matches attribute ending with the specified value
               *[class$='home']

     contains [contains]
     *= operator lets you find elements that matches attribute with a specified value, which is a part of actual attribute value
               *[class*='shell']

     hyphen separated values
     |= operator lets you find elements that matches attribute with hyphen-separated values starting from the left
               *[class|='site']



Css Siblings
     CSS locates sibilings similar to xpath
               Next sibling
               General sibling
               
     Next or Adjacent sibling
     selects the element/sibling next to the current element
               #top + header


     

     General sibling
     selects any number of siblings with matching type coming next to next from the current element
               #top ~ div
 



Pseudo class
     Pseudo-classes are actually not css inborn instead they are an absolute CSS foreigners implemented through JQuery, mootools, etc., listed below are some of the most commonly used pseudo classes for automation,
               :nth()
               :nth-child()
               :first-child
               :last-child
               :first-of-type
               :last-of-type
               :nth-of-type()
               :only-of-type
               hover
               E:focus
               link
               visited

     nth()
     collects the entire child, sub-child of a parent and matches the list in a sequential order or index with value starting from 0 as count 1
               .main-header .container div:nth(2)
               .meta-navigation.container *:nth(0)

     nth-child()
     unlike nth(), nth-child filters only the child with type and location 
               [role='menubar'] *:nth-child(1)

     here, it selects all the first child elements of the type <li>
               [role='menubar'] li:nth-child(1)









     first-child
     first-child is similar to nth-child(1)
               [role='menubar'] li:first-child


     last-child
     last-child is similar to first-child but locates the child's last elements
               [role='menubar'] li:last-child

     
first-of-type
     locates the parent's first elements w.r.t type
               [role='menubar'] li:first-of-type

     
last-of-type
     locates the parent's last elements w.r.t type
               [role='menubar'] li:last-of-type

     only-of-type
     matches all the given type (say, h1 tag) under a specific element
               .main-header .container h1:only-of-type

     hover
     locates element on hover over
               *[href='/psf/membership/']:hover

     
E:focus

     locates element on focus
               *[href='/psf/membership/']:focus

     
link

     locates element if hyperlinked
               *[href='/psf/membership/']:link

     visited
     locates already visited hyperlink
               *[href='/psf/membership/']:visited



Thursday, 21 April 2016

Getting started with Protractor


Note| 
 
Text in Blue [#PYTHON], Rose [#PROTRACTOR], Red [#RUBY] and Orange [#JAVA] can be edited or mentioned important for the entire blog. All the posts are practically done by me.


Getting started with Protractor

1| Create a folder for new project.
2| Open Terminal/cmd_prompt and navigate project location.
3| Download protractor through terminal (make sure you have installed nodejs in your machine before executing the following command)

project-wise installation
npm install protractor

or
global installation
npm install -g protractor

4| And update the selenium-standalone-server.jar file after protractor installation.

project-wise updation
node_modules/protractor/bin/webdriver-manager update

or
global updation
webdriver-manager update

This will update the existing selenium server and ChromeDriver under node_modules/protractor/selenium/selenium-server-standalone-2.xx.x.jar



To update the selenium server alone, enter the following command,
webdriver-manager update --standalone

5| Now, create a spec file using Jasmine unit testing framework #sample

6| And create the Protractor configuration file, protractor-conf.js for execution #sample

7| To run the spec file, you need to start selenium-server first,

project-wise
node_modules/protractor/bin/webdriver-manager start

or
global
webdriver-manager start

8| Let's run the first protractor project now,

project-wise

node_modules/protractor/bin/protractor protractor-conf.js

or
global
protractor protractor-conf.js


Note: For more info. download my sample project from Github Link

Thursday, 15 May 2014

Cucumber BDD framework with Selenium WebDriver


Note|  Text in Blue [#PYTHON] and Orange [#JAVA] can be edited or mentioned important for the entire blog. All the posts are practically done by me.


Cucumber BDD Framework | selenium


1| Add an Eclipse plugin, Cucumber Eclipse feature using the below URL,
http://cucumber.github.com/cucumber-eclipse/update-site
2| Help > install new software... > paste the above url in work with text field and press enter key.
3| After the installation is done, restart Eclipse IDE.



4| Create a Maven project and add the following dependencies in 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>BDD</groupId>
  <artifactId>Cucumber</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>Cucumber</name>
  <url>http://maven.apache.org</url>

    <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

      <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <encoding>UTF-8</encoding>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.12.2</version>
                <configuration>                
                    <useFile>false</useFile>
                </configuration>
            </plugin>
        </plugins>
    </build>
    
      
 <dependencies>

   <dependency>
     <groupId>junit</groupId> 
     <artifactId>junit</artifactId>
     <version>4.11</version>
     <scope>test</scope>
   </dependency>    

<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-server</artifactId>
<version>2.41.0</version>
</dependency>

<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-core</artifactId>
<version>1.1.2</version>
</dependency>

<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.1.2</version>
</dependency>

<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>1.1.2</version>
</dependency>

<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-html</artifactId>
<version>0.2.2</version>
</dependency>

<dependency>
<groupId>info.cukes</groupId>
<artifactId>gherkin</artifactId>
<version>2.11.6</version>
</dependency>

<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>1.3</version>
</dependency>

<dependency>
<groupId>info.cukes</groupId>
<artifactId>gherkin</artifactId>
<version>2.11.6</version>
</dependency>

<dependency>
            <groupId>com.rubiconproject.oss</groupId>
            <artifactId>jchronic</artifactId>
            <version>0.2.6</version>
            <scope>test</scope>
        </dependency>
                    
  </dependencies>
</project>


5| Now, create a test run class file

package BDD.Cucumber;

import org.junit.runner.RunWith;

import cucumber.api.junit.Cucumber;


@RunWith(Cucumber.class)
@Cucumber.Options(format = {"pretty", "html:target/cucumber","json:target/cucumber.json"})
public class RunTest {

}


6| Now, create a test class file

package BDD.Cucumber;

import static org.junit.Assert.assertEquals;

import java.util.concurrent.TimeUnit;

import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import cucumber.api.Scenario;
import cucumber.api.java.After;

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;



public class Googlesearch {

public WebDriver driver = new FirefoxDriver();

@Given("^Google page \"([^\"]*)\"$")
public void i_open_google_page_as(String URL) throws Throwable {
driver.get(URL);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

}


@When("^I enter \"([^\"]*)\" in search box$")
public void i_enter_in_search_box(String arg1) throws Throwable {
driver.findElement(By.name("q")).sendKeys(arg1);
}

@When("^I press enter key$")
public void i_press_enter_key() throws Throwable {
driver.findElement(By.name("q")).submit();

}

@Then("^I should get the results of \"([^\"]*)\"$")
public void i_should_see_results_of(String content) throws Throwable {

Thread.sleep(3000L);
boolean b = driver.getPageSource().contains(content);
Assert.assertTrue(b);
}

@After
public void after(Scenario scenario) {
driver.close();
}

}





7| Create a new source folder, "resources" under src/test/
8| Now, create a package, "BDD.Cucumber"
9| Then create a file with extension .feature
Right click BDD.Cucumber under src/test/resources > New > Other > File
10| Name the file with extension .feature; i.e., test.feature

Feature: test

@foo
Scenario: google search

Given Google page "http://www.google.com"
When I enter "Prashanth Sams" in search box
When I press enter key
Then I should get the results of "Prashanth Sams"


11| Right click on the project > Run As > maven clean
12| Again Right click on the project > Run As > maven install


Note: For more info. download my sample project from Github Link

Wednesday, 7 May 2014

Selenium Data-driven Text file | @DataProvider


Note|  Text in Blue [#PYTHON] and Orange [#JAVA] can be edited or mentioned important for the entire blog. All the posts are practically done by me.


This is the continuation of one my previous topics, #link.  In this method, we are using @dataProvider annotation on TestNG to fetch keywords from a Text file and passing the arguments to Test class. This is our (Prashanth Sams + Karthikeyan) implementation to work with Text file via dataprovider.


Text File | @DataProvider

The below example illustrates on how to work with @dataprovider in-order to fetch values from a text file.

1| Create a Test class file similar to the one given below:


package packagename;

import java.util.HashMap;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class Google {
    private WebDriver driver;

    @DataProvider(name="keywords")
    public Object[][] data() throws Exception {
        HashMap<String,String[]> dataSet= new Text2TestData(System.getProperty("user.dir")+"\\config.txt").getData();
        
        String search1Strings[]=dataSet.get("search1");
        String search2Strings[]=dataSet.get("search2");
        int size =search1Strings.length;
   
        // modify 2 upon the no. of rows; Here, I used two rows, 'search1' & 'search2'
        Object[][] creds = new Object[size][2];  
        for(int i=0;i<size;i++)
        {
            creds[i][0]=search1Strings[i];
            creds[i][1]=search2Strings[i];
        }
        return creds;
    }


    @BeforeTest
    public void setUp() throws Exception {
        driver = new ChromeDriver();

    }

    @Test(dataProvider = "keywords", description = "Google_Test")
    public void search(String search1, String search2) throws Exception {
   
        driver.get("http://www.google.co.in");

        // search google via keyword 1
        driver.findElement(By.name("q")).clear();
        driver.findElement(By.name("q")).sendKeys("" + search1);
        driver.findElement(By.name("q")).submit();
        Thread.sleep(4000);

        // search google via keyword 1
        driver.findElement(By.name("q")).clear();
        driver.findElement(By.name("q")).sendKeys("" + search2);
        driver.findElement(By.name("q")).submit();
        Thread.sleep(4000);

    }
    
    @AfterTest
    public void tearDown() throws Exception {
        driver.quit();
    }

}



Text2TestData

2| Create another java class file, 'Text2TestData' under the same package.


package packagename;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

public class Text2TestData {

    private String fileLocation;

    public Text2TestData(String fileLocation) {
        this.fileLocation = fileLocation;
    }

    public HashMap<String,String[]> getData(){
        FileInputStream fs;
        HashMap<String,String[]> keyValuePair=new HashMap<String,String[]>();
        try (BufferedReader br = new BufferedReader(new FileReader(fileLocation))){
            String stringLine;
            //Read File Line By Line
            while ((stringLine = br.readLine()) != null)   {
                // Print the content on the console
                String[] keyValue=stringLine.split("=");
                keyValuePair.put(keyValue[0],keyValue[1].split(","));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return keyValuePair;
    }


}



3| Create a text data-source file similar to the contents given below separated with comma (,)

search1=Prashanth Sams,bypasshacker
search2=seleniumworks.com,bypasshacker.blogspot.com

4| Now, place the config.txt file inside your project
5| Save the file and run test :)

Selenium Data-driven Properties file | @DataProvider


This is the continuation of one my previous topics, #link.  In this method, we are using @dataProvider annotation on TestNG to fetch keywords from a Properties file and passing the arguments to Test class. This is my implementation to work with Properties file via dataprovider.


Properties File | @DataProvider

The below example illustrates on how to work with @dataprovider in-order to fetch values from a properties file.

1| Create a Test class file similar to the one given below:


package packagename;

import java.util.HashMap;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class Google {
    private WebDriver driver;

    @DataProvider(name="keywords")
    public Object[][] data() throws Exception {
        HashMap<String,String[]> dataSet= new properties2TestData().getData();
        
        String search1Strings[]=dataSet.get("search1");
        String search2Strings[]=dataSet.get("search2");
        int size =search1Strings.length;
   
        // modify 2 upon the no. of rows; Here, I used two rows, 'search1' & 'search2'
        Object[][] creds = new Object[size][2];  
        for(int i=0;i<size;i++)
        {
            creds[i][0]=search1Strings[i];
            creds[i][1]=search2Strings[i];
        }
        return creds;
    }


    @BeforeTest
    public void setUp() throws Exception {
        driver = new ChromeDriver();

    }

    @Test(dataProvider = "keywords", description = "Google_Test")
    public void search(String search1, String search2) throws Exception {
   
        driver.get("http://www.google.co.in");

        // search google via keyword 1
        driver.findElement(By.name("q")).clear();
        driver.findElement(By.name("q")).sendKeys("" + search1);
        driver.findElement(By.name("q")).submit();
        Thread.sleep(4000);

        // search google via keyword 1
        driver.findElement(By.name("q")).clear();
        driver.findElement(By.name("q")).sendKeys("" + search2);
        driver.findElement(By.name("q")).submit();
        Thread.sleep(4000);

    }
    
    @AfterTest
    public void tearDown() throws Exception {
        driver.quit();
    }

}



properties2TestData

2| Create another java class file, 'properties2TestData' under the same package.


package packagename;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.ResourceBundle;

public class properties2TestData {

    public properties2TestData() {
    }

    public HashMap<String,String[]> getData(){
    HashMap<String,String[]> configMap=new HashMap<String,String[]>();
    try{
    ResourceBundle bundle = ResourceBundle.getBundle("config");
        Enumeration<String> keys = bundle.getKeys();
        while(keys.hasMoreElements()){
        String aKey = keys.nextElement();
        String aValue = bundle.getString(aKey);
        configMap.put(aKey, aValue.split(","));
        }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return configMap;
    }

}



3| Create a properties data-source file similar to the contents given below separated with comma (,)

search1=Prashanth Sams,bypasshacker
search2=seleniumworks.com,bypasshacker.blogspot.com

4| Now, place config.properties file inside your project's Source folder[src]
5| Save the file and run test :)

Friday, 25 April 2014

Getting started with Ruby | Selenium Users


Note|  Text in Blue [#PYTHON], Red [#RUBY], and Orange [#JAVA] can be edited or mentioned important for the entire blog. All the posts are practically done by me.


Ruby Installation


In Windows, you can use either RubyInstaller or pik.

1| Download rubyinstaller
2| Check Ruby version
Start > Interactive Ruby
RUBY_VERSION



3| Install Selenium WebDriver library for Ruby
selenium-webdriver-2.41.0.gem
INSTALL > gem install selenium-webdriver



4| Download Devkit before installing json
5| Extract DevKit to path C:\Ruby200\DevKit
6| Open cmd prompt
> cd C:\Ruby200\DevKit
> ruby dk.rb init
> ruby dk.rb review
> ruby dk.rb install


INSTALL > gem install json



7| Download Ruby DLTK plugin for Eclipse IDE [Go to Eclipse Marketplace and search Ruby DLTK]



8| Go to Windows > Preferences > Ruby - Interpreters



9| Click on 'Add' and Locate Ruby.exe  "C:\Ruby200\bin\ruby.exe"



10| Create a New Ruby Project
Right click on package Explorer > New > others 

11| Type 'Ruby'.
12| Select 'Ruby Project' and press Finish.



13| Create a new Ruby module.
Right click on package > New > Ruby module

14| Develop your Ruby selenium script like sample given below

require "selenium-webdriver"

driver = Selenium::WebDriver.for :firefox
driver.navigate.to "http://google.com"

element = driver.find_element(:name, 'q')
element.send_keys "Prashanth Sams"
element.submit

driver.quit

15| Rick click on program Run > Ruby Script



Note| 
1| Rack is a web server interface used for developing web applications in Ruby; Rack is used by almost all Ruby web frameworks and libraries, such as Ruby On Rails and Sinatra.
2| RubyGems is a package manager for Ruby programming language.