Skip to content

Commit 0edfa5a

Browse files
committed
Add test to ensure that PolymorphicModelSerializer is passing the instance to the child serializer
1 parent b5e0d04 commit 0edfa5a

File tree

1 file changed

+44
-1
lines changed

1 file changed

+44
-1
lines changed

example/tests/test_serializers.py

+44-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from rest_framework.request import Request
88
from rest_framework.test import APIRequestFactory
99

10+
from example.factories import ArtProjectFactory
1011
from rest_framework_json_api.serializers import (
1112
DateField,
1213
ModelSerializer,
@@ -15,7 +16,11 @@
1516
from rest_framework_json_api.utils import format_resource_type
1617

1718
from example.models import Author, Blog, Entry
18-
from example.serializers import BlogSerializer
19+
from example.serializers import (
20+
BlogSerializer,
21+
ProjectSerializer,
22+
ArtProjectSerializer,
23+
)
1924

2025
request_factory = APIRequestFactory()
2126
pytestmark = pytest.mark.django_db
@@ -193,3 +198,41 @@ def test_model_serializer_with_implicit_fields(self, comment, client):
193198

194199
assert response.status_code == 200
195200
assert expected == response.json()
201+
202+
203+
class TestPolymorphicModelSerializer(TestCase):
204+
def setUp(self):
205+
self.project = ArtProjectFactory.create()
206+
207+
def test_polymorphic_model_serializer_passes_instance_to_child(self):
208+
"""
209+
Ensure that `PolymorphicModelSerializer` is passing the instance to the
210+
child serializer when initializing it in `to_internal_value`
211+
"""
212+
# Arrange
213+
def to_internal_value(serializer_self, data):
214+
"""
215+
Override `ArtProjectSerializer.to_internal_value` to get the
216+
instance serializer, which is later used assertion
217+
"""
218+
self.serializer_instance = serializer_self.instance
219+
return super(ArtProjectSerializer,
220+
serializer_self).to_internal_value(data)
221+
222+
# Override `to_internal_value` with our own method
223+
ArtProjectSerializer.to_internal_value = to_internal_value
224+
225+
# Initialize a serializer that would partially update a model instance
226+
data = {"artist": "Mark Bishop", "type": "artProjects"}
227+
serializer = ProjectSerializer(
228+
instance=self.project, data=data, partial=True
229+
)
230+
serializer.is_valid(raise_exception=True)
231+
232+
self.serializer_instance = None
233+
234+
# Act
235+
serializer.save()
236+
237+
# Assert
238+
assert self.serializer_instance is not None

0 commit comments

Comments
 (0)