Write dymanic data to a new csv file using Selenium

1. Add this below dependency to pom.xml & rebuild.

         <dependency>
            <groupId>org.apache.any23</groupId>
            <artifactId>apache-any23-csvutils</artifactId>
            <version>2.0</version>
        </dependency>


2.Create a new class which is a utility for writing the values to csv file

package utils;

import com.aventstack.extentreports.Status;
import components.Config;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;


public class WriteToCSV {

    private static WebDriver driver;

    private static final char DEFAULT_SEPARATOR = ',';

    public static void writeLine(Writer w, List<String> values) throws IOException {
        writeLine(w, values, DEFAULT_SEPARATOR, ' ');
    }

    public static void writeLine(Writer w, List<String> values, char separators) throws IOException {
        writeLine(w, values, separators, ' ');
    }

    private static String followCVSformat(String value) {

        String result = value;
        if (result.contains("\"")) {
            result = result.replace("\"", "\"\"");
        }
        return result;
    }

    public static void writeLine(Writer w, List<String> values, char separators, char customQuote) throws IOException {

        boolean first = true;

        //default customQuote is empty

        if (separators == ' ') {
            separators = DEFAULT_SEPARATOR;
        }

        StringBuilder sb = new StringBuilder();
        for (String value : values) {
            if (!first) {
                sb.append(separators);
            }
            if (customQuote == ' ') {
                sb.append(followCVSformat(value));
            } else {
                sb.append(customQuote).append(followCVSformat(value)).append(customQuote);
            }

            first = false;
        }
        sb.append("\n");
        w.append(sb.toString());
    }
}

3.Create a File Writer, add a location to save the generated csv file & Call the method like below.

// This is the default location of the csv file i.e Downloads folder 
fallback.put("downloads", new File("").getAbsolutePath() + "\\Downloads\\");

public static String getDownloads() {
        return config.getProperty("downloads");
    }

    public static void setDownloads(String downloads) {
        config.put("downloads", downloads);
    }

String csvFile = Config.getDownloads()+".csv";
FileWriter writer = new FileWriter(csvFile);
WriteToCSV.writeLine(writer, Arrays.asList("Header1","Header2","Header3"));
WriteToCSV.writeLine(writer, Arrays.asList(Data1,Data2,Data3));


4. Out put looks like below.

Header1,Header2,Header3
Data1,Data2,Data3
Advertisements

Tricks for CSS and Xpath locators used in Automation

(1) Id:
An element's id is defined as "[@id='idName']" in Xpath but "#idName" in CSS.
For example, a 'div' element with id 'panel' will be represented as below:
In Xpath locator
//div[@id='panel']
In CSS selector
css=div#panel

(2) Class:
An element's class is defined as "[@class='className']" in Xpath but ".className" in CSS.  
For example, a 'div' element with class 'panelClass' will be represented as below:
In Xpath locator
//div[@class='panelClass']
In CSS selector
css=div.panelClass
For element with multiple class we need to separate with space(" ") in Xpath and dot(".") in case of CSS. See below example,
In Xpath locator
//div[@class='panelClass1 panelClass2']
In CSS selector
css=div.panelClass1.panelClass2

(3) Any Attributes:
For selecting an element by its any of the attribute(say "name" is an attribute of a 'div' element and "type" in an "input" element) is given below:
In Xpath locator
//div[@name='continue']
//input[@type='button']
In CSS selector
css=div[name='continue']
css=input[type='button']

(4) Direct Child:
A direct child of an element is denoted as "/" in Xpath and ">" in CSS selector. See the example below for a direct child "li" for a "ul" element:
In Xpath locator
//ul/li
In CSS selector
css=ul > li

(5) Child or Subchild:
A direct child of an element is denoted as "//" in Xpath and a wehite-space(" ") in CSS selector. See the example below for a child/subchild "li" for a "ul" element:
In Xpath locator
//ul//li
In CSS selector

    
css=ul li
Note that "ul li" and "ul > li" are different. If you are confusing please go through this article.

