BVB Source Codes

django-rest-framework Show test_request.py Source code

Return Download django-rest-framework: download test_request.py Source code - Download django-rest-framework Source code - Type:.py
  1. """
  2. Tests for content parsing, and form-overloaded content parsing.
  3. """
  4. from __future__ import unicode_literals
  5.  
  6. from django.conf.urls import url
  7. from django.contrib.auth import authenticate, login, logout
  8. from django.contrib.auth.models import User
  9. from django.contrib.sessions.middleware import SessionMiddleware
  10. from django.core.files.uploadedfile import SimpleUploadedFile
  11. from django.test import TestCase, override_settings
  12. from django.utils import six
  13.  
  14. from rest_framework import status
  15. from rest_framework.authentication import SessionAuthentication
  16. from rest_framework.compat import is_anonymous
  17. from rest_framework.parsers import BaseParser, FormParser, MultiPartParser
  18. from rest_framework.request import Request
  19. from rest_framework.response import Response
  20. from rest_framework.test import APIClient, APIRequestFactory
  21. from rest_framework.views import APIView
  22.  
  23. factory = APIRequestFactory()
  24.  
  25.  
  26. class PlainTextParser(BaseParser):
  27.     media_type = 'text/plain'
  28.  
  29.     def parse(self, stream, media_type=None, parser_context=None):
  30.         """
  31.        Returns a 2-tuple of `(data, files)`.
  32.  
  33.        `data` will simply be a string representing the body of the request.
  34.        `files` will always be `None`.
  35.        """
  36.         return stream.read()
  37.  
  38.  
  39. class TestContentParsing(TestCase):
  40.     def test_standard_behaviour_determines_no_content_GET(self):
  41.         """
  42.        Ensure request.data returns empty QueryDict for GET request.
  43.        """
  44.         request = Request(factory.get('/'))
  45.         assert request.data == {}
  46.  
  47.     def test_standard_behaviour_determines_no_content_HEAD(self):
  48.         """
  49.        Ensure request.data returns empty QueryDict for HEAD request.
  50.        """
  51.         request = Request(factory.head('/'))
  52.         assert request.data == {}
  53.  
  54.     def test_request_DATA_with_form_content(self):
  55.         """
  56.        Ensure request.data returns content for POST request with form content.
  57.        """
  58.         data = {'qwerty': 'uiop'}
  59.         request = Request(factory.post('/', data))
  60.         request.parsers = (FormParser(), MultiPartParser())
  61.         assert list(request.data.items()) == list(data.items())
  62.  
  63.     def test_request_DATA_with_text_content(self):
  64.         """
  65.        Ensure request.data returns content for POST request with
  66.        non-form content.
  67.        """
  68.         content = six.b('qwerty')
  69.         content_type = 'text/plain'
  70.         request = Request(factory.post('/', content, content_type=content_type))
  71.         request.parsers = (PlainTextParser(),)
  72.         assert request.data == content
  73.  
  74.     def test_request_POST_with_form_content(self):
  75.         """
  76.        Ensure request.POST returns content for POST request with form content.
  77.        """
  78.         data = {'qwerty': 'uiop'}
  79.         request = Request(factory.post('/', data))
  80.         request.parsers = (FormParser(), MultiPartParser())
  81.         assert list(request.POST.items()) == list(data.items())
  82.  
  83.     def test_request_POST_with_files(self):
  84.         """
  85.        Ensure request.POST returns no content for POST request with file content.
  86.        """
  87.         upload = SimpleUploadedFile("file.txt", b"file_content")
  88.         request = Request(factory.post('/', {'upload': upload}))
  89.         request.parsers = (FormParser(), MultiPartParser())
  90.         assert list(request.POST.keys()) == []
  91.         assert list(request.FILES.keys()) == ['upload']
  92.  
  93.     def test_standard_behaviour_determines_form_content_PUT(self):
  94.         """
  95.        Ensure request.data returns content for PUT request with form content.
  96.        """
  97.         data = {'qwerty': 'uiop'}
  98.         request = Request(factory.put('/', data))
  99.         request.parsers = (FormParser(), MultiPartParser())
  100.         assert list(request.data.items()) == list(data.items())
  101.  
  102.     def test_standard_behaviour_determines_non_form_content_PUT(self):
  103.         """
  104.        Ensure request.data returns content for PUT request with
  105.        non-form content.
  106.        """
  107.         content = six.b('qwerty')
  108.         content_type = 'text/plain'
  109.         request = Request(factory.put('/', content, content_type=content_type))
  110.         request.parsers = (PlainTextParser(), )
  111.         assert request.data == content
  112.  
  113.  
  114. class MockView(APIView):
  115.     authentication_classes = (SessionAuthentication,)
  116.  
  117.     def post(self, request):
  118.         if request.POST.get('example') is not None:
  119.             return Response(status=status.HTTP_200_OK)
  120.  
  121.         return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)
  122.  
  123. urlpatterns = [
  124.     url(r'^$', MockView.as_view()),
  125. ]
  126.  
  127.  
  128. @override_settings(ROOT_URLCONF='tests.test_request')
  129. class TestContentParsingWithAuthentication(TestCase):
  130.     def setUp(self):
  131.         self.csrf_client = APIClient(enforce_csrf_checks=True)
  132.         self.username = 'john'
  133.         self.email = 'lennon@thebeatles.com'
  134.         self.password = 'password'
  135.         self.user = User.objects.create_user(self.username, self.email, self.password)
  136.  
  137.     def test_user_logged_in_authentication_has_POST_when_not_logged_in(self):
  138.         """
  139.        Ensures request.POST exists after SessionAuthentication when user
  140.        doesn't log in.
  141.        """
  142.         content = {'example': 'example'}
  143.  
  144.         response = self.client.post('/', content)
  145.         assert status.HTTP_200_OK == response.status_code
  146.  
  147.         response = self.csrf_client.post('/', content)
  148.         assert status.HTTP_200_OK == response.status_code
  149.  
  150.  
  151. class TestUserSetter(TestCase):
  152.  
  153.     def setUp(self):
  154.         # Pass request object through session middleware so session is
  155.         # available to login and logout functions
  156.         self.wrapped_request = factory.get('/')
  157.         self.request = Request(self.wrapped_request)
  158.         SessionMiddleware().process_request(self.request)
  159.  
  160.         User.objects.create_user('ringo', 'starr@thebeatles.com', 'yellow')
  161.         self.user = authenticate(username='ringo', password='yellow')
  162.  
  163.     def test_user_can_be_set(self):
  164.         self.request.user = self.user
  165.         assert self.request.user == self.user
  166.  
  167.     def test_user_can_login(self):
  168.         login(self.request, self.user)
  169.         assert self.request.user == self.user
  170.  
  171.     def test_user_can_logout(self):
  172.         self.request.user = self.user
  173.         self.assertFalse(is_anonymous(self.request.user))
  174.         logout(self.request)
  175.         self.assertTrue(is_anonymous(self.request.user))
  176.  
  177.     def test_logged_in_user_is_set_on_wrapped_request(self):
  178.         login(self.request, self.user)
  179.         assert self.wrapped_request.user == self.user
  180.  
  181.     def test_calling_user_fails_when_attribute_error_is_raised(self):
  182.         """
  183.        This proves that when an AttributeError is raised inside of the request.user
  184.        property, that we can handle this and report the true, underlying error.
  185.        """
  186.         class AuthRaisesAttributeError(object):
  187.             def authenticate(self, request):
  188.                 import rest_framework
  189.                 rest_framework.MISSPELLED_NAME_THAT_DOESNT_EXIST
  190.  
  191.         self.request = Request(factory.get('/'), authenticators=(AuthRaisesAttributeError(),))
  192.         SessionMiddleware().process_request(self.request)
  193.  
  194.         login(self.request, self.user)
  195.         try:
  196.             self.request.user
  197.         except AttributeError as error:
  198.             assert str(error) in (
  199.                 "'module' object has no attribute 'MISSPELLED_NAME_THAT_DOESNT_EXIST'",  # Python < 3.5
  200.                 "module 'rest_framework' has no attribute 'MISSPELLED_NAME_THAT_DOESNT_EXIST'",  # Python >= 3.5
  201.             )
  202.         else:
  203.             assert False, 'AttributeError not raised'
  204.  
  205.  
  206. class TestAuthSetter(TestCase):
  207.     def test_auth_can_be_set(self):
  208.         request = Request(factory.get('/'))
  209.         request.auth = 'DUMMY'
  210.         assert request.auth == 'DUMMY'
  211.  
  212.  
  213. class TestSecure(TestCase):
  214.  
  215.     def test_default_secure_false(self):
  216.         request = Request(factory.get('/', secure=False))
  217.         assert request.scheme == 'http'
  218.  
  219.     def test_default_secure_true(self):
  220.         request = Request(factory.get('/', secure=True))
  221.         assert request.scheme == 'https'
  222.  
downloadtest_request.py Source code - Download django-rest-framework Source code
Related Source Codes/Software:
lectures - Oxford Deep NLP 2017 course 2017-06-10
algorithms - Minimal examples of data structures and algorithms... 2017-06-10
Awesome-Hacking - A collection of various awesome lists for hackers,... 2017-06-09
lottie-ios - An iOS library to natively render After Effects ve... 2017-06-09
Public-APIs - 2017-06-09
angular-starter - 2017-06-10
redux-saga - An alternative side effect model for Redux apps ... 2017-06-10
pyenv - Simple Python version management 2017-06-10
goreplay - GoReplay is an open-source tool for capturing and ... 2017-06-10
realworld - TodoMVC for the RealWorld - Exemplary fullstack Me... 2017-06-11
CRYENGINE - CRYENGINE is a powerful real-time game development... 2017-06-11
postal - 2017-06-11
reactide - Reactide is the first dedicated IDE for React web ... 2017-06-11
rkt - rkt is a pod-native container engine for Linux. It... 2017-06-11
uWebSockets - Tiny WebSockets https://for... 2017-06-11

 Back to top