Created
December 6, 2022 10:26
-
-
Save kamaroly/610858435af933cb1852c560ab509ef0 to your computer and use it in GitHub Desktop.
Django Rest Framework External API Mock. You must install requests_mock using pip like `pip install requests_mock`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# In your test classes. For example OnboardTransporterAPITest.py | |
================================================================= | |
import requests_mock | |
from rest_framework import status | |
from django.urls import include, path, reverse | |
from rest_framework.test import APITestCase, URLPatternsTestCase | |
@requests_mock.Mocker() | |
class OnboardTransporterAPITest(APITestCase, URLPatternsTestCase): | |
urlpatterns = [ | |
path("v2/vehicle", include('vehicle_type.urls')) | |
] | |
def test_transporter_can_be_onboarded_and_user_be_created(self, requests_mock): | |
# Begin by mocking outside APIs | |
expected_response = '{"status": "Success","code": 201,"message": "Registration Successful","data": [{"id": 37,"names": "Test User","email": "[email protected]","phone_number": "+25470052355"}]}' | |
# Each time the app calls following URL with POST method, return expected response | |
# It does not have to go outside to the internet. | |
requests_mock.post( | |
"https://dev.api.domain.co/v2/auth/user/register/", text=expected_response) | |
payload = '{"name": "John Doe", "email": "[email protected]", "phone_number": "2547571692810"}' | |
response = self.client.post( | |
reverse('transporter_create'), payload, content_type="application/json") | |
assert response.status_code == status.HTTP_201_CREATED | |
assert response.data["status"] == "success" | |
transporter_data = response.data["data"][0] | |
assert transporter_data["id"] == 37 | |
assert transporter_data["names"] == "Test User" | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# in your view example CreateTransporterView.py | |
# ---------------------------------------------- | |
import requests | |
from rest_framework import status | |
class CreateTransporterView(BaseView): | |
def post(self, request): | |
# First register the transporter as the user | |
response = requests.post( | |
"https://dev.api.domain.co/v2/auth/user/register/") | |
transporter_user = response.json() | |
response = { | |
"code": status.HTTP_201_CREATED, | |
"status": "success", | |
"message": "Transporter onboarded", | |
"data": [transporter_user["data"][0]] | |
} | |
return self.response(response, response["code"]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment