Esempio n. 1
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)
Esempio n. 3
0
 def test_default_args(self):
     urlpatterns = patterns("", url(r"^test$", dummy_view, {"foo": "bar"}))
     test_paths = [
         URLTestPath("/test", (), {"foo": "bar"}),
         URLTestPath("/test.api", (), {"foo": "bar", "format": "api"}),
         URLTestPath("/test.asdf", (), {"foo": "bar", "format": "asdf"}),
     ]
     self._resolve_urlpatterns(urlpatterns, test_paths)
Esempio n. 4
0
 def test_format_suffix(self):
     urlpatterns = patterns("", url(r"^test$", dummy_view))
     test_paths = [
         URLTestPath("/test", (), {}),
         URLTestPath("/test.api", (), {"format": "api"}),
         URLTestPath("/test.asdf", (), {"format": "asdf"}),
     ]
     self._resolve_urlpatterns(urlpatterns, test_paths)
 def test_format_suffix(self):
     urlpatterns = patterns(
         '',
         url(r'^test$', dummy_view),
     )
     test_paths = [
         URLTestPath('/test', (), {}),
         URLTestPath('/test.api', (), {'format': 'api'}),
         URLTestPath('/test.asdf', (), {'format': 'asdf'}),
     ]
     self._resolve_urlpatterns(urlpatterns, test_paths)
Esempio n. 6
0
 def test_format_suffix(self):
     urlpatterns = patterns(
         '',
         url(r'^test$', dummy_view),
     )
     test_paths = [
         URLTestPath('/test', (), {}),
         URLTestPath('/test.api', (), {'format': 'api'}),
         URLTestPath('/test.asdf', (), {'format': 'asdf'}),
     ]
     self._resolve_urlpatterns(urlpatterns, test_paths)
Esempio 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 test_default_args(self):
     urlpatterns = patterns(
         '',
         url(r'^test$', dummy_view, {'foo': 'bar'}),
     )
     test_paths = [
         URLTestPath('/test', (), {'foo': 'bar', }),
         URLTestPath('/test.api', (), {'foo': 'bar', 'format': 'api'}),
         URLTestPath('/test.asdf', (), {'foo': 'bar', 'format': 'asdf'}),
     ]
     self._resolve_urlpatterns(urlpatterns, test_paths)
Esempio n. 9
0
 def test_default_args(self):
     urlpatterns = patterns(
         '',
         url(r'^test$', dummy_view, {'foo': 'bar'}),
     )
     test_paths = [
         URLTestPath('/test', (), {
             'foo': 'bar',
         }),
         URLTestPath('/test.api', (), {
             'foo': 'bar',
             'format': 'api'
         }),
         URLTestPath('/test.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)))
Esempio n. 11
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)),
        )
Esempio n. 12
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)),
        )
Esempio n. 13
0
    def get(self, request, **kwargs):
        return Response('text')


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 HttpResponse({'a': 1, 'b': 2, 'c': 3})

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

    def put(self, request):
        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):
Esempio n. 15
0
        return Response('text')


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, )
Esempio n. 16
0
        return HttpResponse({'a': 1, 'b': 2, 'c': 3})

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

    def put(self, request):
        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/$',
Esempio n. 17
0
    pass


class NestedResourceRoot(APIView):
    pass


class NestedResourceInstance(APIView):
    pass


urlpatterns = patterns(
    '',
    url(r'^$', Root.as_view()),
    url(r'^resource/$', ResourceRoot.as_view()),
    url(r'^resource/(?P<key>[0-9]+)$', ResourceInstance.as_view()),
    url(r'^resource/(?P<key>[0-9]+)/$', NestedResourceRoot.as_view()),
    url(r'^resource/(?P<key>[0-9]+)/(?P<other>[A-Za-z]+)$',
        NestedResourceInstance.as_view()),
)


class BreadcrumbTests(TestCase):
    """Tests the breadcrumb functionality used by the HTML renderer."""

    urls = 'rest_framework.tests.breadcrumbs'

    def test_root_breadcrumbs(self):
        url = '/'
        self.assertEqual(get_breadcrumbs(url), [('Root', '/')])
Esempio n. 18
0
 def urls(self):
     if not hasattr(self, '_urls'):
         self._urls = patterns('', *self.get_urls())
     return self._urls
Esempio n. 19
0
        filter_kwargs = {'user': user_pk, 'slug': bucket_slug}

        try:
            obj = _get_object_or_404(queryset, **filter_kwargs)
        except (TypeError, ValueError):
            return Http404

        self.check_object_permissions(self.request, obj)

        return obj


urlpatterns = patterns(
    'django.contrib.auth.views',

    #url(r'^$', ServeView.as_view(), name=''),
    url(r'^bucket/(?P<user_pk>[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})/(?P<bucket_slug>[\w]+)/content/(?P<content_path>.*)$',
        bucket_content_nginx,
        name='extra_serve_bucket_content'),
    url(r'^bucket/(?P<user_pk>[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})/(?P<bucket_slug>[\w]+)/update/users_ro/$',
        BucketUpdateUsersRoView.as_view(),
        name='extra_serve_bucket_update_users_ro'),
    url(r'^bucket/(?P<user_pk>[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})/(?P<bucket_slug>[\w]+)/update/users_ro/add/$',
        BucketM2MAddView.as_view(model=Bucket), {'m2m_field': 'users_ro'},
        name='extra_serve_bucket_update_users_ro_add'),
    url(r'^bucket/(?P<user_pk>[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})/(?P<bucket_slug>[\w]+)/update/users_ro/remove/$',
        BucketM2MRemoveView.as_view(model=Bucket), {'m2m_field': 'users_ro'},
        name='extra_serve_bucket_update_users_ro_remove'),
)
# https://github.com/tomchristie/django-rest-framework/issues/960
from hyperlinked_relational_serializer import serializers_copy as serializers
# from rest_framework import serializers

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


