def test_from_router(self):
        patterns = [
            url(r'from-router', include(naming_collisions_router.urls)),
        ]

        generator = SchemaGenerator(title='Naming Colisions', patterns=patterns)
        schema = generator.get_schema()
        desc = schema['detail_0'].description  # not important here

        expected = coreapi.Document(
            url='',
            title='Naming Colisions',
            content={
                'detail': {
                    'detail_export': coreapi.Link(
                        url='/from-routercollision/detail/export/',
                        action='get',
                        description=desc)
                },
                'detail_0': coreapi.Link(
                    url='/from-routercollision/detail/',
                    action='get',
                    description=desc
                )
            }
        )

        assert schema == expected
Exemplo n.º 2
0
 def get(self, request):
     # Define also the URL prefix for the current API version. Not very nice,
     # but did not find another way.
     generator = SchemaGenerator(
         title='QCAT API v2', url='/api/v2/', urlconf='api.urls.v2')
     schema = generator.get_schema(request=request, public=True)
     return Response(schema)
Exemplo n.º 3
0
 def test_4605_regression(self):
     generator = SchemaGenerator()
     prefix = generator.determine_path_prefix([
         '/api/v1/items/',
         '/auth/convert-token/'
     ])
     assert prefix == '/'
    def test_schema_for_regular_views(self):
        """
        Ensure that AutoField foreign keys are output as Integer.
        """
        generator = SchemaGenerator(title='Example API', patterns=self.patterns)
        schema = generator.get_schema()

        expected = coreapi.Document(
            url='',
            title='Example API',
            content={
                'example': {
                    'create': coreapi.Link(
                        url='/example/',
                        action='post',
                        encoding='application/json',
                        fields=[
                            coreapi.Field('name', required=True, location='form', schema=coreschema.String(title='Name')),
                            coreapi.Field('target', required=True, location='form', schema=coreschema.Integer(description='Target', title='Target')),
                        ]
                    )
                }
            }
        )
        assert schema == expected
Exemplo n.º 5
0
def schema_view(request):
    """
    Swagger test API
    """
    generator = SchemaGenerator(title='Rest Swagger')
    schema = generator.get_schema(request=request)

    return Response(schema)
Exemplo n.º 6
0
    def get(self, request):
        from burl.core.urls import api_v1
        api_url_patterns = [path('api/v1/', include(api_v1))]
        generator = SchemaGenerator(title='burl api',
                                    patterns=api_url_patterns)
        schema = generator.get_schema(request=request)

        return Response(schema)
Exemplo n.º 7
0
    def get(self, request):
        generator = SchemaGenerator(title='Geotrek API v2',
                                    urlconf='geotrek.api.v2.urls',
                                    url='/api/v2',
                                    description="New Geotrek API.")
        schema = generator.get_schema(request=request)

        return response.Response(schema)
Exemplo n.º 8
0
 def get(self, request):
     # Define also the URL prefix for the current API version. Not very nice,
     # but did not find another way.
     generator = SchemaGenerator(title='QCAT API v2',
                                 url='/api/v2/',
                                 urlconf='api.urls.v2')
     schema = generator.get_schema(request=request, public=True)
     return Response(schema)
Exemplo n.º 9
0
 def get(self, request):
     """."""
     generator = SchemaGenerator()
     schema = generator.get_schema(request=request)
     if not schema:
         raise exceptions.ValidationError(
             'The schema generator did not return a schema Document')
     return Response(schema)
Exemplo n.º 10
0
def get_context(request):
    generator = SchemaGenerator(title='ArenaData Cluster Manager API',
                                description=intro())
    data = generator.get_schema(request, True)
    context = {
        'document': data,
        'request': request,
    }
    return context
    def test_from_router(self):
        patterns = [
            url(r'from-router', include(naming_collisions_router.urls)),
        ]

        generator = SchemaGenerator(title='Naming Colisions', patterns=patterns)

        with pytest.raises(ValueError):
            generator.get_schema()
    def test_manually_routing_nested_routes(self):
        patterns = [
            url(r'^test', simple_fbv),
            url(r'^test/list/', simple_fbv),
        ]

        generator = SchemaGenerator(title='Naming Colisions', patterns=patterns)

        with pytest.raises(ValueError):
            generator.get_schema()
