def get_pages(self, url):
        """
        Given a URL return a tuple of:

        (previous page, current page, next page, previous url, next url)
        """
        request = Request(factory.get(url))
        queryset = self.pagination.paginate_queryset(self.queryset, request)
        current = [item.created for item in queryset]

        next_url = self.pagination.get_next_link()
        previous_url = self.pagination.get_previous_link()

        if next_url is not None:
            request = Request(factory.get(next_url))
            queryset = self.pagination.paginate_queryset(
                self.queryset, request)
            next = [item.created for item in queryset]
        else:
            next = None

        if previous_url is not None:
            request = Request(factory.get(previous_url))
            queryset = self.pagination.paginate_queryset(
                self.queryset, request)
            previous = [item.created for item in queryset]
        else:
            previous = None

        return (previous, current, next, previous_url, next_url)
Ejemplo n.º 2
0
 def test_request_DATA_with_form_content(self):
     """
     Ensure request.DATA returns content for POST request with form content.
     """
     data = {'qwerty': 'uiop'}
     request = Request(factory.post('/', data))
     request.parsers = (FormParser(), MultiPartParser())
     self.assertEqual(list(request.DATA.items()), list(data.items()))
 def test_standard_behaviour_determines_form_content_PUT(self):
     """
     Ensure request.DATA returns content for PUT request with form content.
     """
     data = {'qwerty': 'uiop'}
     request = Request(factory.put('/', data))
     request.parsers = (FormParser(), MultiPartParser())
     self.assertEqual(list(request.DATA.items()), list(data.items()))
Ejemplo n.º 4
0
 def test_method(self):
     """
     Request methods should be same as underlying request.
     """
     request = Request(factory.get('/'))
     self.assertEqual(request.method, 'GET')
     request = Request(factory.post('/'))
     self.assertEqual(request.method, 'POST')
 def test_request_DATA_with_form_content(self):
     """
     Ensure request.DATA returns content for POST request with form content.
     """
     data = {'qwerty': 'uiop'}
     request = Request(factory.post('/', data))
     request.parsers = (FormParser(), MultiPartParser())
     self.assertEqual(list(request.DATA.items()), list(data.items()))
Ejemplo n.º 6
0
 def test_standard_behaviour_determines_form_content_PUT(self):
     """
     Ensure request.DATA returns content for PUT request with form content.
     """
     data = {'qwerty': 'uiop'}
     request = Request(factory.put('/', data))
     request.parsers = (FormParser(), MultiPartParser())
     self.assertEqual(list(request.DATA.items()), list(data.items()))
 def test_standard_behaviour_determines_non_form_content_PUT(self):
     """
     Ensure request.DATA returns content for PUT request with
     non-form content.
     """
     content = six.b('qwerty')
     content_type = 'text/plain'
     request = Request(factory.put('/', content, content_type=content_type))
     request.parsers = (PlainTextParser(), )
     self.assertEqual(request.DATA, content)
Ejemplo n.º 8
0
 def test_standard_behaviour_determines_non_form_content_PUT(self):
     """
     Ensure request.DATA returns content for PUT request with
     non-form content.
     """
     content = six.b('qwerty')
     content_type = 'text/plain'
     request = Request(factory.put('/', content, content_type=content_type))
     request.parsers = (PlainTextParser(), )
     self.assertEqual(request.DATA, content)
 def test_request_DATA_with_text_content(self):
     """
     Ensure request.DATA returns content for POST request with
     non-form content.
     """
     content = six.b('qwerty')
     content_type = 'text/plain'
     request = Request(factory.post('/', content, content_type=content_type))
     request.parsers = (PlainTextParser(),)
     self.assertEqual(request.DATA, content)
Ejemplo n.º 10
0
 def test_request_DATA_with_text_content(self):
     """
     Ensure request.DATA returns content for POST request with
     non-form content.
     """
     content = six.b('qwerty')
     content_type = 'text/plain'
     request = Request(factory.post('/', content,
                                    content_type=content_type))
     request.parsers = (PlainTextParser(), )
     self.assertEqual(request.DATA, content)
Ejemplo n.º 11
0
    def test_x_http_method_override_header(self):
        """
        POST requests can also be overloaded to another method by setting
        the X-HTTP-Method-Override header.
        """
        request = Request(
            factory.post('/', {'foo': 'bar'},
                         HTTP_X_HTTP_METHOD_OVERRIDE='DELETE'))
        self.assertEqual(request.method, 'DELETE')

        request = Request(
            factory.get('/', {'foo': 'bar'},
                        HTTP_X_HTTP_METHOD_OVERRIDE='DELETE'))
        self.assertEqual(request.method, 'DELETE')
