|
1 | 1 | from io import BytesIO
|
2 | 2 |
|
| 3 | +from django import VERSION as DJANGO_VERSION |
3 | 4 | from django.contrib.auth.models import User
|
4 | 5 | from django.shortcuts import redirect
|
5 | 6 | from django.test import TestCase, override_settings
|
6 | 7 | from django.urls import path
|
7 | 8 |
|
8 |
| -from rest_framework import fields, serializers |
9 |
| -from rest_framework.decorators import api_view |
| 9 | +from rest_framework import fields, parsers, serializers |
| 10 | +from rest_framework.decorators import api_view, parser_classes |
10 | 11 | from rest_framework.response import Response
|
11 | 12 | from rest_framework.test import (
|
12 | 13 | APIClient, APIRequestFactory, URLPatternsTestCase, force_authenticate
|
@@ -46,11 +47,18 @@ def post_view(request):
|
46 | 47 | return Response(serializer.validated_data)
|
47 | 48 |
|
48 | 49 |
|
| 50 | +@api_view(['POST']) |
| 51 | +@parser_classes((parsers.JSONParser,)) |
| 52 | +def post_json_view(request): |
| 53 | + return Response(request.data) |
| 54 | + |
| 55 | + |
49 | 56 | urlpatterns = [
|
50 | 57 | path('view/', view),
|
51 | 58 | path('session-view/', session_view),
|
52 | 59 | path('redirect-view/', redirect_view),
|
53 | 60 | path('post-view/', post_view)
|
| 61 | + path('post-json-view/', post_json_view), |
54 | 62 | ]
|
55 | 63 |
|
56 | 64 |
|
@@ -200,6 +208,21 @@ def test_empty_post_uses_default_boolean_value(self):
|
200 | 208 | assert response.status_code == 200
|
201 | 209 | assert response.data == {"flag": True}
|
202 | 210 |
|
| 211 | + def test_post_encodes_data_based_on_json_content_type(self): |
| 212 | + data = {'data': True} |
| 213 | + response = self.client.post( |
| 214 | + '/post-json-view/', |
| 215 | + data=data, |
| 216 | + content_type='application/json' |
| 217 | + ) |
| 218 | + |
| 219 | + if DJANGO_VERSION < (2, 1): |
| 220 | + assert response.status_code == 400 |
| 221 | + assert response.data['detail'].code == 'parse_error' |
| 222 | + else: |
| 223 | + assert response.status_code == 200 |
| 224 | + assert response.data == data |
| 225 | + |
203 | 226 |
|
204 | 227 | class TestAPIRequestFactory(TestCase):
|
205 | 228 | def test_csrf_exempt_by_default(self):
|
|
0 commit comments