test_serializers.py 8.08 KB
Newer Older
1
2
3
4
import os
import PIL

from django.core.files.uploadedfile import SimpleUploadedFile
Eliot Berriot's avatar
Eliot Berriot committed
5
from django.urls import reverse
6

Eliot Berriot's avatar
Eliot Berriot committed
7
8
9
import django_filters

from funkwhale_api.common import serializers
10
from funkwhale_api.common import utils
Eliot Berriot's avatar
Eliot Berriot committed
11
from funkwhale_api.users import models
Eliot Berriot's avatar
Eliot Berriot committed
12
from funkwhale_api.federation import utils as federation_utils
Eliot Berriot's avatar
Eliot Berriot committed
13
14
15
16
17


class TestActionFilterSet(django_filters.FilterSet):
    class Meta:
        model = models.User
Eliot Berriot's avatar
Eliot Berriot committed
18
        fields = ["is_active"]
Eliot Berriot's avatar
Eliot Berriot committed
19
20
21


class TestSerializer(serializers.ActionSerializer):
22
    actions = [serializers.Action("test", allow_all=True)]
Eliot Berriot's avatar
Eliot Berriot committed
23
24
25
    filterset_class = TestActionFilterSet

    def handle_test(self, objects):
Eliot Berriot's avatar
Eliot Berriot committed
26
        return {"hello": "world"}
Eliot Berriot's avatar
Eliot Berriot committed
27
28


29
class TestDangerousSerializer(serializers.ActionSerializer):
30
31
32
33
    actions = [
        serializers.Action("test", allow_all=True),
        serializers.Action("test_dangerous"),
    ]
34
35
36
37
38
39
40
41

    def handle_test(self, objects):
        pass

    def handle_test_dangerous(self, objects):
        pass


42
class TestDeleteOnlyInactiveSerializer(serializers.ActionSerializer):
43
44
45
46
47
    actions = [
        serializers.Action(
            "test", allow_all=True, qs_filter=lambda qs: qs.filter(is_active=False)
        )
    ]
48
49
50
51
52
53
    filterset_class = TestActionFilterSet

    def handle_test(self, objects):
        pass


Eliot Berriot's avatar
Eliot Berriot committed
54
def test_action_serializer_validates_action():
Eliot Berriot's avatar
Eliot Berriot committed
55
    data = {"objects": "all", "action": "nope"}
Eliot Berriot's avatar
Eliot Berriot committed
56
57
58
    serializer = TestSerializer(data, queryset=models.User.objects.none())

    assert serializer.is_valid() is False
Eliot Berriot's avatar
Eliot Berriot committed
59
    assert "action" in serializer.errors
Eliot Berriot's avatar
Eliot Berriot committed
60
61
62


def test_action_serializer_validates_objects():
Eliot Berriot's avatar
Eliot Berriot committed
63
    data = {"objects": "nope", "action": "test"}
Eliot Berriot's avatar
Eliot Berriot committed
64
65
66
    serializer = TestSerializer(data, queryset=models.User.objects.none())

    assert serializer.is_valid() is False
Eliot Berriot's avatar
Eliot Berriot committed
67
    assert "objects" in serializer.errors
Eliot Berriot's avatar
Eliot Berriot committed
68
69
70


def test_action_serializers_objects_clean_ids(factories):
Eliot Berriot's avatar
Eliot Berriot committed
71
    user1 = factories["users.User"]()
72
    factories["users.User"]()
Eliot Berriot's avatar
Eliot Berriot committed
73

Eliot Berriot's avatar
Eliot Berriot committed
74
    data = {"objects": [user1.pk], "action": "test"}
Eliot Berriot's avatar
Eliot Berriot committed
75
76
    serializer = TestSerializer(data, queryset=models.User.objects.all())

77
    assert serializer.is_valid(raise_exception=True) is True
