Wednesday, 1 February 2017

Api testing : Get

Simple GetApi code:

Maven dependency:
<!--For Http Get/Post/ect we need HTTP client libs :: http://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.6</version>
</dependency>



<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20160810</version>
</dependency>


import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.testng.Assert;

public class TestGet {

public static void main(String[] args) {

String url = "https://httpbin.org/get";
HttpResponse response = null;

HttpClientBuilder builder = HttpClientBuilder.create();
HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager();
builder.setConnectionManager(connectionManager);
HttpClient httpclient = builder.build();
RequestConfig requestConfig = RequestConfig.custom()
/*
* connectionRequestTimeout happens when you have a pool of
* connections and they are all busy, not allowing the
* connection manager to give you one connection to make the
* request.
*/
.setConnectionRequestTimeout(30000)
/*
* connectTimeout happens when establishing the connection. For
* instance while doing the tcp handshake.
*/
.setConnectTimeout(30000)
/*
* socketTimeout: is the timeout while waiting for data. Usually
* happens when your server is slow
*/
.setSocketTimeout(30000).build();
try {
HttpGet httpget = new HttpGet(url);
httpget.setConfig(requestConfig);
response = httpclient.execute(httpget);
String responseBody = EntityUtils.toString(response.getEntity());
JSONObject jsonObj = new JSONObject(responseBody);
System.out.println(jsonObj.get("origin"));
//Assert.assertTrue(response.getStatusLine().getStatusCode() == 200);
} catch (IOException ex) {

}

}

}

Json utils

As part of api testing, we might need to play with json objects, arrays and key-value pairs.

here is the solution.


Maven dependency:

<!-- Rest Utils Returns JsonObject :: http://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>

Java code:



import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;

/**
 * Class which consists of differnt methods related to Json Utils
 */
