File: test_views.py

package info (click to toggle)
django-haystack 3.3.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,504 kB
  • sloc: python: 23,475; xml: 1,708; sh: 74; makefile: 71
file content (308 lines) | stat: -rw-r--r-- 10,887 bytes parent folder | download | duplicates (2)
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
import queue
import time
from threading import Thread

from django import forms
from django.http import HttpRequest, QueryDict
from django.test import TestCase, override_settings
from django.urls import reverse

from haystack import connections, indexes
from haystack.forms import FacetedSearchForm, ModelSearchForm, SearchForm
from haystack.query import EmptySearchQuerySet
from haystack.utils.loading import UnifiedIndex
from haystack.views import FacetedSearchView, SearchView, search_view_factory
from test_haystack.core.models import AnotherMockModel, MockModel


class InitialedSearchForm(SearchForm):
    q = forms.CharField(initial="Search for...", required=False, label="Search")


class BasicMockModelSearchIndex(indexes.BasicSearchIndex, indexes.Indexable):
    def get_model(self):
        return MockModel


class BasicAnotherMockModelSearchIndex(indexes.BasicSearchIndex, indexes.Indexable):
    def get_model(self):
        return AnotherMockModel


class SearchViewTestCase(TestCase):
    fixtures = ["base_data"]

    def setUp(self):
        super().setUp()

        # Stow.
        self.old_unified_index = connections["default"]._index
        self.ui = UnifiedIndex()
        self.bmmsi = BasicMockModelSearchIndex()
        self.bammsi = BasicAnotherMockModelSearchIndex()
        self.ui.build(indexes=[self.bmmsi, self.bammsi])
        connections["default"]._index = self.ui

        # Update the "index".
        backend = connections["default"].get_backend()
        backend.clear()
        backend.update(self.bmmsi, MockModel.objects.all())

    def tearDown(self):
        connections["default"]._index = self.old_unified_index
        super().tearDown()

    def test_search_no_query(self):
        response = self.client.get(reverse("haystack_search"))
        self.assertEqual(response.status_code, 200)

    def test_search_query(self):
        response = self.client.get(reverse("haystack_search"), {"q": "haystack"})
        self.assertEqual(response.status_code, 200)
        self.assertIn("page", response.context)
        self.assertNotIn("page_obj", response.context)
        self.assertEqual(len(response.context[-1]["page"].object_list), 3)
        self.assertEqual(
            response.context[-1]["page"].object_list[0].content_type(), "core.mockmodel"
        )
        self.assertEqual(response.context[-1]["page"].object_list[0].pk, "1")

    def test_invalid_page(self):
        response = self.client.get(
            reverse("haystack_search"), {"q": "haystack", "page": "165233"}
        )
        self.assertEqual(response.status_code, 404)

    def test_empty_results(self):
        sv = SearchView()
        sv.request = HttpRequest()
        sv.form = sv.build_form()
        self.assertTrue(isinstance(sv.get_results(), EmptySearchQuerySet))

    def test_initial_data(self):
        sv = SearchView(form_class=InitialedSearchForm)
        sv.request = HttpRequest()
        form = sv.build_form()
        self.assertTrue(isinstance(form, InitialedSearchForm))
        self.assertEqual(form.fields["q"].initial, "Search for...")
        para = form.as_p()
        self.assertTrue('<label for="id_q">Search:</label>' in para)
        self.assertTrue('value="Search for..."' in para)

    def test_pagination(self):
        response = self.client.get(
            reverse("haystack_search"), {"q": "haystack", "page": 0}
        )
        self.assertEqual(response.status_code, 404)
        response = self.client.get(
            reverse("haystack_search"), {"q": "haystack", "page": 1}
        )
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.context[-1]["page"].object_list), 3)
        response = self.client.get(
            reverse("haystack_search"), {"q": "haystack", "page": 2}
        )
        self.assertEqual(response.status_code, 404)

    def test_thread_safety(self):
        exceptions = []

        def threaded_view(resp_queue, view, request):
            time.sleep(2)

            try:
                view(request)
                resp_queue.put(request.GET["name"])
            except Exception as e:
                exceptions.append(e)
                raise

        class ThreadedSearchView(SearchView):
            def __call__(self, request):
                print("Name: %s" % request.GET["name"])
                return super().__call__(request)

        view = search_view_factory(view_class=ThreadedSearchView)
        resp_queue = queue.Queue()
        request_1 = HttpRequest()
        request_1.GET = {"name": "foo"}
        request_2 = HttpRequest()
        request_2.GET = {"name": "bar"}

        th1 = Thread(target=threaded_view, args=(resp_queue, view, request_1))
        th2 = Thread(target=threaded_view, args=(resp_queue, view, request_2))

        th1.start()
        th2.start()
        th1.join()
        th2.join()

        foo = resp_queue.get()
        bar = resp_queue.get()
        self.assertNotEqual(foo, bar)

    def test_spelling(self):
        # Stow.
        from django.conf import settings

        old = settings.HAYSTACK_CONNECTIONS["default"].get("INCLUDE_SPELLING", None)

        settings.HAYSTACK_CONNECTIONS["default"]["INCLUDE_SPELLING"] = True

        sv = SearchView()
        sv.query = "Nothing"
        sv.results = []
        sv.build_page = lambda: (None, None)
        sv.create_response()
        context = sv.get_context()

        self.assertIn(
            "suggestion",
            context,
            msg="Spelling suggestions should be present even if"
            " no results were returned",
        )
        self.assertEqual(context["suggestion"], None)

        # Restore
        settings.HAYSTACK_CONNECTIONS["default"]["INCLUDE_SPELLING"] = old

        if old is None:
            del settings.HAYSTACK_CONNECTIONS["default"]["INCLUDE_SPELLING"]