Eliot Berriot's avatar
Eliot Berriot committed
78
    assert list(serializer.validated_data["objects"]) == [user1]
Eliot Berriot's avatar
Eliot Berriot committed
79
80
81


def test_action_serializers_objects_clean_all(factories):
Eliot Berriot's avatar
Eliot Berriot committed
82
83
    user1 = factories["users.User"]()
    user2 = factories["users.User"]()
Eliot Berriot's avatar
Eliot Berriot committed
84

Eliot Berriot's avatar
Eliot Berriot committed
85
    data = {"objects": "all", "action": "test"}
Eliot Berriot's avatar
Eliot Berriot committed
86
87
    serializer = TestSerializer(data, queryset=models.User.objects.all())

88
    assert serializer.is_valid(raise_exception=True) is True
Eliot Berriot's avatar
Eliot Berriot committed
89
    assert list(serializer.validated_data["objects"]) == [user1, user2]
Eliot Berriot's avatar
Eliot Berriot committed
90
91
92


def test_action_serializers_save(factories, mocker):
Eliot Berriot's avatar
Eliot Berriot committed
93
    handler = mocker.spy(TestSerializer, "handle_test")
94
95
    factories["users.User"]()
    factories["users.User"]()
Eliot Berriot's avatar
Eliot Berriot committed
96

Eliot Berriot's avatar
Eliot Berriot committed
97
    data = {"objects": "all", "action": "test"}
Eliot Berriot's avatar
Eliot Berriot committed
98
99
    serializer = TestSerializer(data, queryset=models.User.objects.all())

100
    assert serializer.is_valid(raise_exception=True) is True
Eliot Berriot's avatar
Eliot Berriot committed
101
    result = serializer.save()
Eliot Berriot's avatar
Eliot Berriot committed
102
    assert result == {"updated": 2, "action": "test", "result": {"hello": "world"}}
Eliot Berriot's avatar
Eliot Berriot committed
103
104
105
106
    handler.assert_called_once()


def test_action_serializers_filterset(factories):
107
    factories["users.User"](is_active=False)
Eliot Berriot's avatar
Eliot Berriot committed
108
109
110
    user2 = factories["users.User"](is_active=True)

    data = {"objects": "all", "action": "test", "filters": {"is_active": True}}
Eliot Berriot's avatar
Eliot Berriot committed
111
112
    serializer = TestSerializer(data, queryset=models.User.objects.all())

113
    assert serializer.is_valid(raise_exception=True) is True
Eliot Berriot's avatar
Eliot Berriot committed
114
    assert list(serializer.validated_data["objects"]) == [user2]
115
116
117


def test_action_serializers_validates_at_least_one_object():
Eliot Berriot's avatar
Eliot Berriot committed
118
    data = {"objects": "all", "action": "test"}
119
120
121
    serializer = TestSerializer(data, queryset=models.User.objects.none())

    assert serializer.is_valid() is False
Eliot Berriot's avatar
Eliot Berriot committed
122
    assert "non_field_errors" in serializer.errors
123
124
125


def test_dangerous_actions_refuses_all(factories):
Eliot Berriot's avatar
Eliot Berriot committed
126
127
128
    factories["users.User"]()
    data = {"objects": "all", "action": "test_dangerous"}
    serializer = TestDangerousSerializer(data, queryset=models.User.objects.all())
129
130

    assert serializer.is_valid() is False
Eliot Berriot's avatar
Eliot Berriot committed
131
    assert "non_field_errors" in serializer.errors
132
133


134
135
136
137
def test_action_serializers_can_require_filter(factories):
    user1 = factories["users.User"](is_active=False)
    factories["users.User"](is_active=True)

Eliot Berriot's avatar
Eliot Berriot committed
138
    data = {"objects": "all", "action": "test"}
139
140
141
    serializer = TestDeleteOnlyInactiveSerializer(
        data, queryset=models.User.objects.all()
    )
142

