Harshad Narvekar Automation world…

December 31, 2015

How to automate web-services/API’s using Selenium Webdriver

Filed under: Automation,Selenium Webdriver — narvekar @ 10:41 pm

Recently I wanted to automate web services (REST based services) using Selenium Webdriver for one automation project using json/xml formats and validate the response in json/xml format only.

Firstly, what is a webservice (in short)?

Web services are web application components.Web services can be published, found, and used on the Web.
Web services are application components which communicate using open protocols. Web services are self-contained and self-describing. HTTP and XML is the basis for Web services.

Web Services have Two Types of Uses

Reusable application-components.
Connect existing software.

We are going to take the first type in today’s example of automate testing a webservice

viz. web service on Open Weather Map http://openweathermap.org/forecast16

We are going to use specflow in combination with Selenium webdriver to test the above mentioned web service

As per requirement, we are working on the below mentioned Feature

Feature: Webservice forecast16
       In order to holiday in Sydney
       As a Happy holiday maker
      I want to know the daily weather forecast

Details of technical environment being used is as follows:

Visual Studio IDE, TechTalk.SpecFlow (1.9.0.77), Nunit, Newtonsoft Json Assembly (for Json manipulation) and Chrome browser.

The automation task covers the following below scenario and assertions:

Given webservice named Weather with this url “http://api.openweathermap.org/data/2.5/forecast/daily?cnt=1&units=metric

      And Authenticate with api key “appid=enteryourapikey”
      When I call the api with CityId as Paramater “id=2147714”
      Then I expect to get a valid Response
      And  I expect it to return an response has city “Sydney
And  I expect to return an response with temp greater than 10
And  I expect day to be Thursday “Saturday”

Assertions we are going to do:

       Response is valid json and contains Sydney as a destination (Response ok)
       Day of the weather forecast is Thursday (Assert value returned by web service is correct or not)
       Weather returned is > 10 degrees C (Assert value returned by web service is correct or not)

      Project Structure

I have maintained the below structure, however you are free to maintain any structure depending on your

framework_structure

Data can be parameterized through feature file or external resource. Keeping it basic in this example and reading from feature file.

Code used for calling webservice:

public JObject GetJSONFromWebService(String url, String parameter)
        {

            StringBuilder responseString = new StringBuilder();
           
            String ApiUrlString = String.Format(url);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ApiUrlString);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            // Get the stream associated with the response.
            Stream receiveStream = response.GetResponseStream();
            // Pipes the stream to a higher level stream reader with the required encoding format. 
            if (receiveStream != null)
            {
                StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
                string line = "";
                while ((line = readStream.ReadLine()) != null)
                {
                    responseString.Append(line);
                }

                response.Close();
                readStream.Close();
            }
            JObject json = JObject.Parse(responseString.ToString());
            return json;
        }

Asserting Json response is ok

 public Boolean AssertResponseOK(JObject json, string key)
        {
            Boolean bOk = false;
            foreach (var task in json)
            {
                if (task.Key.ToString().ToLower() == key)
                {
                    String response = task.Value.ToString();
                    
                    if (response.Equals("200"))
                    {
                        bOk = true;
                        break;
                    }
                    else
                    {
                        bOk = false;
                        break;
                    }

                }
                else
                {
                    bOk = false;
                }
            }

            return bOk;
        }

For questions or suggestions on topics to be covered on this blog, please do not hesitate to contact me at harshad@harshadnarvekar.com or leave a reply through the comment form below.

Thanks for visiting my blog. Have a nice day :)

An example of the above project using the pattern described above can be downloaded here.

November 5, 2015

How to consume json rest web service api in C# (.net)

Filed under: Automation,Selenium Webdriver,Software.. — narvekar @ 5:28 am

How to consume json rest web service api in C# (.net)

I wanted to consume a web service while testing (automating) in a project. I wanted to show how simple and straight forward it is to write your own tool/code for consuming JSON based APIs from .NET

Consuming web services and APIs will always be a big topic on our industry. Service oriented architectures enable us to create online endpoints to serve many different clients across the digital world. Application programming interfaces (APIs) are nothing new, they have been with us for a long time, and have consumed a lot of our efforts to communicate digital systems. However, web APIs are becoming more and more relevant, since they allows us to communicate thought networks to serve a wide variety of clients.

Representation State Transfer (REST) design models are the predominant software architecture for such distributed systems. Most modern web APIs are designed following the REST principles, resulting in simpler, general, more scalable web services that are easier to consume.

