Allow context to be provided to get_serializer (#7298)

* Test generics serializer behavior

* Allow context to be provided to get_serializer
This commit is contained in:
Ryan P Kilby 2020-04-29 03:19:44 -07:00 committed by GitHub
parent 05a59095ce
commit e275b9036a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 31 additions and 1 deletions

View File

@ -106,7 +106,7 @@ class GenericAPIView(views.APIView):
deserializing input, and for serializing output.
"""
serializer_class = self.get_serializer_class()
kwargs['context'] = self.get_serializer_context()
kwargs.setdefault('context', self.get_serializer_context())
return serializer_class(*args, **kwargs)
def get_serializer_class(self):

View File

@ -662,3 +662,33 @@ class GetObjectOr404Tests(TestCase):
def test_get_object_or_404_with_invalid_string_for_uuid(self):
with pytest.raises(Http404):
generics.get_object_or_404(UUIDForeignKeyTarget, pk='not-a-uuid')
class TestSerializer(TestCase):
def test_serializer_class_not_provided(self):
class NoSerializerClass(generics.GenericAPIView):
pass
with pytest.raises(AssertionError) as excinfo:
NoSerializerClass().get_serializer_class()
assert str(excinfo.value) == (
"'NoSerializerClass' should either include a `serializer_class` "
"attribute, or override the `get_serializer_class()` method.")
def test_given_context_not_overridden(self):
context = object()
class View(generics.ListAPIView):
serializer_class = serializers.Serializer
def list(self, request):
response = Response()
response.serializer = self.get_serializer(context=context)
return response
response = View.as_view()(factory.get('/'))
serializer = response.serializer
assert serializer.context is context