File: test_viewsets.py

package info (click to toggle)
drf-haystack 1.9.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 564 kB
  • sloc: python: 2,608; makefile: 147
file content (310 lines) | stat: -rw-r--r-- 14,130 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
# -*- coding: utf-8 -*-
#
# Unit tests for the `drf_haystack.viewsets` classes.
#

from __future__ import absolute_import, unicode_literals

import json
from unittest import skipIf

from django.test import TestCase
from django.contrib.auth.models import User

from haystack.query import SearchQuerySet

from rest_framework import status
from rest_framework.pagination import PageNumberPagination
from rest_framework.routers import SimpleRouter
from rest_framework.serializers import Serializer
from rest_framework.test import force_authenticate, APIRequestFactory

from drf_haystack.viewsets import HaystackViewSet
from drf_haystack.serializers import HaystackSerializer, HaystackFacetSerializer
from drf_haystack.mixins import MoreLikeThisMixin, FacetMixin

from . import restframework_version
from .mockapp.models import MockPerson, MockPet
from .mockapp.search_indexes import MockPersonIndex, MockPetIndex


factory = APIRequestFactory()


class HaystackViewSetTestCase(TestCase):

    fixtures = ["mockperson", "mockpet"]

    def setUp(self):
        MockPersonIndex().reindex()
        MockPetIndex().reindex()
        self.router = SimpleRouter()

        class FacetSerializer(HaystackFacetSerializer):

            class Meta:
                fields = ["firstname", "lastname", "created"]

        class ViewSet1(FacetMixin, HaystackViewSet):
            index_models = [MockPerson]
            serializer_class = Serializer
            facet_serializer_class = FacetSerializer

        class ViewSet2(MoreLikeThisMixin, HaystackViewSet):
            index_models = [MockPerson]
            serializer_class = Serializer

        class ViewSet3(HaystackViewSet):
            index_models = [MockPerson, MockPet]
            serializer_class = Serializer

        self.view1 = ViewSet1
        self.view2 = ViewSet2
        self.view3 = ViewSet3

    def tearDown(self):
        MockPersonIndex().clear()

    def test_viewset_get_queryset_no_queryset(self):
        request = factory.get(path="/", data="", content_type="application/json")
        response = self.view1.as_view(actions={"get": "list"})(request)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_viewset_get_queryset_with_queryset(self):
        setattr(self.view1, "queryset", SearchQuerySet().all())
        request = factory.get(path="/", data="", content_type="application/json")
        response = self.view1.as_view(actions={"get": "list"})(request)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_viewset_get_object_single_index(self):
        request = factory.get(path="/", data="", content_type="application/json")
        response = self.view1.as_view(actions={"get": "retrieve"})(request, pk=1)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_viewset_get_object_multiple_indices(self):
        request = factory.get(path="/", data={"model": "mockapp.mockperson"}, content_type="application/json")
        response = self.view3.as_view(actions={"get": "retrieve"})(request, pk=1)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_viewset_get_object_multiple_indices_no_model_query_param(self):
        request = factory.get(path="/", data="", content_type="application/json")
        response = self.view3.as_view(actions={"get": "retrieve"})(request, pk=1)
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_viewset_get_object_multiple_indices_invalid_modelname(self):
        request = factory.get(path="/", data={"model": "spam"}, content_type="application/json")
        response = self.view3.as_view(actions={"get": "retrieve"})(request, pk=1)
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_viewset_get_obj_raise_404(self):
        request = factory.get(path="/", data="", content_type="application/json")
        response = self.view1.as_view(actions={"get": "retrieve"})(request, pk=100000)
        self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

    def test_viewset_get_object_invalid_lookup_field(self):
        request = factory.get(path="/", data="", content_type="application/json")
        self.assertRaises(
            AttributeError,
            self.view1.as_view(actions={"get": "retrieve"}), request, invalid_lookup=1
        )

    def test_viewset_get_obj_override_lookup_field(self):
        setattr(self.view1, "lookup_field", "custom_lookup")
        request = factory.get(path="/", data="", content_type="application/json")
        response = self.view1.as_view(actions={"get": "retrieve"})(request, custom_lookup=1)
        setattr(self.view1, "lookup_field", "pk")
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_viewset_more_like_this_decorator(self):
        route = self.router.get_routes(self.view2)[2:].pop()
        self.assertEqual(route.url, "^{prefix}/{lookup}/more-like-this{trailing_slash}$")
        self.assertEqual(route.mapping, {"get": "more_like_this"})

    def test_viewset_more_like_this_action_route(self):
        request = factory.get(path="/", data={}, content_type="application/json")
        response = self.view2.as_view(actions={"get": "more_like_this"})(request, pk=1)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_viewset_facets_action_route(self):
        request = factory.get(path="/", data={}, content_type="application/json")
        response = self.view1.as_view(actions={"get": "facets"})(request)
        self.assertEqual(response.status_code, status.HTTP_200_OK)


