class TestHyperlinkedRelatedField(URLPatternsTestCase):
    included = [
        url(r'^namespaced/(?P<pk>\d+)/$', dummy_pk_view, name='namespaced'),
    ]

    urlpatterns = [
        url(r'^v1/', include(included, namespace='v1', app_name='v1')),
        url(r'^v2/', include(included, namespace='v2', app_name='v2'))
    ]

    def setUp(self):
        super(TestHyperlinkedRelatedField, self).setUp()

        class MockQueryset(object):
            def get(self, pk):
                return 'object %s' % pk

        self.field = serializers.HyperlinkedRelatedField(
            view_name='namespaced', queryset=MockQueryset())
        request = factory.get('/')
        request.versioning_scheme = NamespaceVersioning()
        request.version = 'v1'
        self.field._context = {'request': request}

    def test_bug_2489(self):
        assert self.field.to_internal_value('/v1/namespaced/3/') == 'object 3'
        with pytest.raises(serializers.ValidationError):
            self.field.to_internal_value('/v2/namespaced/3/')
class TestNamespaceVersioningHyperlinkedRelatedFieldScheme(
        URLPatternsTestCase):
    nested = [
        url(r'^namespaced/(?P<pk>\d+)/$', dummy_pk_view, name='nested'),
    ]
    included = [
        url(r'^namespaced/(?P<pk>\d+)/$', dummy_pk_view, name='namespaced'),
        url(
            r'^nested/',
            include(nested,
                    namespace='nested-namespace',
                    app_name='nested-namespace'))
    ]

    urlpatterns = [
        url(r'^v1/',
            include(included, namespace='v1', app_name='restframeworkv1')),
        url(r'^v2/',
            include(included, namespace='v2', app_name='restframeworkv2')),
        url(r'^non-api/(?P<pk>\d+)/$', dummy_pk_view, name='non-api-view')
    ]

    def _create_field(self, view_name, version):
        request = factory.get("/")
        request.versioning_scheme = NamespaceVersioning()
        request.version = version

        field = serializers.HyperlinkedRelatedField(view_name=view_name,
                                                    read_only=True)
        field._context = {'request': request}
        return field

    def test_api_url_is_properly_reversed_with_v1(self):
        field = self._create_field('namespaced', 'v1')
        assert field.to_representation(
            PKOnlyObject(3)) == 'http://testserver/v1/namespaced/3/'

    def test_api_url_is_properly_reversed_with_v2(self):
        field = self._create_field('namespaced', 'v2')
        assert field.to_representation(
            PKOnlyObject(5)) == 'http://testserver/v2/namespaced/5/'

    def test_api_url_is_properly_reversed_with_nested(self):
        field = self._create_field('nested', 'v1:nested-namespace')
        assert field.to_representation(
            PKOnlyObject(3)) == 'http://testserver/v1/nested/namespaced/3/'

    def test_non_api_url_is_properly_reversed_regardless_of_the_version(self):
        """
        Regression test for #2711
        """
        field = self._create_field('non-api-view', 'v1')
        assert field.to_representation(
            PKOnlyObject(10)) == 'http://testserver/non-api/10/'

        field = self._create_field('non-api-view', 'v2')
        assert field.to_representation(
            PKOnlyObject(10)) == 'http://testserver/non-api/10/'
def apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required):
    ret = []
    for urlpattern in urlpatterns:
        if isinstance(urlpattern, RegexURLResolver):
            # Set of included URL patterns
            regex = urlpattern.regex.pattern
            namespace = urlpattern.namespace
            app_name = urlpattern.app_name
            kwargs = urlpattern.default_kwargs
            # Add in the included patterns, after applying the suffixes
            patterns = apply_suffix_patterns(urlpattern.url_patterns,
                                             suffix_pattern,
                                             suffix_required)
            ret.append(url(regex, include(patterns, namespace, app_name), kwargs))

        else:
            # Regular URL pattern
            regex = urlpattern.regex.pattern.rstrip('$') + suffix_pattern
            view = urlpattern._callback or urlpattern._callback_str
            kwargs = urlpattern.default_args
            name = urlpattern.name
            # Add in both the existing and the new urlpattern
            if not suffix_required:
                ret.append(urlpattern)
            ret.append(url(regex, view, kwargs, name))

    return ret
