Thursday, December 18, 2014

Using Q promises with node.js http requests

This post is intended at providing a code snippet on how to use Q promises with node.js http requests.

I was introduced to the concept of promises and deferred when I found myself uncomfortable writing asynchronous functions within callbacks.

The code is not:
1. Maintanable
2. Readable
3. Intuitive

That is when I stumbled on JQuery Deffered and Promises. Once I got a hang of it I came across the Q Library that does pretty much the same thing with node.js.

I found it difficult to apply it to node.js http requests and after I gave it more time I got a hang of it.

The following gist demonstrates on how to wrap the the node.js http request with the q library.

In the gist we are attempting to invoke the Google News API using the node.js http requests.


//import the http library
var http = require('http'),
//npm install q before requiring it
Q = require('q');
//a js object with options
var googleNewsOptions = {
hostname: 'ajax.googleapis.com',
path: '/ajax/services/search/news?v=1.0&q=nodejs',
method: 'GET'
};
/**
* wrapper for http request object
* @param {Object} requestOptions
* @return Promise Object
*/
function promisedRequest(requestOptions) {
//create a deferred object from Q
var deferred = Q.defer();
var req = http.request(requestOptions, function(response) {
//set the response encoding to parse json string
response.setEncoding('utf8');
var responseData = '';
//append data to responseData variable on the 'data' event emission
response.on('data', function(data) {
responseData += data;
});
//listen to the 'end' event
response.on('end', function() {
//resolve the deferred object with the response
deferred.resolve(responseData);
});
});
//listen to the 'error' event
req.on('error', function(err) {
//if an error occurs reject the deferred
deferred.reject(err);
});
req.end();
//we are returning a promise object
//if we returned the deferred object
//deferred object reject and resolve could potentially be modified
//violating the expected behavior of this function
return deferred.promise;
};
//incoking the above function with the request options
promisedRequest(googleNewsOptions)
.then(function(newsResponse) { //callback invoked on deferred.resolve
console.log(JSON.stringify(newsResponse));
}, function(newsError) { //callback invoked on deferred.reject
console.log(newsError);
});

Wednesday, October 1, 2014

Soap UI Groovy Set POST Parameter

The following code snippet show how we can set a POST parameter value in a testStep in soapui using groovy


//set sessionToken with jwt token to post request
testRunner.testCase.getTestStepByName("TestStep").testRequest.params.setPropertyValue('requestParameterName','requestParameterValue');

Tuesday, September 30, 2014

SoapUI Groovy Set Headers to Test Steps

During the development of my project we had to develop multiple REST endpoints.

A call to each of these REST endpoints needed to be authenticated by passing an oauth-token in their header.

Post development we had to change the core REST endpoints code to incorporate design changes.

In such situations it is necessary to do a quick regression test before pushing the code to QA.

In the following groovy snippet in soap ui we do the following:

1. Get the oauth token from the first test step
2. Parse the JSON reponse (refer to my previous post)
3. Iterate through each of the test steps and set the headers for each of them


import groovy.json.JsonSlurper;
import com.eviware.soapui.support.types.StringToStringMap;
//get the response from the test step that makes the call to get the authentication token
def authResponse = testRunner.testCase.getTestStepByName("GetToken").getPropertyValue("response");
//parse the json response
def authResponseJSON = new JsonSlurper().parseText(authResponse);
//access the access_token property in the respose
def oauthToken = authResponseJSON.access_token;
//create a new empty map for headers
def headers = new StringToStringMap();
//create a key value pair in the headers mao
headers.put("OAuth-Token", oauthToken);
//obtain the list of test steps
def steps = context.testCase.getTestStepList();
//iterate thru each of the test steps and set the oauth token to each of the steps
steps.each{
// This block will loop through the test steps and set headers for each of them
if (it.name != 'GetToken' && it.name != 'TransferOauthToken')
it.testRequest.setRequestHeaders(headers);
}

SoapUI Groovy parse json

I came across a situation where I had to use groovy scripts in to test some REST endpoints that return JSON responses.

So following is a groovy code snippet which does the following:
1. Import the json parsing library
2. Fetch the JSON response from a test step
3. Parse the JSON response
4. Access properties in the JSON response