(6) nth Child:
For finding 'nth' child, in Xpath we denote as "[n]" and in CSS we denote as ":nth-of-type(n)". See the below example,

<ol id="cars">
  <li>Audi</li>
  <li>BMW</li>
  <li>Toyota</li>
  <li>Benz</li>
  <li>Volvo</li>
</ol>    

In Xpath locator
//ul[@id='drinks']/li[3]
In CSS selector
css=ul#drinks li:nth-of-type(3)

We can use nth element ":nth-child" but the difference between ":nth-child" and ":nth-of-type(n)" is:
li:nth-child(2)
This means, select an element if It is a paragraph element and the second child of a parent.
li:nth-of-type(2)

This means, select the second paragraph child of a parent. This is less conditional.
See here for more details on difference between the above two.

If we want to select the "fifth li element" (cars) in this list, we can use the nth-of-type, which will find the fifth li in the list.
css=ul#cars li:nth-of-type(5)

On the other hand, if we want to get the "fifth element" only if it is a li element, we can use a filtered nth-child which will select again (Soft Drinks) here.
css=ul#drinks li:nth-child(5)

(7) Parent of an element:
Parent of an element can be represented as "/.." in Xpath and ":parent" in CSS selectors. For example, if you want to indicate parent of the list item of class 'blue'
   
<ul>
  <li class="red">first</li>
  <li>second</li>
  <li>third</li>
  <li>fourth</li>
  <li>fifth</li>
</ul>

In Xpath locator
//li[@class='blue']/..
In CSS selector
css=li.blue:parent

(8) Next Sibling:
Next sibling is nothing but next adjacent element which is inside the same parent on the page. An adjacent sibling combinator selector allows you to select an element that is directly after another specific element. For example, If you want to select the sibling of "li" element with class "blue" which is 'second' list item,
In Xpath locator
//li[@class='blue']/../li[2]
In CSS selector
css=li.blue + li

Similarly, if you want to indicate 'fifth' list item, see the below
In Xpath locator
//li[@class='blue']/../li[5]
In CSS selector
css=li.blue + li + li

(9) Match by Innertext:
There is a javascript methodcontains() which can be used to check the inner text of a web element. For example a link with text "Sign in"
In Xpath locator
//a[contains(text(),'Sign in')]
or
//a[contains(string(),'Sign in')]
In CSS selector
css=a:contains('Sign in')

(10) Match by Sub-string:
This is interesting and is described below. With this we can match strings with its partial text. E.g. prefix, suffix or any pattern(sub-string)
(a) Match a Sub-string(pattern):
 Taking an example of a 'div' with an 'id' that contains the text "pattern"
 
 
In Xpath locator, we need to use "contains()" to match a sub-string  //div[contains(@id,'pattern')]  In CSS selector, we need to use "*=" for matching a sub-string  css=div[id*='pattern'] (b) Match a prefix: Taking an example of a 'div' with an 'id' that starts with the text "prefixString"
In Xpath locator, we need to use "starts-with" to match a prefix //div[starts-with(@id,"prefixString")] In CSS selector, we need to use "^=" for matching a prefix css=div[id^='prefixString'] (c) Match a suffix: Taking an example of a 'div' with an 'id' that starts with the text "suffixString"
In Xpath locator, we need to use "ends-with" to match a suffix Note that "ends-with()" is a standard XPath 2.0 function only, it won't work if you are using Xpath 1.0 engine //div[ends-with(@id,"suffixString")] In CSS selector, we need to use "$=" for matching a suffix css=div[id$='suffixString'] Match a Sub-string     Match a Prefix     Match a Suffix Xpath      contains()      starts-with()      ends-with() CSS      *=      ^=      $=

 

 

Unzip the Zip folder using Selenium

package com.test;

import com.aventstack.extentreports.Status;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class UnZip {

    private static WebDriver driver;

    public static String ZipFunction(String Zipfilename) throws Exception
    {
        String home = System.getProperty("user.home");
        File file = new File(Absolute path of the output of extracted zip file); //Creating a output folder 
        boolean fileexists = false;
        if (!file.exists()) {
            fileexists = file.mkdirs();
        }
        if (fileexists)
            System.out.println("Directory successfully created");
        else
            System.out.println("Failed to create directory");
        
        File zipFile = new File("Absolute path of input Zip file");
        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry ze = zis.getNextEntry();
        String XMLFileName = ze.getName().toString();
        while (ze != null) {
        //String entryName = ze.getName();
        System.out.print("Extracting " + XMLFileName + " -> " + outputFolder + File.separator + XMLFileName + "...");
        File f = new File(outputFolder + File.separator + XMLFileName);
        //create all folder needed to store in correct relative path.
        f.getParentFile().mkdirs();
        FileOutputStream fos = new FileOutputStream(f);
        int len;
        byte buffer[] = new byte[1024];
        while ((len = zis.read(buffer)) > 0) 
        {
         fos.write(buffer, 0, len);
        }
        fos.close();
        System.out.println("OK!");
        ze = zis.getNextEntry();
        }
        zis.closeEntry();
        zis.close();
        String XMLFile = outputFolder+File.separator+XMLFileName;
        return XMLFile;      
    }
    
    /*public static String XMLFile(String value) throws Exception
    {
        if(value != null){
            System.out.println("-------------------------------------");
            System.out.println(value);
            System.out.println("-------------------------------------");
            return value;
        } else {
            return null;
        }
       
    }*/
}

Reading all XML tags with values in XML file using Selenium

package com.test;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.IOException;

public class XMLRead {

  public static void main(String argv[]) throws ParserConfigurationException, SAXException, IOException {

      File fXmlFile = new File(Absolute Path of XML file); 
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);
        
        doc.getDocumentElement().normalize();
        System.out.println("Root element " + doc.getDocumentElement().getNodeName());
        NodeList nodeList=doc.getElementsByTagName("*");       
         for (int count = 0; count < nodeList.getLength(); count++) 
             {
                Node tempNode = nodeList.item(count);
                // make sure it's element node.
                if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
                    // get node name and value
                    System.out.println("\nNode Name  =" + tempNode.getNodeName()); // + " [OPEN]");
                    System.out.println("Node Value  =" + tempNode.getTextContent());
                    System.out.println("Node Name =" + tempNode.getNodeName()); // + " [CLOSE]");
                    }
              }
            }
          }



Sample XML File :

<?xml version="1.0" encoding="UTF-8"?>
<addresses xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation='test.xsd'>
  <address>
    <name>Joe Tester</name>
    <street>Baker street 5</street>
  </address>
</addresses>


Output:

Node Name =address

Node Name  =name
Node Value  =Joe Tester
Node Name =name

Node Name  =street
Node Value  =Baker street 5
Node Name =street



Upload file using Selenium (SendKeys Method)

package com.test;
 
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
 
  public class UploadFile{

  public static void main(String[] args) {  

  WebDriver driver = new FirefoxDriver();
  driver.manage().window().maximize();        
  driver.get("http://www.helloselenium.com/2015/03/how-to-upload-file-using-sendkeys.html");

// Web element of Upload file & valid absolute path of the file
  WebElement fileInput = driver.findElement(By.name("uploadFileInput"));
  fileInput.sendKeys("provide a valid absolute path of the file");

//Web element of Upload Button
  WebElement ButtonFile = driver.findElement(By.name("uploadFileButton"));
  ButtonFile.click();   
  driver.quit(); 
 }
}

Web App Testing In Ruby using RUBY

Hi folks, Today I’m going to explain how to test the web apps using the testing frame work WATIR in Ruby. WATIR is a free open source tool , WATIR pronounced water, is an open-source (BSD) family of Ruby libraries for automating web browsers. It supports your app no matter what technology it is developed in. They support Internet Explorer on Windows, Firefox and Chrome on Windows, Mac and Linux.fOR MORE INFO VISIT http://watir.com/

Currently supported drivers are:

Below are the steps for installing & getting started for WATIR.

  • Add it into your Gemfile
    gem "watir"

    Or install it manually with the following command:

    gem install watir
    

    Then in your test file:

    require "watir"
    browser = Watir::Browser.new
  • To know path of web elements , we need to install HTML Inspector
  • On Firefox, use Firebug
    • On Internet Explorer, use the IE Developer Toolbar
      To use Watir effectively, you’ll need to be able to browse through the structure of your application’s HTML pages. These tools help you do that.
  • Now open a text file and add the below code
  •  Now save the file with an extension of .rb , now go to the terminal and go to the file path. Type ruby Filename.rb and press enter.Now web browser is initiated and opens the google web page.

 

 

Native Mobile Apps Automation Testing Using Calabash Framework with Ruby.

Hi folks, Today I’m going to explain how to test the mobile apps native(with hybrid I faced challenges like id is displaying as empty and we have to follow WebView and this WebView is different for different frameworks) using the testing frame work Calabash in Ruby. Calabash is a free open source project,developed &  maintained by Xamarin.You can get additional information at GitHub repository: https://github.com/calabash The following tools are required to test the mobile app.

  1. Ruby
  2. Android SDK
  3. Java

Now follow the below steps: Step 1: Open ruby and check for the version you are using.For this type the below command in your Ruby command prompt. ruby -v Install the below listed gems : calabash-android, calabash-common ,calabash-cucumber, calabash-extras cucumber  ,cucumber-core ,gherkin(2.12.2 ruby x86-mingw32) ,gherkin-ruby, io-console, motion-calabash, multi_json, retriable, rspec rspec-core, rspec-expectations, rspec-mocks, rspec-support ,gametel And type gem list in Ruby command prompt to view the list of gems installed in your machine.

1

Step 2 : Install Android SDK and create a virtual devise inorder to test the app in emulator else you can plug android devise to system to check on your devise. To list all the devises attached to the system type the below command : adb devices 2

Step 3: Configuring Environmental Variables 1.Right click on My Computer and select Properties. 2.Select Environment variables>Create new variable 3.Put varaible name as ANDROID_HOME and set variable value as Android SDK path i.e (c:\foldername\sdk). 4.Set the value as JAVA_HOME variable value as JAVA JDK folder.

3

5.Set the value for Android platform variable name as Path and variable value as  path of  android-sdk under platform-tools in SDK folder. 4

Now your testing environment is ready so lets get started with the testing process. 1.First make a directory and paste the apk file of the mobile application in that directory.

2.Create a gem file and copy the gem list in that file as below and type the below command in the ruby command prompt bundle exec install or bundle install. Gemfile.lock file will be generated in that folder after  executed the above command.

5

3.Now open the command prompt and you are in the folder of you application. And run the below command calabash-android gen This command will generate a skeleton folder structure consisting features and sub folders as shown below. 7        7 Now go to the command prompt and type the below command to get the apk signed. calabash-android resign

8

Now open the terminal or command prompt and type the below command to enter into the console mode of the application. calabash-android console 9

Here the test server is created for the application and now we have to install the app into the emulator or the devise for that use the below command in console. >reinstall_apps

10

The app is installed into your emulator or devise successfully, if you get any errors try to uninstall the app or try with the same command again because sometimes the app building gets failed due to delay in app starting. Find my_first.features file in features folder and write the test cases here and execute using the below commands on emulator or devise. 4. Now exit from console and type the below command in the command line to run the test case. calabash-android run  If you want the detailed report saved as html file then use the below command. calabash-android run -f html -o test-result.html

13

The test report is saved in the application folder you can view the report on the browser.