File: test_loading.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 (423 lines) | stat: -rw-r--r-- 15,245 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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
import unittest

from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase, override_settings

from haystack import indexes
from haystack.exceptions import NotHandled, SearchFieldError
from haystack.utils import loading
from test_haystack.core.models import AnotherMockModel, MockModel

try:
    import pysolr
except ImportError:
    pysolr = False


class ConnectionHandlerTestCase(TestCase):
    def test_init(self):
        ch = loading.ConnectionHandler({})
        self.assertEqual(ch.connections_info, {})

        ch = loading.ConnectionHandler(
            {
                "default": {
                    "ENGINE": "haystack.backends.solr_backend.SolrEngine",
                    "URL": "http://localhost:9001/solr/test_default",
                }
            }
        )
        self.assertEqual(
            ch.connections_info,
            {
                "default": {
                    "ENGINE": "haystack.backends.solr_backend.SolrEngine",
                    "URL": "http://localhost:9001/solr/test_default",
                }
            },
        )

    @unittest.skipIf(pysolr is False, "pysolr required")
    def test_get_item(self):
        ch = loading.ConnectionHandler({})

        try:
            empty_engine = ch["default"]
            self.fail()
        except ImproperlyConfigured:
            pass

        ch = loading.ConnectionHandler(
            {
                "default": {
                    "ENGINE": "haystack.backends.solr_backend.SolrEngine",
                    "URL": "http://localhost:9001/solr/test_default",
                }
            }
        )
        solr_engine = ch["default"]
        backend_path, memory_address = (
            repr(solr_engine).strip("<>").split(" object at ")
        )
        self.assertEqual(backend_path, "haystack.backends.solr_backend.SolrEngine")

        solr_engine_2 = ch["default"]
        backend_path_2, memory_address_2 = (
            repr(solr_engine_2).strip("<>").split(" object at ")
        )
        self.assertEqual(backend_path_2, "haystack.backends.solr_backend.SolrEngine")
        # Ensure we're loading out of the memorized connection.
        self.assertEqual(memory_address_2, memory_address)

        try:
            empty_engine = ch["slave"]
            self.fail()
        except ImproperlyConfigured:
            pass

    def test_get_unified_index(self):
        ch = loading.ConnectionHandler(
            {"default": {"ENGINE": "haystack.backends.simple_backend.SimpleEngine"}}
        )
        ui = ch["default"].get_unified_index()
        klass, address = repr(ui).strip("<>").split(" object at ")
        self.assertEqual(str(klass), "haystack.utils.loading.UnifiedIndex")

        ui_2 = ch["default"].get_unified_index()
        klass_2, address_2 = repr(ui_2).strip("<>").split(" object at ")
        self.assertEqual(str(klass_2), "haystack.utils.loading.UnifiedIndex")
        self.assertEqual(address_2, address)


class ConnectionRouterTestCase(TestCase):
    @override_settings()
    def test_init(self):
        del settings.HAYSTACK_ROUTERS
        cr = loading.ConnectionRouter()
        self.assertEqual(
            [str(route.__class__) for route in cr.routers],
            ["<class 'haystack.routers.DefaultRouter'>"],
        )

    @override_settings(HAYSTACK_ROUTERS=["haystack.routers.DefaultRouter"])
    def test_router_override1(self):
        cr = loading.ConnectionRouter()
        self.assertEqual(
            [str(route.__class__) for route in cr.routers],
            ["<class 'haystack.routers.DefaultRouter'>"],
        )

    @override_settings(HAYSTACK_ROUTERS=[])
    def test_router_override2(self):
        cr = loading.ConnectionRouter()
        self.assertEqual(
            [str(route.__class__) for route in cr.routers],
            ["<class 'haystack.routers.DefaultRouter'>"],
        )

    @override_settings(
        HAYSTACK_ROUTERS=[
            "test_haystack.mocks.MockMasterSlaveRouter",
            "haystack.routers.DefaultRouter",
        ]
    )
    def test_router_override3(self):
        cr = loading.ConnectionRouter()
        self.assertEqual(
            [str(route.__class__) for route in cr.routers],
            [
                "<class 'test_haystack.mocks.MockMasterSlaveRouter'>",
                "<class 'haystack.routers.DefaultRouter'>",
            ],
        )

    @override_settings()
    def test_actions1(self):
        del settings.HAYSTACK_ROUTERS
        cr = loading.ConnectionRouter()
        self.assertEqual(cr.for_read(), "default")
        self.assertEqual(cr.for_write(), ["default"])

    @override_settings(
        HAYSTACK_ROUTERS=[
            "test_haystack.mocks.MockMasterSlaveRouter",
            "haystack.routers.DefaultRouter",
        ]
    )
    def test_actions2(self):
        cr = loading.ConnectionRouter()
        self.assertEqual(cr.for_read(), "slave")
        self.assertEqual(cr.for_write(), ["master", "default"])

    @override_settings(
        HAYSTACK_ROUTERS=[
            "test_haystack.mocks.MockPassthroughRouter",
            "test_haystack.mocks.MockMasterSlaveRouter",
            "haystack.routers.DefaultRouter",
        ]
    )
    def test_actions3(self):
        cr = loading.ConnectionRouter()
        # Demonstrate pass-through
        self.assertEqual(cr.for_read(), "slave")
        self.assertEqual(cr.for_write(), ["master", "default"])
        # Demonstrate that hinting can change routing.
        self.assertEqual(cr.for_read(pass_through=False), "pass")
        self.assertEqual(
            cr.for_write(pass_through=False), ["pass", "master", "default"]
        )

    @override_settings(
        HAYSTACK_ROUTERS=[
            "test_haystack.mocks.MockMultiRouter",
            "haystack.routers.DefaultRouter",
        ]
    )
    def test_actions4(self):
        cr = loading.ConnectionRouter()
        # Demonstrate that a router can return multiple backends in the "for_write" method
        self.assertEqual(cr.for_read(), "default")
        self.assertEqual(cr.for_write(), ["multi1", "multi2", "default"])