Exemplo n.º 4
0
def apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required):
    ret = []
    for urlpattern in urlpatterns:
        if isinstance(urlpattern, RegexURLResolver):
            # Set of included URL patterns
            regex = urlpattern.regex.pattern
            namespace = urlpattern.namespace
            app_name = urlpattern.app_name
            kwargs = urlpattern.default_kwargs
            # Add in the included patterns, after applying the suffixes
            patterns = apply_suffix_patterns(urlpattern.url_patterns,
                                             suffix_pattern,
                                             suffix_required)
            ret.append(url(regex, include(patterns, namespace, app_name), kwargs))

        else:
            # Regular URL pattern
            regex = urlpattern.regex.pattern.rstrip('$').rstrip('/') + suffix_pattern
            view = urlpattern.callback
            kwargs = urlpattern.default_args
            name = urlpattern.name
            # Add in both the existing and the new urlpattern
            if not suffix_required:
                ret.append(urlpattern)
            ret.append(url(regex, view, kwargs, name))

    return ret
Exemplo n.º 5
0
 def test_included_urls(self):
     nested_patterns = patterns("", url(r"^path$", dummy_view))
     urlpatterns = patterns("", url(r"^test/", include(nested_patterns), {"foo": "bar"}))
     test_paths = [
         URLTestPath("/test/path", (), {"foo": "bar"}),
         URLTestPath("/test/path.api", (), {"foo": "bar", "format": "api"}),
         URLTestPath("/test/path.asdf", (), {"foo": "bar", "format": "asdf"}),
     ]
     self._resolve_urlpatterns(urlpatterns, test_paths)
 def test_included_urls(self):
     nested_patterns = patterns(
         '',
         url(r'^path$', dummy_view)
     )
     urlpatterns = patterns(
         '',
         url(r'^test/', include(nested_patterns), {'foo': 'bar'}),
     )
     test_paths = [
         URLTestPath('/test/path', (), {'foo': 'bar', }),
         URLTestPath('/test/path.api', (), {'foo': 'bar', 'format': 'api'}),
         URLTestPath('/test/path.asdf', (), {'foo': 'bar', 'format': 'asdf'}),
     ]
     self._resolve_urlpatterns(urlpatterns, test_paths)
Exemplo n.º 7
0
 def test_included_urls(self):
     nested_patterns = patterns('', url(r'^path$', dummy_view))
     urlpatterns = patterns(
         '',
         url(r'^test/', include(nested_patterns), {'foo': 'bar'}),
     )
     test_paths = [
         URLTestPath('/test/path', (), {
             'foo': 'bar',
         }),
         URLTestPath('/test/path.api', (), {
             'foo': 'bar',
             'format': 'api'
         }),
         URLTestPath('/test/path.asdf', (), {
             'foo': 'bar',
             'format': 'asdf'
         }),
     ]
     self._resolve_urlpatterns(urlpatterns, test_paths)
    def setUp(self):
        class NoteSerializer(serializers.HyperlinkedModelSerializer):
            class Meta:
                model = RouterTestModel
                lookup_field = "uuid"
                fields = ("url", "uuid", "text")

        class NoteViewSet(viewsets.ModelViewSet):
            queryset = RouterTestModel.objects.all()
            serializer_class = NoteSerializer
            lookup_field = "uuid"

        RouterTestModel.objects.create(uuid="123", text="foo bar")

        self.router = SimpleRouter()
        self.router.register(r"notes", NoteViewSet)

        from rest_framework.tests import test_routers

        urls = getattr(test_routers, "urlpatterns")
        urls += patterns("", url(r"^", include(self.router.urls)))
Exemplo n.º 9
0
    def setUp(self):
        class NoteSerializer(serializers.HyperlinkedModelSerializer):
            class Meta:
                model = RouterTestModel
                lookup_field = 'uuid'
                fields = ('url', 'uuid', 'text')

        class NoteViewSet(viewsets.ModelViewSet):
            queryset = RouterTestModel.objects.all()
            serializer_class = NoteSerializer
            lookup_field = 'uuid'

        RouterTestModel.objects.create(uuid='123', text='foo bar')

        self.router = SimpleRouter()
        self.router.register(r'notes', NoteViewSet)

        from rest_framework.tests import test_routers
        urls = getattr(test_routers, 'urlpatterns')
        urls += patterns('',
            url(r'^', include(self.router.urls)),
        )