Ejemplo n.º 12
0
 def test_overloaded_behaviour_allows_content_tunnelling(self):
     """
     Ensure request.DATA returns content for overloaded POST request.
     """
     json_data = {'foobar': 'qwerty'}
     content = json.dumps(json_data)
     content_type = 'application/json'
     form_data = {
         api_settings.FORM_CONTENT_OVERRIDE: content,
         api_settings.FORM_CONTENTTYPE_OVERRIDE: content_type
     }
     request = Request(factory.post('/', form_data))
     request.parsers = (JSONParser(), )
     self.assertEqual(request.DATA, json_data)
 def test_overloaded_behaviour_allows_content_tunnelling(self):
     """
     Ensure request.DATA returns content for overloaded POST request.
     """
     json_data = {'foobar': 'qwerty'}
     content = json.dumps(json_data)
     content_type = 'application/json'
     form_data = {
         api_settings.FORM_CONTENT_OVERRIDE: content,
         api_settings.FORM_CONTENTTYPE_OVERRIDE: content_type
     }
     request = Request(factory.post('/', form_data))
     request.parsers = (JSONParser(), )
     self.assertEqual(request.DATA, json_data)
 def test_last_page(self):
     request = Request(factory.get('/', {'page': 'last'}))
     queryset = self.paginate_queryset(request)
     content = self.get_paginated_content(queryset)
     context = self.get_html_context()
     assert queryset == [96, 97, 98, 99, 100]
     assert content == {
         'results': [96, 97, 98, 99, 100],
         'previous': 'http://testserver/?page=19',
         'next': None,
         'count': 100
     }
     assert context == {
         'previous_url':
         'http://testserver/?page=19',
         'next_url':
         None,
         'page_links': [
             PageLink('http://testserver/', 1, False, False),
             PAGE_BREAK,
             PageLink('http://testserver/?page=18', 18, False, False),
             PageLink('http://testserver/?page=19', 19, False, False),
             PageLink('http://testserver/?page=20', 20, True, False),
         ]
     }
 def test_middle_offset(self):
     request = Request(factory.get('/', {'limit': 5, 'offset': 10}))
     queryset = self.paginate_queryset(request)
     content = self.get_paginated_content(queryset)
     context = self.get_html_context()
     assert queryset == [11, 12, 13, 14, 15]
     assert content == {
         'results': [11, 12, 13, 14, 15],
         'previous': 'http://testserver/?limit=5&offset=5',
         'next': 'http://testserver/?limit=5&offset=15',
         'count': 100
     }
     assert context == {
         'previous_url':
         'http://testserver/?limit=5&offset=5',
         'next_url':
         'http://testserver/?limit=5&offset=15',
         'page_links': [
             PageLink('http://testserver/?limit=5', 1, False, False),
             PageLink('http://testserver/?limit=5&offset=5', 2, False,
                      False),
             PageLink('http://testserver/?limit=5&offset=10', 3, True,
                      False),
             PageLink('http://testserver/?limit=5&offset=15', 4, False,
                      False),
             PAGE_BREAK,
             PageLink('http://testserver/?limit=5&offset=95', 20, False,
                      False),
         ]
     }
 def test_second_page(self):
     request = Request(factory.get('/', {'page': 2}))
     queryset = self.paginate_queryset(request)
     content = self.get_paginated_content(queryset)
     context = self.get_html_context()
     assert queryset == [6, 7, 8, 9, 10]
     assert content == {
         'results': [6, 7, 8, 9, 10],
         'previous': 'http://testserver/',
         'next': 'http://testserver/?page=3',
         'count': 100
     }
     assert context == {
         'previous_url':
         'http://testserver/',
         'next_url':
         'http://testserver/?page=3',
         'page_links': [
             PageLink('http://testserver/', 1, False, False),
             PageLink('http://testserver/?page=2', 2, True, False),
             PageLink('http://testserver/?page=3', 3, False, False),
             PAGE_BREAK,
             PageLink('http://testserver/?page=20', 20, False, False),
         ]
     }
 def test_invalid_offset(self):
     """
     An invalid offset query param should be treated as 0.
     """
     request = Request(factory.get('/', {'limit': 5, 'offset': 'invalid'}))
     queryset = self.paginate_queryset(request)
     assert queryset == [1, 2, 3, 4, 5]
 def test_ending_offset(self):
     request = Request(factory.get('/', {'limit': 5, 'offset': 95}))
     queryset = self.paginate_queryset(request)
     content = self.get_paginated_content(queryset)
     context = self.get_html_context()
     assert queryset == [96, 97, 98, 99, 100]
     assert content == {
         'results': [96, 97, 98, 99, 100],
         'previous': 'http://testserver/?limit=5&offset=90',
         'next': None,
         'count': 100
     }
     assert context == {
         'previous_url':
         'http://testserver/?limit=5&offset=90',
         'next_url':
         None,
         'page_links': [
             PageLink('http://testserver/?limit=5', 1, False, False),
             PAGE_BREAK,
             PageLink('http://testserver/?limit=5&offset=85', 18, False,
                      False),
             PageLink('http://testserver/?limit=5&offset=90', 19, False,
                      False),
             PageLink('http://testserver/?limit=5&offset=95', 20, True,
                      False),
         ]
     }
 def test_invalid_limit(self):
     """
     An invalid limit query param should be ignored in favor of the default.
     """
     request = Request(factory.get('/', {'limit': 'invalid', 'offset': 0}))
     queryset = self.paginate_queryset(request)
     assert queryset == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Ejemplo n.º 20