class MockNotAModel:
    pass


class FakeSearchIndex(indexes.BasicSearchIndex, indexes.Indexable):
    def update_object(self, instance, **kwargs):
        # Incorrect behavior but easy to test and all we care about is that we
        # make it here. We rely on the `SearchIndex` tests to ensure correct
        # behavior.
        return True

    def remove_object(self, instance, **kwargs):
        # Incorrect behavior but easy to test and all we care about is that we
        # make it here. We rely on the `SearchIndex` tests to ensure correct
        # behavior.
        return True

    def get_model(self):
        return MockModel


class InvalidSearchIndex(indexes.SearchIndex, indexes.Indexable):
    document = indexes.CharField(document=True)

    def get_model(self):
        return MockModel


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 ValidSearchIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True)
    author = indexes.CharField(index_fieldname="name")
    title = indexes.CharField(indexed=False)

    def get_model(self):
        return MockModel


class AlternateValidSearchIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True)
    author = indexes.CharField(faceted=True)
    title = indexes.CharField(faceted=True)

    def get_model(self):
        return AnotherMockModel


class ExplicitFacetSearchIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True)
    author = indexes.CharField(faceted=True)
    title = indexes.CharField()
    title_facet = indexes.FacetCharField(facet_for="title")
    bare_facet = indexes.FacetCharField()

    def get_model(self):
        return MockModel


class MultiValueValidSearchIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True)
    author = indexes.MultiValueField(stored=False)
    title = indexes.CharField(indexed=False)

    def get_model(self):
        return MockModel