def fake_view(request):
    pass


urlpatterns = patterns('',
    url(r'^vegetable/$', fake_view, name = 'vegetable-list'),
    url(r'^vegetable/(?P<pk>[0-9]+)/$', fake_view, name = 'vegetable-detail'),
    url(r'^meat/$', fake_view, name = 'meat-list'),
    url(r'^meat/(?P<pk>[0-9]+)/$', fake_view, name = 'meat-detail'),
    url(r'^meal/$', fake_view, name = 'meal-list'),
    url(r'^meal/(?P<pk>[0-9]+)/$', fake_view, name = 'meal-detail'),
)


class VegetableSerializer(HyperLinkedRelationalSerializer):

    class Meta:
        view_name = "vegetable-detail"
        queryset = Vegetable.objects.all()
        model = Vegetable

class MeatSerializer(HyperLinkedRelationalSerializer):

    class Meta:
Esempio n. 21
0
# The following patch overrides the URL patterns for the MockView class used in
# rest_framework.tests.test_authentication so that the corresponding AllowInactiveUser
# classes are tested instead.
@skipUnless(settings.FEATURES.get('ENABLE_OAUTH2_PROVIDER'),
            'OAuth2 not enabled')
@patch.object(
    test_authentication, 'urlpatterns',
    patterns(
        '',
        url(
            r'^oauth2-test/$',
            test_authentication.MockView.as_view(
                authentication_classes=[OAuth2AuthenticationAllowInactiveUser
                                        ])),
        url(
            r'^oauth2-test-debug/$',
            test_authentication.MockView.as_view(
                authentication_classes=[OAuth2AuthAllowInactiveUserDebug])),
        url(
            r'^oauth2-with-scope-test/$',
            test_authentication.MockView.as_view(
                authentication_classes=[OAuth2AuthenticationAllowInactiveUser],
                permission_classes=[permissions.TokenHasReadWriteScope]))))
class OAuth2AuthenticationAllowInactiveUserTestCase(
        test_authentication.OAuth2Tests):
    """
    Tests the OAuth2AuthenticationAllowInactiveUser class by running all the existing tests in
    OAuth2Tests but with the is_active flag on the user set to False.
    """
    def setUp(self):
        super(OAuth2AuthenticationAllowInactiveUserTestCase, self).setUp()
Esempio n. 22
0
"""
Login and logout views for the browsable API.

Add these to your root URLconf if you're using the browsable API and
your API requires authentication.

The urls must be namespaced as 'rest_framework', and you should make sure
your authentication settings include `SessionAuthentication`.

    urlpatterns = patterns('',
        ...
        url(r'^auth', include('rest_framework.urls', namespace='rest_framework'))
    )
"""
from __future__ import unicode_literals
from rest_framework.compat import patterns, url

template_name = {'template_name': 'rest_framework/login.html'}

