def test_document_with_link_named_data(self):
        """
        Ref #5395: Doc's `document.data` would fail with a Link named "data".
            As per #4972, use templatetag instead.
        """
        document = coreapi.Document(title='Data Endpoint API',
                                    url='https://api.example.org/',
                                    content={
                                        'data':
                                        coreapi.Link(
                                            url='/data/',
                                            action='get',
                                            fields=[],
                                            description='Return data.')
                                    })

        factory = APIRequestFactory()
        request = factory.get('/')

        renderer = DocumentationRenderer()

        html = renderer.render(document,
                               accepted_media_type="text/html",
                               renderer_context={"request": request})
        assert '<h1>Data Endpoint API</h1>' in html
    def setUp(self):
        self.throttle = ScopedRateThrottle()

        class XYScopedRateThrottle(ScopedRateThrottle):
            TIMER_SECONDS = 0
            THROTTLE_RATES = {'x': '3/min', 'y': '1/min'}

            def timer(self):
                return self.TIMER_SECONDS

        class XView(APIView):
            throttle_classes = (XYScopedRateThrottle, )
            throttle_scope = 'x'

            def get(self, request):
                return Response('x')

        class YView(APIView):
            throttle_classes = (XYScopedRateThrottle, )
            throttle_scope = 'y'

            def get(self, request):
                return Response('y')

        class UnscopedView(APIView):
            throttle_classes = (XYScopedRateThrottle, )

            def get(self, request):
                return Response('y')

        self.throttle_class = XYScopedRateThrottle
        self.factory = APIRequestFactory()
        self.x_view = XView.as_view()
        self.y_view = YView.as_view()
        self.unscoped_view = UnscopedView.as_view()
    def _resolve_urlpatterns(self, urlpatterns, test_paths, allowed=None):
        factory = APIRequestFactory()
        try:
            urlpatterns = format_suffix_patterns(urlpatterns, allowed=allowed)
        except Exception:
            self.fail(
                "Failed to apply `format_suffix_patterns` on  the supplied urlpatterns"
            )
        resolver = make_url_resolver(r'^/', urlpatterns)
        for test_path in test_paths:
            try:
                test_path, expected_resolved = test_path
            except (TypeError, ValueError):
                expected_resolved = True

            request = factory.get(test_path.path)
            try:
                callback, callback_args, callback_kwargs = resolver.resolve(
                    request.path_info)
            except Resolver404:
                callback, callback_args, callback_kwargs = (None, None, None)
                if expected_resolved:
                    raise
            except Exception:
                self.fail("Failed to resolve URL: %s" % request.path_info)

            if not expected_resolved:
                assert callback is None
                continue

            assert callback_args == test_path.args
            assert callback_kwargs == test_path.kwargs
 def test_only_permitted_forms_are_displayed(self):
     view = POSTDeniedView.as_view()
     request = APIRequestFactory().get('/')
     response = view(request).render()
     self.assertNotContains(response, '>POST<')
     self.assertContains(response, '>PUT<')
     self.assertContains(response, '>PATCH<')
Exemplo n.º 5
0
 def test_empty_request_content_type(self):
     factory = APIRequestFactory()
     request = factory.post(
         '/post-view/',
         data=None,
         content_type='application/json',
     )
     assert request.META['CONTENT_TYPE'] == 'application/json'
Exemplo n.º 6
0
 def test_request_factory_url_arguments(self):
     """
     This is a non regression test against #1461
     """
     factory = APIRequestFactory()
     request = factory.get('/view/?demo=test')
     assert dict(request.GET) == {'demo': ['test']}
     request = factory.get('/view/', {'demo': 'test'})
     assert dict(request.GET) == {'demo': ['test']}
Exemplo n.º 7
0
 def test_csrf_exempt_by_default(self):
     """
     By default, the test client is CSRF exempt.
     """
     user = User.objects.create_user('example', '*****@*****.**', 'password')
     factory = APIRequestFactory()
     request = factory.post('/view/')
     request.user = user
     response = view(request)
     assert response.status_code == 200
Exemplo n.º 8
0
 def test_force_authenticate(self):
     """
     Setting `force_authenticate()` forcibly authenticates the request.
     """
     user = User.objects.create_user('example', '*****@*****.**')
     factory = APIRequestFactory()
     request = factory.get('/view')
     force_authenticate(request, user=user)
     response = view(request)
     assert response.data['user'] == 'example'
Exemplo n.º 9
0
 def test_invalid_format(self):
     """
     Attempting to use a format that is not configured will raise an
     assertion error.
     """
     factory = APIRequestFactory()
     self.assertRaises(
         AssertionError, factory.post,
         path='/view/', data={'example': 1}, format='xml'
     )