class HaystackViewSetPermissionsTestCase(TestCase):

    fixtures = ["mockperson"]

    def setUp(self):
        MockPersonIndex().reindex()

        class ViewSet(HaystackViewSet):
            serializer_class = Serializer

        self.view = ViewSet
        self.user = User.objects.create_user(username="user", email="user@example.com", password="user")
        self.admin_user = User.objects.create_superuser(username="admin", email="admin@example.com", password="admin")

    def tearDown(self):
        MockPersonIndex().clear()

    def test_viewset_get_queryset_with_no_permsission(self):
        setattr(self.view, "permission_classes", [])

        request = factory.get(path="/", data="", content_type="application/json")
        response = self.view.as_view(actions={"get": "list"})(request)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_viewset_get_queryset_with_AllowAny_permission(self):
        from rest_framework.permissions import AllowAny
        setattr(self.view, "permission_classes", (AllowAny, ))

        request = factory.get(path="/", data="", content_type="application/json")
        response = self.view.as_view(actions={"get": "list"})(request)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_viewset_get_queryset_with_IsAuthenticated_permission(self):
        from rest_framework.permissions import IsAuthenticated
        setattr(self.view, "permission_classes", (IsAuthenticated, ))

        request = factory.get(path="/", data="", content_type="application/json")
        response = self.view.as_view(actions={"get": "list"})(request)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

        force_authenticate(request, user=self.user)
        response = self.view.as_view(actions={"get": "list"})(request)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_viewset_get_queryset_with_IsAdminUser_permission(self):
        from rest_framework.permissions import IsAdminUser
        setattr(self.view, "permission_classes", (IsAdminUser,))

        request = factory.get(path="/", data="", content_type="application/json")
        force_authenticate(request, user=self.user)
        response = self.view.as_view(actions={"get": "list"})(request)
        self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)

        force_authenticate(request, user=self.admin_user)
        response = self.view.as_view(actions={"get": "list"})(request)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

    def test_viewset_get_queryset_with_IsAuthenticatedOrReadOnly_permission(self):
        from rest_framework.permissions import IsAuthenticatedOrReadOnly
        setattr(self.view, "permission_classes", (IsAuthenticatedOrReadOnly,))

        # Unauthenticated GET requests should pass
        request = factory.get(path="/", data="", content_type="application/json")
        response = self.view.as_view(actions={"get": "list"})(request)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        # Authenticated GET requests should pass
        request = factory.get(path="/", data="", content_type="application/json")
        force_authenticate(request, user=self.user)
        response = self.view.as_view(actions={"get": "list"})(request)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        # POST, PUT, PATCH and DELETE requests are not supported, so they will
        # raise an error. No need to test the permission.

    @skipIf(not restframework_version < (3, 7), "Skipped due to fix in django-rest-framework > 3.6")
    def test_viewset_get_queryset_with_DjangoModelPermissions_permission(self):
        from rest_framework.permissions import DjangoModelPermissions
        setattr(self.view, "permission_classes", (DjangoModelPermissions,))

        # The `DjangoModelPermissions` is not supported and should raise an
        # AssertionError from rest_framework.permissions.
        request = factory.get(path="/", data="", content_type="application/json")
        try:
            self.view.as_view(actions={"get": "list"})(request)
            self.fail("Did not fail with AssertionError or AttributeError "
                      "when calling HaystackView with DjangoModelPermissions")
        except (AttributeError, AssertionError) as e:
            if isinstance(e, AttributeError):
                self.assertEqual(str(e), "'SearchQuerySet' object has no attribute 'model'")
            else:
                self.assertEqual(str(e), "Cannot apply DjangoModelPermissions on a view that does "
                                         "not have `.model` or `.queryset` property.")

    def test_viewset_get_queryset_with_DjangoModelPermissionsOrAnonReadOnly_permission(self):
        from rest_framework.permissions import DjangoModelPermissionsOrAnonReadOnly
        setattr(self.view, "permission_classes", (DjangoModelPermissionsOrAnonReadOnly,))

        # The `DjangoModelPermissionsOrAnonReadOnly` is not supported and should raise an
        # AssertionError from rest_framework.permissions.
        request = factory.get(path="/", data="", content_type="application/json")
        try:
            self.view.as_view(actions={"get": "list"})(request)
            self.fail("Did not fail with AssertionError when calling HaystackView "
                      "with DjangoModelPermissionsOrAnonReadOnly")
        except (AttributeError, AssertionError) as e:
            if isinstance(e, AttributeError):
                self.assertEqual(str(e), "'SearchQuerySet' object has no attribute 'model'")
            else:
                self.assertEqual(str(e), "Cannot apply DjangoModelPermissions on a view that does "
                                         "not have `.model` or `.queryset` property.")

    @skipIf(not restframework_version < (3, 7), "Skipped due to fix in django-rest-framework > 3.6")
    def test_viewset_get_queryset_with_DjangoObjectPermissions_permission(self):
        from rest_framework.permissions import DjangoObjectPermissions
        setattr(self.view, "permission_classes", (DjangoObjectPermissions,))

        # The `DjangoObjectPermissions` is a subclass of `DjangoModelPermissions` and
        # therefore unsupported.
        request = factory.get(path="/", data="", content_type="application/json")
        try:
            self.view.as_view(actions={"get": "list"})(request)
            self.fail("Did not fail with AssertionError when calling HaystackView with DjangoModelPermissions")
        except (AttributeError, AssertionError) as e:
            if isinstance(e, AttributeError):
                self.assertEqual(str(e), "'SearchQuerySet' object has no attribute 'model'")
            else:
                self.assertEqual(str(e), "Cannot apply DjangoModelPermissions on a view that does "
                                         "not have `.model` or `.queryset` property.")


