Wednesday, 20 January 2016

REST API Automation:- Frisby.js , node.js , Jasmine, Javascript.

REST API Automation:- Frisby.js ,  node.js , Jasmine, Javascript.

Easy, Fast Rest API automation that really works . Fast paced , consistent result.

Back Ground:-

I came across such Rest API automation where  requirements for API automation is given below:-

1. Easy to automate ( QA non much technical knowledge) :- Its usually case in software industry where QA doesn't  have in depth technical expertise
2. Easy installation :- ease of installation is must ( 2-5 minutes).
3. Easy language used :- no OOPS
4. Cleaner reports :- not unnecessary failures.
5. Open source :- not licensed
6. Fast in execution :- faster reports on time.
7. Easy to code :- not much expertise required.
8. Continuous Integration support :- Jenkins support . Must run on multiple slave machine.
9. Free libraries available :- docs , sample code etc.
10. Consistent results
11. Easy to maintain :- framework is easy to maintain.
12. Simple framework development :- easy to develop and start.
13. Quick in producing results (gestation period). ( very quick)
14. Must show results in 2-3 hrs ( including installation , scripts , debugging , scripting and execution for novice users QA). Its really tough challenge for me.

 How this can be possible in such a short span of time? . But I made it happen looks pretty impossible.

I have worked  with Postman Rest client for manual testing of API and SoapUI Pro ( API Automation). Since It cant provide all the features required by Client because its licensed,
Easy of handling, Groovy scripting , consistent results, framework development , expert resource required. I was pretty confused what to do . I started reaching lot of tools available in the market where I am came across amazing libraries  known as frisby.js here.

Problems:- There are very few articles on the internet on same. Which describes how its really works. It took me sometime to understand documentation/libraries  here  . Since I am
pretty comfortable with basic JS / Groovy ( since It is one of the requirements not to use OOPS). You can go through through frisby.js  here and documentation for reference here

 How I can make them really work ? . That was biggest challenge.

There are multiple tools required to frisby.js to work  ( node.js and jasmine). I am assuming development environment doesn't have node.js and package manager npm.

Lets start :-

1. Installation :- there are many jagrons available on internet for same but thing that worked in totally different for me. Lets start here :- environment I am using is Win 7 

There are two ways to do Installation . I will quote easiest way first.:-

1. You need to install node.js (Go to nodejs.org and install it). and go to cmd to check node-v, npm -v. Note while installing node.js check npm package manager. restart machine after installation.

2. After machine restart-  Just create json file name it as package.json in any editor notepad, notepad++.

{
"name": "rest_tester",
"author": "Rahul Gupta Bangalore version 1.0",
"main": "rest_service_spec.js",
"version": "0.0.1",
"dependencies": {
"frisby": "latest",
"jasmine-node": "latest"
}
}

Save file on the desktop. Kindly check json syntax here . It must be valid json. Note we have dependencies to install frisby, jasmine.

1. Open cmd
2. Cd Desktop
3. npm Install

This will install frisby and jasmine libraries . Now we are ready to write first sample Rest (get/post/put) API automation. We are ready to go with scripting and developing framework.
I will give one example of each get, post, requests. Then we will start execution of scripts ,developing framework with TestNG, Eclipse etc.

This method of installation worked for me. Didn't show any errors.

2. Second way of installation:-

Step 1: Install Node.js (Frisby requires both node.js and NPM)
Go to nodejs.org and install it .

Step 2:-  Install Frisby
Go to cmd
npm install -g frisby

Check there are no errors shown while installation and note down path of frisby installation

Step 3:- Install jasmine
npm install -g jasmine-node

Installation of frisby.js is done with All required software's.


2. Writing scripts :- GET Request

 Rest Get Sample 1:-

//Author :- Rahul Gupta ( Automation Engineer bangalore India)
//Admin routes
//URL: http://admin.madaarride.com/users
// API GET:- http://admin.madaarride.com/users/trips

var frisby = require('frisby');
frisby.create('GET JSON data with parameters')
.get('http://admin.madaarride.com/users/trips')
.expectStatus(200)
.after(function (err, res, body) {
        if (res.statusCode !== 200) {
            console.log(body);
        }else{
console.info("Success");
}
    }).afterJSON(function (body) {
//console.log(body);

// Configuration test Data
expect(body[0].tripId).toMatch(6426024)
    //adminMadaarrideDrivers();
}).toss();


Save this file as sample_spec.js. Kindly make sure you name file as fileName_spec.js (required). lets go by synatx what it does.

//creates object frisby
var frisby = require('frisby');
frisby.create('GET JSON data with parameters')


// expectStatus(200)
method checks we get http 200 ok status as response . Its a assertion here.