urlpatterns = patterns(
    'django.contrib.auth.views',
    url(r'^login/$', 'login', template_name, name='login'),
    url(r'^logout/$', 'logout', template_name, name='logout'),
)
Esempio n. 23
0
    def get(self, request, **kwargs):
        return Response('text')


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'^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."""
Esempio n. 24
0
urlpatterns = patterns(
    '',
    url(r'^$', MetadataView.as_view(), name='tp_metadata'),

    # Snippet
    url(r'^snippet/$', SnippetView.as_view(), name='tp_metadata_snippet'),
    url(r'^snippet/filter/$',
        SnippetFilterView.as_view(),
        name='tp_metadata_snippet_filter'),
    url(r'^snippet/create/$',
        SnippetCreateView.as_view(),
        name='tp_metadata_snippet_create'),
    url(r'^snippet/(?P<pk>[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})/$',
        SnippetRetrieveView.as_view(),
        name='tp_metadata_snippet_retrieve'),
    url(r'^snippet/(?P<pk>[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})/update/$',
        SnippetUpdateView.as_view(),
        name='tp_metadata_snippet_update'),
    url(
        r'^snippet/(?P<pk>[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})/content$',
        SnippetRetrieveView.as_view(),
        {'serve_content': True},
        name='tp_metadata_snippet_content',
    ),

    # M2M Add/Remove

    # Assigned users
    url(r'^snippet/(?P<pk>[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})/update/assigned_users/$',
        SnippetUpdateAssignedUsersView.as_view(),
        name='tp_metadata_snippet_update_assigned_users'),
    url(r'^snippet/(?P<pk>[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})/update/assigned_users/add/$',
        M2MAddView.as_view(model=Snippet), {'m2m_field': 'assigned_users'},
        name='tp_metadata_snippet_update_assigned_users_add'),
    url(r'^snippet/(?P<pk>[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})/update/assigned_users/remove/$',
        M2MRemoveView.as_view(model=Snippet), {'m2m_field': 'assigned_users'},
        name='tp_metadata_snippet_update_assigned_users_remove'),

    # Assigned units
    url(r'^snippet/(?P<pk>[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})/update/assigned_units/$',
        SnippetUpdateAssignedUnitsView.as_view(),
        name='tp_metadata_snippet_update_assigned_units'),
    url(r'^snippet/(?P<pk>[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})/update/assigned_units/add/$',
        M2MAddView.as_view(model=Snippet), {'m2m_field': 'assigned_units'},
        name='tp_metadata_snippet_update_assigned_units_add'),
    url(r'^snippet/(?P<pk>[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})/update/assigned_units/remove/$',
        M2MRemoveView.as_view(model=Snippet), {'m2m_field': 'assigned_units'},
        name='tp_metadata_snippet_update_assigned_units_remove'),

    # Assigned quantities
    url(r'^snippet/(?P<pk>[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})/update/assigned_quantities/$',
        SnippetUpdateAssignedQuantitiesView.as_view(),
        name='tp_metadata_snippet_update_assigned_quantities'),
    url(r'^snippet/(?P<pk>[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})/update/assigned_quantities/add/$',
        M2MAddView.as_view(model=Snippet),
        {'m2m_field': 'assigned_quantities'},
        name='tp_metadata_snippet_update_assigned_quantities_add'),
    url(r'^snippet/(?P<pk>[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})/update/assigned_quantities/remove/$',
        M2MRemoveView.as_view(model=Snippet),
        {'m2m_field': 'assigned_quantities'},
        name='tp_metadata_snippet_update_assigned_quantities_remove'),

    # Assigned scopes
    url(r'^snippet/(?P<pk>[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})/update/assigned_scopes/$',
        SnippetUpdateAssignedScopesView.as_view(),
        name='tp_metadata_snippet_update_assigned_scopes'),
    url(r'^snippet/(?P<pk>[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})/update/assigned_scopes/add/$',
        M2MAddView.as_view(model=Snippet), {'m2m_field': 'assigned_scopes'},
        name='tp_metadata_snippet_update_assigned_scopes_add'),
    url(r'^snippet/(?P<pk>[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})/update/assigned_scopes/remove/$',
        M2MRemoveView.as_view(model=Snippet), {'m2m_field': 'assigned_scopes'},
        name='tp_metadata_snippet_update_assigned_scopes_remove'),

    # Assigned counters
    url(r'^snippet/(?P<pk>[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})/update/assigned_counters/$',
        SnippetUpdateAssignedQuantitiesView.as_view(),
        name='tp_metadata_snippet_update_assigned_counters'),
    url(r'^snippet/(?P<pk>[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})/update/assigned_counters/add/$',
        M2MAddView.as_view(model=Snippet), {'m2m_field': 'assigned_counters'},
        name='tp_metadata_snippet_update_assigned_counters_add'),
    url(r'^snippet/(?P<pk>[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})/update/assigned_counters/remove/$',
        M2MRemoveView.as_view(model=Snippet),
        {'m2m_field': 'assigned_counters'},
        name='tp_metadata_snippet_update_assigned_counters_remove'),

    # Assigned marks
    url(r'^snippet/(?P<pk>[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})/update/assigned_marks/$',
        SnippetUpdateAssignedQuantitiesView.as_view(),
        name='tp_metadata_snippet_update_assigned_marks'),
    url(r'^snippet/(?P<pk>[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})/update/assigned_marks/add/$',
        M2MAddView.as_view(model=Snippet), {'m2m_field': 'assigned_marks'},
        name='tp_metadata_snippet_update_assigned_marks_add'),
    url(r'^snippet/(?P<pk>[\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12})/update/assigned_marks/remove/$',
        M2MRemoveView.as_view(model=Snippet), {'m2m_field': 'assigned_marks'},
        name='tp_metadata_snippet_update_assigned_marks_remove'),
)
Esempio n. 25
0
from django.contrib.auth import get_user_model
from django.test import Client, TestCase

from rest_framework import HTTP_HEADER_ENCODING
from rest_framework.tests.test_authentication import MockView
from rest_framework.authtoken.models import Token
from rest_framework.compat import patterns

from rest_framework_digestauth.authentication import DigestAuthentication
from rest_framework_digestauth.utils import parse_dict_header
from rest_framework_digestauth.backends import DatabaseBackend

User = get_user_model()

urlpatterns = patterns(
    '',
    (r'^digest-auth/$',
    MockView.as_view(authentication_classes=[DigestAuthentication])))


def build_basic_header(username, password):
    credentials = '%s:%s' % (username, password)
    base64_credentials = base64.b64encode(
        credentials.encode(HTTP_HEADER_ENCODING)
    ).decode(HTTP_HEADER_ENCODING)
    return 'Basic %s' % base64_credentials


def build_digest_header(username, password, challenge_header, method, path,
                        nonce_count=1, cnonce=None):
    challenge_data = parse_dict_header(challenge_header.replace('Digest ', ''))
    realm = challenge_data['realm']
Esempio n. 26
0
USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_URL = '/static/'