0
 def test_form_POST_unicode(self):
     """
     JSON POST via default web interface with unicode data
     """
     # Note: environ and other variables here have simplified content compared to real Request
     CONTENT = b'_content_type=application%2Fjson&_content=%7B%22request%22%3A+4%2C+%22firm%22%3A+1%2C+%22text%22%3A+%22%D0%9F%D1%80%D0%B8%D0%B2%D0%B5%D1%82%21%22%7D'
     environ = {
         'REQUEST_METHOD': 'POST',
         'CONTENT_TYPE': 'application/x-www-form-urlencoded',
         'CONTENT_LENGTH': len(CONTENT),
         'wsgi.input': BytesIO(CONTENT),
     }
     wsgi_request = WSGIRequest(environ=environ)
     wsgi_request._load_post_and_files()
     parsers = (JSONParser(), FormParser(), MultiPartParser())
     parser_context = {
         'encoding': 'utf-8',
         'kwargs': {},
         'args': (),
     }
     request = Request(wsgi_request,
                       parsers=parsers,
                       parser_context=parser_context)
     method = request.method
     self.assertEqual(method, 'POST')
     self.assertEqual(request._content_type, 'application/json')
     self.assertEqual(
         request._stream.getvalue(),
         b'{"request": 4, "firm": 1, "text": "\xd0\x9f\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82!"}'
     )
     self.assertEqual(request._data, Empty)
     self.assertEqual(request._files, Empty)
 def test_single_offset(self):
     """
     When the offset is not a multiple of the limit we get some edge cases:
     * The first page should still be offset zero.
     * We may end up displaying an extra page in the pagination control.
     """
     request = Request(factory.get('/', {'limit': 5, 'offset': 1}))
     queryset = self.paginate_queryset(request)
     content = self.get_paginated_content(queryset)
     context = self.get_html_context()
     assert queryset == [2, 3, 4, 5, 6]
     assert content == {
         'results': [2, 3, 4, 5, 6],
         'previous': 'http://testserver/?limit=5',
         'next': 'http://testserver/?limit=5&offset=6',
         'count': 100
     }
     assert context == {
         'previous_url':
         'http://testserver/?limit=5',
         'next_url':
         'http://testserver/?limit=5&offset=6',
         'page_links': [
             PageLink('http://testserver/?limit=5', 1, False, False),
             PageLink('http://testserver/?limit=5&offset=1', 2, True,
                      False),
             PageLink('http://testserver/?limit=5&offset=6', 3, False,
                      False),
             PAGE_BREAK,
             PageLink('http://testserver/?limit=5&offset=96', 21, False,
                      False),
         ]
     }
 def test_no_offset(self):
     request = Request(factory.get('/', {'limit': 5}))
     queryset = self.paginate_queryset(request)
     content = self.get_paginated_content(queryset)
     context = self.get_html_context()
     assert queryset == [1, 2, 3, 4, 5]
     assert content == {
         'results': [1, 2, 3, 4, 5],
         'previous': None,
         'next': 'http://testserver/?limit=5&offset=5',
         'count': 100
     }
     assert context == {
         'previous_url':
         None,
         'next_url':
         'http://testserver/?limit=5&offset=5',
         'page_links': [
             PageLink('http://testserver/?limit=5', 1, True, False),
             PageLink('http://testserver/?limit=5&offset=5', 2, False,
                      False),
             PageLink('http://testserver/?limit=5&offset=10', 3, False,
                      False),
             PAGE_BREAK,
             PageLink('http://testserver/?limit=5&offset=95', 20, False,
                      False),
         ]
     }
     assert self.pagination.display_page_controls
     assert isinstance(self.pagination.to_html(), type(''))