Exemplo n.º 13
0
        def get(self, request):
            generator = SchemaGenerator(title=title, url=url)
            schema = generator.get_schema(request=request)

            if not schema:
                raise exceptions.ValidationError(
                    'The schema generator did not return a schema Document'
                )

            return Response(schema)
Exemplo n.º 14
0
    def test_url_under_same_key_not_replaced(self):
        patterns = [
            url(r'example/(?P<pk>\d+)/$', BasicNamingCollisionView.as_view()),
            url(r'example/(?P<slug>\w+)/$', BasicNamingCollisionView.as_view()),
        ]

        generator = SchemaGenerator(title='Naming Colisions', patterns=patterns)
        schema = generator.get_schema()

        assert schema['example']['read'].url == '/example/{id}/'
        assert schema['example']['read_0'].url == '/example/{slug}/'
Exemplo n.º 15
0
    def get(self, request):
        generator = SchemaGenerator(title='Base API')
        try:
            user = User.objects.get(username='******')
        except User.DoesNotExist:
            user = User.objects.create(username='******')
        request.user = user
        request.auth = (user, None)
        schema = generator.get_schema(request)

        return Response(schema)
Exemplo n.º 16
0
    def test_url_under_same_key_not_replaced(self):
        patterns = [
            url(r'example/(?P<pk>\d+)/$', BasicNamingCollisionView.as_view()),
            url(r'example/(?P<slug>\w+)/$', BasicNamingCollisionView.as_view()),
        ]

        generator = SchemaGenerator(title='Naming Colisions', patterns=patterns)
        schema = generator.get_schema()

        assert schema['example']['read'].url == '/example/{id}/'
        assert schema['example']['read_0'].url == '/example/{slug}/'
    def test_viewset_action_with_null_schema(self):
        class CustomViewSet(GenericViewSet):
            @action(detail=True, schema=None)
            def extra_action(self, pk, **kwargs):
                pass

        router = SimpleRouter()
        router.register(r'detail', CustomViewSet, basename='detail')

        generator = SchemaGenerator()
        view = generator.create_view(router.urls[0].callback, 'GET')
        assert view.schema is None
Exemplo n.º 18
0
    def test_url_under_same_key_not_replaced_another(self):

        patterns = [
            url(r'^test/list/', simple_fbv),
            url(r'^test/(?P<pk>\d+)/list/', simple_fbv),
        ]

        generator = SchemaGenerator(title='Naming Colisions', patterns=patterns)
        schema = generator.get_schema()

        assert schema['test']['list']['list'].url == '/test/list/'
        assert schema['test']['list']['list_0'].url == '/test/{id}/list/'
    def test_schema_for_regular_views(self):
        """
        Ensure that schema generation works for ViewSet classes
        with method limitation by Django CBV's http_method_names attribute
        """
        generator = SchemaGenerator(title='Example API', patterns=self.patterns)
        request = factory.get('/example1/')
        schema = generator.get_schema(Request(request))

        expected = coreapi.Document(
            url='http://testserver/example1/',
            title='Example API',
            content={
                'example1': {
                    'list': coreapi.Link(
                        url='/example1/',
                        action='get',
                        fields=[
                            coreapi.Field('page', required=False, location='query', schema=coreschema.Integer(title='Page', description='A page number within the paginated result set.')),
                            coreapi.Field('page_size', required=False, location='query', schema=coreschema.Integer(title='Page size', description='Number of results to return per page.')),
                            coreapi.Field('ordering', required=False, location='query', schema=coreschema.String(title='Ordering', description='Which field to use when ordering the results.'))
                        ]
                    ),
                    'custom_list_action': coreapi.Link(
                        url='/example1/custom_list_action/',
                        action='get'
                    ),
                    'custom_list_action_multiple_methods': {
                        'read': coreapi.Link(
                            url='/example1/custom_list_action_multiple_methods/',
                            action='get',
                            description='Custom description.',
                        )
                    },
                    'documented_custom_action': {
                        'read': coreapi.Link(
                            url='/example1/documented_custom_action/',
                            action='get',
                            description='A description of the get method on the custom action.',
                        ),
                    },
                    'read': coreapi.Link(
                        url='/example1/{id}/',
                        action='get',
                        fields=[
                            coreapi.Field('id', required=True, location='path', schema=coreschema.String()),
                            coreapi.Field('ordering', required=False, location='query', schema=coreschema.String(title='Ordering', description='Which field to use when ordering the results.'))
                        ]
                    )
                }
            }
        )
        assert schema == expected
Exemplo n.º 20
0
        def get(self, request):
            generator = SchemaGenerator(title=title,
                                        url=url,
                                        patterns=patterns,
                                        urlconf=urlconf)
            schema = generator.get_schema(request=request, public=True)

            if not schema:
                raise exceptions.ValidationError(
                    "The schema generator did not return a schema Document")

            return Response(schema)
Exemplo n.º 21
0
        def get(self, request):
            # bubble modify (SchemaGenerator->CustomerSchemaGenerator)
            generator = SchemaGenerator(title=title, url=url)
            # bubble modify end
            schema = generator.get_schema(request=request)

            if not schema:
                raise exceptions.ValidationError(
                    'The schema generator did not return a schema Document'
                )

            return Response(schema)
Exemplo n.º 22
0
    def get(self, request):
        generator = SchemaGenerator(title='Discovery API')
        schema = generator.get_schema(request=request)

        if not schema:
            # get_schema() uses the same permissions check as the API endpoints.
            # If we don't get a schema document back, it means the user is not
            # authenticated or doesn't have permission to access the API.
            # api_docs_permission_denied_handler() handles both of these cases.
            return api_docs_permission_denied_handler(request)

        return Response(schema)
Exemplo n.º 23
0
    def test_schema_for_regular_views(self):
        """
        Ensure that schema generation works for ViewSet classes
        with method limitation by Django CBV's http_method_names attribute
        """
        generator = SchemaGenerator(title='Example API', patterns=self.patterns)
        request = factory.get('/example1/')
        schema = generator.get_schema(Request(request))

        expected = coreapi.Document(
            url='http://testserver/example1/',
            title='Example API',
            content={
                'example1': {
                    'list': coreapi.Link(
                        url='/example1/',
                        action='get',
                        fields=[
                            coreapi.Field('page', required=False, location='query', schema=coreschema.Integer(title='Page', description='A page number within the paginated result set.')),
                            coreapi.Field('page_size', required=False, location='query', schema=coreschema.Integer(title='Page size', description='Number of results to return per page.')),
                            coreapi.Field('ordering', required=False, location='query', schema=coreschema.String(title='Ordering', description='Which field to use when ordering the results.'))
                        ]
                    ),
                    'custom_list_action': coreapi.Link(
                        url='/example1/custom_list_action/',
                        action='get'
                    ),
                    'custom_list_action_multiple_methods': {
                        'read': coreapi.Link(
                            url='/example1/custom_list_action_multiple_methods/',
                            action='get',
                            description='Custom description.',
                        )
                    },
                    'documented_custom_action': {
                        'read': coreapi.Link(
                            url='/example1/documented_custom_action/',
                            action='get',
                            description='A description of the get method on the custom action.',
                        ),
                    },
                    'read': coreapi.Link(
                        url='/example1/{id}/',
                        action='get',
                        fields=[
                            coreapi.Field('id', required=True, location='path', schema=coreschema.String()),
                            coreapi.Field('ordering', required=False, location='query', schema=coreschema.String(title='Ordering', description='Which field to use when ordering the results.'))
                        ]
                    )
                }
            }
        )
        assert schema == expected
Exemplo n.º 24
0
    def test_viewset_action_with_null_schema(self):
        class CustomViewSet(GenericViewSet):
            @action(detail=True, schema=None)
            def extra_action(self, pk, **kwargs):
                pass

        router = SimpleRouter()
        router.register(r'detail', CustomViewSet, basename='detail')

        generator = SchemaGenerator()
        view = generator.create_view(router.urls[0].callback, 'GET')
        assert view.schema is None
Exemplo n.º 25
0
    def test_url_under_same_key_not_replaced_another(self):

        patterns = [
            url(r'^test/list/', simple_fbv),
            url(r'^test/(?P<pk>\d+)/list/', simple_fbv),
        ]

        generator = SchemaGenerator(title='Naming Colisions', patterns=patterns)
        schema = generator.get_schema()

        assert schema['test']['list']['list'].url == '/test/list/'
        assert schema['test']['list']['list_0'].url == '/test/{id}/list/'
Exemplo n.º 26
0
 def get(self, request):
     params = {"urlconf": "api_v2.urls"}
     if "HTTP_X_FORWARDED_HOST" in request.META:
         # forwarding via tob-web
         # params["url"] = "{}://{}/api".format(
         #    request.META.get("HTTP_X_FORWARDED_PROTO", "http"),
         #    request.META["HTTP_X_FORWARDED_HOST"])
         params["url"] = "/api"
     else:
         params["url"] = "/api/v2"
     generator = SchemaGenerator(**params)
     schema = generator.get_schema(request=request)
     return Response(schema)
Exemplo n.º 27
0
        def get(self, request):
            generator = SchemaGenerator(title=title,
                                        url=url,
                                        patterns=patterns,
                                        urlconf=urlconf)
            schema = generator.get_schema(request=request)

            if settings.SWAGGER_HTTPS:
                schema._url = schema._url.replace('http', 'https')

            if not schema:
                raise exceptions.ValidationError(
                    'The schema generator did not return a schema Document')

            return Response(schema)
Exemplo n.º 28
0
        def get(self, request):
            generator = SchemaGenerator(title=title,
                                        url=url,
                                        patterns=patterns,
                                        urlconf=urlconf)

            # Showing all the endpoints, no mather the user permissions
            # schema = generator.get_schema(request=request)
            schema = generator.get_schema()

            if not schema:
                raise exceptions.ValidationError(
                    'The schema generator did not return a schema Document')

            return Response(schema)
    def test_manually_routing_generic_view(self):
        patterns = [
            url(r'^test', NamingCollisionView.as_view()),
            url(r'^test/retrieve/', NamingCollisionView.as_view()),
            url(r'^test/update/', NamingCollisionView.as_view()),

            # Fails with method names:
            url(r'^test/get/', NamingCollisionView.as_view()),
            url(r'^test/put/', NamingCollisionView.as_view()),
            url(r'^test/delete/', NamingCollisionView.as_view()),
        ]

        generator = SchemaGenerator(title='Naming Colisions', patterns=patterns)

        with pytest.raises(ValueError):
            generator.get_schema()
Exemplo n.º 30
0
def get_schema(use_cache=True):
    global _schema_cache
    if use_cache and _schema_cache:
        return _schema_cache
    generator = SchemaGenerator()
    enumerator = generator.endpoint_inspector_cls()
    end_points = enumerator.get_api_endpoints()
    schema = {}
    for url, http_method_name, view_func in end_points:
        generated_view = generator.create_view(view_func, http_method_name,
                                               None)
        coerced_url = generator.coerce_path(url, http_method_name,
                                            generated_view)
        try:
            feature = getattr(view_func.cls,
                              REGISTRY_ATTR_NAME)[http_method_name.lower()]
        except AttributeError:
            if settings.feature_settings.RAISE_FOR_MISSING_VIEW:
                raise ImproperlyConfigured(
                    '%s view has no schema configuration' % (view_func, ))
            else:
                continue
        except KeyError:
            raise ImproperlyConfigured(
                '%s view is missing %s schema configuration' %
                (view_func, http_method_name))

        description, http_method_name, view_class = feature
        *groups, feature_name = description
        if feature_name in schema:
            raise ImproperlyConfigured(
                'Duplicate feature names are not allowed. %s is already registered with %s'
                % (feature_name, schema[feature_name]['view_class']))
        verbose_name = _humanize_pattern.sub(r'\1 \2', feature_name).lower()
        feature_def = dict(
            name=feature_name,
            url=url,
            coerced_url=coerced_url,
            http_method_name=http_method_name,
            view_class=view_class,
            groups=groups,
            description=description,
            verbose_name=verbose_name,
        )
        schema[feature_name] = feature_def
    _schema_cache = schema
    return schema
