I have created a package which uploads a data to some storage using Azure AD access token, now I want to write test cases for the code, as I'm not aware of writing test cases have tried few. Can anyone help here, below is the code for my package.
__init__.py
file
import json
import requests
import sys
from data import Data
import datetime
from singleton import singleton
@singleton
class CertifiedLogProvider:
def __init__(self, client_id, client_secret):
self.client_id=client_id
self.client_secret= client_secret
self.grant_type="client_credentials"
self.resource="*****"
self.url="https://login.microsoftonline.com/azureford.onmicrosoft.com/oauth2/token"
self.api_url="http://example.com"
self.get_access_token()
def get_access_token(self)-> None:
data={'client_id':self.client_id,'client_secret':self.client_secret,
'grant_type':self.grant_type,'resource':self.resource}
response = requests.post(self.url, data=data)
if response.status_code == 200:
self.token_dict=response.content
self.access_token = response.json()["access_token"]
else:
print(f"An Error occurred: \n {response.text}")
def is_expired(self) -> bool:
token_dict=json.loads(self.token_dict.decode('utf-8'))
if int(datetime.datetime.now().timestamp()) > int(token_dict['expires_on']):
return True
else:
return False
def send_clp_data(self,payload:dict):
obj=Data()
data=obj.data
data['event_metric_body']=payload
if self.is_expired() is True:
self.get_access_token()
headers={"Authorization": "Bearer {}".format(self.access_token),
"Content-Type": "application/json",}
response = requests.post(self.api_url,data=json.dumps(data), headers=headers)
if response.status_code == 201:
print('Data uploaded successfully')
else:
print(f"An Error occurred: \n {response.text}")
singleton.py
def singleton(class_):
instances = {}
def getinstance(*args, **kwargs):
if class_ not in instances:
instances[class_] = class_(*args, **kwargs)
return instances[class_]
return getinstance
data.py
Contains data which is static
test.py
import json
import unittest
from unittest import TestCase
from unittest.mock import patch
import requests
from unittest.mock import MagicMock
from __init__ import CertifiedLogProvider
import pytest
class MyTestCase(TestCase):
def test_can_construct_clp_instance(self):
object= CertifiedLogProvider(1,2)
@patch('requests.post')
def test_send_clp_data(self, mock_post):
info={"test1":"value1", "test2": "value2"}
response = requests.post("www.clp_api.com", data=json.dumps(info), headers={'Content-Type': 'application/json'})
mock_post.assert_called_with("www.clp_api.com", data=json.dumps(info), headers={'Content-Type': 'application/json'})
if __name__ == '__main__':
unittest.main()
How can we test boolean method and method containing requests?