cleanup comments
[wolnelektury.git] / src / search / mock_search.py
1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 #
5 from mock import Mock
6 from catalogue.models import Book, Tag
7 from random import randint, choice
8
9
10 class Search(Mock):
11     """
12     Search mock for development without setting up Solr.
13
14     Instead of connecting to an actual search server, it returns
15     some random results for any query.
16     """
17     class MockIndex(Mock):
18         def analyze(*args, **kwargs):
19             return []
20
21     index = MockIndex()
22
23     @staticmethod
24     def _find_some_books(snippets=False, query_terms=None, max_results=20):
25         from .index import SearchResult
26
27         qs = Book.objects.order_by('?')
28         if snippets:
29             qs = qs.exclude(fragments=None)
30         results = []
31         for book in qs[:randint(1, max_results)]:
32             doc = {
33                 'score': randint(0, 100),
34                 'book_id': book.pk,
35                 'published_date': randint(1000, 1920),
36                 }
37             if snippets:
38                 fragment = book.fragments.order_by('?')[0]
39                 doc.update({
40                     'header_type': choice(['strofa', 'akap']),
41                     'header_index': randint(100, 200),
42                     'header_span': randint(100, 200),
43                     'fragment_anchor': fragment.anchor,
44                     'snippets_position': randint(100, 200),
45                     'snippets_length': randint(100, 200),
46                     'snippets_revision': randint(1, 100),
47                     'themes_pl': fragment.tags.filter(category='theme'),
48                 })
49             res = SearchResult(doc, how_found='mock', query_terms=query_terms)
50             if snippets:
51                 res.snippets = [fragment.short_text]
52             results.append(res)
53         return results
54
55     def search_phrase(self, searched, field='text', book=False, filters=None, snippets=False):
56         return self._find_some_books(snippets)
57
58     def search_some(self, searched, fields, book=True, filters=None, snippets=True, query_terms=None):
59         return self._find_some_books(snippets, query_terms)
60
61     # WTF
62     def search_books(self, query, filters=None, max_results=10):
63         return self._find_some_books(snippets, max_results=max_results)
64
65     def search_everywhere(self, searched, query_terms=None):
66         return []
67
68     def hint_tags(self, query, pdcounter=True, prefix=True):
69         return Tag.objects.exclude(category='set').order_by('?')[:randint(1, 10)]
70
71     def hint_books(self, prefix):
72         return Book.objects.order_by('?')[:randint(1, 10)]