From cae3234dbe32031650ade4a6480ec8fcff55cecc Mon Sep 17 00:00:00 2001 From: Kevin Brown Date: Wed, 6 Mar 2019 08:04:54 -0500 Subject: [PATCH] Added test for schemas for many-to-many fields This adds a test that makes sure we generate the schema for a many-to-many field such that it actually has the right type. For some reason we did not previously have any tests for schema generation that included them, so hopefully this will prevent any future issues from popping up. This should serve as a regression test for the `items` field on to-many relationships, which was previously forced to a `String` even though in most cases it is a different inner type within the array. --- tests/test_schemas.py | 47 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/tests/test_schemas.py b/tests/test_schemas.py index d3bd43073..3cb9e0cda 100644 --- a/tests/test_schemas.py +++ b/tests/test_schemas.py @@ -24,7 +24,7 @@ from rest_framework.utils import formatting from rest_framework.views import APIView from rest_framework.viewsets import GenericViewSet, ModelViewSet -from .models import BasicModel, ForeignKeySource +from .models import BasicModel, ForeignKeySource, ManyToManySource factory = APIRequestFactory() @@ -701,6 +701,51 @@ class TestSchemaGeneratorWithForeignKey(TestCase): assert schema == expected +class ManyToManySourceSerializer(serializers.ModelSerializer): + class Meta: + model = ManyToManySource + fields = ('id', 'name', 'targets') + + +class ManyToManySourceView(generics.CreateAPIView): + queryset = ManyToManySource.objects.all() + serializer_class = ManyToManySourceSerializer + + +@unittest.skipUnless(coreapi, 'coreapi is not installed') +class TestSchemaGeneratorWithManyToMany(TestCase): + def setUp(self): + self.patterns = [ + url(r'^example/?$', ManyToManySourceView.as_view()), + ] + + def test_schema_for_regular_views(self): + """ + Ensure that AutoField many to many fields 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('targets', required=True, location='form', schema=coreschema.Array(title='Targets', items=coreschema.Integer())), + ] + ) + } + } + ) + assert schema == expected + + @unittest.skipUnless(coreapi, 'coreapi is not installed') class Test4605Regression(TestCase): def test_4605_regression(self):