.NET has come a long way in terms of web services architectures. Most of us will remember traditional ASP.NET services, SOAP based services, WCF services and XML-based services without too much excitement. Although they were powerful service oriented technologies and frameworks, not many will say that they were easy to implement. RESTful services have also become the predominant model design in .NET, and now more than ever, consuming and exposing RESTful services relatively easy. However, there seems to be a lot of confusion about how to do such things in the .NET world!

will implement a simple Weather API client by using the OpenWeatherMap.org JSON API. The API will allow us to locate a city location and get the weather forecast information.

By Default Get method’s input and output parameters are of type XML(default) or JSON and returned in string format. Here the method returns in JSON format.

Below are steps we will perform in order to consume a RESTful service

  1. Create a HTTPWebRequest WebRequest object with the provided REST service URL
  2. Initiate the request and get response
  3. Read the stream from the response
  4. Serialize the stream and read the result (using Newtonsoft JSON library)

Step 1:

 // web service target 
            string url = " http://api.openweathermap.org/data/2.5/forecast/daily?cnt=1&units=metric&appid=useyourapikey";
            
            // Create a Web Request object type 
            WebRequest req = WebRequest.Create(@url);

            //Get method
            req.Method = "GET";

Step 2

 // Initiating the request
    HttpWebResponse resp = req.GetResponse() as HttpWebResponse;

Step 3

// Reading the response
 if (resp.StatusCode == HttpStatusCode.OK)
            {
                // reading the reponse 
                using (Stream respStream = resp.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(respStream, Encoding.UTF8);
                   // Console.WriteLine(reader.ReadToEnd());
                    String jsonstr = reader.ReadToEnd();
}

Step 4

   // Serialize the stream and read the result (using Newtonsoft JSON library)

                    JObject result = JObject.Parse(jsonstr);
                    //Console.WriteLine("json is: ---------------------" + result);

Entire solution

 class Program
    {
        static void Main(string[] args)
        {
            // web service target 
            string url = " http://api.openweathermap.org/data/2.5/forecast/daily?cnt=1&units=metric&appid=useyourapikey";
            
            // Create a Web Request object type 
            WebRequest req = WebRequest.Create(@url);

            //Get method
            req.Method = "GET";

            // Initiating the request
            HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
            if (resp.StatusCode == HttpStatusCode.OK)
            {
                // reading the reponse 
                using (Stream respStream = resp.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(respStream, Encoding.UTF8);
                   // Console.WriteLine(reader.ReadToEnd());
                    String jsonstr = reader.ReadToEnd();

                    // Serialize the stream and read the result (using Newtonsoft JSON library)

                    JObject result = JObject.Parse(jsonstr);
                    //Console.WriteLine("json is: ---------------------" + result);
                }
            }
            else
            {
                Console.WriteLine(string.Format("Status Code: {0}, Status Description: {1}", resp.StatusCode, resp.StatusDescription));
            }
            Console.Read();
            
        }
    }

I may write on POST method if any one if you are interested in it.
Please take a couple of minutes to leave comments, questions or suggestions. I’m more than happy to get in touch and help you, or learn from whatever you can share.

September 3, 2009

Does tweets (from twitter) help to increase your seo ranking?

Filed under: Blogging,Open source,PHP — Tags: , , , — narvekar @ 3:40 pm

Recently I saw twitter tool integrated on 1 of the blog. I thought to my self what a well-chosen plug-in it is to be used on your blog. I immediately integrated the plug-in on to my blog.

The features were simple and straight forward, however very effective.

1) You can Post tweets from the blog itself.

2) You can show the last few tweets on your blog.

3) (The most adored one) You can make post of your each tweet, or you can post the entire weeks or months tweets as a post on the blog and that too automatically.

Here is a snapshot of the settings:
twitter_Tool_harshadnarvekar

Thus we can keep updating our blogs daily, or weekly basis. This means you keep track of your daily rather min by min detail. Isnt that great!! Keeping a track of min by min details on your online diary?

I think this tool is great and will post blog post on your behalf. Increase in the post shall increase the number of pages and that in turn may increase your seo ranking, isnt it?

August 22, 2009

Pass Sessions between subdomains in php

Recently was working on a social networking project, where site was divided into subdomains based on states. Thus if user wanted to swtich from 1 state to another (i.e. 1 subdomain to other), system had to pass the user session from 1subdomain to another subdomain.

