Overview

Skill Level: Intermediate

This python scripts converts the Json/Swagger documentation into python automation code

Ingredients

Python Automation Framework

Step-by-step

  1. Background

    One of the best approaches in cloud computing today is microservice-based implementation for cloud applications. API calls are made to perform all the actions. Now these APIs are implemented using frameworks like IBM StrongLoop (now IBM APIConnect), where documentation is done in an automated way with Swagger/JSON format. Automation is the key for the success of any product as it speeds up the delivery and plays a critical role on the quality of the product.

  2. About StrongLoop

    StrongLoop, or IBM APIConnect, is a complete solution that addresses all aspects of the API lifecycle, for both on-premises and cloud environments. It offers comprehensive capabilities to create, run, manage, secure, and monetize APIs and microservices. Delivering an unparalleled, integrated user experience, it enables rapid deployment and simplified administration of APIs.

    https://strongloop.com

  3. About Swagger

    The open source Swagger framework provides the OpenAPI Specification (formerly known as the Swagger specification) for creating RESTful API documentation formatted in JSON or YAML, a human-friendly superset of JSON: http://swagger.io

  4. Automating REST API

    We can automate the REST API using any language – Python, Java, or Perl, and so on. We used Python language as it is simple to use and easy to implement

  5. About Python Test Automation Framework

    This is simple test automation implementation written in Python Language where “http requests” are made from Python code and “http response” is captured.

     

     

    Picture1

     

     

    Following diagram explains automation workflow:

     

     

    Picture2

     

     

    a) Tests can be triggered with the Python script, which calls the Python test suit.

    b) Test Suit internally calls the individual python tests.

    c) Individual Tests calls the Test API’s [or Test Method] and also specifies the different input or parameters which are required for the tests.Note: We can define multiple tests with the single Test Method or Test API and the reason for defining the Test Method in a different file.

    d) Tests picks up the Test Data/Configuration from Test Configuration file e) Logs are generated and results will be generated in different file.

    Note that, even for automation, we need to write the code manually. When we have APIs in large numbers, we need to spend a lot of time writing the automation code to support those APIs.

  6. REST API Test Code Generator

    This JSON code convertor is written in Python and generates the API tests (or Test Method), which can be executed in the Python framework. The expectation is that the JSON file is provided as the input, which consists of all the supported APIs.

  7. How it Works

    The JSON convertor code converts the JSON file into Python API tests [Test method] in the required format, which can be directly used in the Python Test Automation Framework.

  8. Integrated Test Automation Workflow

    Picture3

     

    Picture4

     

    There is no need to write the manual Test API as it is generated automatically from the convertor code.

     

     

  9. Code Snippet:

    class PythonCodeGenerator:
    def __init__(self, indentation='\t'):
    self.indentation = indentation self.level = 0
    self.code = ''
    def indent(self): self.level += 1
    def dedent(self): if self.level > 0:
    self.level -= 1
    def __add__(self, value):
    temp = PythonCodeGenerator(indentation=self.indentation)
    temp.level = self.level
    temp.code = str(self) + ''.join([self.indentation for i in range(0, self.level)]) +
    str(value) return temp
    def __str__(self): return str(self.code)
    def writetofile(self):
     
    f = open('tests.py','w') f.write(str(self)) f.close()
    with open("ibm_cloud_brokerage.json") as data_file: data = json.load(data_file)
    a = PythonCodeGenerator() a += 'import json\n'
    a += 'import requests\n\n' print data["paths"]
    for key in data["paths"]:
    for rest_call in data["paths"][key]:
    func = str(rest_call+key)
    func = re.sub(r"/","_",func) func1 = re.sub(r"\{\}","",func) print func1
    func_name = 'def '+func1+'\n' a += func_name
    a.indent()
    if(str(rest_call) == "get"):
    a += 'resp = requests.get(url, headers=headers, verify=False)\n' elif(str(rest_call) == "post"):
    a += 'resp = requests.post(url, body, headers=headers, verify=False)\n' elif(str(rest_call) == "delete"):
    a += 'resp = requests.delete(url, headers=headers, verify=False)\n' elif(str(rest_call) == "put"):
    a += 'resp = requests.put(url, body, headers=headers, verify=False)\n' a += 'passed = assertEqual(resp, 200)\n'
    a += 'global status\n'
    a += 'return passed\n'
    a.dedent()
    a.writetofile()
    Generated Code Example:
    ======================================= def post_api_assets_vdcs_{AssetId}_virtualmachines
    resp = requests.post(url, body, headers=headers, verify=False) passed = assertEqual(resp, 200)
    global status
    return passed
    def get_api_assets_vdcs_{AssetId}_virtualmachines
    resp = requests.get(url, headers=headers, verify=False) passed = assertEqual(resp, 200)
    global status
    return passed
  10. Generated Code Example

    /*Code Goes Here*/
    def post_api_assets_vdcs_{AssetId}_virtualmachines
    resp = requests.post(url, body, headers=headers, verify=False)
    passed = assertEqual(resp, 200)
    global status
    return passed
    
    def get_api_assets_vdcs_{AssetId}_virtualmachines
    resp = requests.get(url, headers=headers, verify=False)
    passed = assertEqual(resp, 200)
    global status
    return passed
  11. Conclusion

    This automation, which automates the JSON files to Python Code, saves you a lot of time as there is no need to manually define

    Any number [100s or 500s] of APIs can be converted into Test API with no time.

    Note: Only Test Case needs to be created with the required parameters for Test API.

  12. Meet Authors

    • Harish Nayak[harish.nayak@in.ibm.com]
    • Tirumalesh Killamsetty[tikillam@in.ibm.com]

1 comment on"Generate the Test Automation code from StrongLoop Json/Swagger documentation"

  1. developer2018 December 28, 2017

    Would it be possible to get a cleaner version of the code snippit?

Join The Discussion