Exemplo n.º 31
0
    def test_schema_generator_excludes_correctly(self):
        """Schema should not include excluded views"""
        generator = SchemaGenerator(title='Exclusions', patterns=self.patterns)
        schema = generator.get_schema()
        expected = coreapi.Document(
            url='',
            title='Exclusions',
            content={
                'included-fbv': {
                    'list': coreapi.Link(url='/included-fbv/', action='get')
                }
            }
        )

        assert len(schema.data) == 1
        assert 'included-fbv' in schema.data
        assert schema == expected
Exemplo n.º 32
0
    def __init__(self,
                 info,
                 version='',
                 url=None,
                 patterns=None,
                 urlconf=None,
                 swagger_settings=_swagger_settings):
        """

        :param openapi.Info info: information about the API
        :param str version: API version string; if omitted, `info.default_version` will be used
        :param str url: API scheme, host and port; if ``None`` is passed and ``DEFAULT_API_URL`` is not set, the url
            will be inferred from the request made against the schema view, so you should generally not need to set
            this parameter explicitly; if the empty string is passed, no host and scheme will be emitted

            If `url` is not ``None`` or the empty string, it must be a scheme-absolute uri (i.e. starting with http://
            or https://), and any path component is ignored;

            See also: :ref:`documentation on base URL construction <custom-spec-base-url>`
        :param patterns: if given, only these patterns will be enumerated for inclusion in the API spec
        :param urlconf: if patterns is not given, use this urlconf to enumerate patterns;
            if not given, the default urlconf is used
        :param swagger_settings: if given global swagger_settings are overridden with local settings
        """
        self._gen = SchemaGenerator(info.title, url,
                                    info.get('description',
                                             ''), patterns, urlconf)
        self.info = info
        self.swagger_settings = swagger_settings
        self.version = version
        self.consumes = []
        self.produces = []

        if url is None and swagger_settings.DEFAULT_API_URL is not None:
            url = swagger_settings.DEFAULT_API_URL

        if url:
            parsed_url = urlparse.urlparse(url)
            if parsed_url.scheme not in ('http',
                                         'https') or not parsed_url.netloc:
                raise SwaggerGenerationError(
                    "`url` must be an absolute HTTP(S) url")
            if parsed_url.path:
                logger.warning(
                    "path component of api base URL %s is ignored; use FORCE_SCRIPT_NAME instead"
                    % url)
Exemplo n.º 33
0
    def test_schema_generator_excludes_correctly(self):
        """Schema should not include excluded views"""
        generator = SchemaGenerator(title='Exclusions', patterns=self.patterns)
        schema = generator.get_schema()
        expected = coreapi.Document(url='',
                                    title='Exclusions',
                                    content={
                                        'included-fbv': {
                                            'list':
                                            coreapi.Link(url='/included-fbv/',
                                                         action='get')
                                        }
                                    })

        assert len(schema.data) == 1
        assert 'included-fbv' in schema.data
        assert schema == expected
Exemplo n.º 34
0
        def get(self, request):
            """

            Args:
              request:

            Returns:

            """
            generator = SchemaGenerator(title=title, url=url)
            schema = generator.get_schema(request=request)

            if not schema:
                raise exceptions.ValidationError(
                    'The schema generator did not return a schema Document')

            return Response(schema)
Exemplo n.º 35
0
 def test_schema_for_regular_views(self):
     """
     Ensure that schema generation with an API that is not at the URL
     root continues to use correct structure for link keys.
     """
     generator = SchemaGenerator(title='Example API',
                                 patterns=self.patterns)
     schema = generator.get_schema()
     expected = coreapi.Document(
         url='',
         title='Example API',
         content={
             'example': {
                 'create':
                 coreapi.Link(url='/api/v1/example/',
                              action='post',
                              fields=[]),
                 'list':
                 coreapi.Link(url='/api/v1/example/',
                              action='get',
                              fields=[]),
                 'read':
                 coreapi.Link(url='/api/v1/example/{id}/',
                              action='get',
                              fields=[
                                  coreapi.Field('id',
                                                required=True,
                                                location='path',
                                                schema=coreschema.String())
                              ]),
                 'sub': {
                     'list':
                     coreapi.Link(url='/api/v1/example/{id}/sub/',
                                  action='get',
                                  fields=[
                                      coreapi.Field(
                                          'id',
                                          required=True,
                                          location='path',
                                          schema=coreschema.String())
                                  ])
                 }
             }
         })
     assert schema == expected
Exemplo n.º 36
0
    def get_api_root_view(self, api_urls=None):
        """
        Return a view to use as the API root.
        """
        api_root_dict = OrderedDict()
        list_name = self.routes[0].name
        for prefix, viewset, basename in self.registry:
            api_root_dict[prefix] = list_name.format(basename=basename)

        view_renderers = list(self.root_renderers)
        schema_media_types = []

        if api_urls and self.schema_title:
            view_renderers += list(self.schema_renderers)
            schema_generator = SchemaGenerator(
                title=self.schema_title,
                url=self.schema_url,
                patterns=api_urls
            )
            schema_media_types = [
                renderer.media_type
                for renderer in self.schema_renderers
            ]

        class APIRoot(views.APIView):
            _ignore_model_permissions = True
            renderer_classes = view_renderers

            def get(self, request, *args, **kwargs):
                if request.accepted_renderer.media_type in schema_media_types:
                    # Return a schema response.
                    schema = schema_generator.get_schema(request)
                    if schema is None:
                        raise exceptions.PermissionDenied()
                    return Response(schema)

                # Return a plain {"name": "hyperlink"} response.
                ret = OrderedDict()
                namespace = request.resolver_match.namespace
                for key, url_name in api_root_dict.items():
                    if namespace:
                        url_name = namespace + ':' + url_name
                    try:
                        ret[key] = reverse(
                            url_name,
                            args=args,
                            kwargs=kwargs,
                            request=request,
                            format=kwargs.get('format', None)
                        )
                    except NoReverseMatch:
                        # Don't bail out if eg. no list routes exist, only detail routes.
                        continue

                return Response(ret)

        return APIRoot.as_view()
Exemplo n.º 37
0
def get_schema_view(title=None, url=None, description=None, urlconf=None, renderer_classes=None, public=False):
    """Return a schema view.
    """
    generator = SchemaGenerator(title=title, url=url, description=description, urlconf=urlconf)
    return MySchemaView.as_view(
        renderer_classes=renderer_classes,
        schema_generator=generator,
        public=public,
    )
Exemplo n.º 38
0
    def get(self, request):
        generator = SchemaGenerator(
            title="Stargeo API",
        )
        schema = generator.get_schema(request=request)
        schema['analysis']['df']._fields = [
            coreapi.Field(name='specie', required=True),
            coreapi.Field(name='case_query', required=True),
            coreapi.Field(name='control_query', required=True),
            coreapi.Field(name='modifier_query', required=False),
        ]

        if not schema:
            raise exceptions.ValidationError(
                'The schema generator did not return a schema Document'
            )

        return Response(schema)