########NEW FILE########
__FILENAME__ = urls
"""
Blank URLConf just to keep runtests.py happy.
"""
from rest_framework.compat import patterns

urlpatterns = patterns('', )

########NEW FILE########
__FILENAME__ = serializers
from django.contrib.auth import authenticate
from rest_framework import serializers

from rest_framework_jwt.settings import api_settings

jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER


class JSONWebTokenSerializer(serializers.Serializer):
    """
    Serializer class used to validate a username and password.
Esempio n. 27
0
@api_view(('GET', ))
@renderer_classes((TemplateHTMLRenderer, ))
def permission_denied(request):
    raise PermissionDenied()


@api_view(('GET', ))
@renderer_classes((TemplateHTMLRenderer, ))
def not_found(request):
    raise Http404()


urlpatterns = patterns(
    '',
    url(r'^$', example),
    url(r'^permission_denied$', permission_denied),
    url(r'^not_found$', not_found),
)


class TemplateHTMLRendererTests(TestCase):
    urls = 'rest_framework.tests.htmlrenderer'

    def setUp(self):
        """
        Monkeypatch get_template
        """
        self.get_template = django.template.loader.get_template

        def get_template(template_name):
            if template_name == 'example.html':
Esempio n. 28
0
from __future__ import unicode_literals
from django.db import models
from django.test import TestCase
from django.core.exceptions import ImproperlyConfigured
from rest_framework import serializers, viewsets, permissions
from rest_framework.compat import include, patterns, url
from rest_framework.decorators import link, action
from rest_framework.response import Response
from rest_framework.routers import SimpleRouter, DefaultRouter
from rest_framework.test import APIRequestFactory

factory = APIRequestFactory()

urlpatterns = patterns('', )


class BasicViewSet(viewsets.ViewSet):
    def list(self, request, *args, **kwargs):
        return Response({'method': 'list'})

    @action()
    def action1(self, request, *args, **kwargs):
        return Response({'method': 'action1'})

    @action()
    def action2(self, request, *args, **kwargs):
        return Response({'method': 'action2'})

    @action(methods=['post', 'delete'])
    def action3(self, request, *args, **kwargs):
        return Response({'method': 'action2'})
import json
import base64


class MockView(APIView):
    permission_classes = (permissions.IsAuthenticated,)

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

    def put(self, request):
        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'),
)


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

    def setUp(self):
        self.csrf_client = Client(enforce_csrf_checks=True)
        self.username = '******'
        self.email = '*****@*****.**'
        self.password = '******'
        self.user = User.objects.create_user(self.username, self.email, self.password)
Esempio n. 30
0
from __future__ import unicode_literals
from django.test import TestCase
from django.test.client import RequestFactory
from rest_framework.compat import patterns, url
from rest_framework.reverse import reverse

factory = RequestFactory()


def null_view(request):
    pass


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


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

    def test_reversed_urls_are_fully_qualified(self):
        request = factory.get('/view')
        url = reverse('view', request=request)
        self.assertEqual(url, 'http://testserver/view')
Esempio n. 31
0
from __future__ import unicode_literals
from django.db import models
from django.test import TestCase
from django.core.exceptions import ImproperlyConfigured
from rest_framework import serializers, viewsets, permissions
from rest_framework.compat import include, patterns, url
from rest_framework.decorators import link, action
from rest_framework.response import Response
from rest_framework.routers import SimpleRouter, DefaultRouter
from rest_framework.test import APIRequestFactory

factory = APIRequestFactory()

urlpatterns = patterns('',)


class BasicViewSet(viewsets.ViewSet):
    def list(self, request, *args, **kwargs):
        return Response({'method': 'list'})

    @action()
    def action1(self, request, *args, **kwargs):
        return Response({'method': 'action1'})

    @action()
    def action2(self, request, *args, **kwargs):
        return Response({'method': 'action2'})

    @action(methods=['post', 'delete'])
    def action3(self, request, *args, **kwargs):
        return Response({'method': 'action2'})
@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer,))
def permission_denied(request):
    raise PermissionDenied()


@api_view(('GET',))
@renderer_classes((TemplateHTMLRenderer,))
def not_found(request):
    raise Http404()


urlpatterns = patterns('',
    url(r'^$', example),
    url(r'^permission_denied$', permission_denied),
    url(r'^not_found$', not_found),
)


class TemplateHTMLRendererTests(TestCase):
    urls = 'rest_framework.tests.test_htmlrenderer'

    def setUp(self):
        """
        Monkeypatch get_template
        """
        self.get_template = django.template.loader.get_template

        def get_template(template_name, dirs=None):
            if template_name == 'app_scaffolding.html':
class ExtraKwargDetailSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = ExtraKwargModel

class ExtraKwargDetail(generics.RetrieveUpdateDestroyAPIView):
    model = ExtraKwargModel
    serializer_class = ExtraKwargDetailSerializer

urlpatterns = patterns('',
    url(r'^basic/$', BasicList.as_view(), name='basicmodel-list'),
    url(r'^basic/(?P<pk>\d+)/$', BasicDetail.as_view(), name='basicmodel-detail'),
    url(r'^anchor/(?P<pk>\d+)/$', AnchorDetail.as_view(), name='anchor-detail'),
    url(r'^manytomany/$', ManyToManyList.as_view(), name='manytomanymodel-list'),
    url(r'^manytomany/(?P<pk>\d+)/$', ManyToManyDetail.as_view(), name='manytomanymodel-detail'),
    url(r'^posts/(?P<pk>\d+)/$', BlogPostDetail.as_view(), name='blogpost-detail'),
    url(r'^comments/$', BlogPostCommentListCreate.as_view(), name='blogpostcomment-list'),
    url(r'^comments/(?P<pk>\d+)/$', BlogPostCommentDetail.as_view(), name='blogpostcomment-detail'),
    url(r'^albums/(?P<title>\w[\w-]*)/$', AlbumDetail.as_view(), name='album-detail'),
    url(r'^photos/$', PhotoListCreate.as_view(), name='photo-list'),
    url(r'^optionalrelation/(?P<pk>\d+)/$', OptionalRelationDetail.as_view(), name='optionalrelationmodel-detail'),
    url(r'^root/(?P<extra_kwarg>\d+)/extrakwarg/(?P<pk>\d+)/$', ExtraKwargDetail.as_view(), name='extrakwargmodel-detail'),
)


class TestBasicHyperlinkedView(TestCase):
    urls = 'rest_framework.tests.hyperlinkedserializers'

    def setUp(self):
        """
        Create 3 BasicModel instances.
        """
from django.test import TestCase
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.compat import patterns
from rest_framework.test import APIClient

from rest_framework_jwt import utils


urlpatterns = patterns("", (r"^auth-token/$", "rest_framework_jwt.views.obtain_jwt_token"))


class ObtainJSONWebTokenTests(TestCase):
    urls = "rest_framework_jwt.tests.test_views"

    def setUp(self):
        self.email = "*****@*****.**"
        self.username = "******"
        self.password = "******"
        self.user = User.objects.create_user(self.username, self.email, self.password)

        self.data = {"username": self.username, "password": self.password}

    def test_jwt_login_json(self):
        """
        Ensure JWT login view using JSON POST works.
        """
        client = APIClient(enforce_csrf_checks=True)

        response = client.post("/auth-token/", self.data, format="json")
Esempio n. 35
0
from django.core.urlresolvers import reverse

from rest_framework.compat import patterns, url
from rest_framework.test import APITestCase
from rest_framework.tests.models import NullableForeignKeySource
from rest_framework.tests.serializers import NullableFKSourceSerializer
from rest_framework.tests.views import NullableFKSourceDetail


urlpatterns = patterns(
    '',
    url(r'^objects/(?P<pk>\d+)/$', NullableFKSourceDetail.as_view(), name='object-detail'),
)


class NullableForeignKeyTests(APITestCase):
    """
    DRF should be able to handle nullable foreign keys when a test
    Client POST/PUT request is made with its own serialized object.
    """
    urls = 'rest_framework.tests.test_nullable_fields'

    def test_updating_object_with_null_fk(self):
        obj = NullableForeignKeySource(name='example', target=None)
        obj.save()
        serialized_data = NullableFKSourceSerializer(obj).data

        response = self.client.put(reverse('object-detail', args=[obj.pk]), serialized_data)

        self.assertEqual(response.data, serialized_data)
urlpatterns = patterns(
    '',
    url(r'^basic/$', BasicList.as_view(), name='basicmodel-list'),
    url(r'^basic/(?P<pk>\d+)/$',
        BasicDetail.as_view(),
        name='basicmodel-detail'),
    url(r'^anchor/(?P<pk>\d+)/$', AnchorDetail.as_view(),
        name='anchor-detail'),
    url(r'^manytomany/$',
        ManyToManyList.as_view(),
        name='manytomanymodel-list'),
    url(r'^manytomany/(?P<pk>\d+)/$',
        ManyToManyDetail.as_view(),
        name='manytomanymodel-detail'),
    url(r'^posts/(?P<pk>\d+)/$',
        BlogPostDetail.as_view(),
        name='blogpost-detail'),
    url(r'^comments/$',
        BlogPostCommentListCreate.as_view(),
        name='blogpostcomment-list'),
    url(r'^comments/(?P<pk>\d+)/$',
        BlogPostCommentDetail.as_view(),
        name='blogpostcomment-detail'),
    url(r'^albums/(?P<title>\w[\w-]*)/$',
        AlbumDetail.as_view(),
        name='album-detail'),
    url(r'^photos/$', PhotoListCreate.as_view(), name='photo-list'),
    url(r'^optionalrelation/(?P<pk>\d+)/$',
        OptionalRelationDetail.as_view(),
        name='optionalrelationmodel-detail'),
)
Esempio n. 37
0
    permission_classes = (permissions.IsAuthenticated,)

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

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


urlpatterns = patterns(
    '',
    (r'^jwt/$', MockView.as_view(
     authentication_classes=[JSONWebTokenAuthentication])),

    (r'^jwt-oauth2/$', MockView.as_view(
        authentication_classes=[
            JSONWebTokenAuthentication, OAuth2Authentication])),

    (r'^oauth2-jwt/$', MockView.as_view(
        authentication_classes=[
            OAuth2Authentication, JSONWebTokenAuthentication])),
)


class JSONWebTokenAuthenticationTests(TestCase):
    """JSON Web Token Authentication"""
    urls = 'rest_framework_jwt.tests.test_authentication'

    def setUp(self):
        self.csrf_client = APIClient(enforce_csrf_checks=True)
        self.username = '******'
Esempio n. 38
0
from __future__ import unicode_literals
from django.test import TestCase
from django.test.client import RequestFactory
from rest_framework.compat import patterns, url
from rest_framework.reverse import reverse

factory = RequestFactory()


def null_view(request):
    pass


urlpatterns = patterns("", url(r"^view$", null_view, name="view"))


class ReverseTests(TestCase):
    """
    Tests for fully qualified URLs when using `reverse`.
    """

    urls = "rest_framework.tests.reverse"

    def test_reversed_urls_are_fully_qualified(self):
        request = factory.get("/view")
        url = reverse("view", request=request)
        self.assertEqual(url, "http://testserver/view")
Esempio n. 39
0
class MockView(APIView):
    permission_classes = (permissions.IsAuthenticated, )

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

    def put(self, request):
        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'),
)


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

    def setUp(self):
        self.csrf_client = Client(enforce_csrf_checks=True)
        self.username = '******'
        self.email = '*****@*****.**'
        self.password = '******'
# The following patch overrides the URL patterns for the MockView class used in
# rest_framework.tests.test_authentication so that the corresponding AllowInactiveUser
# classes are tested instead.
@skipUnless(settings.FEATURES.get('ENABLE_OAUTH2_PROVIDER'), 'OAuth2 not enabled')
@patch.object(
    test_authentication,
    'urlpatterns',
    patterns(
        '',
        url(
            r'^oauth2-test/$',
            test_authentication.MockView.as_view(authentication_classes=[OAuth2AuthenticationAllowInactiveUser])
        ),
        url(
            r'^oauth2-test-debug/$',
            test_authentication.MockView.as_view(authentication_classes=[OAuth2AuthAllowInactiveUserDebug])
        ),
        url(
            r'^oauth2-with-scope-test/$',
            test_authentication.MockView.as_view(
                authentication_classes=[OAuth2AuthenticationAllowInactiveUser],
                permission_classes=[permissions.TokenHasReadWriteScope]
            )
        )
    )
)
class OAuth2AuthenticationAllowInactiveUserTestCase(test_authentication.OAuth2Tests):
    """
    Tests the OAuth2AuthenticationAllowInactiveUser class by running all the existing tests in
    OAuth2Tests but with the is_active flag on the user set to False.
    """
    def setUp(self):
from django.test import TestCase
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.compat import patterns
from rest_framework.test import APIClient

from rest_framework_jwt import utils

urlpatterns = patterns(
    '',
    (r'^auth-token/$', 'rest_framework_jwt.views.obtain_jwt_token'),
)


class ObtainJSONWebTokenTests(TestCase):
    urls = 'rest_framework_jwt.tests.test_views'

    def setUp(self):
        self.email = '*****@*****.**'
        self.username = '******'
        self.password = '******'
        self.user = User.objects.create_user(self.username, self.email,
                                             self.password)

        self.data = {'username': self.username, 'password': self.password}

    def test_jwt_login_json(self):
        """
        Ensure JWT login view using JSON POST works.
        """
        client = APIClient(enforce_csrf_checks=True)
Esempio n. 42
0
from rest_framework.compat import patterns, url
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.test import APIClient, APIRequestFactory, force_authenticate


@api_view(['GET', 'POST'])
def view(request):
    return Response({
        'auth': request.META.get('HTTP_AUTHORIZATION', b''),
        'user': request.user.username
    })


urlpatterns = patterns(
    '',
    url(r'^view/$', view),
)


class TestAPITestClient(TestCase):
    urls = 'rest_framework.tests.test_testing'

    def setUp(self):
        self.client = APIClient()

    def test_credentials(self):
        """
        Setting `.credentials()` adds the required headers to each request.
        """
        self.client.credentials(HTTP_AUTHORIZATION='example')
        for _ in range(0, 3):
    #     request = factory.post('/', form_data, parsers=parsers)
    #     self.assertEqual(request.POST.items(), form_data.items())
    #     self.assertEqual(request.DATA.items(), data.items())


class MockView(APIView):
    authentication_classes = (SessionAuthentication,)

    def post(self, request):
        if request.POST.get('app_scaffolding') is not None:
            return Response(status=status.HTTP_200_OK)

        return Response(status=status.INTERNAL_SERVER_ERROR)

urlpatterns = patterns('',
    (r'^$', MockView.as_view()),
)


class TestContentParsingWithAuthentication(TestCase):
    urls = 'rest_framework.tests.test_request'

    def setUp(self):
        self.csrf_client = APIClient(enforce_csrf_checks=True)
        self.username = '******'
        self.email = '*****@*****.**'
        self.password = '******'
        self.user = User.objects.create_user(self.username, self.email, self.password)

    def test_user_logged_in_authentication_has_POST_when_not_logged_in(self):
        """
