From 81bac6fe51e0c2db2d324dc2e105911ad128c3a3 Mon Sep 17 00:00:00 2001 From: Carlton Gibson Date: Tue, 29 Aug 2017 11:45:24 +0200 Subject: [PATCH] Add `ManualSchema` class --- docs/api-guide/schemas.md | 15 +++++++++++++++ rest_framework/schemas.py | 12 ++++++++++++ tests/test_schemas.py | 17 ++++++++++++++++- 3 files changed, 43 insertions(+), 1 deletion(-) diff --git a/docs/api-guide/schemas.md b/docs/api-guide/schemas.md index 9c7423f83..d805d5f16 100644 --- a/docs/api-guide/schemas.md +++ b/docs/api-guide/schemas.md @@ -463,6 +463,21 @@ Return a list of `coreapi.Link()` instances, as returned by the `get_schema_fiel Return a list of `coreapi.Link()` instances, as returned by the `get_schema_fields()` method of any filter classes used by the view. + +## ManualSchema + +`APIViewSchemaDescriptor` subclass for specifying a manual schema. + + class MyView(APIView): + schema = ManualSchema(coreapi.Link( + url='/example/', + action='get', + fields=[] + )) + +The `ManualSchema` constructor takes a single parameter `link`, +the `coreapi.Link` instance for the view. + --- ## Core API diff --git a/rest_framework/schemas.py b/rest_framework/schemas.py index b49ed7f6a..93149f72b 100644 --- a/rest_framework/schemas.py +++ b/rest_framework/schemas.py @@ -500,6 +500,18 @@ class APIViewSchemaDescriptor(object): APIView.schema = APIViewSchemaDescriptor() +class ManualSchema(APIViewSchemaDescriptor): + """ + Overrides get_link to return manually specified schema. + """ + def __init__(self, link): + assert isinstance(link, coreapi.Link) + self._link = link + + def get_link(self, *args): + return self._link + + class SchemaGenerator(object): # Map HTTP methods onto actions. default_mapping = { diff --git a/tests/test_schemas.py b/tests/test_schemas.py index 84ea2e855..eeece024e 100644 --- a/tests/test_schemas.py +++ b/tests/test_schemas.py @@ -12,7 +12,7 @@ from rest_framework.decorators import detail_route, list_route from rest_framework.request import Request from rest_framework.routers import DefaultRouter from rest_framework.schemas import ( - APIViewSchemaDescriptor, SchemaGenerator, get_schema_view + APIViewSchemaDescriptor, ManualSchema, SchemaGenerator, get_schema_view ) from rest_framework.test import APIClient, APIRequestFactory from rest_framework.views import APIView @@ -512,3 +512,18 @@ class TestDescriptor(TestCase): descriptor = APIView.schema # Accessed from class with pytest.raises(AssertionError): descriptor.get_link(None, None, None) # ???: Do the dummy arguments require a tighter assert? + + def test_view_with_manual_schema(self): + + expected = coreapi.Link( + url='/example/', + action='get', + fields=[] + ) + + class CustomView(APIView): + schema = ManualSchema(expected) + + view = CustomView() + link = view.schema.get_link() + assert link == expected