// after(function (err, res, body)
used to validate after receiving response.

 //  console.log(body);
 printing on the cmd console

 //afterJSON(function (body)
 used to perform action on the json received as response. (kindly refer frisby document to use more method)

 // toss
 It used to end testcase.

 There are many types of validation we can do on response :-
 1. Http status code check
 2. Validation of response body.
 3. Kindly note we received many objects in the above request ( that why used body[0].tripId)). Basically use can use js syntax to validate response.
 4. commented line can be used to call another function (next testcase) in the same script. Its basically calling function to execute.
 5. You can parametrised url , variables etc can be put in config files in the framework. Libraries package will contain frisby.js functions
 6. External reporting can be used with TestNg or use java function to create custom report.
 7. All spec files can be put under Spec folder.
 8. There are many github links available to see coding /understand  framework
 9. Test Data can be kept in the one of the files (same as SoapUi pro ) to validate response with expected output.


 //-----------------------------------------------------------------------------------------------------------------
Rest Get Sample 2:
function adminMadaarrideDrivers() {
 var frisby = require('frisby');
 frisby.create('Description of the testcase here with TCID')
  .get('http://httpbin.org/get')
  .expectStatus(200)
  .expectHeader('Content-Type', 'application/json')
  .expectJSON({
'url': 'http://httpbin.org/get'
}).toss();
}

// .expectHeader('Content-Type', 'application/json')
Used to send content type in the header as and when required.

//.expectJSON
Method is used to validate json response.

//.expectJSON({ 'args': { 'param1': 'goodbye' }}
Based on response received we need to validate (nested object example)

//.expectJSONTypes({ 'origin': String })
Used to check data Types of keys received in the response.


//------------------------------------------------------------------------------------------------------------------------
Rest Get Sample 3:-


frisby.create('Rahul Gupta Testing the twitter api')
.get('https://api.twitter.com/1/statuses/user_timeline.json?screen_name=anyname')
//Verifying expected outcomes
.expectStatus(410)
.expectHeaderContains('content-type', 'application/json')
.expectJSONTypes('errors.*',{
message: String,
})
.expectJSON('errors.*',{
code: 74,
})
.toss();



//------------------------------------------------------------------------------------------------------------------------
Rest Post Method

Sample :-1

Sample test script:

function login_driver_account_1() {
    frisby.create(“login driver account”)
        .post("https://" + config.host + '/driver',
     {
        json: true,
        headers: headers <- this will contain Authorization variable
    })
        .expectStatus(201)
        .after(function (err, res, body) {
        if (res.statusCode !== 201) {
            console.log(body);
        }
    })
        .afterJSON(function (data) {
        expect(data.success).toMatch('true');
        token is not Null
     
        nextFunction();
    })

//-------------------------------------------------------------------------------------------------------------------------

Sample 2:-

// Post
 //http://admin.madaarride.com/users/driver/update

function adminMadaarrideDriverupdate() {
 frisby.create('GET JSON data with parameters')
 .post('http://admin.madaarride.com/users/driver/update',
 { Phone: xxxxx, Password: xxxxxxx }, { json: true }, { headers: { 'Content-Type': 'text/html; charset=utf-8' }})
 .expectStatus(200) .expectHeader('Content-Type', 'text/html; charset=utf-8')
 .after(function (err, res, body) {
        if (res.statusCode !== 200) {
            console.log(body);
        }else{
console.info("Success");
}.afterJSON(function (data) {
        expect(data).toMatch('Success');

/* include auth token in the header of all future requests */
frisby.globalSetup({ request: { headers: { 'x-access-token': res.token } } });
   //console.log(body);
   expect(body).toMatch('Error occurred. Failed to redirect')

    }).toss();
}


This example is self understood.

//---------------------------------------------------------------------------------------------------------------------------------

Execution or running of Frisby.js scripts

1.Go to cmd
2. Navigate to folder where are present ( example cd absolute path)
3. Jasmine-node filename_spec.js

It will execute and show how many assertion pass and failed.

//---------------------------------------------------------------------------------------------------------------------------------

Developing framework till :-
create following
1. Spec folder:- contains scripts js
2. Config folder - conatins input.properties file (stores input data), config.properties (stores password, url (request)).
3. Report :- external html use java to create same
4. Library :- conatins jasmine libraries
5. functions conatins ( resuable /utiltity function ( to read excel files , html report , read properties files))
6. Bat files
7. test Suite to run them as suite
8. Execution which conatins .xls files conatins tcid, testdescription , status and execution date and time.


//------------------------------------------------------------------------------------------------------------------------------------

I tried to make this document as simple as possible . Hope this helps . Happy automating Rest API...:)

Thanks In advance
Rahul Gupta

3 comments:

  1. @RAHUL - Very well explained article. I was going through it and found quite good. I was wondering if we can get the error messaes in the html report of frisby as of now it shows the failures of specific tests but if I want to show the stacktrace or error message how can I do that?

    ReplyDelete
  2. Thanks for appreciation. There are many libraries available which can customise and inject stacktrace for failed testcases along with status of testcase

    ReplyDelete
  3. What is the method to use to display Request Body in the Console

    ReplyDelete