class AlbumDetail(generics.RetrieveAPIView):
    model = Album


class OptionalRelationDetail(generics.RetrieveUpdateDestroyAPIView):
    model = OptionalRelationModel
    model_serializer_class = serializers.HyperlinkedModelSerializer


urlpatterns = patterns(
    "",
    url(r"^basic/$", BasicList.as_view(), name="basicmodel-list"),
    url(r"^basic/(?P<pk>\d+)/$", BasicDetail.as_view(), name="basicmodel-detail"),
    url(r"^anchor/(?P<pk>\d+)/$", AnchorDetail.as_view(), name="anchor-detail"),
    url(r"^manytomany/$", ManyToManyList.as_view(), name="manytomanymodel-list"),
    url(r"^manytomany/(?P<pk>\d+)/$", ManyToManyDetail.as_view(), name="manytomanymodel-detail"),
    url(r"^posts/(?P<pk>\d+)/$", BlogPostDetail.as_view(), name="blogpost-detail"),
    url(r"^comments/$", BlogPostCommentListCreate.as_view(), name="blogpostcomment-list"),
    url(r"^comments/(?P<pk>\d+)/$", BlogPostCommentDetail.as_view(), name="blogpostcomment-detail"),
    url(r"^albums/(?P<title>\w[\w-]*)/$", AlbumDetail.as_view(), name="album-detail"),
    url(r"^photos/$", PhotoListCreate.as_view(), name="photo-list"),
    url(r"^optionalrelation/(?P<pk>\d+)/$", OptionalRelationDetail.as_view(), name="optionalrelationmodel-detail"),
)


