| 1 |
# -*- coding: utf-8 -*- |
| 2 |
# |
| 3 |
# Unit tests for the `drf_haystack.viewsets` classes. |
| 4 |
# |
| 5 |
|
| 6 |
from __future__ import absolute_import, unicode_literals |
| 7 |
|
| 8 |
import json |
| 9 |
from unittest import skipIf |
| 10 |
|
| 11 |
from django.test import TestCase |
| 12 |
from django.contrib.auth.models import User |
| 13 |
|
| 14 |
from haystack.query import SearchQuerySet |
| 15 |
|
| 16 |
from rest_framework import status |
| 17 |
from rest_framework.pagination import PageNumberPagination |
| 18 |
from rest_framework.routers import SimpleRouter |
| 19 |
from rest_framework.serializers import Serializer |
| 20 |
from rest_framework.test import force_authenticate, APIRequestFactory |
| 21 |
|
| 22 |
from drf_haystack.viewsets import HaystackViewSet |
| 23 |
from drf_haystack.serializers import HaystackSerializer, HaystackFacetSerializer |
| 24 |
from drf_haystack.mixins import MoreLikeThisMixin, FacetMixin |
| 25 |
|
| 26 |
from . import restframework_version |
| 27 |
from .mockapp.models import MockPerson, MockPet |
| 28 |
from .mockapp.search_indexes import MockPersonIndex, MockPetIndex |
| 29 |
|
| 30 |
|
| 31 |
factory = APIRequestFactory() |
| 32 |
|
| 33 |
|
| 34 |
class HaystackViewSetTestCase(TestCase): |
| 35 |
|
| 36 |
fixtures = ["mockperson", "mockpet"] |
| 37 |
|
| 38 |
def setUp(self): |
| 39 |
MockPersonIndex().reindex() |
| 40 |
MockPetIndex().reindex() |
| 41 |
self.router = SimpleRouter() |
| 42 |
|
| 43 |
class FacetSerializer(HaystackFacetSerializer): |
| 44 |
|
| 45 |
class Meta: |
| 46 |
fields = ["firstname", "lastname", "created"] |
| 47 |
|
| 48 |
class ViewSet1(FacetMixin, HaystackViewSet): |
| 49 |
index_models = [MockPerson] |
| 50 |
serializer_class = Serializer |
| 51 |
facet_serializer_class = FacetSerializer |
| 52 |
|
| 53 |
class ViewSet2(MoreLikeThisMixin, HaystackViewSet): |
| 54 |
index_models = [MockPerson] |
| 55 |
serializer_class = Serializer |
| 56 |
|
| 57 |
class ViewSet3(HaystackViewSet): |
| 58 |
index_models = [MockPerson, MockPet] |
| 59 |
serializer_class = Serializer |
| 60 |
|
| 61 |
self.view1 = ViewSet1 |
| 62 |
self.view2 = ViewSet2 |
| 63 |
self.view3 = ViewSet3 |
| 64 |
|
| 65 |
def tearDown(self): |
| 66 |
MockPersonIndex().clear() |
| 67 |
|
| 68 |
def test_viewset_get_queryset_no_queryset(self): |
| 69 |
request = factory.get(path="/", data="", content_type="application/json") |
| 70 |
response = self.view1.as_view(actions={"get": "list"})(request) |
| 71 |
self.assertEqual(response.status_code, status.HTTP_200_OK) |
| 72 |
|
| 73 |
def test_viewset_get_queryset_with_queryset(self): |
| 74 |
setattr(self.view1, "queryset", SearchQuerySet().all()) |
| 75 |
request = factory.get(path="/", data="", content_type="application/json") |
| 76 |
response = self.view1.as_view(actions={"get": "list"})(request) |
| 77 |
self.assertEqual(response.status_code, status.HTTP_200_OK) |
| 78 |
|
| 79 |
def test_viewset_get_object_single_index(self): |
| 80 |
request = factory.get(path="/", data="", content_type="application/json") |
| 81 |
response = self.view1.as_view(actions={"get": "retrieve"})(request, pk=1) |
| 82 |
self.assertEqual(response.status_code, status.HTTP_200_OK) |
| 83 |
|
| 84 |
def test_viewset_get_object_multiple_indices(self): |
| 85 |
request = factory.get(path="/", data={"model": "mockapp.mockperson"}, content_type="application/json") |
| 86 |
response = self.view3.as_view(actions={"get": "retrieve"})(request, pk=1) |
| 87 |
self.assertEqual(response.status_code, status.HTTP_200_OK) |
| 88 |
|
| 89 |
def test_viewset_get_object_multiple_indices_no_model_query_param(self): |
| 90 |
request = factory.get(path="/", data="", content_type="application/json") |
| 91 |
response = self.view3.as_view(actions={"get": "retrieve"})(request, pk=1) |
| 92 |
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) |
| 93 |
|
| 94 |
def test_viewset_get_object_multiple_indices_invalid_modelname(self): |
| 95 |
request = factory.get(path="/", data={"model": "spam"}, content_type="application/json") |
| 96 |
response = self.view3.as_view(actions={"get": "retrieve"})(request, pk=1) |
| 97 |
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) |
| 98 |
|
| 99 |
def test_viewset_get_obj_raise_404(self): |
| 100 |
request = factory.get(path="/", data="", content_type="application/json") |
| 101 |
response = self.view1.as_view(actions={"get": "retrieve"})(request, pk=100000) |
| 102 |
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) |
| 103 |
|
| 104 |
def test_viewset_get_object_invalid_lookup_field(self): |
| 105 |
request = factory.get(path="/", data="", content_type="application/json") |
| 106 |
self.assertRaises( |
| 107 |
AttributeError, |
| 108 |
self.view1.as_view(actions={"get": "retrieve"}), request, invalid_lookup=1 |
| 109 |
) |
| 110 |
|
| 111 |
def test_viewset_get_obj_override_lookup_field(self): |
| 112 |
setattr(self.view1, "lookup_field", "custom_lookup") |
| 113 |
request = factory.get(path="/", data="", content_type="application/json") |
| 114 |
response = self.view1.as_view(actions={"get": "retrieve"})(request, custom_lookup=1) |
| 115 |
setattr(self.view1, "lookup_field", "pk") |
| 116 |
self.assertEqual(response.status_code, status.HTTP_200_OK) |
| 117 |
|
| 118 |
def test_viewset_more_like_this_decorator(self): |
| 119 |
route = self.router.get_routes(self.view2)[2:].pop() |
| 120 |
self.assertEqual(route.url, "^{prefix}/{lookup}/more-like-this{trailing_slash}$") |
| 121 |
self.assertEqual(route.mapping, {"get": "more_like_this"}) |
| 122 |
|
| 123 |
def test_viewset_more_like_this_action_route(self): |
| 124 |
request = factory.get(path="/", data={}, content_type="application/json") |
| 125 |
response = self.view2.as_view(actions={"get": "more_like_this"})(request, pk=1) |
| 126 |
self.assertEqual(response.status_code, status.HTTP_200_OK) |
| 127 |
|
| 128 |
def test_viewset_facets_action_route(self): |
| 129 |
request = factory.get(path="/", data={}, content_type="application/json") |
| 130 |
response = self.view1.as_view(actions={"get": "facets"})(request) |
| 131 |
self.assertEqual(response.status_code, status.HTTP_200_OK) |
| 132 |
|
| 133 |
|
| 134 |
class HaystackViewSetPermissionsTestCase(TestCase): |
| 135 |
|
| 136 |
fixtures = ["mockperson"] |
| 137 |
|
| 138 |
def setUp(self): |
| 139 |
MockPersonIndex().reindex() |
| 140 |
|
| 141 |
class ViewSet(HaystackViewSet): |
| 142 |
serializer_class = Serializer |
| 143 |
|
| 144 |
self.view = ViewSet |
| 145 |
self.user = User.objects.create_user(username="user", email="[email protected]", password="user") |
| 146 |
self.admin_user = User.objects.create_superuser(username="admin", email="[email protected]", password="admin") |
| 147 |
|
| 148 |
def tearDown(self): |
| 149 |
MockPersonIndex().clear() |
| 150 |
|
| 151 |
def test_viewset_get_queryset_with_no_permsission(self): |
| 152 |
setattr(self.view, "permission_classes", []) |
| 153 |
|
| 154 |
request = factory.get(path="/", data="", content_type="application/json") |
| 155 |
response = self.view.as_view(actions={"get": "list"})(request) |
| 156 |
self.assertEqual(response.status_code, status.HTTP_200_OK) |
| 157 |
|
| 158 |
def test_viewset_get_queryset_with_AllowAny_permission(self): |
| 159 |
from rest_framework.permissions import AllowAny |
| 160 |
setattr(self.view, "permission_classes", (AllowAny, )) |
| 161 |
|
| 162 |
request = factory.get(path="/", data="", content_type="application/json") |
| 163 |
response = self.view.as_view(actions={"get": "list"})(request) |
| 164 |
self.assertEqual(response.status_code, status.HTTP_200_OK) |
| 165 |
|
| 166 |
def test_viewset_get_queryset_with_IsAuthenticated_permission(self): |
| 167 |
from rest_framework.permissions import IsAuthenticated |
| 168 |
setattr(self.view, "permission_classes", (IsAuthenticated, )) |
| 169 |
|
| 170 |
request = factory.get(path="/", data="", content_type="application/json") |
| 171 |
response = self.view.as_view(actions={"get": "list"})(request) |
| 172 |
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) |
| 173 |
|
| 174 |
force_authenticate(request, user=self.user) |
| 175 |
response = self.view.as_view(actions={"get": "list"})(request) |
| 176 |
self.assertEqual(response.status_code, status.HTTP_200_OK) |
| 177 |
|
| 178 |
def test_viewset_get_queryset_with_IsAdminUser_permission(self): |
| 179 |
from rest_framework.permissions import IsAdminUser |
| 180 |
setattr(self.view, "permission_classes", (IsAdminUser,)) |
| 181 |
|
| 182 |
request = factory.get(path="/", data="", content_type="application/json") |
| 183 |
force_authenticate(request, user=self.user) |
| 184 |
response = self.view.as_view(actions={"get": "list"})(request) |
| 185 |
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) |
| 186 |
|
| 187 |
force_authenticate(request, user=self.admin_user) |
| 188 |
response = self.view.as_view(actions={"get": "list"})(request) |
| 189 |
self.assertEqual(response.status_code, status.HTTP_200_OK) |
| 190 |
|
| 191 |
def test_viewset_get_queryset_with_IsAuthenticatedOrReadOnly_permission(self): |
| 192 |
from rest_framework.permissions import IsAuthenticatedOrReadOnly |
| 193 |
setattr(self.view, "permission_classes", (IsAuthenticatedOrReadOnly,)) |
| 194 |
|
| 195 |
# Unauthenticated GET requests should pass |
| 196 |
request = factory.get(path="/", data="", content_type="application/json") |
| 197 |
response = self.view.as_view(actions={"get": "list"})(request) |
| 198 |
self.assertEqual(response.status_code, status.HTTP_200_OK) |
| 199 |
|
| 200 |
# Authenticated GET requests should pass |
| 201 |
request = factory.get(path="/", data="", content_type="application/json") |
| 202 |
force_authenticate(request, user=self.user) |
| 203 |
response = self.view.as_view(actions={"get": "list"})(request) |
| 204 |
self.assertEqual(response.status_code, status.HTTP_200_OK) |
| 205 |
|
| 206 |
# POST, PUT, PATCH and DELETE requests are not supported, so they will |
| 207 |
# raise an error. No need to test the permission. |
| 208 |
|
| 209 |
@skipIf(not restframework_version < (3, 7), "Skipped due to fix in django-rest-framework > 3.6") |
| 210 |
def test_viewset_get_queryset_with_DjangoModelPermissions_permission(self): |
| 211 |
from rest_framework.permissions import DjangoModelPermissions |
| 212 |
setattr(self.view, "permission_classes", (DjangoModelPermissions,)) |
| 213 |
|
| 214 |
# The `DjangoModelPermissions` is not supported and should raise an |
| 215 |
# AssertionError from rest_framework.permissions. |
| 216 |
request = factory.get(path="/", data="", content_type="application/json") |
| 217 |
try: |
| 218 |
self.view.as_view(actions={"get": "list"})(request) |
| 219 |
self.fail("Did not fail with AssertionError or AttributeError " |
| 220 |
"when calling HaystackView with DjangoModelPermissions") |
| 221 |
except (AttributeError, AssertionError) as e: |
| 222 |
if isinstance(e, AttributeError): |
| 223 |
self.assertEqual(str(e), "'SearchQuerySet' object has no attribute 'model'") |
| 224 |
else: |
| 225 |
self.assertEqual(str(e), "Cannot apply DjangoModelPermissions on a view that does " |
| 226 |
"not have `.model` or `.queryset` property.") |
| 227 |
|
| 228 |
def test_viewset_get_queryset_with_DjangoModelPermissionsOrAnonReadOnly_permission(self): |
| 229 |
from rest_framework.permissions import DjangoModelPermissionsOrAnonReadOnly |
| 230 |
setattr(self.view, "permission_classes", (DjangoModelPermissionsOrAnonReadOnly,)) |
| 231 |
|
| 232 |
# The `DjangoModelPermissionsOrAnonReadOnly` is not supported and should raise an |
| 233 |
# AssertionError from rest_framework.permissions. |
| 234 |
request = factory.get(path="/", data="", content_type="application/json") |
| 235 |
try: |
| 236 |
self.view.as_view(actions={"get": "list"})(request) |
| 237 |
self.fail("Did not fail with AssertionError when calling HaystackView " |
| 238 |
"with DjangoModelPermissionsOrAnonReadOnly") |
| 239 |
except (AttributeError, AssertionError) as e: |
| 240 |
if isinstance(e, AttributeError): |
| 241 |
self.assertEqual(str(e), "'SearchQuerySet' object has no attribute 'model'") |
| 242 |
else: |
| 243 |
self.assertEqual(str(e), "Cannot apply DjangoModelPermissions on a view that does " |
| 244 |
"not have `.model` or `.queryset` property.") |
| 245 |
|
| 246 |
@skipIf(not restframework_version < (3, 7), "Skipped due to fix in django-rest-framework > 3.6") |
| 247 |
def test_viewset_get_queryset_with_DjangoObjectPermissions_permission(self): |
| 248 |
from rest_framework.permissions import DjangoObjectPermissions |
| 249 |
setattr(self.view, "permission_classes", (DjangoObjectPermissions,)) |
| 250 |
|
| 251 |
# The `DjangoObjectPermissions` is a subclass of `DjangoModelPermissions` and |
| 252 |
# therefore unsupported. |
| 253 |
request = factory.get(path="/", data="", content_type="application/json") |
| 254 |
try: |
| 255 |
self.view.as_view(actions={"get": "list"})(request) |
| 256 |
self.fail("Did not fail with AssertionError when calling HaystackView with DjangoModelPermissions") |
| 257 |
except (AttributeError, AssertionError) as e: |
| 258 |
if isinstance(e, AttributeError): |
| 259 |
self.assertEqual(str(e), "'SearchQuerySet' object has no attribute 'model'") |
| 260 |
else: |
| 261 |
self.assertEqual(str(e), "Cannot apply DjangoModelPermissions on a view that does " |
| 262 |
"not have `.model` or `.queryset` property.") |
| 263 |
|
| 264 |
|
| 265 |
class PaginatedHaystackViewSetTestCase(TestCase): |
| 266 |
|
| 267 |
fixtures = ["mockperson"] |
| 268 |
|
| 269 |
def setUp(self): |
| 270 |
|
| 271 |
MockPersonIndex().reindex() |
| 272 |
|
| 273 |
class Serializer1(HaystackSerializer): |
| 274 |
|
| 275 |
class Meta: |
| 276 |
fields = ["firstname", "lastname"] |
| 277 |
index_classes = [MockPersonIndex] |
| 278 |
|
| 279 |
class NumberPagination(PageNumberPagination): |
| 280 |
|
| 281 |
page_size = 5 |
| 282 |
|
| 283 |
class ViewSet1(HaystackViewSet): |
| 284 |
|
| 285 |
index_models = [MockPerson] |
| 286 |
serializer_class = Serializer1 |
| 287 |
pagination_class = NumberPagination |
| 288 |
|
| 289 |
self.view1 = ViewSet1 |
| 290 |
|
| 291 |
def tearDown(self): |
| 292 |
MockPersonIndex().clear() |
| 293 |
|
| 294 |
def test_viewset_PageNumberPagination_results(self): |
| 295 |
request = factory.get(path="/", data="", content_type="application/json") |
| 296 |
response = self.view1.as_view(actions={"get": "list"})(request) |
| 297 |
response.render() |
| 298 |
content = json.loads(response.content.decode()) |
| 299 |
|
| 300 |
self.assertTrue(all(k in content for k in ("count", "next", "previous", "results"))) |
| 301 |
self.assertEqual(len(content["results"]), 5) |
| 302 |
|
| 303 |
def test_viewset_PageNumberPagination_navigation_urls(self): |
| 304 |
request = factory.get(path="/", data={"page": 2}, content_type="application/json") |
| 305 |
response = self.view1.as_view(actions={"get": "list"})(request) |
| 306 |
response.render() |
| 307 |
content = json.loads(response.content.decode()) |
| 308 |
|
| 309 |
self.assertEqual(content["previous"], "http://testserver/") |
| 310 |
self.assertEqual(content["next"], "http://testserver/?page=3") |