class UnifiedIndexTestCase(TestCase):
    def setUp(self):
        super().setUp()
        self.ui = loading.UnifiedIndex()
        self.ui.build([])

    def test_get_index(self):
        self.assertRaises(NotHandled, self.ui.get_index, MockModel)
        try:
            self.ui.get_index(MockModel)
        except NotHandled as e:
            self.assertTrue(MockModel.__name__ in str(e))

        self.ui.build(indexes=[BasicMockModelSearchIndex()])
        self.assertTrue(
            isinstance(self.ui.get_index(MockModel), indexes.BasicSearchIndex)
        )

    def test_get_indexed_models(self):
        self.assertEqual(self.ui.get_indexed_models(), [])

        self.ui.build(indexes=[ValidSearchIndex()])
        indexed_models = self.ui.get_indexed_models()
        self.assertEqual(len(indexed_models), 1)
        self.assertTrue(MockModel in indexed_models)

    def test_get_indexes(self):
        self.assertEqual(self.ui.get_indexes(), {})

        index = ValidSearchIndex()
        self.ui.build(indexes=[index])

        results = self.ui.get_indexes()
        self.assertEqual(len(results), 1)
        self.assertTrue(MockModel in results)
        self.assertEqual(results[MockModel], index)

    def test_all_searchfields(self):
        self.ui.build(indexes=[BasicMockModelSearchIndex()])
        fields = self.ui.all_searchfields()
        self.assertEqual(len(fields), 1)
        self.assertTrue("text" in fields)
        self.assertTrue(isinstance(fields["text"], indexes.CharField))
        self.assertEqual(fields["text"].document, True)
        self.assertEqual(fields["text"].use_template, True)

        self.ui.build(
            indexes=[BasicMockModelSearchIndex(), AlternateValidSearchIndex()]
        )
        fields = self.ui.all_searchfields()
        self.assertEqual(len(fields), 5)
        self.assertEqual(
            sorted(fields.keys()),
            ["author", "author_exact", "text", "title", "title_exact"],
        )
        self.assertTrue("text" in fields)
        self.assertTrue(isinstance(fields["text"], indexes.CharField))
        self.assertEqual(fields["text"].document, True)
        self.assertEqual(fields["text"].use_template, True)
        self.assertTrue("title" in fields)
        self.assertTrue(isinstance(fields["title"], indexes.CharField))
        self.assertEqual(fields["title"].document, False)
        self.assertEqual(fields["title"].use_template, False)
        self.assertEqual(fields["title"].faceted, True)
        self.assertEqual(fields["title"].indexed, True)
        self.assertTrue("author" in fields)
        self.assertTrue(isinstance(fields["author"], indexes.CharField))
        self.assertEqual(fields["author"].document, False)
        self.assertEqual(fields["author"].use_template, False)
        self.assertEqual(fields["author"].faceted, True)
        self.assertEqual(fields["author"].stored, True)
        self.assertEqual(fields["author"].index_fieldname, "author")

        self.ui.build(
            indexes=[AlternateValidSearchIndex(), MultiValueValidSearchIndex()]
        )
        fields = self.ui.all_searchfields()
        self.assertEqual(len(fields), 5)
        self.assertEqual(
            sorted(fields.keys()),
            ["author", "author_exact", "text", "title", "title_exact"],
        )
        self.assertTrue("text" in fields)
        self.assertTrue(isinstance(fields["text"], indexes.CharField))
        self.assertEqual(fields["text"].document, True)
        self.assertEqual(fields["text"].use_template, False)
        self.assertTrue("title" in fields)
        self.assertTrue(isinstance(fields["title"], indexes.CharField))
        self.assertEqual(fields["title"].document, False)
        self.assertEqual(fields["title"].use_template, False)
        self.assertEqual(fields["title"].faceted, True)
        self.assertEqual(fields["title"].indexed, True)
        self.assertTrue("author" in fields)
        self.assertTrue(isinstance(fields["author"], indexes.MultiValueField))
        self.assertEqual(fields["author"].document, False)
        self.assertEqual(fields["author"].use_template, False)
        self.assertEqual(fields["author"].stored, True)
        self.assertEqual(fields["author"].faceted, True)
        self.assertEqual(fields["author"].index_fieldname, "author")

        try:
            self.ui.build(indexes=[AlternateValidSearchIndex(), InvalidSearchIndex()])
            self.fail()
        except SearchFieldError:
            pass

    def test_get_index_fieldname(self):
        self.assertEqual(self.ui._fieldnames, {})

        self.ui.build(indexes=[ValidSearchIndex(), BasicAnotherMockModelSearchIndex()])
        self.ui.get_index_fieldname("text")
        self.assertEqual(
            self.ui._fieldnames, {"text": "text", "title": "title", "author": "name"}
        )
        self.assertEqual(self.ui.get_index_fieldname("text"), "text")
        self.assertEqual(self.ui.get_index_fieldname("author"), "name")
        self.assertEqual(self.ui.get_index_fieldname("title"), "title")

        # Reset the internal state to test the invalid case.
        self.ui.reset()
        self.assertEqual(self.ui._fieldnames, {})

        try:
            self.ui.build(indexes=[ValidSearchIndex(), AlternateValidSearchIndex()])
            self.fail()
        except SearchFieldError:
            pass

    def test_basic_get_facet_field_name(self):
        self.assertEqual(self.ui._facet_fieldnames, {})

        self.ui.build(
            indexes=[BasicMockModelSearchIndex(), AlternateValidSearchIndex()]
        )
        self.ui.get_facet_fieldname("text")
        self.assertEqual(
            self.ui._facet_fieldnames,
            {"title": "title_exact", "author": "author_exact"},
        )
        self.assertEqual(self.ui.get_index_fieldname("text"), "text")
        self.assertEqual(self.ui.get_index_fieldname("author"), "author")
        self.assertEqual(self.ui.get_index_fieldname("title"), "title")

        self.assertEqual(self.ui.get_facet_fieldname("text"), "text")
        self.assertEqual(self.ui.get_facet_fieldname("author"), "author_exact")
        self.assertEqual(self.ui.get_facet_fieldname("title"), "title_exact")

    def test_more_advanced_get_facet_field_name(self):
        self.assertEqual(self.ui._facet_fieldnames, {})

        self.ui.build(
            indexes=[BasicAnotherMockModelSearchIndex(), ExplicitFacetSearchIndex()]
        )
        self.ui.get_facet_fieldname("text")
        self.assertEqual(
            self.ui._facet_fieldnames,
            {
                "bare_facet": "bare_facet",
                "title": "title_facet",
                "author": "author_exact",
            },
        )
        self.assertEqual(self.ui.get_facet_fieldname("title"), "title_facet")
        self.assertEqual(self.ui.get_facet_fieldname("bare_facet"), "bare_facet")