I’m trying to create a unit test for a POST request. If I don’t allow the request to follow, I get a 302 with the URL pointing to the same URL I’m trying to post to. If I do allow the request to follow it is redirected to the view I’m trying to hit but loses all data and becomes a GET request.
Here is my unit test:
import uuid
from django.contrib.auth import get_user
from django.contrib.auth.models import User
from django.urls import reverse
from rest_framework.test import APITestCase, force_authenticate
class MeetingChatAPITest(APITestCase):
USERNAME = "test_username"
EMAIL = "a@b.com"
PASSWORD = "password"
def setUp(self):
self.user = User.objects.get(username=self.USERNAME)
def test_meeting_chat_with_text_input(self):
url = "/meeting-chat/"
request_payload = {
"foo": "bar"
}
self.asertTrue(self.client.login(username=self.USERNAME, password=self.PASSWORD))
response = self.client.post(url, request_payload, format="json", follow=True)
self.assertEqual(response.status_code, 200)
And my urls:
# core.urls
app_name = 'core'
urlpatterns = [
path('meeting-chat/', chat_meeting, name='meeting_chat'),
]
# <project>urls
urlpatterns = [
path('', include('core.urls')),
]
And my view function:
@login_required
@require_POST
@csrf_exempt
def chat_meeting(request):
try:
payload = json.loads(request.body.decode('utf-8'))
except json.JSONDecodeError:
return JsonResponse({'error': 'Invalid JSON'}, status=400) # This line is only hit if I do follow=True on the request and remove the @require_POST decoration