public class JsonUtils {

/**
* Method to Converts given String to JSON object
*
* @param str
* @return json Object
*/
public static JSONObject getJsonObjectFromString(String str) {
return new JSONObject(str);
}

/**
* Method to Converts given String to JSON Array
*
* @param str
* @return json array
*/
public static JSONArray getJsonArrayFromString(String str) {
return new JSONArray(str);
}

/**
* method to read json object form resp object
*
* @param response
* @return json object
*/
public static JSONObject getJsonFromResponse(HttpResponse response) {
String responseBody = null;
try {
responseBody = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
JSONObject jsonObj = new JSONObject(responseBody);
return jsonObj;
}

/**
* method to read json array form resp object
* @param response
* @return JsonArray
* @throws JSONException
*/
public static JSONArray getJsonArrayFromResponse(HttpResponse response) {
String responseBody = null;
try {
responseBody = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
JSONArray jsonObj = new JSONArray(responseBody);
return jsonObj;
}

/**
* Method to read value from json for the said key
*
* @param jsonObj
* @param key
* @return
*/
public static Object getValueFromJson(JSONObject jsonObj, String key) {
Object propertyUtilityCount = 0;
propertyUtilityCount = jsonObj.get(key);
return propertyUtilityCount;
}

/**
* Method to read json array from json object for the said key
*
* @param jsonObj
* @param key
* @return
*/
public static JSONArray getSaidJSonArrayFromJson(JSONObject jsonObj, String key) {
Object object = jsonObj.getJSONArray(key);
if (object instanceof JSONArray) {
return (JSONArray) object;
} else {
throw new JSONException(key + " JSONObject is not a JSONArray.");
}
}

/**
* Fetch the object with in an array and through index we fetch which Object
* we want to fetch
*
* @param getResponse
* @param i
* @return
* @throws IOException
*/
public static JSONObject getJsonArrayFromJsonObject(HttpResponse getResponse, int i) {

String result = "";
try {
result = EntityUtils.toString(getResponse.getEntity());
} catch (ParseException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
JSONArray e = new JSONArray(result);
JSONObject obj = e.getJSONObject(i);
return obj;
}

/**
* Method to fetch json object from json array for the said index
*
* @param jsonArray
* @param i
* @return json object
*/
public static JSONObject getSaidJsonObjectFromJsonArray(JSONArray jsonArray, int i) {
JSONObject obj = new JSONObject();
obj = jsonArray.getJSONObject(i);
return obj;
}

/**
* Method to fetch json object from json object for the said key
*
* @param jsonObj
* @param key
* @return json object
*/
public static JSONObject getSaidJsonObjectFromJsonObject(JSONObject jsonObj, String key) {
JSONObject obj = new JSONObject();
obj = jsonObj.getJSONObject(key);
return obj;
}

/**
* Method to fetch json object from json object
*
* @param jsonObj
* @return json object
*/
public static JSONObject getSaidJsonObjectFromJsonObject(JSONObject jsonObj) {
JSONObject obj = new JSONObject();
return obj;
}

/**
* verifies that given json is empty or not
*
* @param json
*            obj
* @return boolean value
*/
public static boolean isNonEmpty(JSONObject obj) {
boolean result = false;
if (obj.length() <= 0 || obj != null) {
result = true;
}
return result;
}

/**
* checks the given json array is empty or not
*
* @param obj
* @return boolean value
*/
public static boolean isNonEmpty(JSONArray obj) {
boolean result = false;
if (obj.length() <= 0 || obj != null) {
result = true;
}
return result;
}

/**
* converts json object to xml
*
* @param jsonObj
* @return String
*/
public String toXML(JSONObject jsonObj) {
String xml = XML.toString(jsonObj);
return xml;
}

}

Excell read / update using apache libs

Here is the Maven dependency:
<!-- THis is to read and write excel sheest for data and other purposes:
https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>

add below one, if not a maven project i.e manual jar adition

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.15</version>
</dependency>


Code:


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * Method to read and update Excel sheet
 */
public class ExcelReader {
private Cell openCell;
private Row openRow;
private Sheet openSheet;
private String data;
private Workbook openWorkbook;
InputStream inp;
File f;

/**
* Creates an Excel reader object and open the said workbook at the
* specified path.
*
* @param excelPath
*            - The path of the excel file
*/
public ExcelReader(String excelPath) throws Exception {
this(new File(excelPath));
}

/**
* Creates an Excel reader object and open the said workbook at the
* specified path.
*
* @param excelFile
*            - File object of the excel file
*/
public ExcelReader(File excelFile) throws Exception {
f = excelFile;
inp = new FileInputStream(excelFile);
if (isXlsx(excelFile))
openWorkbook = new XSSFWorkbook(inp);
else
openWorkbook = new HSSFWorkbook(inp);
}

/**
* Returns true or false depending upon whether file name ends with xlsx
* * @param fl
*
* @return
*/
private boolean isXlsx(File fl) {
String fileName = fl.getName();
if (fileName.endsWith("xlsx"))
return true;
return false;
}

/**
* Open sheet with the specified name
*
* @param sheetName
*/
public void openSheet(String sheetName) {
openSheet = openWorkbook.getSheet(sheetName);
}

/**
* Gets current sheet name
*
* @param sheetNo
*            - Index of sheet
* @return - Sheet name
*/
public String getCurrentSheetName(int sheetNo) {
openSheet = openWorkbook.getSheetAt(sheetNo);
return openSheet.getSheetName();
}

/**
* Gets number of sheets in the given workbook
*
* @return - number of sheets in the workbook
*/
public int getNoOfSheets() {
return openWorkbook.getNumberOfSheets();
}

/**
* Gets the data from the currently opened sheet present on the specified
* row and column
*
* @param column
* @param row
* @return - Respective data in string format. "" if the said row -column
*         does not exist
*/
public String getData(int column, int row) {
try {

openRow = openSheet.getRow(row);
openCell = openRow.getCell(column);
@SuppressWarnings("deprecation")
int cellType = openCell.getCellType();
switch (cellType) {
case 0:
if (DateUtil.isCellDateFormatted(openCell)) {
Date dt = openCell.getDateCellValue();
SimpleDateFormat sdf = new SimpleDateFormat("dd MM yyyy HH:mm:ss");
data = sdf.format(dt);
} else
data = Long.toString(Math.round(openCell.getNumericCellValue()));
break;
case 1:
data = openCell.getRichStringCellValue().getString();
break;
case 2:
data = openCell.getRichStringCellValue().getString();
break;
case 3:
data = openCell.getRichStringCellValue().getString();
break;
case 4:
data = Boolean.toString(openCell.getBooleanCellValue());
break;
case 5:
data = Byte.toString(openCell.getErrorCellValue());
break;
default:
data = openCell.getRichStringCellValue().getString();
}

if (data == null) {
data = "";
}
return data;
} catch (Exception e) {
if (openRow == null || openCell == null || data == null) {
data = "";
return data;
} else {
System.out.println(e);
return "";
}
}

}

/**
* Number of rows in the said sheet.
*
* @return
*/
public int getNoOfRows() {
return (openSheet.getLastRowNum() + 1);
}

/**
* Number of columns in the first row of the sheet
*
* @return
*/
public int getNoOfColumn() {
Row rw = openSheet.getRow(0);
if (rw == null)
return 0;
return rw.getLastCellNum();
}

/**
* Number of columns of a particular row number that is specified
*
* @param rowNumber
* @return
*/
public int getNoOfColumn(int rowNumber) {
Row rw = openSheet.getRow(rowNumber);
if (rw == null)
return 0;
return rw.getLastCellNum();
}

/**
* Gets the current open sheet name
*
* @return
*/
public String getSheetName() {
return openSheet.getSheetName();
}

/**
* Updates current sheet with given data.
*
* @param col
* @param row
* @param data
*/
public void updateData(int col, int row, String data) {
try {
openRow = openSheet.getRow(row);
openCell = openRow.createCell(col);
openCell.setCellValue(data);
inp.close();
FileOutputStream out = new FileOutputStream(f);
openWorkbook.write(out);
out.close();
} catch (Exception ex) {
}

}
}

Generic utils for any project / Random number / String generators


here is the maven dependency.

<!--utils For Random Number / String generation:: https://mvnrepository.com/artifact/commons-lang/commons-lang -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>


Code:

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.RandomStringUtils;

/**
 * a common utils class to generate random alphanumerics and project specific
 * strings
 *
 */
public class CommonUtils {

/**
* Method to generate random alpha numeric string of size 10
*
* @return
*/
public static String getRandomAlphaNumeric() {
return RandomStringUtils.randomAlphanumeric(10);
}

/**
* Method to generate random alphabet string of size 10
*
* @return
*/
public static String getRandomAlphabetic() {
return RandomStringUtils.randomAlphabetic(10);
}

/**
* Method to generate random numeric string of size 10
*
* @return
*/
public static String getRandomNumeric() {
return RandomStringUtils.randomNumeric(10);
}

/**
* Method to generate random numeric from the given max and min numbers
*
* @param max
* @param min
* @return
*/
public static int getRandomNumeric(int max, int min) {
Random rand = new Random();
int randomNum = rand.nextInt(max) + min;
return randomNum;
}

/**
* Method to generate random dates for checkin and checkout
*
* @return map of string, string
*/
public static HashMap<String, String> getDates() {
HashMap<String, String> map = new HashMap<String, String>();
int i = getRandomNumeric(285, 1);// checkin date
int j = getRandomNumeric(14, 1);// checkout date
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); // date format
Calendar c = Calendar.getInstance();
c.setTime(new Date()); // Now use today date.
c.add(Calendar.DATE, i); // Adding i days
String checkinDate = sdf.format(c.getTime());
map.put("CHECKIN", checkinDate);

c.add(Calendar.DATE, j); // Adding j days
String checkoutDate = sdf.format(c.getTime());
map.put("CHECKOUT", checkoutDate);
return map;
}

/**
* Method to generate random email id
*
* @return
*/
public static String getRandomEmailId() {
return "John" + RandomStringUtils.randomNumeric(10) + ".Smith@test.com";
}

/**
* Method to convert given millsecs to hours,min,secs and milli secs
*
* @param millis
* @return
*/
public static String timeConversion(long millis) {
String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) % TimeUnit.HOURS.toMinutes(1),
TimeUnit.MILLISECONDS.toSeconds(millis) % TimeUnit.MINUTES.toSeconds(1));
String strMilli = TimeUnit.MILLISECONDS.toMillis(millis) % TimeUnit.MINUTES.toMillis(1) + "";

hms = hms + ":" + strMilli;
return hms;
}
}

