Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

APIs are ubiquitous, and Python is the go-to tool fortesting REST APIs. The goal of this capstone is to mimic areal-world scenario of API testing.

APIs are ubiquitous, and Python is the go-to tool fortesting REST APIs. The goal of this capstone is to mimic areal-world scenario of API testing. You must write several unittests that validate an example website’s endpoints. Unit tests area testing method in which individual units of code are tested todetermine if that unit is fit for use and working as expected. Toguarantee stability over time, several JSON files will beaccessible to represent the website under test. You will combinethe skills learned in the course with some new skills. Theapplication will use the requests package and pytest forbasic unit testing.

 

Implement the class AccessApi that will access a RESTAPI using the requests package and perform basicfunctionality. The requests package has been installed inthe environment for you; however, if you needed to, you can installthe package by using the following command: sudo pip3 installrequests. You will need write several unit tests with pytest,implementing the AccessApi class you create. Lastly, youwill need to refactor two of the unit tests so they areparametrized.

Use annotations to give type hints. Some languages are stronglytyped meaning the interpreter will force every variable, method,object etc., to be declared as a type and will throw an error whena different type is used. Python is not a strongly typed language,which could be beneficial because this allows for flexibility inthe code. Python does allow for “hinting” of types beginning withversion 3. A developer can give type hints that all IDEs will useand when a type is passed that doesn’t match the one defined, theIDE will give an error. This increases readability and reduceserrors in your code with only minor functionality being given up.There is a limitation to this “hinting”, as the types are notenforced at runtime. In other words, these hints are used only bythird party tools as an aid to the developer in writing thecode.

Example:

def function(arg: ) -> :my_variable:  = 

Docstrings are very helpful in decreasing the effort required tobecome familiar with a body of code. When possible, always try toadd useful information, but do not over-document.

This topic is not limited to Python but is relevant to anywritten software. Software is typically written in phases oriterations. Some functionality is added, tested, bugs corrected,additional functionality, etc., Unfortunately, the process of“enhancing” or “fixing” software sometimes has the unwanted sideeffect of breaking existing functionality. One way to determine ifthis has happened is for a person in the test organization toexercise all known tests with every software change. This isimpractical, however so often the development team writes automatedUnit Tests which test basic functionality. Every time the projectis built, automated unit tests are executed against the build. Ifsome functionality fails, the team knows that something has beeninadvertently broken and needs to be corrected.

Unit tests are “low-level” tests that exercise the software at afunctional level with a pass or fail result. In the case of Python,a simple unit test implementation is to put assert statements inthe code to verify that the run time state is as expected. Forexample, suppose there is a Boolean variablecalled myValue that should be True at a certainpoint in a program’s execution. You could do the followingstatement at that point: assertTrue(myValue == True, “ERROR:myValue is False”). When the previous statement is executed, ifmyValue is False an AssertionError isgenerated, the message is printed, and execution stops. This is asimple example of unit test step but there are a number of packagesavailable to assist in writing unit tests.

In order to access external REST APIs, for this assignment, youmust use the requests package to communicate in the HTTPprotocol.

Finish the implementation of the class called AccessApi.There are 7 method stubs that will need to be completed:

  1. A constructor that requires the developer to input a base URLas a string that will host the REST API endpoint. Example:“http://google.com”
  2. A method to get the current URL base.
  3. A method to set the current URL base.
  4. A method to test if the URL is responding to GET requests toallow for a simple alive test.
  5. A method to input an endpoint, as a string, and have thatendpoint concatenated to the base URL and then send a GET requestusing the requests package to the combined URL. Then, return theJSON sent as a list.
  6. A method to input an endpoint and have that endpointconcatenated to the base URL and then send a GET request using therequests package to the combined URL. Then, return the statuscode.
  7. A method to input an endpoint and have that endpointconcatenated to the base URL and then send a GET request using therequests package to the combined URL. Then, return the totalelapsed time used for the GET request.

Now that the AccessApi class has been created, we mustcreate tests for each of the API endpoints.

Schema’s of response JSON’s

  • getBillingInfo.json

      "id": < INT>,  "FirstName": ,  "LastName": ,  "city": ,  "state": ,  "Lang": ,  "SSN":
  • getCustomers.json

    "id": < INT>,"first_name": ,"last_name":,"email":,"ip_address":,"address": 
  • getSites.json

    "id": ,"address": ,"ThirdParty":,"admin": 

