Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?

Automating your API tests using Python and Pytest

Did you ever thought how one can exams your APIs utilizing python? Within the article we’ll find out how we are able to check our APIs utilizing Python and the pytest framework.
For this tutorial you have to have the python put in, you may obtain it here




Abstract:




What’s Python and Pytest Framework

Python is a high-level, general-purpose programming language recognized for its simplicity and readability. It was created by Guido van Rossum and first launched in 1991. Python is designed to be straightforward to study and has a clear and concise syntax, which makes it a preferred selection for each freshmen and skilled programmers.

The pytest framework makes it straightforward to jot down small, readable exams, and might scale to help complicated purposeful testing for functions and libraries.




Configuration of our Challenge



Creation of digital surroundings with python

Earlier than we begin creating, let’s perceive what’s an digital surroundings on python.
A digital surroundings in Python is a self-contained listing or folder that means that you can create and handle remoted Python environments to your tasks. With environments you may straightforward handle your dependencies, keep away from conflicts with totally different variations of python.

A digital surroundings is (amongst different issues):

  • Used to comprise a particular Python interpreter and software program libraries and binaries that are wanted to help a venture (library or software). These are by default remoted from software program in different digital environments and Python interpreters and libraries put in within the working system.
  • Contained in a listing, conventionally both named venv or .venv within the venture listing, or below a container listing for plenty of digital environments, reminiscent of ~/.virtualenvs.
  • Not checked into supply management methods reminiscent of Git.
  • Thought of as disposable – it ought to be easy to delete and recreate it from scratch. You don’t place any venture code within the surroundings
  • Not thought-about as movable or copyable – you simply recreate the identical surroundings within the goal location.

You’ll be able to learn extra about environments on python here.



Home windows

First, create a folder to your venture, after that, open your cmd and navigate to this folder utilizing the command cd:

 cd tests_with_python
Enter fullscreen mode

Exit fullscreen mode

If you do not know the place your folder is, you may run the command ls, you will notice the checklist of the folders and you’ll navigate by way of them. Inside our venture folder, run the comply with command:

 python -m venv name_of_environment
Enter fullscreen mode

Exit fullscreen mode

The identify of your surroundings might be anybody, simply do not forget that python is case delicate, check out PEP 8 Style Guide to study extra about Python conference.

To activate the environment, we use the command:

name_of_environmentScriptsActivate
Enter fullscreen mode

Exit fullscreen mode

If every part is appropriate, your surroundings will likely be activated and on the cmd you will notice like this:

(name_of_environment) C:Usertests 
Enter fullscreen mode

Exit fullscreen mode

To disable your surroundings simply run:

deactivate
Enter fullscreen mode

Exit fullscreen mode



Linux or MacOS

Create a folder to your venture, after that, open your cmd and navigate to this folder utilizing the command cd:

 cd tests_with_python
Enter fullscreen mode

Exit fullscreen mode

To activate the environment, we use the command:

supply name_of_environment/bin/activate
Enter fullscreen mode

Exit fullscreen mode

If every part is appropriate, your surroundings will likely be activated and on the cmd you will notice like this:

(name_of_environment) your_user_name exams %
Enter fullscreen mode

Exit fullscreen mode

To disable your surroundings simply run:

deactivate
Enter fullscreen mode

Exit fullscreen mode



Setup of dependencies for the exams

As we will check APIs, we have to set up dependencies to assist us throughout our exams, first we’ll set up the requestslibrary to assist us to make the requests:
PS: Make it possible for your surroundings is activated earlier than run this command

pip set up requests
Enter fullscreen mode

Exit fullscreen mode

And to make our exams, we’ll set up the pytests framework:

pip set up pytest
Enter fullscreen mode

Exit fullscreen mode




Creating our first exams



Definition of the API that will likely be examined

For this tutorial, we’ll use the Nasa API that return an inventory of asteroids: Asteroids – NeoWs and we’ll check the endpoint that Retrieve an inventory of Asteroids based mostly on their closest strategy date to Earth.

In regards to the API:

  • Base URL: https://api.nasa.gov/neo/relaxation/v1/feed
  • Question parameters:
Parameter Kind Default Description
start_date YYYY-MM-DD none Beginning date for asteroid search
end_date YYYY-MM-DD 7 days after start_date Ending date for asteroid search
api_key string DEMO_KEY api.nasa.gov key for expanded utilization

For this tutorial, we’ll concentrate on three sorts of exams:

  • Contract: If the API is ready to validate the question parameters which can be despatched
  • Standing: If the standing codes are appropriate
  • Authentication: Even this API does not requires the token, we are able to do exams with this

Our Situations:

Technique Take a look at Anticipated Consequence
GET Search with success – Return a standing code 200
The physique response accommodates the checklist of asteroids
GET Search with none question parameter – Return a standing code 403
GET Search with begin date solely – Return a standing code 200
The physique response comprise the checklist of asteroid
GET Search with finish date solely – Return a standing code 200
The physique response comprise the checklist of asteroid
GET Search in an legitimate vary of dates – Return a standing code 200
– The physique response comprise all fields non empty
GET Search when begin date is greater than finish date – Return a standing code 400
GET Search with invalid API Token – Return a standing code 403
The physique response comprise the checklist of asteroid



Creating our check

First, we’ll create a file referred to as exams.py , at this file we’ll write our exams. To assist us to make use of good practices and write an excellent automated check, let’s use TDD(Test-Driven Development) method.

This system consists in:

  • RED – make a check that fail
  • GREEN – make this check cross
  • Refactor – Refactoring what was achieved, eradicating duplication

