Search code examples
pythonresttestingautomated-tests

Needed advice to automate REST services test


I am kind of new to REST and testing dept. I needed to write automation scripts to test our REST services. We are planning to run these scripts from a Jenkins CI job regularly. I prefer writing these in python as we already have UI functionality testing scripts in python generated by selenium IDE, but I am open to any good solution. I checked httplib, simplejson and Xunit, but looking for better solutions available out there.

And also, I would prefer to write a template and generate actual script for each REST API by reading API info from XML or something.


Solution

  • I usually use Cucumber to test my restful APIs. The following example is in Ruby, but could easily be translated to python using either the rubypy gem or lettuce.

    Start with a set of RESTful base steps:

    When /^I send a GET request for "([^\"]*)"$/ do |path|
      get path
    end
    
    When /^I send a POST request to "([^\"]*)" with the following:$/ do |path, body|
      post path, body
    end
    
    When /^I send a PUT request to "([^\"]*)" with the following:$/ do |path, body|
      put path, body
    end
    
    When /^I send a DELETE request to "([^\"]*)"$/ do |path|
      delete path
    end
    
    Then /^the response should be "([^\"]*)"$/ do |status|
      last_response.status.should == status.to_i
    end
    
    Then /^the response JSON should be:$/ do |body|
      JSON.parse(last_response.body).should == JSON.parse(body)
    end
    

    And now we can write features that test the API by actually issuing the requests.

    Feature: The users endpoints
    
      Scenario: Creating a user
        When I send a POST request to "/users" with the following:
          """
          { "name": "Swift", "status": "awesome" }
          """
        Then the response should be "200"
    
      Scenario: Listing users
        Given I send a POST request to "/users" with the following:
          """
          { "name": "Swift", "status": "awesome" }
          """
        When I send a GET request for "/users"
        Then the response should be "200"
        And the response JSON should be:
          """
          [{ "name": "Swift", "status": "awesome" }]
          """
    
       ... etc ...
    

    These are easy to run on a CI system of your choice. See these links for references: