Making an API call and unit testing in Python
This post is about mocking functions which have api calls.
Consider the following python function which makes an API call to the url www.testurl.com
import requests
def api_call_demo(name,telephone):
# add queryParams (Replace this with your query params)
queryParams = {
'name': name,
'address': telephone,
}retry = 1
retry_counter = 3
# Replace this with the proper url
url = "www.testurl.com"
for retry in range(1, retry_counter):
try:
# make a http get call
response = requests.get(url,
params=queryParams,
timeout=200.0,
)
# request error
except (ConnectionError, ConnectionResetError) as cerr:
print(f"Received error {cerr} for {url} on try {retry}", file=sys.stderr)
if retry == retry_counter - 1:
return None
# continue retrying
continue
break
if response is None or response.status_code != 200:
return None
if response.json() is not None:
# Replace this to suit your http response
print(response["data"])
If you would like to unit test this bit of code you would want to have something like this.
import unittest
import json
from unittest import mock
from requests import Response
from api import api_call_demo
def new_response(status_code, content):
response = Response()
response.status_code = status_code
response_content = json.dumps(content)
response._content = str.encode(response_content)
return response
class TestMockCalls(unittest.TestCase):
@mock.patch('requests.get')
def test_api_call_demo(self, mock_requests):
response_data = '{"data":"unit_testing"}'
mock_requests.return_value = new_response(200, json.loads(response_data))
api_call_demo("testname", "1234567890")
# Write assertions here
Comments
Post a Comment