Soft Assertion util. VerifyTestUtil

As part of the project, we might need to soft assert our assertions and show all error message at a time instead of breaking the execution then and their.

here is the solution.


import java.util.ArrayList;

import org.testng.Assert;

/**
 * Class to verify multiple assertions and sums of error messages
 *
 */
public class VerifyTestUtil {
private ArrayList<String> results = new ArrayList<String>();

/**
* method to verify one condition and add err message ot err list
*
* @param condition
* @param message
*/
public void verify(boolean condition, String message) {
if (!condition)
results.add(message);
}

/**
* final verification to check whether the test is passed or not
*
* @return
*/
public boolean isPassed() {
return results.size() == 0;
}

/**
* Method to read messages
*
* @return
*/
public String getMessage() {
return results.toString();
}

/**
* final method to execute
*
* @return
*/
public boolean assertTestResult() {
for (String str : results)
System.out.println(str);
Assert.assertTrue(results.size() == 0, results.toString());
return results.size() == 0;
}

/**
* verifies result
*
* @param message
* @return
*/
public boolean assertTestResult(String message) {
for (String str : results)
System.out.println(str);
Assert.assertTrue(results.size() == 0, message + " " + results.toString());
return results.size() == 0;
}

/**
* compare two strings and append err message if any
*
* @param one
* @param two
* @param message
* @return
*/
public boolean assertEqual(String one, String two, String message) {
if (one.contentEquals(two))
return true;
else {
results.add(message);
return false;
}
}

/**
* comares two integers
*
* @param one
* @param two
* @param message
* @return
*/
public boolean assertEqual(int one, int two, String message) {
if (one == two)
return true;
else {
results.add(message);
return false;
}
}

/**
* method to asserts  true
* @param condition
* @param message
*/
public void assertTrue(boolean condition, String message) {
Assert.assertTrue(condition, message);
}
}