Exemplo n.º 10
0
 def test_explicitly_enforce_csrf_checks(self):
     """
     The test client can enforce CSRF checks.
     """
     user = User.objects.create_user('example', '*****@*****.**', 'password')
     factory = APIRequestFactory(enforce_csrf_checks=True)
     request = factory.post('/view/')
     request.user = user
     response = view(request)
     expected = {'detail': 'CSRF Failed: CSRF cookie not set.'}
     assert response.status_code == 403
     assert response.data == expected
    def test_schemajs_output(self):
        """
        Test output of the SchemaJS renderer as per #5608. Django 2.0 on Py3 prints binary data as b'xyz' in templates,
        and the base64 encoding used by SchemaJSRenderer outputs base64 as binary. Test fix.
        """
        factory = APIRequestFactory()
        request = factory.get('/')

        renderer = SchemaJSRenderer()

        output = renderer.render('data', renderer_context={"request": request})
        assert "'ImRhdGEi'" in output
        assert "'b'ImRhdGEi''" not in output
    def test_get_result_url_no_result(self):
        factory = APIRequestFactory()

        class DummyView(APIView):
            lookup_field = 'test'

        # get the view instance instead of the view function
        view = DummyView.as_view()
        request = factory.get('/')
        response = view(request)
        view = response.renderer_context['view']

        self.assertIsNone(self.renderer.get_result_url({'test': 1}, view))
        self.assertIsNone(self.renderer.get_result_url({}, view))
    def test_render_dict_with_iteritems_key(self):
        factory = APIRequestFactory()

        class DummyView(APIView):
            renderer_classes = (AdminRenderer, )

            def get(self, request):
                return Response({'iteritems': 'a string'})

        view = DummyView.as_view()
        request = factory.get('/')
        response = view(request)
        response.render()
        self.assertContains(response,
                            '<tr><th>Iteritems</th><td>a string</td></tr>',
                            html=True)
    def test_get_result_url(self):
        factory = APIRequestFactory()

        class DummyGenericViewsetLike(APIView):
            lookup_field = 'test'

            def reverse_action(view, *args, **kwargs):
                self.assertEqual(kwargs['kwargs']['test'], 1)
                return '/example/'

        # get the view instance instead of the view function
        view = DummyGenericViewsetLike.as_view()
        request = factory.get('/')
        response = view(request)
        view = response.renderer_context['view']

        self.assertEqual(self.renderer.get_result_url({'test': 1}, view),
                         '/example/')
        self.assertIsNone(self.renderer.get_result_url({}, view))
    def test_get_context_result_urls(self):
        factory = APIRequestFactory()

        class DummyView(APIView):
            lookup_field = 'test'

            def reverse_action(view, url_name, args=None, kwargs=None):
                return '/%s/%d' % (url_name, kwargs['test'])

        # get the view instance instead of the view function
        view = DummyView.as_view()
        request = factory.get('/')
        response = view(request)

        data = [
            {
                'test': 1
            },
            {
                'url': '/example',
                'test': 2
            },
            {
                'url': None,
                'test': 3
            },
            {},
        ]
        context = {
            'view': DummyView(),
            'request': Request(request),
            'response': response
        }

        context = self.renderer.get_context(data, None, context)
        results = context['results']

        self.assertEqual(len(results), 4)
        self.assertEqual(results[0]['url'], '/detail/1')
        self.assertEqual(results[1]['url'], '/example')
        self.assertEqual(results[2]['url'], None)
        self.assertNotIn('url', results[3])
    def setUp(self):
        class Throttle(ScopedRateThrottle):
            THROTTLE_RATES = {'test_limit': '1/day'}
            TIMER_SECONDS = 0

            def timer(self):
                return self.TIMER_SECONDS

        class View(APIView):
            throttle_classes = (Throttle, )
            throttle_scope = 'test_limit'

            def get(self, request):
                return Response('test_limit')

        cache.clear()
        self.throttle = Throttle()
        self.view = View.as_view()
        self.request = APIRequestFactory().get('/some_uri')
        self.request.META['REMOTE_ADDR'] = '3.3.3.3'
        self.request.META['HTTP_X_FORWARDED_FOR'] = '0.0.0.0, 1.1.1.1, 2.2.2.2'
from __future__ import unicode_literals

import pytest
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.test import TestCase

from mind_core import (exceptions, metadata, serializers, status, versioning,
                       views)
from mind_core.renderers import BrowsableAPIRenderer
from mind_core.test import APIRequestFactory

from .models import BasicModel

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


class TestMetadata:
    def test_determine_metadata_abstract_method_raises_proper_error(self):
        with pytest.raises(NotImplementedError):
            metadata.BaseMetadata().determine_metadata(None, None)

    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()
 def setUp(self):
     """
     Reset the cache so that no throttles will be active
     """
     cache.clear()
     self.factory = APIRequestFactory()
Exemplo n.º 19
0
 def test_request_factory_url_arguments_with_unicode(self):
     factory = APIRequestFactory()
     request = factory.get('/view/?demo=testé')
     assert dict(request.GET) == {'demo': ['testé']}
     request = factory.get('/view/', {'demo': 'testé'})
     assert dict(request.GET) == {'demo': ['testé']}
Exemplo n.º 20
0
 def setUp(self):
     self.factory = APIRequestFactory()
        # because models have not been initialized.
        oauth2_provider = None

from mind_core.test import APIClient
from mind_core.test import APIRequestFactory

from mind_jwt import utils
from mind_jwt.compat import get_user_model
from mind_jwt.settings import DEFAULTS
from mind_jwt.settings import api_settings

User = get_user_model()

DJANGO_OAUTH2_PROVIDER_NOT_INSTALLED = 'django-oauth2-provider not installed'

factory = APIRequestFactory()


class JSONWebTokenAuthenticationTests(TestCase):
    """JSON Web Token Authentication"""
    def setUp(self):
        self.csrf_client = APIClient(enforce_csrf_checks=True)
        self.username = '******'
        self.email = '*****@*****.**'
        self.user = User.objects.create_user(self.username, self.email)

    def test_post_form_passing_jwt_auth(self):
        """
        Ensure POSTing form over JWT auth with correct credentials
        passes and does not require CSRF
        """
Exemplo n.º 22
0
 def test_upload_file(self):
     # This is a 1x1 black png
     simple_png = BytesIO(b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\rIDATx\x9cc````\x00\x00\x00\x05\x00\x01\xa5\xf6E@\x00\x00\x00\x00IEND\xaeB`\x82')
     simple_png.name = 'test.png'
     factory = APIRequestFactory()
     factory.post('/', data={'image': simple_png})