Exemplo n.º 39
0
    def test1_rest_docs(self):
        from drf_yasg.generators import OpenAPISchemaGenerator
        from rest_framework.schemas import SchemaGenerator
        from rest_framework import serializers
        from drf_yasg.errors import SwaggerGenerationError

        class TestSerializer(serializers.Serializer):
            email = serializers.EmailField()
            username = serializers.CharField(max_length=100)

        class UserSerializer1(serializers.ModelSerializer):
            class Meta:
                model = User

                exclude = ['role', 'session_key']

        class CommentSerializer(serializers.Serializer):
            user = TestSerializer()
            admin = UserSerializer1()
            content = serializers.CharField(max_length=200)
            created = serializers.DateTimeField()

        from drf_yasg import openapi
        from rest_framework.metadata import SimpleMetadata
        from drf_yasg.codecs import OpenAPICodecJson
        try:
            schema = OpenAPISchemaGenerator(
                openapi.Info(
                    title="Snippets API",
                    default_version='v1',
                    description="Test description",
                    terms_of_service="https://www.google.com/policies/terms/",
                    contact=openapi.Contact(email="*****@*****.**"),
                    license=openapi.License(name="BSD License"),
                )).get_schema()
            codec = OpenAPICodecJson(validators=[], pretty=True)
            swagger_json = codec.encode(schema).decode('utf-8')
            #print(swagger_json)
            b = SimpleMetadata().get_serializer_info(CommentSerializer())
            #  print(b)
            schema_generator = SchemaGenerator()
            schema = schema_generator.get_schema()
        except SwaggerGenerationError as e:
            pass
Exemplo n.º 40
0
    def get(self, request):
        generator = SchemaGenerator(
            title='CyBorgBackup API',
            patterns=None,
            urlconf=None
        )
        schema = generator.get_schema(request=request)
        # python core-api doesn't support the deprecation yet, so track it
        # ourselves and return it in a response header
        _deprecated = []

        # By default, DRF OpenAPI serialization places all endpoints in
        # a single node based on their root path (/api).  Instead, we want to
        # group them by topic/tag so that they're categorized in the rendered
        # output
        document = schema._data.pop('api')
        for path, node in document.items():
            if isinstance(node, Object):
                for action in node.values():
                    topic = getattr(action, 'topic', None)
                    if topic:
                        schema._data.setdefault(topic, Object())
                        schema._data[topic]._data[path] = node

                    if isinstance(action, Object):
                        for link in action.links.values():
                            if link.deprecated:
                                _deprecated.append(link.url)
            elif isinstance(node, Link):
                topic = getattr(node, 'topic', None)
                if topic:
                    schema._data.setdefault(topic, Object())
                    schema._data[topic]._data[path] = node

        if not schema:
            raise exceptions.ValidationError(
                'The schema generator did not return a schema Document'
            )

        return Response(
            schema,
            headers={'X-Deprecated-Paths': json.dumps(_deprecated)}
        )
Exemplo n.º 41
0
 def test_schema_for_regular_views(self):
     """
     Ensure that schema generation with an API that is not at the URL
     root continues to use correct structure for link keys.
     """
     generator = SchemaGenerator(title='Example API', patterns=self.patterns)
     schema = generator.get_schema()
     expected = coreapi.Document(
         url='',
         title='Example API',
         content={
             'example': {
                 'create': coreapi.Link(
                     url='/api/v1/example/',
                     action='post',
                     fields=[]
                 ),
                 'list': coreapi.Link(
                     url='/api/v1/example/',
                     action='get',
                     fields=[]
                 ),
                 'read': coreapi.Link(
                     url='/api/v1/example/{id}/',
                     action='get',
                     fields=[
                         coreapi.Field('id', required=True, location='path')
                     ]
                 ),
                 'sub': {
                     'list': coreapi.Link(
                         url='/api/v1/example/{id}/sub/',
                         action='get',
                         fields=[
                             coreapi.Field('id', required=True, location='path')
                         ]
                     )
                 }
             }
         }
     )
     assert schema == expected
Exemplo n.º 42
0
 def test_schema_for_regular_views(self):
     """
     Ensure that schema generation works for APIView classes.
     """
     generator = SchemaGenerator(title='Example API', patterns=self.patterns)
     schema = generator.get_schema()
     expected = coreapi.Document(
         url='',
         title='Example API',
         content={
             'example': {
                 'create': coreapi.Link(
                     url='/example/',
                     action='post',
                     fields=[]
                 ),
                 'list': coreapi.Link(
                     url='/example/',
                     action='get',
                     fields=[]
                 ),
                 'read': coreapi.Link(
                     url='/example/{id}/',
                     action='get',
                     fields=[
                         coreapi.Field('id', required=True, location='path')
                     ]
                 ),
                 'sub': {
                     'list': coreapi.Link(
                         url='/example/{id}/sub/',
                         action='get',
                         fields=[
                             coreapi.Field('id', required=True, location='path')
                         ]
                     )
                 }
             }
         }
     )
     assert schema == expected