Exemplo n.º 10
0
    def setUp(self):
        class NoteSerializer(serializers.HyperlinkedModelSerializer):
            class Meta:
                model = RouterTestModel
                lookup_field = 'uuid'
                fields = ('url', 'uuid', 'text')

        class NoteViewSet(viewsets.ModelViewSet):
            queryset = RouterTestModel.objects.all()
            serializer_class = NoteSerializer
            lookup_field = 'uuid'

        RouterTestModel.objects.create(uuid='123', text='foo bar')

        self.router = SimpleRouter()
        self.router.register(r'notes', NoteViewSet)

        from rest_framework.tests import test_routers
        urls = getattr(test_routers, 'urlpatterns')
        urls += patterns('',
            url(r'^', include(self.router.urls)),
        )
Exemplo n.º 11
0
    def get(self, request, **kwargs):
        return Response('text')


urlpatterns = patterns(
    '',
    url(r'^.*\.(?P<format>.+)$',
        MockView.as_view(renderer_classes=[RendererA, RendererB])),
    url(r'^$', MockView.as_view(renderer_classes=[RendererA, RendererB])),
    url(r'^cache$', MockGETView.as_view()),
    url(r'^jsonp/jsonrenderer$',
        MockGETView.as_view(renderer_classes=[JSONRenderer, JSONPRenderer])),
    url(r'^jsonp/nojsonrenderer$',
        MockGETView.as_view(renderer_classes=[JSONPRenderer])),
    url(r'^html$', HTMLView.as_view()), url(r'^html1$', HTMLView1.as_view()),
    url(r'^api', include('rest_framework.urls', namespace='rest_framework')))


class POSTDeniedPermission(permissions.BasePermission):
    def has_permission(self, request, view):
        return request.method != 'POST'


class POSTDeniedView(APIView):
    renderer_classes = (BrowsableAPIRenderer, )
    permission_classes = (POSTDeniedPermission, )

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

    def post(self, request):
Exemplo n.º 12
0
class HTMLView1(APIView):
    renderer_classes = (BrowsableAPIRenderer, JSONRenderer)

    def get(self, request, **kwargs):
        return Response('text')

urlpatterns = patterns('',
    url(r'^.*\.(?P<format>.+)$', MockView.as_view(renderer_classes=[RendererA, RendererB])),
    url(r'^$', MockView.as_view(renderer_classes=[RendererA, RendererB])),
    url(r'^cache$', MockGETView.as_view()),
    url(r'^jsonp/jsonrenderer$', MockGETView.as_view(renderer_classes=[JSONRenderer, JSONPRenderer])),
    url(r'^jsonp/nojsonrenderer$', MockGETView.as_view(renderer_classes=[JSONPRenderer])),
    url(r'^html$', HTMLView.as_view()),
    url(r'^html1$', HTMLView1.as_view()),
    url(r'^api', include('rest_framework.urls', namespace='rest_framework'))
)


class POSTDeniedPermission(permissions.BasePermission):
    def has_permission(self, request, view):
        return request.method != 'POST'


class POSTDeniedView(APIView):
    renderer_classes = (BrowsableAPIRenderer,)
    permission_classes = (POSTDeniedPermission,)

    def get(self, request):
        return Response()
Exemplo n.º 13
0
from django.conf.urls import url
from rest_framework.compat import include
from rest_framework.routers import DefaultRouter
from rest_framework.authtoken import views

from .views import LemmaViewSet, MeaningViewSet, ValenceFrameViewSet, MeaningValenceViewSet, ExampleViewSet, \
    api_token_auth_session, UserViewSet, lemma_of_the_day

router = DefaultRouter()
router.register(r'lemmas', LemmaViewSet)
router.register(r'meanings', MeaningViewSet)
router.register(r'valence-frames', ValenceFrameViewSet)
router.register(r'meaning-valences', MeaningValenceViewSet)
router.register(r'examples', ExampleViewSet)
router.register(r'users', UserViewSet)