Here is the solution:

1) If you have the access to php.ini file then you need to add this line to your php.ini file

session.cookie_domain = .mydomain.com

2) If you dont have access to the php.ini file then you need to add the following before the session.start() function on any page which creates the session cookie.

ini_set(“session.cookie_domain”, “.mydomain.com”);

Incase there is any better or alternate way then kindly share with me.

Thanks for reading!

August 18, 2009

The secret of negotiation!!

This is what Wikipedia has to say about “Negotiation”. And I totally agree to it.
Negotiation is a dialogue intended to resolve disputes, to produce an agreement upon courses of action, to bargain for individual or collective advantage, or to craft outcomes to satisfy various interests. It is the primary method of alternative dispute resolution.

Negotiation occurs in business, non-profit organizations, government branches, legal proceedings, among nations and in personal situations such as marriage, divorce, parenting, and everyday life. The study of the subject is called negotiation theory. Professional negotiators are often specialized, such as union negotiators, leverage buyout negotiators, peace negotiators, hostage negotiators, or may work under other titles, such as diplomats, legislators or brokers.

Thirty-Three Rules to Remember:

Thirty-Three Rules to Remember which I read from a book called- Start With NO / by Jim Camp

1 Every negotiation is an agreement between two or more parties with all parties having the right to veto – the right to say “no”.
2 Your job is not to be liked. It is to be respected and effective.
3 Results are NOT valid goals.
4 Money has nothing to do with a valid mission and purpose.
5 Never, ever, spill your beans in the lobby-or anywhere else.
6 Never enter a negotiation without a valid agenda
7 The only valid goals are those that you can control: behavior and activity.
8 Mission and Purpose must be set in the adversary’s world; our world must be secondary.
9 Spend maximum time on payside activity and minimum time on nonpayside activity.10. You do NOT need it. You only want it.
10 You do NOT need it. You only want it.
11 No saving. You cannot save the adversary.
12 Only one person in the negotiation can feel okay. That person is the adversary.
13 All actions and all decisions begin with vision. Without vision, there is no action.
14 Always show respect to the blocker
15 All agreements must be clarified point by point and sealed the times (3+).
16 The clearer the picture of pain, the easier the decision-making process.
17 The value of negotiation increases by multiples as time, energy, money, and emotion are spent.
18 No talking.
19 Let the adversary save face at all times.
20 The greatest presentation you will ever give is one your adversary will never see.
21 A negotiation is only over when you want it to be over.
22 No is good, “yes” is bad, “maybe” is worse.
23 Absolutely no closing.
24 Dance with the tiger.
25 Our greatest strength is our greatest weakness (Emerson).
26 Paint the Pain.
27 Mission and Purpose drive everything.
28 Decisions are 100% emotional.
29 Interrogative-led questions drive vision.
30 Nurture.
31 No assumptions. No expectations. Only blank slate.
32 Who are the decision makers? Do you know ALL of them?
33 Pay forward.

August 16, 2009

The Google Promote Button and Remove button and SEO

Filed under: Open source,PHP — Tags: , , , , , , , — narvekar @ 6:12 pm

google-promote-button-harshad-narvekar
I am sure you must be using google for searching anything/something on internet (What a foolish question). While doing that you must have noticed a new arrow button to each search result (1 shown in the above image). Yes that arrow up and arrow down button is called the google promote buttons. This is a new google gizmo which is introduced again to make user experience better on google.

It is rather simple button, when we click takes that search result on the top. But people (where I mean ‘I’) thought that is another SEO antic which Google might have introduced to help increase the page rank of that site and that so instantally. Hurray!! Isnt it? Hmm….Not quite so…the Google promote button is meant to be a personal button, a way to ensure that sites you like stay at the top of your search results. It does not mean a credit card affiliate can type “credit card” in Google, click their site, and think that this further optimizes the site for that search term. If anything, it’s just a way for webmasters to get a little ego boost seeing their results at the top of the page.

But does this promote button have any SEO value? Will it help increase the SERPS or SEO of a page? What if 1000 of people click the promote button for a site/page and increase their chance on google? There are so many black hat SEO techniques which already are doing it and this will engage people into a new SEO war.

Do you think Google thinks the way we do? Or has google already contemplated these point? Google must have already chalked out a solvent to all these problems. Google is not dump. Google just kept these buttons – promote and remove per-user. These are not yet digg or hot or not tools. They are just mean to organize your search results. The fav ones on the top and the less fav ones below.
Isnt it this a out of box feature or just a simple feature but affective one? Thats what google aims to – Make life simple. God! Please give me brains 1% as Google has.