class PaginatedHaystackViewSetTestCase(TestCase):

    fixtures = ["mockperson"]

    def setUp(self):

        MockPersonIndex().reindex()

        class Serializer1(HaystackSerializer):

            class Meta:
                fields = ["firstname", "lastname"]
                index_classes = [MockPersonIndex]

        class NumberPagination(PageNumberPagination):

            page_size = 5

        class ViewSet1(HaystackViewSet):

            index_models = [MockPerson]
            serializer_class = Serializer1
            pagination_class = NumberPagination

        self.view1 = ViewSet1

    def tearDown(self):
        MockPersonIndex().clear()

    def test_viewset_PageNumberPagination_results(self):
        request = factory.get(path="/", data="", content_type="application/json")
        response = self.view1.as_view(actions={"get": "list"})(request)
        response.render()
        content = json.loads(response.content.decode())

        self.assertTrue(all(k in content for k in ("count", "next", "previous", "results")))
        self.assertEqual(len(content["results"]), 5)

    def test_viewset_PageNumberPagination_navigation_urls(self):
        request = factory.get(path="/", data={"page": 2}, content_type="application/json")
        response = self.view1.as_view(actions={"get": "list"})(request)
        response.render()
        content = json.loads(response.content.decode())

        self.assertEqual(content["previous"], "http://testserver/")
        self.assertEqual(content["next"], "http://testserver/?page=3")