basic tag filtering tests
[wolnelektury.git] / apps / catalogue / tests.py
1 # -*- coding: utf-8 -*-
2 from django.test import TestCase
3 from catalogue import models, views
4 from django.core.files.base import ContentFile
5 from django.contrib.auth.models import User, AnonymousUser
6 from django.test.client import Client
7
8 from nose.tools import raises
9 from StringIO import StringIO
10
11 class BasicSearchLogicTests(TestCase):
12
13     def setUp(self):
14         self.author_tag = models.Tag.objects.create(
15                                 name=u'Adam Mickiewicz [SubWord]',
16                                 category=u'author', slug="one")
17
18         self.unicode_tag = models.Tag.objects.create(
19                                 name=u'Tadeusz Żeleński (Boy)',
20                                 category=u'author', slug="two")
21
22         self.polish_tag = models.Tag.objects.create(
23                                 name=u'ĘÓĄŚŁŻŹĆŃęóąśłżźćń',
24                                 category=u'author', slug="three")
25
26     @raises(ValueError)
27     def test_empty_query(self):
28         """ Check that empty queries raise an error. """
29         views.find_best_matches(u'')
30
31     @raises(ValueError)
32     def test_one_letter_query(self):
33         """ Check that one letter queries aren't permitted. """
34         views.find_best_matches(u't')
35
36     def test_match_by_prefix(self):
37         """ Tags should be matched by prefix of words within it's name. """
38         self.assertEqual(views.find_best_matches(u'Ada'), (self.author_tag,))
39         self.assertEqual(views.find_best_matches(u'Mic'), (self.author_tag,))
40         self.assertEqual(views.find_best_matches(u'Mickiewicz'), (self.author_tag,))
41
42     def test_match_case_insensitive(self):
43         """ Tag names should match case insensitive. """
44         self.assertEqual(views.find_best_matches(u'adam mickiewicz'), (self.author_tag,))
45
46     def test_match_case_insensitive_unicode(self):
47         """ Tag names should match case insensitive (unicode). """
48         self.assertEqual(views.find_best_matches(u'tadeusz żeleński (boy)'), (self.unicode_tag,))
49
50     def test_word_boundary(self):
51         self.assertEqual(views.find_best_matches(u'SubWord'), (self.author_tag,))
52         self.assertEqual(views.find_best_matches(u'[SubWord'), (self.author_tag,))
53
54     def test_unrelated_search(self):
55         self.assertEqual(views.find_best_matches(u'alamakota'), tuple())
56         self.assertEqual(views.find_best_matches(u'Adama'), ())
57
58     def test_infix_doesnt_match(self):
59         """ Searching for middle of a word shouldn't match. """
60         self.assertEqual(views.find_best_matches(u'deusz'), tuple())
61
62     def test_diactricts_removal_pl(self):
63         """ Tags should match both with and without national characters. """
64         self.assertEqual(views.find_best_matches(u'ĘÓĄŚŁŻŹĆŃęóąśłżźćń'), (self.polish_tag,))
65         self.assertEqual(views.find_best_matches(u'EOASLZZCNeoaslzzcn'), (self.polish_tag,))
66         self.assertEqual(views.find_best_matches(u'eoaslzzcneoaslzzcn'), (self.polish_tag,))
67
68     def test_diactricts_query_removal_pl(self):
69         """ Tags without national characters shouldn't be matched by queries with them. """
70         self.assertEqual(views.find_best_matches(u'Adąm'), ())
71
72     def test_sloppy(self):
73         self.assertEqual(views.find_best_matches(u'Żelenski'), (self.unicode_tag,))
74         self.assertEqual(views.find_best_matches(u'zelenski'), (self.unicode_tag,))
75
76
77 class PersonStub(object):
78
79     def __init__(self, first_names, last_name):
80         self.first_names = first_names
81         self.last_name = last_name
82
83 class BookInfoStub(object):
84
85     def __init__(self, **kwargs):
86         self.__dict = kwargs
87
88     def __setattr__(self, key, value):
89         if not key.startswith('_'):
90             self.__dict[key] = value
91         return object.__setattr__(self, key, value)
92
93     def __getattr__(self, key):
94         return self.__dict[key]
95
96     def to_dict(self):
97         return dict((key, unicode(value)) for key, value in self.__dict.items())
98
99 class BookImportLogicTests(TestCase):
100
101     def setUp(self):
102         self.book_info = BookInfoStub(
103             url=u"http://wolnelektury.pl/example/default_book",
104             about=u"http://wolnelektury.pl/example/URI/default_book",
105             title=u"Default Book",
106             author=PersonStub(("Jim",), "Lazy"),
107             kind="X-Kind",
108             genre="X-Genre",
109             epoch="X-Epoch",
110         )
111
112         self.expected_tags = [
113            ('author', 'jim-lazy'),
114            ('book', 'l-default_book'),
115            ('genre', 'x-genre'),
116            ('epoch', 'x-epoch'),
117            ('kind', 'x-kind'),
118         ]
119         self.expected_tags.sort()
120
121     def test_empty_book(self):
122         BOOK_TEXT = "<utwor />"
123         book = models.Book.from_text_and_meta(ContentFile(BOOK_TEXT), self.book_info)
124
125         self.assertEqual(book.title, "Default Book")
126         self.assertEqual(book.slug, "default_book")
127         self.assert_(book.parent is None)
128         self.assertTrue(book.has_html_file())
129
130         # no fragments generated
131         self.assertEqual(book.fragments.count(), 0)
132
133         # TODO: this should be filled out probably...
134         self.assertEqual(book.wiki_link, '')
135         self.assertEqual(book.gazeta_link, '')
136         self.assertEqual(book._short_html, '')
137         self.assertEqual(book.description, '')
138
139         tags = [ (tag.category, tag.slug) for tag in book.tags ]
140         tags.sort()
141
142         self.assertEqual(tags, self.expected_tags)
143
144     def test_book_with_fragment(self):
145         BOOK_TEXT = """<utwor>
146         <opowiadanie>
147             <akap><begin id="m01" /><motyw id="m01">Love</motyw>Ala ma kota<end id="m01" /></akap>
148         </opowiadanie></utwor>
149         """
150
151         book = models.Book.from_text_and_meta(ContentFile(BOOK_TEXT), self.book_info)
152
153         self.assertEqual(book.fragments.count(), 1)
154         self.assertEqual(book.fragments.all()[0].text, u'<p class="paragraph">Ala ma kota</p>\n')
155
156         self.assert_(('theme', 'love') in [ (tag.category, tag.slug) for tag in book.tags ])
157
158     def test_book_replace_title(self):
159         BOOK_TEXT = """<utwor />"""
160         self.book_info.title = u"Extraordinary"
161         book = models.Book.from_text_and_meta(ContentFile(BOOK_TEXT), self.book_info)
162
163         tags = [ (tag.category, tag.slug) for tag in book.tags ]
164         tags.sort()
165
166         self.assertEqual(tags, self.expected_tags)
167
168     def test_book_replace_author(self):
169         BOOK_TEXT = """<utwor />"""
170         self.book_info.author = PersonStub(("Hans", "Christian"), "Andersen")
171         book = models.Book.from_text_and_meta(ContentFile(BOOK_TEXT), self.book_info)
172
173         tags = [ (tag.category, tag.slug) for tag in book.tags ]
174         tags.sort()
175
176         self.expected_tags.remove(('author', 'jim-lazy'))
177         self.expected_tags.append(('author', 'hans-christian-andersen'))
178         self.expected_tags.sort()
179
180         self.assertEqual(tags, self.expected_tags)
181
182         # the old tag should disappear 
183         self.assertRaises(models.Tag.DoesNotExist, models.Tag.objects.get,
184                     slug="jim-lazy", category="author")
185
186
187     
188 class BooksByTagFlat(TestCase):
189     def setUp(self):
190         self.tag_empty = models.Tag(name='Empty tag', slug='empty', category='author')
191         self.tag_common = models.Tag(name='Common author', slug='common', category='author')
192
193         self.tag_kind1 = models.Tag(name='Type 1', slug='type1', category='kind')
194         self.tag_kind2 = models.Tag(name='Type 2', slug='type2', category='kind')
195         self.tag_kind3 = models.Tag(name='Type 3', slug='type3', category='kind')
196         for tag in self.tag_empty, self.tag_common, self.tag_kind1, self.tag_kind2, self.tag_kind3:
197             tag.save()
198         
199         
200         self.parent = models.Book(title='Parent', slug='parent')
201         self.parent.save()
202         
203         self.similar_child = models.Book(title='Similar child', 
204                                          slug='similar_child', 
205                                          parent=self.parent)
206         self.similar_child.save()
207         self.similar_grandchild = models.Book(title='Similar grandchild', 
208                                               slug='similar_grandchild',
209                                               parent=self.similar_child)
210         self.similar_grandchild.save()
211         for book in self.parent, self.similar_child, self.similar_grandchild:
212             book.tags = [self.tag_common, self.tag_kind1]
213             book.save()
214         
215         self.different_child = models.Book(title='Different child', 
216                                            slug='different_child', 
217                                            parent=self.parent)
218         self.different_child.save()
219         self.different_child.tags = [self.tag_common, self.tag_kind2]
220         self.different_child.save()
221         self.different_grandchild = models.Book(title='Different grandchild', 
222                                                 slug='different_grandchild',
223                                                 parent=self.different_child)
224         self.different_grandchild.save()
225         self.different_grandchild.tags = [self.tag_common, self.tag_kind3]
226         self.different_grandchild.save()
227
228         for book in models.Book.objects.all():
229             l_tag = models.Tag(name=book.title, slug='l-'+book.slug, category='book')
230             l_tag.save()
231             book.tags = list(book.tags) + [l_tag]
232
233
234         self.client = Client()
235     
236     def test_nonexistent_tag(self):
237         """ Looking for a non-existent tag should yield 404 """
238         self.assertEqual(404, self.client.get('/katalog/czeslaw_milosz/').status_code)
239         
240     def test_book_tag(self):
241         """ Looking for a book tag isn't permitted """
242         self.assertEqual(404, self.client.get('/katalog/parent/').status_code)
243     
244     def test_tag_empty(self):
245         """ Tag with no books should return no books and no related tags """
246         context = self.client.get('/katalog/empty/').context
247         self.assertEqual(0, len(context['object_list']))
248         self.assertEqual(0, len(context['categories']))
249     
250     def test_tag_common(self):
251         """ Filtering by tag should only yield top-level books """
252         context = self.client.get('/katalog/%s/' % self.tag_common.slug).context
253         self.assertEqual(list(context['object_list']),
254                          [self.parent])
255
256