@override_settings(ROOT_URLCONF="test_haystack.results_per_page_urls")
class ResultsPerPageTestCase(TestCase):
    fixtures = ["base_data"]

    def setUp(self):
        super().setUp()

        # Stow.
        self.old_unified_index = connections["default"]._index
        self.ui = UnifiedIndex()
        self.bmmsi = BasicMockModelSearchIndex()
        self.bammsi = BasicAnotherMockModelSearchIndex()
        self.ui.build(indexes=[self.bmmsi, self.bammsi])
        connections["default"]._index = self.ui

        # Update the "index".
        backend = connections["default"].get_backend()
        backend.clear()
        backend.update(self.bmmsi, MockModel.objects.all())

    def tearDown(self):
        connections["default"]._index = self.old_unified_index
        super().tearDown()

    def test_custom_results_per_page(self):
        response = self.client.get("/search/", {"q": "haystack"})
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.context[-1]["page"].object_list), 1)
        self.assertEqual(response.context[-1]["paginator"].per_page, 1)

        response = self.client.get("/search2/", {"q": "hello world"})
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.context[-1]["page"].object_list), 2)
        self.assertEqual(response.context[-1]["paginator"].per_page, 2)


class FacetedSearchViewTestCase(TestCase):
    def setUp(self):
        super().setUp()

        # Stow.
        self.old_unified_index = connections["default"]._index
        self.ui = UnifiedIndex()
        self.bmmsi = BasicMockModelSearchIndex()
        self.bammsi = BasicAnotherMockModelSearchIndex()
        self.ui.build(indexes=[self.bmmsi, self.bammsi])
        connections["default"]._index = self.ui

        # Update the "index".
        backend = connections["default"].get_backend()
        backend.clear()
        backend.update(self.bmmsi, MockModel.objects.all())

    def tearDown(self):
        connections["default"]._index = self.old_unified_index
        super().tearDown()

    def test_search_no_query(self):
        response = self.client.get(reverse("haystack_faceted_search"))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context["facets"], {})

    def test_empty_results(self):
        fsv = FacetedSearchView()
        fsv.request = HttpRequest()
        fsv.request.GET = QueryDict("")
        fsv.form = fsv.build_form()
        self.assertTrue(isinstance(fsv.get_results(), EmptySearchQuerySet))

    def test_default_form(self):
        fsv = FacetedSearchView()
        fsv.request = HttpRequest()
        fsv.request.GET = QueryDict("")
        fsv.form = fsv.build_form()
        self.assertTrue(isinstance(fsv.form, FacetedSearchForm))

    def test_list_selected_facets(self):
        fsv = FacetedSearchView()
        fsv.request = HttpRequest()
        fsv.request.GET = QueryDict("")
        fsv.form = fsv.build_form()
        self.assertEqual(fsv.form.selected_facets, [])

        fsv = FacetedSearchView()
        fsv.request = HttpRequest()
        fsv.request.GET = QueryDict(
            "selected_facets=author:daniel&selected_facets=author:chris"
        )
        fsv.form = fsv.build_form()
        self.assertEqual(fsv.form.selected_facets, ["author:daniel", "author:chris"])


class BasicSearchViewTestCase(TestCase):
    fixtures = ["base_data"]

    def setUp(self):
        super().setUp()

        # Stow.
        self.old_unified_index = connections["default"]._index
        self.ui = UnifiedIndex()
        self.bmmsi = BasicMockModelSearchIndex()
        self.bammsi = BasicAnotherMockModelSearchIndex()
        self.ui.build(indexes=[self.bmmsi, self.bammsi])
        connections["default"]._index = self.ui

        # Update the "index".
        backend = connections["default"].get_backend()
        backend.clear()
        backend.update(self.bmmsi, MockModel.objects.all())

    def tearDown(self):
        connections["default"]._index = self.old_unified_index
        super().tearDown()

    def test_search_no_query(self):
        response = self.client.get(reverse("haystack_basic_search"))
        self.assertEqual(response.status_code, 200)

    def test_search_query(self):
        response = self.client.get(reverse("haystack_basic_search"), {"q": "haystack"})
        self.assertEqual(response.status_code, 200)
        self.assertEqual(type(response.context[-1]["form"]), ModelSearchForm)
        self.assertEqual(len(response.context[-1]["page"].object_list), 3)
        self.assertEqual(
            response.context[-1]["page"].object_list[0].content_type(), "core.mockmodel"
        )
        self.assertEqual(response.context[-1]["page"].object_list[0].pk, "1")
        self.assertEqual(response.context[-1]["query"], "haystack")

    def test_invalid_page(self):
        response = self.client.get(
            reverse("haystack_basic_search"), {"q": "haystack", "page": "165233"}
        )
        self.assertEqual(response.status_code, 404)