urlpatterns = [
    url(r'^api-token-auth-session/', api_token_auth_session),
    url(r'^api-token-auth/', views.obtain_auth_token),
    url(r'^lemma-of-the-day/', lemma_of_the_day),
    url('^', include(router.urls))
]
Exemplo n.º 14
0
        return Response('text')


urlpatterns = patterns(
    '',
    url(
        r'^setbyview$',
        MockViewSettingCharset.as_view(
            renderer_classes=[RendererA, RendererB, RendererC])),
    url(r'^.*\.(?P<format>.+)$',
        MockView.as_view(renderer_classes=[RendererA, RendererB, RendererC])),
    url(r'^$',
        MockView.as_view(renderer_classes=[RendererA, RendererB, RendererC])),
    url(r'^html$', HTMLView.as_view()), url(r'^html1$', HTMLView1.as_view()),
    url(r'^restframework',
        include('rest_framework.urls', namespace='rest_framework')))


# TODO: Clean tests bellow - remove duplicates with above, better unit testing, ...
class RendererIntegrationTests(TestCase):
    """
    End-to-end testing of renderers using an ResponseMixin on a generic view.
    """

    urls = 'rest_framework.tests.response'

    def test_default_renderer_serializes_content(self):
        """If the Accept header is not set the default renderer should serialize the response."""
        resp = self.client.get('/')
        self.assertEqual(resp['Content-Type'], RendererA.media_type)
        self.assertEqual(resp.content, RENDERER_A_SERIALIZER(DUMMYCONTENT))
Exemplo n.º 15
0
    (r'^basic/$',
     MockView.as_view(authentication_classes=[BasicAuthentication])),
    (r'^token/$',
     MockView.as_view(authentication_classes=[TokenAuthentication])),
    (r'^auth-token/$', 'rest_framework.authtoken.views.obtain_auth_token'),
    (r'^oauth/$',
     MockView.as_view(authentication_classes=[OAuthAuthentication])),
    (r'^oauth-with-scope/$',
     MockView.as_view(authentication_classes=[OAuthAuthentication],
                      permission_classes=[permissions.TokenHasReadWriteScope
                                          ])))

if oauth2_provider is not None:
    urlpatterns += patterns(
        '',
        url(r'^oauth2/', include('provider.oauth2.urls', namespace='oauth2')),
        url(r'^oauth2-test/$',
            MockView.as_view(authentication_classes=[OAuth2Authentication])),
        url(
            r'^oauth2-with-scope-test/$',
            MockView.as_view(
                authentication_classes=[OAuth2Authentication],
                permission_classes=[permissions.TokenHasReadWriteScope])),
    )


class BasicAuthTests(TestCase):
    """Basic authentication"""
    urls = 'rest_framework.tests.test_authentication'

    def setUp(self):
        return HttpResponse({'a': 1, 'b': 2, 'c': 3})


urlpatterns = patterns('',
    (r'^session/$', MockView.as_view(authentication_classes=[SessionAuthentication])),
    (r'^basic/$', MockView.as_view(authentication_classes=[BasicAuthentication])),
    (r'^token/$', MockView.as_view(authentication_classes=[TokenAuthentication])),
    (r'^auth-token/$', 'rest_framework.authtoken.views.obtain_auth_token'),
    (r'^oauth/$', MockView.as_view(authentication_classes=[OAuthAuthentication])),
    (r'^oauth-with-scope/$', MockView.as_view(authentication_classes=[OAuthAuthentication],
        permission_classes=[permissions.TokenHasReadWriteScope]))
)

if oauth2_provider is not None:
    urlpatterns += patterns('',
        url(r'^oauth2/', include('provider.oauth2.urls', namespace='oauth2')),
        url(r'^oauth2-test/$', MockView.as_view(authentication_classes=[OAuth2Authentication])),
        url(r'^oauth2-with-scope-test/$', MockView.as_view(authentication_classes=[OAuth2Authentication],
            permission_classes=[permissions.TokenHasReadWriteScope])),
    )


class BasicAuthTests(TestCase):
    """Basic authentication"""
    urls = 'rest_framework.tests.test_authentication'

    def setUp(self):
        self.csrf_client = Client(enforce_csrf_checks=True)
        self.username = '******'
        self.email = '*****@*****.**'
        self.password = '******'