Do you want to read property file ?

Many of us wanted to read property file as part of framework development and here we go.

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * Class to read said property file and load in Properties object
 */
public class PropertiesReaderUtility {

private Properties properties = new Properties();

/**
* constructor which takes file path as input
*
* @param fileName
*/
public PropertiesReaderUtility(String filePath) {
try {
properties.load(new FileInputStream(filePath));
} catch (IOException e) {
throw new RuntimeException(e);
}
assert !properties.isEmpty();
}

/**
* gets the value for the said key
*
* @param key
* @return
*/
public String getProperty(final String key) {
String property = properties.getProperty(key);
return property != null ? property.trim() : property;
}
}

Oracle-JDBC DBUtil : Helps you connect to Oracle DB from java

Here is the DBUtil to connecto to Oracle DB

NOTE: Need to download ojdbc6.jar from oracle official site and add it in the libraries.

We can get this from maven, but some times it might not work as expected.

<!-- https://mvnrepository.com/artifact/oracle/ojdbc6 -->
<dependency>
    <groupId>oracle</groupId>
    <artifactId>ojdbc6</artifactId>
    <version>11.2.0.3</version>
</dependency>

Code starts here

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;

/**
 * DBUtil class is to make connections to DB and execute query
 */
public class DbUtil {
Connection sqlConnection = null;
ResultSet resultSet = null;
Statement statement = null;
String driver = "oracle.jdbc.driver.OracleDriver";
String serverName, dbName, portNo, userName, PassWord;

/**
* Constructor, which fetches db property values form config files
*/
public DbUtil() {
/* fetches working directory path */
String user_dir = System.getProperty("user.dir");
/*
* PropertiesReaderUtility reads selenium.properties and loads in prop
* variable
*/
PropertiesReaderUtility prop = new PropertiesReaderUtility(user_dir + "/selenium.properties");
serverName = System.getProperty("test.db.servername", prop.getProperty("test.db.servername"));
dbName = System.getProperty("test.db.dbname", prop.getProperty("test.db.dbname"));
portNo = System.getProperty("test.db.port", prop.getProperty("test.db.port"));
userName = System.getProperty("test.db.username", prop.getProperty("test.db.username"));
PassWord = System.getProperty("test.db.password", prop.getProperty("test.db.password"));
}

/**
* makes DB connection
*
* @return
*/
private Connection getConncetion() {
try {
Class.forName(driver);
String host = "jdbc:oracle:thin:@" + serverName + ":" + portNo + "/" + dbName;
sqlConnection = DriverManager.getConnection(host, userName, PassWord);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return sqlConnection;
}

/**
* connect to db and execute the query and fills in resultset
*
* @param query
* @return
*/
public ResultSet runQuery(String query) {
try {
sqlConnection = getConncetion();
statement = sqlConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
resultSet = statement.executeQuery(query);
} catch (Exception e) {
e.printStackTrace();
}
return resultSet;
}

/**
* Method to fetch no. of rows or size of the given result set
*
* @param rs
* @return
*/
public int getResultSetSize(ResultSet rs) {
int i = 0;
try {
while (rs.next()) {
i++;
}
while (rs.previous()) {
}
} catch (SQLException e) {
e.printStackTrace();
}
return i;
}

/**
* closes the all the opened objects
*/
public void close() {
try {
if (resultSet != null)
resultSet.close();
if (statement != null)
statement.close();
if (sqlConnection != null)
sqlConnection.close();
} catch (Exception ex) {
}
}
}

Eclipse - Maven - Archetype

Here is the archetype for a new maven project for automation

maven-archetype-quickstart

Adding multiple modules in one project : eclipse


A project can consist multiple modules, where a module is a project with some dependency on each other.


Create a Parent project:  ( which behaves like parent to further maven modules)

File – New – Other – Maven Project
Check “Create a simple Project (Skip archetype selection)
Next
Group id : com.parent
Artifact id : parent
Packaging : POM ß
Finish

This is how pom.xml looks like

<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.parent</groupId>
  <artifactId>parent</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>pom</packaging>
</project>

Create a child / maven module:

File – New – Other – Maven Module
Check “Create a simple Project (Skip archetype selection)
Module Name: Child
Parent Project: Parent
Finish

This is how pom.xml looks like
<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>
  <parent>
    <groupId>com.parent</groupId>
    <artifactId>parent</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <artifactId>child</artifactId>
</project>

Observations:

In child pom.xml:  observe that parent tag, which talks about who is my parent

Note: any dependencies declared in parent pom.xml are available to child pom.xml by default.

Testing:

GO to parent pom.xml file folder and say > mvn clean
Now two projects will be created.