Ejemplo n.º 23
0
 def test_overloaded_method(self):
     """
     POST requests can be overloaded to another method by setting a
     reserved form field
     """
     request = Request(
         factory.post('/', {api_settings.FORM_METHOD_OVERRIDE: 'DELETE'}))
     self.assertEqual(request.method, 'DELETE')
    def test_use_with_ordering_filter(self):
        class MockView:
            filter_backends = (filters.OrderingFilter, )
            ordering_fields = ['username', 'created']
            ordering = 'created'

        request = Request(factory.get('/', {'ordering': 'username'}))
        ordering = self.pagination.get_ordering(request, [], MockView())
        assert ordering == ('username', )

        request = Request(factory.get('/', {'ordering': '-username'}))
        ordering = self.pagination.get_ordering(request, [], MockView())
        assert ordering == ('-username', )

        request = Request(factory.get('/', {'ordering': 'invalid'}))
        ordering = self.pagination.get_ordering(request, [], MockView())
        assert ordering == ('created', )
Ejemplo n.º 25
0
    def setUp(self):
        # Pass request object through session middleware so session is
        # available to login and logout functions
        self.wrapped_request = factory.get('/')
        self.request = Request(self.wrapped_request)
        SessionMiddleware().process_request(self.request)

        User.objects.create_user('ringo', '*****@*****.**', 'yellow')
        self.user = authenticate(username='******', password='******')
Ejemplo n.º 26
0
    def initialize_request(self, request, *args, **kwargs):
        """
        Returns the initial request object.
        """
        parser_context = self.get_parser_context(request)

        return Request(
            request,
            parsers=self.get_parsers(),
            authenticators=self.get_authenticators(),
            negotiator=self.get_content_negotiator(),
            parser_context=parser_context
        )
Ejemplo n.º 27
0
    def test_calling_user_fails_when_attribute_error_is_raised(self):
        """
        This proves that when an AttributeError is raised inside of the request.user
        property, that we can handle this and report the true, underlying error.
        """
        class AuthRaisesAttributeError(object):
            def authenticate(self, request):
                import rest_framework
                rest_framework_3.MISSPELLED_NAME_THAT_DOESNT_EXIST

        self.request = Request(factory.get('/'),
                               authenticators=(AuthRaisesAttributeError(), ))
        SessionMiddleware().process_request(self.request)

        login(self.request, self.user)
        try:
            self.request.user
        except AttributeError as error:
            self.assertEqual(
                str(error),
                "'module' object has no attribute 'MISSPELLED_NAME_THAT_DOESNT_EXIST'"
            )
        else:
            assert False, 'AttributeError not raised'
 def test_invalid_page(self):
     request = Request(factory.get('/', {'page': 'invalid'}))
     with pytest.raises(exceptions.NotFound):
         self.paginate_queryset(request)
 def test_invalid_cursor(self):
     request = Request(factory.get('/', {'cursor': '123'}))
     with pytest.raises(exceptions.NotFound):
         self.pagination.paginate_queryset(self.queryset, request)
Ejemplo n.º 30
0
 def test_standard_behaviour_determines_no_content_HEAD(self):
     """
     Ensure request.DATA returns empty QueryDict for HEAD request.
     """
     request = Request(factory.head('/'))
     self.assertEqual(request.DATA, {})
Ejemplo n.º 31
0
 def test_auth_can_be_set(self):
     request = Request(factory.get('/'))
     request.auth = 'DUMMY'
     self.assertEqual(request.auth, 'DUMMY')
 def test_auth_can_be_set(self):
     request = Request(factory.get('/'))
     request.auth = 'DUMMY'
     self.assertEqual(request.auth, 'DUMMY')
 def test_client_overspecifies_accept_use_client(self):
     request = Request(
         factory.get('/', HTTP_ACCEPT='application/json; indent=8'))
     accepted_renderer, accepted_media_type = self.select_renderer(request)
     self.assertEqual(accepted_media_type, 'application/json; indent=8')
from __future__ import unicode_literals
from rest_framework_3 import exceptions, metadata, serializers, status, views, versioning
from rest_framework_3.request import Request
from rest_framework_3.renderers import BrowsableAPIRenderer
from rest_framework_3.test import APIRequestFactory

request = Request(APIRequestFactory().options('/'))


class TestMetadata:
    def test_metadata(self):
        """
        OPTIONS requests to views should return a valid 200 response.
        """
        class ExampleView(views.APIView):
            """Example view."""
            pass

        view = ExampleView.as_view()
        response = view(request=request)
        expected = {
            'name':
            'Example',
            'description':
            'Example view.',
            'renders': ['application/json', 'text/html'],
            'parses': [
                'application/json', 'application/x-www-form-urlencoded',
                'multipart/form-data'
            ]
        }
 def test_client_without_accept_use_renderer(self):
     request = Request(factory.get('/'))
     accepted_renderer, accepted_media_type = self.select_renderer(request)
     self.assertEqual(accepted_media_type, 'application/json')