Mock requests.Session()
2 min readSep 27, 2018
I have an endpoint and it is in the middle between the other server. Then it has to shoot another one.
@api_view(['GET', 'POST'])
def receive_token(request):
if request.method == 'GET':
return Response(
data={'message': "Accept access-token with POST"},
status=status.HTTP_400_BAD_REQUEST
)
else:
serializer = TokenSerializer(data=request.POST)
if serializer.is_valid():
try:
subscribe(serializer.data.get('access_token'))
except AssertionError as err:
logging.error(err)
return Response(data={'message': str(err)}, status=status.HTTP_424_FAILED_DEPENDENCY)
else:
return Response(data={'message': "Good"}, status=status.HTTP_200_OK)
else:
return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST)
subscribe
is a function that calling M1cr0$0ft endpoint
def subscribe(token):
"""
Shoot the M$ endpoint
:return:
"""
from datetime import datetime, timedelta
import copy
expiration_dt = (datetime.utcnow() + timedelta(days=2)).isoformat() + 'Z'
headers = {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json',
}
body = copy.deepcopy(settings.MS_GRAPH_SUBSCRIPTION)
body['expirationDateTime'] = expiration_dt
session = requests.Session()
res = session.post(settings.MS_GRAPH_SUBSCRIPTION_URL, json=body, headers=headers)
assert 201 == res.status_code
The outcome will be 201
or not 201
Then I intentionally put assert
there.
Here is my sample mock requests.Session
I can simply do this since it is a new class :)
tests.py
from unittest.mock import patch
from django.test import TestCase
from requests import Session
from rest_framework import status
from rest_framework.reverse import reverse
from rest_framework.test import APIClient
from renew_subscription_scheduler.users.serializers import TokenSerializer
class MockResponse:
def __init__(self, status_code):
self.status_code = status_code
self.content = "Mock content"
class TestEndpoint(TestCase):
def setUp(self):
self.token = "xxx"
def test_serializer(self):
serializer = TokenSerializer(data={'access_token': self.token})
self.assertTrue(serializer.is_valid())
@patch.object(Session, 'post', return_value=MockResponse(status.HTTP_201_CREATED))
def test_shoot_endpoint(self, mock_response):
url = reverse('tokens')
client = APIClient()
res = client.post(url, data={'access_token': self.token})
self.assertEqual(status.HTTP_200_OK, res.status_code)
@patch.object(Session, 'post', return_value=MockResponse(status.HTTP_403_FORBIDDEN))
def test_ms_exception(self, mock_exception):
url = reverse('tokens')
client = APIClient()
res = client.post(url, data={'access_token': self.token})
self.assertEqual(status.HTTP_424_FAILED_DEPENDENCY, res.status_code)
Original Question: