|
1 | 1 | import pytest |
| 2 | +from django.utils import six |
2 | 3 | from django.conf import settings |
3 | 4 | from django.contrib.auth import get_user_model |
4 | 5 | from rest_framework import serializers |
|
7 | 8 |
|
8 | 9 | from rest_framework_json_api import utils |
9 | 10 |
|
| 11 | +from example.serializers import (EntrySerializer, BlogSerializer, |
| 12 | + AuthorSerializer, CommentSerializer) |
| 13 | +from rest_framework_json_api.utils import get_included_serializers |
| 14 | + |
10 | 15 | pytestmark = pytest.mark.django_db |
11 | 16 |
|
12 | 17 | class ResourceView(APIView): |
@@ -100,3 +105,43 @@ def test_build_json_resource_obj(): |
100 | 105 | assert utils.build_json_resource_obj( |
101 | 106 | serializer.fields, resource, resource_instance, 'user') == output |
102 | 107 |
|
| 108 | + |
| 109 | +class SerializerWithIncludedSerializers(EntrySerializer): |
| 110 | + included_serializers = { |
| 111 | + 'blog': BlogSerializer, |
| 112 | + 'authors': 'example.serializers.AuthorSerializer', |
| 113 | + 'comments': 'example.serializers.CommentSerializer', |
| 114 | + 'self': 'self' # this wouldn't make sense in practice (and would be prohibited by |
| 115 | + # IncludedResourcesValidationMixin) but it's useful for the test |
| 116 | + } |
| 117 | + |
| 118 | + |
| 119 | +def test_get_included_serializers_against_class(): |
| 120 | + klass = SerializerWithIncludedSerializers |
| 121 | + included_serializers = get_included_serializers(klass) |
| 122 | + expected_included_serializers = { |
| 123 | + 'blog': BlogSerializer, |
| 124 | + 'authors': AuthorSerializer, |
| 125 | + 'comments': CommentSerializer, |
| 126 | + 'self': klass |
| 127 | + } |
| 128 | + assert (six.viewkeys(included_serializers) == six.viewkeys(klass.included_serializers), |
| 129 | + 'the keys must be preserved') |
| 130 | + |
| 131 | + assert included_serializers == expected_included_serializers |
| 132 | + |
| 133 | + |
| 134 | +def test_get_included_serializers_against_instance(): |
| 135 | + klass = SerializerWithIncludedSerializers |
| 136 | + instance = klass() |
| 137 | + included_serializers = get_included_serializers(instance) |
| 138 | + expected_included_serializers = { |
| 139 | + 'blog': BlogSerializer, |
| 140 | + 'authors': AuthorSerializer, |
| 141 | + 'comments': CommentSerializer, |
| 142 | + 'self': klass |
| 143 | + } |
| 144 | + assert (six.viewkeys(included_serializers) == six.viewkeys(klass.included_serializers), |
| 145 | + 'the keys must be preserved') |
| 146 | + |
| 147 | + assert included_serializers == expected_included_serializers |
0 commit comments