A Go-To-Guide For API Testing Using Pytest!!

0
22647
Soft development isometric vector, web design process, laptop with data, programming and code writing, dark neon

API (Application Program Interfaces) are the method to transfer data between non-compatible platforms, and hence they act as an interface between different software components. Almost all enterprises depend completely on APIs as they have different software dependencies and APIs reduce the complications in the transfer of data. Hence, API testing is vital for all enterprises because failure in any API can cause a complete system breakdown. 

API
Source: Experion

API Testing

API Testing is a crucial part of the software development life cycle as it determines if the applications perfectly meet the expectations for functionality, performance, reliability, and security of the system. API Testing can be broadly classified into two categories: 

  1. Manual Testing: Humans manually execute the APIs, verify the test cases and report the results.
  2. Automation Testing: Machines automatically execute the APIs, verify the test cases, and report the results.

In this article, we will focus on automated API testing. We will start with understanding a simple test case. We will build a basic API testing flow with the simulation of API by using python functions and database using Python dictionary. We will use the Pytest module as our testing framework. Let’s get started by installing the Pytest module in the Python IDE. In this tutorial Visual Studio Code is used as the IDE and it is assumed that Python 3 is set up in your particular IDE.

Also Read: Visual Studio Code Is So Popular, But Why?

API Testing
Source: Xenonstack

Installation of Pytest Module

Python: Python 3.6, 3.7, 3.8, 3.9, PyPy3

Platforms: Linux and Windows

Step1: Run the following command in your command line

pip install -U pytest

Step2: Check that you have installed the pytest properly

pytest –version

If pytest is installed property in the environment then the command line will not show any error. If the command line shows an error then copy the error text and google it to find the Stack Overflow link. Most of the time the issues arise because of the difference in dependencies and can be solved by following steps in the Stack Overflow’s verified answers.

For a more detailed explanation regarding the installation process, visit Pytest’s official documentation.

Simple Test Case in Pytest

Open a Python file for creating a simple test case for using the pytest module.

The basic flow of testing is to create a principal function that has to be tested and a testing function whose name starts with the “test” abbreviation. For running the test case write “py.test” command in the command line and click the enter button. 

The pytest module detects the “test” expression and executes that particular function. Further, it looks for the assert command inside the testing function and computes the boolean-based expression written next to it. If the result of the computed boolean expression is True then the testing function passes, on the contrary, if the result of the computed boolean expression is False then the testing function fails. It will be more clear after having a look at an example.

Principal Function: addition(a,b)

Testing Function: test_addition()

Pass Case Example:

Code:

Simple test case in Pytest- image 1

Result:

Simple test case in Pytest- result- image 2

As 5+6=11, hence this test case passes.

Fail Case Example:

Code:

Fail case. eg. Image 3

Result:

Fail case. eg. result. image 4

As 5+7 11, hence this test case fails.

NOTE: The Python file should also start with the “test” abbreviation, hence the test_simple_testcase.py name is used in the above example.

Also Read: Python vs JavaScript- The Competition Of The Giants!

Basic Automated API Testing Flow

The algorithm for automated API testing is as follows:

  • Start
  • Call the API by passing an input payload
  • Check the response of API

If actual response==expected response:

            Test Passes

 Else:

      Test Fails

  • End

This will be more clear after having a look at an example.

Example:

Database

Let’s consider a database in the form of a Python dictionary.

Basic automatest testing API flow - Image 5

This database contains information about players of a particular tournament. The columns of the database have the following fields:

  1. Player Id
  2. Player Name
  3. Team Name
  4. Age
  5. Average Score

Simulation of API by Python Function

Now let’s build a function that simulates an API that reads player data from the database when Player Id is given in the input payload. The Python dictionary is already in the JSON format, so we need not make any changes in the structure of the data.

Simulation of API by Python Function- Image 6

The read_player() function takes payload as input, it stores the “Player_id” value in the id variable. The function checks if the player id value is present in the database. If the player id value is present in the database then it returns the player data corresponding to that particular player id in the JSON format, else it returns an error message with 404 code.

Also Read: Automating Testing Tools and Continuous Integration

API Testing Function

Before testing the function, a test input payload is created with a player id value. The API testing function “test_read_player()” executes the API call “read_player()” with “test_payload” as its input parameter and returns the response which is stored in the “response” variable. Now, the “Code” value is read from the response variable and checked with the ‘200’ value, as a boolean expression. If the response code is equal to 200 then the API test passes, else it fails.

Example of the passed test case when player id exists in the database:

Code:

Code Example of the passed test case when player id exists in the database- Image 7

Result:

Result Example of the passed test case when player id exists in the database- Image 8

Example of the failed test case when player id does not exist in the database:

Code:

Code example of the failed test case when player id does not exist in the database- Image 9

Result:

Result Example of the failed test case when player id does not exist in the database- image 10

NOTE: The Python file should also start with the “test” abbreviation, hence the test_basic_api_testing_flow.py name is used in the above example.

Similarly, this concept can be used to create multiple test cases for multiple APIs. A class can be created to perform test cases for a particular unit of the software. CRUD operation is the best example to create a complete pipeline of automated API testing.

Complete Python Code:

# DATABASE
# Columns: | Player Id | Player Name | Team Name | Age | Average Score | 

Database={
    1:["Akash", "A", 23, 58],
    2:["Ashish", "B", 22, 60],
    3:["Ashok", "C", 23, 56],
    4:["Ayush", "A", 24, 53]
        }



# API simulation of READ operation

# Input Payload
'''
    payload={
            "Player_id": id
        }
'''

def read_player(payload):
    id = payload["Player_id"]
    if id in Database:
        entry=Database[id]
        return {"Code":200, 
                "Response":{"Name":entry[0],"Team":entry[1],"Age":entry[2],"Average":entry[3]},
                "Message":"Read Operation Succesful"}

    else:
        return {"Code":404,"Message":"Player does not exists"}



# API Testing Function

# Testing function

test_payload={
        "Player_id":5
    }

def test_read_player():
    response=read_player(test_payload)
    assert response.get("Code")==200

Also Read: Creating a “Serverless” API using “Firebase Cloud Function”

For In-Depth Understanding:

Previous articleCoding Tutorials: Top 5 Trends Of 2021
Next article3 Tips for Creating Short Videos to Boost Customer Loyalty

LEAVE A REPLY

Please enter your comment!
Please enter your name here