Exemplo n.º 43
0
 def test_schema_for_regular_views(self):
     """
     Ensure that schema generation works for ViewSet classes
     with permission classes raising exceptions.
     """
     generator = SchemaGenerator(title='Example API', patterns=self.patterns)
     request = factory.get('/')
     schema = generator.get_schema(Request(request))
     expected = coreapi.Document(
         url='',
         title='Example API',
         content={
             'example': {
                 'list': coreapi.Link(
                     url='/example/',
                     action='get',
                     fields=[]
                 ),
             },
         }
     )
     assert schema == expected
 def test_view(self):
     schema_generator = SchemaGenerator(title='Test View', patterns=urlpatterns2)
     schema = schema_generator.get_schema()
     expected = coreapi.Document(
         url='',
         title='Test View',
         content={
             'example-view': {
                 'create': coreapi.Link(
                     url='/example-view/',
                     action='post',
                     fields=[]
                 ),
                 'read': coreapi.Link(
                     url='/example-view/',
                     action='get',
                     fields=[]
                 )
             }
         }
     )
     self.assertEquals(schema, expected)
Exemplo n.º 45
0
    def test_manually_routing_generic_view(self):
        patterns = [
            url(r'^test', NamingCollisionView.as_view()),
            url(r'^test/retrieve/', NamingCollisionView.as_view()),
            url(r'^test/update/', NamingCollisionView.as_view()),

            # Fails with method names:
            url(r'^test/get/', NamingCollisionView.as_view()),
            url(r'^test/put/', NamingCollisionView.as_view()),
            url(r'^test/delete/', NamingCollisionView.as_view()),
        ]

        generator = SchemaGenerator(title='Naming Colisions', patterns=patterns)

        schema = generator.get_schema()

        self._verify_cbv_links(schema['test']['delete'], '/test/delete/')
        self._verify_cbv_links(schema['test']['put'], '/test/put/')
        self._verify_cbv_links(schema['test']['get'], '/test/get/')
        self._verify_cbv_links(schema['test']['update'], '/test/update/')
        self._verify_cbv_links(schema['test']['retrieve'], '/test/retrieve/')
        self._verify_cbv_links(schema['test'], '/test', suffixes=(None, '0', None, '0'))
Exemplo n.º 46
0
    def test_manually_routing_nested_routes(self):
        patterns = [
            url(r'^test', simple_fbv),
            url(r'^test/list/', simple_fbv),
        ]

        generator = SchemaGenerator(title='Naming Colisions', patterns=patterns)
        schema = generator.get_schema()

        expected = coreapi.Document(
            url='',
            title='Naming Colisions',
            content={
                'test': {
                    'list': {
                        'list': coreapi.Link(url='/test/list/', action='get')
                    },
                    'list_0': coreapi.Link(url='/test', action='get')
                }
            }
        )

        assert expected == schema
    def test_viewset_action_with_schema(self):
        class CustomViewSet(GenericViewSet):
            @action(detail=True, schema=AutoSchema(manual_fields=[
                coreapi.Field(
                    "my_extra_field",
                    required=True,
                    location="path",
                    schema=coreschema.String()
                ),
            ]))
            def extra_action(self, pk, **kwargs):
                pass

        router = SimpleRouter()
        router.register(r'detail', CustomViewSet, basename='detail')

        generator = SchemaGenerator()
        view = generator.create_view(router.urls[0].callback, 'GET')
        link = view.schema.get_link('/a/url/{id}/', 'GET', '')
        fields = link.fields

        assert len(fields) == 2
        assert "my_extra_field" in [f.name for f in fields]
Exemplo n.º 48
0
def schema_view(request):
    generator = SchemaGenerator(title='Koldunov API')
    return Response(generator.get_schema())
Exemplo n.º 49
0
def schema_view(request):
    generator = SchemaGenerator()
    return Response(generator.get_schema(request=request))