1# encoding: utf-8
2
3from __future__ import absolute_import, division, print_function, unicode_literals
4
5from django.test import TestCase
6from test_haystack.discovery.search_indexes import FooIndex
7
8from haystack import connections
9from haystack.utils.loading import UnifiedIndex
10
11EXPECTED_INDEX_MODEL_COUNT = 6
12
13
14class ManualDiscoveryTestCase(TestCase):
15    def test_discovery(self):
16        old_ui = connections['default'].get_unified_index()
17        connections['default']._index = UnifiedIndex()
18        ui = connections['default'].get_unified_index()
19        self.assertEqual(len(ui.get_indexed_models()), EXPECTED_INDEX_MODEL_COUNT)
20
21        ui.build(indexes=[FooIndex()])
22
23        self.assertListEqual(['discovery.foo'],
24                             [str(i._meta) for i in ui.get_indexed_models()])
25
26        ui.build(indexes=[])
27
28        self.assertListEqual([], ui.get_indexed_models())
29        connections['default']._index = old_ui
30
31
32class AutomaticDiscoveryTestCase(TestCase):
33    def test_discovery(self):
34        old_ui = connections['default'].get_unified_index()
35        connections['default']._index = UnifiedIndex()
36        ui = connections['default'].get_unified_index()
37        self.assertEqual(len(ui.get_indexed_models()), EXPECTED_INDEX_MODEL_COUNT)
38
39        # Test exclusions.
40        ui.excluded_indexes = ['test_haystack.discovery.search_indexes.BarIndex']
41        ui.build()
42
43        indexed_model_names = [str(i._meta) for i in ui.get_indexed_models()]
44        self.assertIn('multipleindex.foo', indexed_model_names)
45        self.assertIn('multipleindex.bar', indexed_model_names)
46        self.assertNotIn('discovery.bar', indexed_model_names)
47
48        ui.excluded_indexes = ['test_haystack.discovery.search_indexes.BarIndex',
49                               'test_haystack.discovery.search_indexes.FooIndex']
50        ui.build()
51
52        indexed_model_names = [str(i._meta) for i in ui.get_indexed_models()]
53        self.assertIn('multipleindex.foo', indexed_model_names)
54        self.assertIn('multipleindex.bar', indexed_model_names)
55        self.assertListEqual([], [i for i in indexed_model_names if i.startswith('discovery')])
56        connections['default']._index = old_ui
57