Exemplo n.º 17
0
        return Response({'pk': pk, 'kwarg': kwarg})


notes_router = SimpleRouter()
notes_router.register(r'notes', NoteViewSet)

kwarged_notes_router = SimpleRouter()
kwarged_notes_router.register(r'notes', KWargedNoteViewSet)

namespaced_router = DefaultRouter()
namespaced_router.register(r'example', MockViewSet, base_name='example')

empty_prefix_router = SimpleRouter()
empty_prefix_router.register(r'', EmptyPrefixViewSet, base_name='empty_prefix')
empty_prefix_urls = [
    url(r'^', include(empty_prefix_router.urls)),
]

regex_url_path_router = SimpleRouter()
regex_url_path_router.register(r'', RegexUrlPathViewSet, base_name='regex')

urlpatterns = [
    url(r'^non-namespaced/', include(namespaced_router.urls)),
    url(r'^namespaced/', include(namespaced_router.urls, namespace='example', app_name='example')),
    url(r'^example/', include(notes_router.urls)),
    url(r'^example2/', include(kwarged_notes_router.urls)),

    url(r'^empty-prefix/', include(empty_prefix_urls)),
    url(r'^regex/', include(regex_url_path_router.urls))
]
class TestURLReversing(URLPatternsTestCase):
    included = [
        url(r'^namespaced/$', dummy_view, name='another'),
        url(r'^example/(?P<pk>\d+)/$', dummy_pk_view, name='example-detail')
    ]

    urlpatterns = [
        url(r'^v1/', include(included, namespace='v1', app_name='v1')),
        url(r'^another/$', dummy_view, name='another'),
        url(r'^(?P<version>[v1|v2]+)/another/$', dummy_view, name='another'),
    ]

    def test_reverse_unversioned(self):
        view = ReverseView.as_view()

        request = factory.get('/endpoint/')
        response = view(request)
        assert response.data == {'url': 'http://testserver/another/'}

    def test_reverse_query_param_versioning(self):
        scheme = versioning.QueryParameterVersioning
        view = ReverseView.as_view(versioning_class=scheme)

        request = factory.get('/endpoint/?version=v1')
        response = view(request)
        assert response.data == {
            'url': 'http://testserver/another/?version=v1'
        }

        request = factory.get('/endpoint/')
        response = view(request)
        assert response.data == {'url': 'http://testserver/another/'}

    @override_settings(ALLOWED_HOSTS=['*'])
    def test_reverse_host_name_versioning(self):
        scheme = versioning.HostNameVersioning
        view = ReverseView.as_view(versioning_class=scheme)

        request = factory.get('/endpoint/', HTTP_HOST='v1.example.org')
        response = view(request)
        assert response.data == {'url': 'http://v1.example.org/another/'}

        request = factory.get('/endpoint/')
        response = view(request)
        assert response.data == {'url': 'http://testserver/another/'}

    def test_reverse_url_path_versioning(self):
        scheme = versioning.URLPathVersioning
        view = ReverseView.as_view(versioning_class=scheme)

        request = factory.get('/v1/endpoint/')
        response = view(request, version='v1')
        assert response.data == {'url': 'http://testserver/v1/another/'}

        request = factory.get('/endpoint/')
        response = view(request)
        assert response.data == {'url': 'http://testserver/another/'}

    def test_reverse_namespace_versioning(self):
        class FakeResolverMatch:
            namespace = 'v1'

        scheme = versioning.NamespaceVersioning
        view = ReverseView.as_view(versioning_class=scheme)

        request = factory.get('/v1/endpoint/')
        request.resolver_match = FakeResolverMatch
        response = view(request, version='v1')
        assert response.data == {'url': 'http://testserver/v1/namespaced/'}

        request = factory.get('/endpoint/')
        response = view(request)
        assert response.data == {'url': 'http://testserver/another/'}
Exemplo n.º 19
0
    def get(self, request, **kwargs):
        return Response("text")


urlpatterns = patterns(
    "",
    url(r"^.*\.(?P<format>.+)$", MockView.as_view(renderer_classes=[RendererA, RendererB])),
    url(r"^$", MockView.as_view(renderer_classes=[RendererA, RendererB])),
    url(r"^cache$", MockGETView.as_view()),
    url(r"^jsonp/jsonrenderer$", MockGETView.as_view(renderer_classes=[JSONRenderer, JSONPRenderer])),
    url(r"^jsonp/nojsonrenderer$", MockGETView.as_view(renderer_classes=[JSONPRenderer])),
    url(r"^parseerror$", MockPOSTView.as_view(renderer_classes=[JSONRenderer, BrowsableAPIRenderer])),
    url(r"^html$", HTMLView.as_view()),
    url(r"^html1$", HTMLView1.as_view()),
    url(r"^empty$", EmptyGETView.as_view()),
    url(r"^api", include("rest_framework.urls", namespace="rest_framework")),
)


class POSTDeniedPermission(permissions.BasePermission):
    def has_permission(self, request, view):
        return request.method != "POST"


class POSTDeniedView(APIView):
    renderer_classes = (BrowsableAPIRenderer,)
    permission_classes = (POSTDeniedPermission,)

    def get(self, request):
        return Response()
Exemplo n.º 20
0
from django.conf.urls import url
from django.contrib import admin
from rest_framework.compat import include
from zticket_viewer_web_app import api_urls
from zticket_viewer_web_app import views

urlpatterns = [
    url(r'^api/v1/', include(api_urls), name='api'),
    url(r'.*', views.not_found, name='not-found')
]
        return self.queryset[index]


notes_router = SimpleRouter()
notes_router.register(r'notes', NoteViewSet)

kwarged_notes_router = SimpleRouter()
kwarged_notes_router.register(r'notes', KWargedNoteViewSet)

namespaced_router = DefaultRouter()
namespaced_router.register(r'example', MockViewSet, base_name='example')

empty_prefix_router = SimpleRouter()
empty_prefix_router.register(r'', EmptyPrefixViewSet, base_name='empty_prefix')
empty_prefix_urls = [
    url(r'^', include(empty_prefix_router.urls)),
]

urlpatterns = [
    url(r'^non-namespaced/', include(namespaced_router.urls)),
    url(
        r'^namespaced/',
        include(namespaced_router.urls,
                namespace='example',
                app_name='example')),
    url(r'^example/', include(notes_router.urls)),
    url(r'^example2/', include(kwarged_notes_router.urls)),
    url(r'^empty-prefix/', include(empty_prefix_urls)),
]

Exemplo n.º 22
0
from django.conf.urls import url
from api import views
from rest_framework.compat import include
from rest_framework.urlpatterns import format_suffix_patterns

urlpatterns = [
    url(r'^user/login/$', view=views.login_user, name='login'),
    url(r'^user/matches/$', view=views.Matches.as_view(), name='matches'),
    url(r'^user/suggestions/$',
        view=views.Suggestions.as_view(),
        name='suggestions'),
    url(r'^user/create/$', view=views.UserView.as_view(), name='create_user')
]

urlpatterns += [url(r'^api-auth/', include('rest_framework.urls'))]

urlpatterns = format_suffix_patterns(urlpatterns)
Exemplo n.º 23
0
v0_urlpatterns = patterns('',
    url(r'^view$', null_view, name='view'),
    url(r'^other-view', null_view, name="other-view"),
)

v1_urlpatterns = patterns('',
    url(r'^view$', null_view, name='view'),
)

v2_urlpatterns = patterns('',
    url(r'^view$', null_view, name='view'),
)

urlpatterns = patterns('',
    url(r'', include(v0_urlpatterns)),  # Un-versioned.
    url(r'v1/', include(v1_urlpatterns, namespace='v1')),
    url(r'v2/', include(v2_urlpatterns, namespace='v2')),
)


class ReverseTests(TestCase):
    """
    Tests for fully qualified URLs when using `reverse`.
    """
    urls = 'rest_framework.tests.test_reverse'

    def test_reversed_urls_are_fully_qualified(self):
        request = factory.get('/view')
        url = reverse('view', request=request)
        self.assertEqual(url, 'http://testserver/view')
Exemplo n.º 24
0
    serializer_class = BasicModelSerializer
    model = BasicModel


