From fa5ad1d0d9dba0e0c1e7a806e5902e7ba1acdaf3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ryan=20O=E2=80=99Hara?= Date: Mon, 15 Jan 2018 14:58:38 -0800 Subject: [PATCH] Add failing test for fallback to pk-only optimization Not sure if this is the right place to put the test or where the situation comes up in the real world when not using ORM hacks (like how we found it), but it *does* test the thing. --- tests/test_relations.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/tests/test_relations.py b/tests/test_relations.py index fd3256e89..7c4610301 100644 --- a/tests/test_relations.py +++ b/tests/test_relations.py @@ -3,7 +3,7 @@ import uuid import pytest from _pytest.monkeypatch import MonkeyPatch from django.conf.urls import url -from django.core.exceptions import ImproperlyConfigured +from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist from django.test import override_settings from django.utils.datastructures import MultiValueDict @@ -167,6 +167,22 @@ class TestHyperlinkedRelatedField(APISimpleTestCase): representation = self.field.to_representation(MockObject(pk='')) assert representation is None + def test_serialize_empty_relationship_attribute(self): + class TestSerializer(serializers.Serializer): + via_unreachable = serializers.HyperlinkedRelatedField( + source='does_not_exist.unreachable', + view_name='example', + read_only=True, + ) + + class TestSerializable: + @property + def does_not_exist(self): + raise ObjectDoesNotExist + + serializer = TestSerializer(TestSerializable()) + assert serializer.data == {'via_unreachable': None} + def test_hyperlinked_related_lookup_exists(self): instance = self.field.to_internal_value('http://example.org/example/foobar/') assert instance is self.queryset.items[0]