//import library to parse JSON
import groovy.json.JsonSlurper;
//get the JSON response from the test step that makes the call to some test step to get a JSON repsonse
def response = testRunner.testCase.getTestStepByName("TestStepName").getPropertyValue("response");
//parse the json response
def responseJSON = new JsonSlurper().parseText(response);
//access the propertyname
def property = responseJSON.propertyname;

Wednesday, September 24, 2014

Selenium Web Driver node.js set chrome options

The following code snippet demonstrates on how to set command line options to the chrome webdriver in selenium.

Here we are using the selenium-webdriver npm available for node.js
//import the selenium web driver
var webdriver = require('selenium-webdriver');
var chromeCapabilities = webdriver.Capabilities.chrome();
//setting chrome options to start the browser fully maximized
var chromeOptions = {
'args': ['--test-type', '--start-maximized']
};
chromeCapabilities.set('chromeOptions', chromeOptions);
var driver = new webdriver.Builder().withCapabilities(chromeCapabilities).build();




Thursday, July 17, 2014

CURLOPT_SSL_VERIFYPEER option for PHP

When trying to use curl with PHP to invoke REST API, we encounter an error and on googling it the simple fix suggested is to set the CURLOPT_SSL_VERIFYPEER option to false.

It turns out that if CURLOPT_SSL_VERIFYPEER is set to false on production systems then API calls could become victims to Man In the middle attachs

The ideal way to resolve this error is to follow the following instructions

1. Download the CA root certificate bundle from http://curl.haxx.se/docs/caextract.html
2. Then set a path to it in your php.ini file, e.g. on Windows:
    eg. curl.cainfo=c:\php\cacert.pem
3. Restart your php instance

Monday, June 4, 2012

Proxy Settings For Google Maps On the Android Emulator

Android Google Maps - Proxy settings for Emulator

Many of us have faced the problem when using the Google Maps app
on emulators when we are sitting behind a corporate firewall.

The Google Maps app just shows a blank screen.

Then we google (search) it up and we come up with many answers (most of them from stackoverflow.com)

Following are the steps on the internet in the order of least useful to most useful (in my opinion !!)

1. Many posts suggest that we go to the Emulator and do the following settings

    Get the Proxy Host Address and port number of your network
    Open the Menu->settings->Wireless & Networks->Mobile Networks->Access Point Names in Android Emulator
    Open Telkila
    Edit Proxy to your Proxy Host Address like-10.117.123.169
    Edit Port to the your Port like-8080
    Remove * from Username, Password and Server fields and make them blank().
    Set Authentication Type as “PAP or CHAP”
    Now, Press Menu->Save

    I got this one from Garg Engineer
   
    This works fine for the browser but not for apps using the Google Maps App.
   
2. Then there is a suggestion to start the emulator with the proxy settings from the command line as

   emulator.exe -avd Android2.3.3 -http-proxy http://:
   or
   emulator.exe -avd Android2.3.3 -http-proxy http://:@:
  
   For futher reference please see the Android Emulator reference @ http://developer.android.com/guide/developing/tools/emulator.html
  
   Where Android2.3.3 is the name of the virtual device I have created using my AVD manager targeted at Android 2.3.3, SDK Level 10.
  
   Now when your are sitting behind a corporate firewall you might have to type your username as: USERNAME or DOMAIN\USERNAME
  
   Also note if your password has the character '@' you will run into problems
  
   Now most of the corporates use Automatic proxy configuration URL, which looks like http://servername/xxxx.pac
  
   In such cases just type your proxy URL, i.e, http://servername/xxxx.pac in your browser.
  
   It will either prompt you to download a file or display the file in the browser itself.
  
   It might look like
  
  

  var proxyList = new Array();

  {
    proxyList[0] = "proxy1:port";
    proxyList[1] = "proxy2:port";
  }


   or
  
   var proxyConfig = "PROXY proxy:port";
  
   So extract your proxy IP and PORT and use them in the command line as specified above
  
   Unfortunately this might not work for all.
  
3. So finally the stuff that did work for me was to add the -dns-server option.

   To know what your DNS servers are, type ipconfig/all in your command line and you should see one or more DNS Servers

   So the proxy-setting that finally worked for me was like this
  
   emulator.exe -avd Android2.3.3 -http-proxy http://:@: -dns-server ,
  
   I got this from http://stackoverflow.com/questions/6339246/android-no-internet-access-on-emulator-proxy-settings
  
   Hope this helps