And to jot down an excellent suite of check, we’ll use the 3A method:

  • Organize: put together the context.
  • Act: carry out the motion we need to display.
  • Assert: present that the end result we anticipated really occurred.

Beginning with pink and utilizing 3A method, we’ll write the primary check Search asteroids with success:

import pytest

def test_search_asteroids_with_sucess():
    # Organize:
    api_key = "DEMO_KEY"
    #Act:
    response = make_request(api_key)
    #Assertion:
    assert response.status_code == 200  # Validation of standing code  
    knowledge = response.json()  
    # Assertion of physique response content material:  
    assert len(knowledge) > 0  
    assert knowledge["element_count"] > 0
Enter fullscreen mode

Exit fullscreen mode

  • Organize: We create an variable to insert the api_key, on this step, you may insert any knowledge that will likely be essential to execute your check. Usually, at this step we create mock knowledge.
  • Act: On this step we referred to as the strategy accountable to make the request
  • Assertion: We validate the response

The identify of the strategy or class ought to begins with check

To run our check, at command immediate, run:

pytest check.py
Enter fullscreen mode

Exit fullscreen mode

We are going to obtain an error as a result of we did not created our methodology to do the request:

check.py F                                                                                                                                      [100%]

====================================================================== FAILURES ======================================================================
_________________________________________________________ test_search_asteroids_with_sucess __________________________________________________________

    def test_search_asteroids_with_sucess():
>       response = make_request()
E       NameError: identify 'make_request' just isn't outlined

check.py:5: NameError
============================================================== quick check abstract information ===============================================================
FAILED check.py::test_search_asteroids_with_sucess - NameError: identify 'make_request' just isn't outlined
================================================================= 1 failed in 0.01s ==================================================================
Enter fullscreen mode

Exit fullscreen mode

Now, let’s create our methodology to do the request:

import requests

def make_request(api_key):
    base_url = "https://api.nasa.gov/neo/relaxation/v1/feed/"
    response = requests.get(f'{base_url}?api_key={api_key}')
    return response
Enter fullscreen mode

Exit fullscreen mode

Now, working once more our check:

================================================================ check session begins =================================================================
platform darwin -- Python 3.11.5, pytest-7.4.3, pluggy-1.3.0
rootdir: /Customers/Paperwork/tests_python
collected 1 merchandise                                                                                                                                     

check.py .                                                                                                                                      [100%]

================================================================= 1 handed in 20.22s =================================================================
Enter fullscreen mode

Exit fullscreen mode




Refactoring our exams

Now that we already now how we create a check utilizing pytest and the way create a request, we are able to write the opposite exams and beginning refactor the exams. The primary refactor that we are going to do is to take away our request methodology from our check file. We are going to create a brand new file referred to as make_requests.py that can comprise our requests, and we’ll transfer the request that we did to this file:

import requests

def make_request(api_key):
    base_url = "https://api.nasa.gov/neo/relaxation/v1/feed/"
    response = requests.get(f'{base_url}?api_key={api_key}')
    return response
Enter fullscreen mode

Exit fullscreen mode

Now, we have to assume in an approach to re-use this methodology for our different exams, trigger we have to cross totally different parameters for various exams. There’s lots of ways in which we are able to do it, for this tutorial, we’ll change the identify of the parameter from api_key to query_parameters. We are going to do that to permit our methodology be extra versatile and we are able to cross the parameters as soon as for the exams:

import requests

def make_request(query_parameters):
    base_url = "https://api.nasa.gov/neo/relaxation/v1/feed/"
    response = requests.get(f'{base_url}?{query_parameters}')
    return response
Enter fullscreen mode

Exit fullscreen mode

After that, we have to change our check file. We are going to import this methodology that we created:

from make_requests import make_request
Enter fullscreen mode

Exit fullscreen mode

To have our exams organized in a greater means, and following the advice of pytest documentation, we’ll transfer our exams to a category TestClass:

Operating our exams once more:

============================= check session begins ==============================
accumulating ... collected 7 gadgets

check.py::TestClass::test_search_asteroids_with_sucess 
check.py::TestClass::test_search_asteroids_with_query_parameters_empty 
check.py::TestClass::test_search_asteroids_with_start_date 
check.py::TestClass::test_search_asteroids_with_end_date 
check.py::TestClass::test_search_asteroids_in_valid_range 
check.py::TestClass::test_search_asteroids_in_invalid_range 
check.py::TestClass::test_search_asteroids_in_invalid_token 

============================== 7 handed in 5.85s ===============================
PASSED             [ 14%]PASSED [ 28%]PASSED         [ 42%]PASSED           [ 57%]PASSED          [ 71%]PASSED        [ 85%]PASSED        [100%]
Course of completed with exit code 0
Enter fullscreen mode

Exit fullscreen mode



Producing html report end result

To have a greater visualization of your exams outcomes, we are able to use the pytest-html-reporter library to generate an report html, to do it, first we have to set up the bundle:

pip set up pytest-html
Enter fullscreen mode

Exit fullscreen mode

To generate the report, when working the exams, add:

pytest check.py --html-report=./report/report.html 
Enter fullscreen mode

Exit fullscreen mode

Will likely be generated one file .html with the outcomes of the exams, like this:



Conclusion

This text is a tutorial of how one can begin to write your automated exams for an API utilizing python and pytest framework and the way generate one report html.
You’ll be able to entry the venture used on this tutorial here.
I hope this content material will likely be helpful for you.

When you’ve got any questions, be at liberty to achieve out to me! 

Bisous, à la semaine prochaine 💅🏼

Add a Comment

Your email address will not be published. Required fields are marked *

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?