class TestBasicHyperlinkedView(TestCase):
    urls = "rest_framework.tests.hyperlinkedserializers"

    def setUp(self):
        """
        Create 3 BasicModel instances.
        """
Esempio n. 45
0
class HTMLNewModelView(generics.ListCreateAPIView):
    renderer_classes = (BrowsableAPIRenderer,)
    permission_classes = []
    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):
import base64
import json

from django.test import TestCase
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.compat import patterns
from rest_framework.test import APIClient

from rest_framework_jwt import utils


urlpatterns = patterns(
    '',
    (r'^auth-token/$', 'rest_framework_jwt.views.obtain_jwt_token'),
)


class ObtainJSONWebTokenTests(TestCase):
    urls = 'rest_framework_jwt.tests.test_views'

    def setUp(self):
        self.csrf_client = APIClient(enforce_csrf_checks=True)
        self.email = '*****@*****.**'
        self.username = '******'
        self.password = '******'
        self.user = User.objects.create_user(
            self.username, self.email, self.password)

        self.data = {
            'username': self.username,
from django.db import models
from django.test import TestCase
from rest_framework import serializers
from rest_framework.compat import patterns, url


def dummy_view(request, pk):
    pass

urlpatterns = patterns('',
    url(r'^manytomanysource/(?P<pk>[0-9]+)/$', dummy_view, name='manytomanysource-detail'),
    url(r'^manytomanytarget/(?P<pk>[0-9]+)/$', dummy_view, name='manytomanytarget-detail'),
    url(r'^foreignkeysource/(?P<pk>[0-9]+)/$', dummy_view, name='foreignkeysource-detail'),
    url(r'^foreignkeytarget/(?P<pk>[0-9]+)/$', dummy_view, name='foreignkeytarget-detail'),
    url(r'^nullableforeignkeysource/(?P<pk>[0-9]+)/$', dummy_view, name='nullableforeignkeysource-detail'),
)


# ManyToMany

class ManyToManyTarget(models.Model):
    name = models.CharField(max_length=100)


class ManyToManySource(models.Model):
    name = models.CharField(max_length=100)
    targets = models.ManyToManyField(ManyToManyTarget, related_name='sources')


class ManyToManyTargetSerializer(serializers.HyperlinkedModelSerializer):
    sources = serializers.ManyHyperlinkedRelatedField(view_name='manytomanysource-detail')
Esempio n. 48
0
class ResourceInstance(APIView):
    pass


class NestedResourceRoot(APIView):
    pass


class NestedResourceInstance(APIView):
    pass

urlpatterns = patterns('',
    url(r'^$', Root.as_view()),
    url(r'^resource/$', ResourceRoot.as_view()),
    url(r'^resource/(?P<key>[0-9]+)$', ResourceInstance.as_view()),
    url(r'^resource/(?P<key>[0-9]+)/$', NestedResourceRoot.as_view()),
    url(r'^resource/(?P<key>[0-9]+)/(?P<other>[A-Za-z]+)$', NestedResourceInstance.as_view()),
)


class BreadcrumbTests(TestCase):
    """Tests the breadcrumb functionality used by the HTML renderer."""

    urls = 'rest_framework.tests.breadcrumbs'

    def test_root_breadcrumbs(self):
        url = '/'
        self.assertEqual(get_breadcrumbs(url), [('Root', '/')])

    def test_resource_root_breadcrumbs(self):
Esempio n. 49
0
        queryset = FilterableItem.objects.all()
        serializer_class = FilterableItemSerializer
        filter_fields = ['decimal', 'date']
        filter_backends = (filters.DjangoFilterBackend,)

    class GetQuerysetView(generics.ListCreateAPIView):
        serializer_class = FilterableItemSerializer
        filter_class = SeveralFieldsFilter
        filter_backends = (filters.DjangoFilterBackend,)

        def get_queryset(self):
            return FilterableItem.objects.all()

    urlpatterns = patterns('',
        url(r'^(?P<pk>\d+)/$', FilterClassDetailView.as_view(), name='detail-view'),
        url(r'^$', FilterClassRootView.as_view(), name='root-view'),
        url(r'^get-queryset/$', GetQuerysetView.as_view(),
            name='get-queryset-view'),
    )


class CommonFilteringTestCase(TestCase):
    def _serialize_object(self, obj):
        return {'id': obj.id, 'text': obj.text, 'decimal': obj.decimal, 'date': obj.date}

    def setUp(self):
        """
        Create 10 FilterableItem instances.
        """
        base_data = ('a', Decimal('0.25'), datetime.date(2012, 10, 8))
        for i in range(10):
            text = chr(i + ord(base_data[0])) * 3  # Produces string 'aaa', 'bbb', etc.
    pass


urlpatterns = patterns(
    '',
    url(r'^dummyurl/(?P<pk>[0-9]+)/$', dummy_view, name='dummy-url'),
    url(r'^manytomanysource/(?P<pk>[0-9]+)/$',
        dummy_view,
        name='manytomanysource-detail'),
    url(r'^manytomanytarget/(?P<pk>[0-9]+)/$',
        dummy_view,
        name='manytomanytarget-detail'),
    url(r'^foreignkeysource/(?P<pk>[0-9]+)/$',
        dummy_view,
        name='foreignkeysource-detail'),
    url(r'^foreignkeytarget/(?P<pk>[0-9]+)/$',
        dummy_view,
        name='foreignkeytarget-detail'),
    url(r'^nullableforeignkeysource/(?P<pk>[0-9]+)/$',
        dummy_view,
        name='nullableforeignkeysource-detail'),
    url(r'^onetoonetarget/(?P<pk>[0-9]+)/$',
        dummy_view,
        name='onetoonetarget-detail'),
    url(r'^nullableonetoonesource/(?P<pk>[0-9]+)/$',
        dummy_view,
        name='nullableonetoonesource-detail'),
)


# ManyToMany
Esempio n. 51
0
    renderer_classes = (BrowsableAPIRenderer, )

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


class HTMLView1(APIView):
    renderer_classes = (BrowsableAPIRenderer, JSONRenderer)

    def get(self, request, **kwargs):
        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."""
Esempio n. 52
0
# -*- coding: utf-8 -*-
from rest_framework.compat import patterns, url

from .views import client_headers_bounce

urlpatterns = patterns(
    'django.contrib.auth.views',
    url(r'^client_headers_bounce/', client_headers_bounce),
)
from ...utils.tests import BaseTestCase
from ..models import User
from ..authentication import JWTAuthentication


class MockView(APIView):
    permission_classes = (permissions.IsAuthenticated, )
    authentication_classes = (JWTAuthentication, )

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


urlpatterns = patterns(
    '',
    (r'^jwt/$', MockView.as_view()),
)


class JSONWebTokenAuthenticationTests(BaseTestCase):
    urls = 'blimp_boards.users.tests.test_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_token_version_change_should_invalidate_token(self):
        """
        Tests that a token is invalidated if User.token_version changes.
Esempio n. 54
0
        class Meta:
            model = BasicModel
            fields = ['text']

    class IncorrectlyConfiguredRootView(generics.ListCreateAPIView):
        model = FilterableItem
        filter_class = MisconfiguredFilter
        filter_backend = filters.DjangoFilterBackend

    class FilterClassDetailView(generics.RetrieveAPIView):
        model = FilterableItem
        filter_class = SeveralFieldsFilter
        filter_backend = filters.DjangoFilterBackend

    urlpatterns = patterns('',
        url(r'^(?P<pk>\d+)/$', FilterClassDetailView.as_view(), name='detail-view'),
        url(r'^$', FilterClassRootView.as_view(), name='root-view'),
    )


class CommonFilteringTestCase(TestCase):
    def _serialize_object(self, obj):
        return {'id': obj.id, 'text': obj.text, 'decimal': obj.decimal, 'date': obj.date}
    
    def setUp(self):
        """
        Create 10 FilterableItem instances.
        """
        base_data = ('a', Decimal('0.25'), datetime.date(2012, 10, 8))
        for i in range(10):
            text = chr(i + ord(base_data[0])) * 3  # Produces string 'aaa', 'bbb', etc.
            decimal = base_data[1] + i
Esempio n. 55
0
        'auth': request.META.get('HTTP_AUTHORIZATION', b''),
        'user': request.user.username
    })


@api_view(['GET', 'POST'])
def session_view(request):
    active_session = request.session.get('active_session', False)
    request.session['active_session'] = True
    return Response({
        'active_session': active_session
    })


urlpatterns = patterns('',
    url(r'^view/$', view),
    url(r'^session-view/$', session_view),
)


class TestAPITestClient(TestCase):
    urls = 'rest_framework.tests.test_testing'

    def setUp(self):
        self.client = APIClient()

    def test_credentials(self):
        """
        Setting `.credentials()` adds the required headers to each request.
        """
        self.client.credentials(HTTP_AUTHORIZATION='example')
        for _ in range(0, 3):
from __future__ import unicode_literals
from django.test import TestCase
from rest_framework.compat import patterns, url
from rest_framework.reverse import reverse
from rest_framework.test import APIRequestFactory

factory = APIRequestFactory()


def null_view(request):
    pass

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


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')