In the file test_company_api.py, you will findtest method stubs. Create the following four tests for each of theAPI endpoints:

  1. Validate the HTTP status codeis 200.
  2. Validate the schema matches the one provided on a very simplelevel. Determine that the JSON keys are correct. For example, ingetSites check that there are 4keys: id, address, ThirdParty and admin.Also check that the type of the value matches the schema provided.A schema is the layout of the data, which could be columns in aspreadsheet or key’s and nested key’s in a dictionary. To validatethe schema, you would verify that the structure matches what isexpected.

  3. Validate the accuracy of the data by picking a random dataelement and verifying the data is in the correct format. Forexample, a SSN should be all integers, in a format ofXXX-XX-XXXX.

  4. Validate that the response time should be less than oneminute.

Endpoints:

• Billing

• Sites

• Customers

The JSON files can be found here. For now, pleaseuse: https://github.com/bclipp/APItesting as the baseURL. For examplefor https://github.com/bclipp/APItesting/blob/master/getBillingInfo.json

A simple pytest looks like as follows:

def ():                          assert 

A simple example is as follows:

def testing_my_class(age:int):    assert age <= 50           

Tasks

The billing endpoint works as expected.

4

The customer endpoint works as expected

4

The site endpoint works as expected

4

test_company_api.py completes without errors orfailures.

We now have a testing platform and some useful tests for ourcompany’s website. The tests we have done are not maintainable andhard, which is not very pythonic.

Pythonic can be thought of as simple, and straightforward way towrite and read. The next task is to refactor two of our tests, sothat they use the parametrize functionality of pytest.

import pytest@pytest.mark.parametrize(",,", [    ("String1", true),    ("String2", false),    ("String3",true),    ])def test_eval((,):    …. 

Tests to refactor:

  1. Validate the HTTP status codeis 200.
  2. Validate that the response time should be less than oneminute.

import AccessApi as mws

import pytest

base_url: str = "https://raw.githubusercontent.com/bclipp/"

billing_end_point: str = "APItesting/master/getBillingInfo.json"

customer_end_point: str = "APItesting/master/getCustomers.json"

site_end_point: str = "APItesting/master/getSites.json"

# TASK 2

# billing

def test_billing_status_code():

def test_billing_validate_schema():

def test_billing_validate_ssn():

def test_billing_validate_time():


# customers

def test_customers_status_code():

def test_customers_validate_schema():

def test_customers_validate_ssn():

def test_customers_validate_time():


# site

def test_site_status_code():

def test_site_validate_schema():

def test_site_validate_ssn():

def test_site_validate_time():

# task 3

@pytest.mark.parametrize('base_url', [base_url])

@pytest.mark.parametrize('billing_end_point', [billing_end_point, customer_end_point, site_end_point])


@pytest.mark.parametrize('base_url', [base_url])

@pytest.mark.parametrize('billing_end_point',[billing_end_point,customer_end_point,site_end_point])

def test_billing_validate_time(base_url,billing_end_point):

import requests

import json


class AccessApi:

"""

Class AccessApi is used to abstract lower level access to course required API

Attributes

----------

url : str

A valid website used to hold the courses json filesS

Methods

-------

url_active()

returns True if the url is currently responding without errors, and False if not.

get_end_point(endpoint)

returns the json output of the GET request

"""

#1

def __init__(self, url):

"""

Parameters

----------

url: str

a valid website forexample: http://google.com

"""

#2

@property

def url(self) -> str:

#3

@url.setter

def url(self, url: str):

#4

def url_active(self) -> bool:

#5

def get_end_point(self, end_point:str) -> dict:

"""

Parameters

----------

end_point: str

a valid endpoint on a website "api/sites/master.json"

"""

#6

def get_status_code(self, end_point:str) -> int:

"""

Parameters

----------

end_point: str

a valid endpoint on a website "api/sites/master.json"

"""

#7

def get_elapsed_time(self, end_point:str) -> float:

"""

Parameters

----------

end_point: str

a valid endpoint on a website "api/sites/master.json"

"""

Step by Step Solution

3.49 Rating (159 Votes )

There are 3 Steps involved in it

Step: 1

Below is an implementation of the AccessApi class based on the given requirements and method stubs p... blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Quantitative Chemical Analysis

Authors: Daniel C. Harris

8th edition

1429218150, 978-1429218153

More Books

Students also viewed these Programming questions

Question

Using Table as an example, create two alternative access plans.

Answered: 1 week ago

Question

Draw a picture consisting parts of monocot leaf

Answered: 1 week ago