August 13, 2009

You’re Not Crazy-You’re an Entrepreneur

Filed under: General — Tags: , , — narvekar @ 7:15 pm

I was reading The Guy Kawasaki blog and came across to this interesting and inspiring article written on an American Express Open Forum. it was posted by Pamela Slim. This articles explains the four stages of entrepreneurship—and why you probably not crazy! Check it out by clicking here

July 4, 2009

Dhirajlal Hirachand Ambani, also known as Dhirubhai ambani

Filed under: General — Tags: , , — narvekar @ 7:54 pm

A man with the uncommon capacity of seeing beyond, into the future!

What a class act he was…1 of the greatest personality I have read in Indian history…My top salute to such a sensational immortal personality.

Dhirubhai Ambani, was a Indian rags-to-riches business tycoon who founded Reliance Industries in Mumbai with his cousin. Ambani took his company (Reliance) public in 1977, and by 2007 the combined fortune of the family (sons Anil and Mukesh) was 60 billion dollars,[Rs. 60, 000 crore] making the Ambanis one of the richest families in the world.

From beginning Dhirubhai was seen in high-regard. His success in the petro-chemical business and his story of rags to riches made him a cult figure in the minds of Indian people. As a quality of business leader he was also a motivator. He gave few public speeches but the words he spoke are still remembered for their value. ” With the force of 3 * “Give the youth a proper environment. Motivate them. Extend them the support they need. Each one of them has infinite source of energy. They will deliver.”

* “Between my past, the present and the future, there is one common factor: Relationship and Trust. This is the foundation of our growth”
* “We bet on people.”
* “Meeting the deadlines is not good enough, beating the deadlines is my expectation.”
* “Don’t give up, courage is my conviction.”
* “We cannot change our Rulers, but we can change the way they Rule Us.”

* “Dhirubhai will go one day. But Reliance’s employees and shareholders will keep it afloat. Reliance is now a concept in which the Ambanis have become irrelevant.”

A tribute and salute to Dhirubhai Ambani…he is truly a hero of Indian business…

May 16, 2009

Problems Using Absolute Paths with SSL

Filed under: Open source,PHP — Tags: , , , , — narvekar @ 11:19 am

Problems Using Absolute Paths with SSL

If you are borrowing use of an SSL certificate, such as the one provided free of charge to Internet Connection customers, when a webpage changes from http protocol to https (SSL), if you embed any images by absolute paths without domain names (/images/o.jpg), they will be broken.
If you embed images with full URL absolute paths (http://yourdomain.com/images/o.jpg), the images will show up, but the user will get warning messages that the page is a mix between secure and non-secure items.

On web pages that make transitions between http and https, one should use relative paths to avoid these problems.

May 6, 2009

Destroying session on closing browser or tab or body unload (PHP)

We had build an online dating website with a online chat functionality/feature.
The client had a requirement to show an user offline once user clicks on either Logout button
or closes the tab or browser. The first part was easily achieved, however for the 2nd part I had to spend
around 2 hours to find out the solution.

Problem:
When the user forgot to log out and closes the browser directly, the
session stil exists because when the user opens the browser again and comes back to the site
user is still loged in. And client does not want that to happen.
I/Client want the session to be destroyed when the user closes the browser
immediately.

There were a couple of solutions which came across, however i tested and used the 2nd option

1)

<body onunload=”destroy()”>

<script lenguage=”javascript”>
function destroy()
{
window.open(‘destroyCode.php’); <– this page would have the PHP Destroy session code..
}
</script>

PHP file (destroyCode.php):
session_destroy();

2) In your php.ini file, set the value:

session.cookie_lifetime=0

Or, before EVERY session_start() call, use:

session_set_cookie_params(0);


I had a conception that if you set a cookie (or session), the session automatically destroys on browser close. Howerver this did not happen as I had the session/cookie available in my temp folder.

While that can be true for cookies (depending on the settings), that is not true for sessions. Sessions are stored on the server, the server has no way of knowing when you close your browser. Sessions are destroyed after a certain amount of time of inactivity.

You cant destroy a session when the browser closes. It requires a server side command to do close a session. That mean, you could have javascript make an ajax call to a script when the browser closes.

Older Posts »

Powered by WordPress