143
144
    assert serializer.is_valid(raise_exception=True) is True
    assert list(serializer.validated_data["objects"]) == [user1]
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173


def test_track_fields_for_update(mocker):
    @serializers.track_fields_for_update("field1", "field2")
    class S(serializers.serializers.Serializer):
        field1 = serializers.serializers.CharField()
        field2 = serializers.serializers.CharField()

        def update(self, obj, validated_data):
            for key, value in validated_data.items():
                setattr(obj, key, value)
            return obj

        on_updated_fields = mocker.stub()

    class Obj(object):
        field1 = "value1"
        field2 = "value2"

    obj = Obj()
    serializer = S(obj, data={"field1": "newvalue1", "field2": "newvalue2"})
    assert serializer.is_valid(raise_exception=True)
    serializer.save()

    serializer.on_updated_fields.assert_called_once_with(
        obj,
        {"field1": "value1", "field2": "value2"},
        {"field1": "newvalue1", "field2": "newvalue2"},
    )
174
175
176
177
178
179
180
181
182
183
184
185
186
187


def test_strip_exif_field():
    source_path = os.path.join(os.path.dirname(__file__), "exif.jpg")
    source = PIL.Image.open(source_path)

    assert bool(source._getexif())

    with open(source_path, "rb") as f:
        uploaded = SimpleUploadedFile("source.jpg", f.read(), content_type="image/jpeg")
    field = serializers.StripExifImageField()

    cleaned = PIL.Image.open(field.to_internal_value(uploaded))
    assert cleaned._getexif() is None
Eliot Berriot's avatar
Eliot Berriot committed
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202


def test_attachment_serializer_existing_file(factories, to_api_date):
    attachment = factories["common.Attachment"]()
    expected = {
        "uuid": str(attachment.uuid),
        "size": attachment.size,
        "mimetype": attachment.mimetype,
        "creation_date": to_api_date(attachment.creation_date),
        "urls": {
            "source": attachment.url,
            "original": federation_utils.full_url(attachment.file.url),
            "medium_square_crop": federation_utils.full_url(
                attachment.file.crop["200x200"].url
            ),
203
204
205
            "large_square_crop": federation_utils.full_url(
                attachment.file.crop["600x600"].url
            ),
Eliot Berriot's avatar
Eliot Berriot committed
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
        },
    }

    serializer = serializers.AttachmentSerializer(attachment)

    assert serializer.data == expected


def test_attachment_serializer_remote_file(factories, to_api_date):
    attachment = factories["common.Attachment"](file=None)
    proxy_url = reverse("api:v1:attachments-proxy", kwargs={"uuid": attachment.uuid})
    expected = {
        "uuid": str(attachment.uuid),
        "size": attachment.size,
        "mimetype": attachment.mimetype,
        "creation_date": to_api_date(attachment.creation_date),
        # everything is the same, except for the urls field because:
        #  - the file isn't available on the local pod
        #  - we need to return different URLs so that the client can trigger
        #    a fetch and get redirected to the desired version
        #
        "urls": {
            "source": attachment.url,
            "original": federation_utils.full_url(proxy_url + "?next=original"),
            "medium_square_crop": federation_utils.full_url(
                proxy_url + "?next=medium_square_crop"
            ),
233
234
235
            "large_square_crop": federation_utils.full_url(
                proxy_url + "?next=large_square_crop"
            ),
Eliot Berriot's avatar
Eliot Berriot committed
236
237
238
239
240
241
        },
    }

    serializer = serializers.AttachmentSerializer(attachment)

    assert serializer.data == expected
242
243
244
245
246
247
248
249
250
251
252
253
254
255


def test_content_serializer(factories):
    content = factories["common.Content"]()

    expected = {
        "text": content.text,
        "content_type": content.content_type,
        "html": utils.render_html(content.text, content.content_type),
    }

    serializer = serializers.ContentSerializer(content)

    assert serializer.data == expected