new_model_viewset_router = routers.DefaultRouter()
new_model_viewset_router.register(r'', HTMLNewModelViewSet)


urlpatterns = patterns('',
    url(r'^setbyview$', MockViewSettingContentType.as_view(renderer_classes=[RendererA, RendererB, RendererC])),
    url(r'^.*\.(?P<format>.+)$', MockView.as_view(renderer_classes=[RendererA, RendererB, RendererC])),
    url(r'^$', MockView.as_view(renderer_classes=[RendererA, RendererB, RendererC])),
    url(r'^html$', HTMLView.as_view()),
    url(r'^html1$', HTMLView1.as_view()),
    url(r'^html_new_model$', HTMLNewModelView.as_view()),
    url(r'^html_new_model_viewset', include(new_model_viewset_router.urls)),
    url(r'^restframework', include('rest_framework.urls', namespace='rest_framework'))
)


# TODO: Clean tests bellow - remove duplicates with above, better unit testing, ...
class RendererIntegrationTests(TestCase):
    """
    End-to-end testing of renderers using an ResponseMixin on a generic view.
    """

    urls = 'rest_framework.tests.test_response'

    def test_default_renderer_serializes_content(self):
        """If the Accept header is not set the default renderer should serialize the response."""
        resp = self.client.get('/')
Exemplo n.º 25
0
router = DefaultRouter()
router.register("users", UserViewSet, base_name="users_api")
router.register("posts", PostViewSet, base_name="posts_api")

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    # blogs
    url(r'^$', posts_list, name='posts_list'),
    url(r'^blogs/$', blogs_list, name='blogs_list'),
    url(r'^blogs/(?P<username>[0-9a-zA-Z]+)/$',
        user_posts_list,
        name="user_posts_list"),
    url(r'^blogs/(?P<username>[0-9a-zA-Z]+)/(?P<post_pk>[0-9]+)$',
        user_post_detail,
        name="user_post_detail"),
    url(r'^new-post$', NewPostView.as_view(), name="new_post"),
    # login
    url(r'^login$', LoginView.as_view(), name='login'),
    url(r'^logout$', logout, name='logout'),
    url(r'^signup$', SignupView.as_view(), name='signup'),

    # api de usuarios y posts
    url(r'^api/1.0/', include(router.urls)),
    # api de blogs
    url(r'^api/1.0/blogs/$', BlogsAPI.as_view(), name='blogs_api'),
    # api de posts
    url(r'^api/1.0/blogs/(?P<username>[0-9a-zA-Z]+)/$',
        PostViewSet.as_view({'get': 'list'}),
        name='user_posts_list_api')
]
        r"^oauth-with-scope/$",
        MockView.as_view(
            authentication_classes=[OAuthAuthentication], permission_classes=[permissions.TokenHasReadWriteScope]
        ),
    ),
)


class OAuth2AuthenticationDebug(OAuth2Authentication):
    allow_query_params_token = True


if oauth2_provider is not None:
    urlpatterns += patterns(
        "",
        url(r"^oauth2/", include("provider.oauth2.urls", namespace="oauth2")),
        url(r"^oauth2-test/$", MockView.as_view(authentication_classes=[OAuth2Authentication])),
        url(r"^oauth2-test-debug/$", MockView.as_view(authentication_classes=[OAuth2AuthenticationDebug])),
        url(
            r"^oauth2-with-scope-test/$",
            MockView.as_view(
                authentication_classes=[OAuth2Authentication], permission_classes=[permissions.TokenHasReadWriteScope]
            ),
        ),
    )


class BasicAuthTests(TestCase):
    """Basic authentication"""

    urls = "rest_framework.tests.test_authentication"
Exemplo n.º 27
0
from django.conf.urls import url
from rest_framework.compat import include
from .views import CreateGetAlbumsAPI, AlbumDetailAPIView

urlpatterns = [
    url(r'(?P<album_id>\d+)/images/?', include("src.images.api.urls", namespace='album-images')),
    url(r'(?P<album_id>\d+)/?$', AlbumDetailAPIView.as_view(), name='detail'),
    url(r'$', CreateGetAlbumsAPI.as_view(), name='list')
]