Code layout change.
[wolnelektury.git] / src / catalogue / tests / tags.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 django.core.files.base import ContentFile
6 from django.test import Client
7 from catalogue import models
8 from catalogue.test_utils import *
9
10
11 class BooksByTagTests(WLTestCase):
12     """ tests the /katalog/category/tag page for found books """
13
14     def setUp(self):
15         WLTestCase.setUp(self)
16         author = PersonStub(("Common",), "Man")
17
18         # grandchild
19         self.gchild_info = BookInfoStub(genre='Genre', epoch='Epoch', kind='Kind', author=author,
20                                         **info_args("GChild"))
21         # child
22         self.child_info = BookInfoStub(genre='Genre', epoch='Epoch', kind='Other Kind', author=author,
23                                        parts=[self.gchild_info.url],
24                                        **info_args("Child"))
25         # parent
26         self.parent_info = BookInfoStub(genre='Genre', epoch='Epoch', kind='Kind', author=author,
27                                         parts=[self.child_info.url],
28                                         **info_args("Parent"))
29
30         self.book_file = ContentFile('<utwor />')
31
32     def test_nonexistent_tag(self):
33         """ Looking for a non-existent tag should yield 404 """
34         self.assertEqual(404, self.client.get('/katalog/autor/czeslaw-milosz/').status_code)
35
36     def test_book_tag(self):
37         """ Looking for a book tag isn't permitted """
38         models.Book.from_text_and_meta(self.book_file, self.gchild_info)
39         self.assertEqual(404, self.client.get('/katalog/gchild/').status_code)
40
41     def test_tag_empty(self):
42         """ Tag with no books should return no books """
43         models.Book.from_text_and_meta(self.book_file, self.gchild_info)
44         models.Tag.objects.create(name='Empty tag', slug='empty', category='author')
45
46         context = self.client.get('/katalog/autor/empty/').context
47         self.assertEqual(0, len(context['object_list']))
48
49     def test_tag_eliminate(self):
50         """ Filtering by tag should only yield top-level qualifying books. """
51         for info in self.gchild_info, self.child_info, self.parent_info:
52             models.Book.from_text_and_meta(self.book_file, info)
53
54         # all three qualify
55         context = self.client.get('/katalog/gatunek/genre/').context
56         self.assertEqual([book.title for book in context['object_list']],
57                          ['Parent'])
58
59         # parent and gchild qualify, child doesn't
60         context = self.client.get('/katalog/rodzaj/kind/').context
61         self.assertEqual([book.title for book in context['object_list']],
62                          ['Parent'])
63
64         # Filtering by child's tag should yield the child
65         context = self.client.get('/katalog/rodzaj/other-kind/').context
66         self.assertEqual([book.title for book in context['object_list']],
67                          ['Child'])
68
69
70 class TagRelatedTagsTests(WLTestCase):
71     """ tests the /katalog/category/tag/ page for related tags """
72
73     def setUp(self):
74         WLTestCase.setUp(self)
75         self.client = Client()
76         author = PersonStub(("Common",), "Man")
77
78         gchild_info = BookInfoStub(author=author, genre="GchildGenre", epoch='Epoch', kind="Kind",
79                                    **info_args(u"GChild"))
80         child1_info = BookInfoStub(author=author, genre="ChildGenre", epoch='Epoch', kind="ChildKind",
81                                    parts=[gchild_info.url],
82                                    **info_args(u"Child1"))
83         child2_info = BookInfoStub(author=author, genre="ChildGenre", epoch='Epoch', kind="ChildKind",
84                                    **info_args(u"Child2"))
85         parent_info = BookInfoStub(author=author, genre="Genre", epoch='Epoch', kind="Kind",
86                                    parts=[child1_info.url, child2_info.url],
87                                    **info_args(u"Parent"))
88
89         for info in gchild_info, child1_info, child2_info, parent_info:
90             book_text = """<utwor><opowiadanie><akap>
91                 <begin id="m01" />
92                     <motyw id="m01">Theme, %sTheme</motyw>
93                     Ala ma kota
94                 <end id="m01" />
95                 </akap></opowiadanie></utwor>
96                 """ % info.title.encode('utf-8')
97             book = models.Book.from_text_and_meta(ContentFile(book_text), info)
98             book.save()
99
100         tag_empty = models.Tag(name='Empty tag', slug='empty', category='author')
101         tag_empty.save()
102
103     def test_empty(self):
104         """ empty tag should have no related tags """
105
106         cats = self.client.get('/katalog/autor/empty/').context['categories']
107         self.assertEqual({k: v for (k, v) in cats.items() if v}, {},
108             'tags related to empty tag')
109
110     def test_has_related(self):
111         """ related own and descendants' tags should be generated """
112
113         cats = self.client.get('/katalog/rodzaj/kind/').context['categories']
114         self.assertTrue('Common Man' in [tag.name for tag in cats['author']],
115                         'missing `author` related tag')
116         self.assertTrue('Epoch' in [tag.name for tag in cats['epoch']],
117                         'missing `epoch` related tag')
118         self.assertFalse(cats.get("kind", False),
119                         "There should be no child-only related `kind` tags")
120         self.assertTrue("Genre" in [tag.name for tag in cats['genre']],
121                         'missing `genre` related tag')
122         self.assertFalse("ChildGenre" in [tag.name for tag in cats['genre']],
123                         "There should be no child-only related `genre` tags")
124         self.assertTrue("GchildGenre" in [tag.name for tag in cats['genre']],
125                         "missing grandchild's related tag")
126         self.assertTrue('Theme' in [tag.name for tag in cats['theme']],
127                         "missing related theme")
128         self.assertFalse('Child1Theme' in [tag.name for tag in cats['theme']],
129                         "There should be no child-only related `theme` tags")
130         self.assertTrue('GChildTheme' in [tag.name for tag in cats['theme']],
131                         "missing grandchild's related theme")
132
133     def test_related_differ(self):
134         """ related tags shouldn't include filtering tags """
135
136         response = self.client.get('/katalog/rodzaj/kind/')
137         cats = response.context['categories']
138         self.assertFalse(cats.get('kind', False),
139                          'filtering tag wrongly included in related')
140         cats = self.client.get('/katalog/motyw/theme/').context['categories']
141         self.assertFalse('Theme' in [tag.name for tag in cats['theme']],
142                          'filtering theme wrongly included in related')
143
144     def test_parent_tag_once(self):
145         """ if parent and descendants have a common tag, count it only once """
146
147         cats = self.client.get('/katalog/rodzaj/kind/').context['categories']
148         self.assertEqual([(tag.name, tag.count) for tag in cats['epoch']],
149                          [('Epoch', 1)],
150                          'wrong related tag epoch tag on tag page')
151
152
153     def test_siblings_tags_count(self):
154         """ if children have tags and parent hasn't, count the children """
155
156         cats = self.client.get('/katalog/epoka/epoch/').context['categories']
157         self.assertTrue(('ChildKind', 2) in [(tag.name, tag.count) for tag in cats['kind']],
158                     'wrong related kind tags on tag page, got: ' +
159                     unicode([(tag.name, tag.count) for tag in cats['kind']]))
160
161         # all occurencies of theme should be counted
162         self.assertTrue(('Theme', 4) in [(tag.name, tag.count) for tag in cats['theme']],
163                     'wrong related theme count')
164
165     def test_query_child_tag(self):
166         """
167         If child and parent have a common tag, but parent isn't included
168         in the result, child should still count.
169         """
170         cats = self.client.get('/katalog/gatunek/childgenre/').context['categories']
171         self.assertTrue(('Epoch', 2) in [(tag.name, tag.count) for tag in cats['epoch']],
172                     'wrong related kind tags on tag page, got: ' +
173                     unicode([(tag.name, tag.count) for tag in cats['epoch']]))
174
175
176 class CleanTagRelationTests(WLTestCase):
177     """ tests for tag relations cleaning after deleting things """
178
179     def setUp(self):
180         WLTestCase.setUp(self)
181         author = PersonStub(("Common",), "Man")
182
183         book_info = BookInfoStub(author=author, genre="G", epoch='E', kind="K",
184                                    **info_args(u"Book"))
185         book_text = """<utwor><opowiadanie><akap>
186             <begin id="m01" /><motyw id="m01">Theme</motyw>Ala ma kota
187             <end id="m01" />
188             </akap></opowiadanie></utwor>
189             """
190         self.book = models.Book.from_text_and_meta(ContentFile(book_text), book_info)
191
192     def test_delete_objects(self):
193         """ there should be no related tags left after deleting some objects """
194
195         models.Book.objects.all().delete()
196         cats = self.client.get('/katalog/rodzaj/k/').context['categories']
197         self.assertEqual({k: v for (k, v) in cats.items() if v}, {})
198         self.assertEqual(models.Fragment.objects.all().count(), 0,
199                          "orphaned fragments left")
200         self.assertEqual(models.Tag.intermediary_table_model.objects.all().count(), 0,
201                          "orphaned TagRelation objects left")
202
203     def test_deleted_tag(self):
204         """ there should be no tag relations left after deleting tags """
205
206         models.Tag.objects.all().delete()
207         self.assertEqual(len(self.book.related_themes()), 0)
208         self.assertEqual(models.Tag.intermediary_table_model.objects.all().count(), 0,
209                          "orphaned TagRelation objects left")
210
211
212 class TestIdenticalTag(WLTestCase):
213
214     def setUp(self):
215         WLTestCase.setUp(self)
216         author = PersonStub((), "Tag")
217
218         self.book_info = BookInfoStub(author=author,
219                                  genre="tag",
220                                  epoch='tag',
221                                  kind="tag",
222                                    **info_args(u"tag"))
223         self.book_text = """<utwor>
224             <opowiadanie>
225             <akap>
226                 <begin id="m01" /><motyw id="m01">tag</motyw>Ala ma kota<end id="m01" />
227             </akap>
228             </opowiadanie>
229             </utwor>
230         """
231
232
233     def test_book_tags(self):
234         """ there should be all related tags in relevant categories """
235         book = models.Book.from_text_and_meta(ContentFile(self.book_text), self.book_info)
236
237         related_themes = book.related_themes()
238         for category in 'author', 'kind', 'genre', 'epoch':
239             self.assertTrue('tag' in [tag.slug for tag in book.tags.filter(category=category)],
240                             'missing related tag for %s' % category)
241         self.assertTrue('tag' in [tag.slug for tag in related_themes])
242
243     def test_qualified_url(self):
244         models.Book.from_text_and_meta(ContentFile(self.book_text), self.book_info)
245         categories = {'author': 'autor', 'theme': 'motyw', 'epoch': 'epoka', 'kind':'rodzaj', 'genre':'gatunek'}
246         for cat, localcat in categories.iteritems():
247             context = self.client.get('/katalog/%s/tag/' % localcat).context
248             self.assertEqual(1, len(context['object_list']))
249             self.assertNotEqual({}, context['categories'])
250             self.assertFalse(context['categories'].get(cat, False))
251
252
253 class BookTagsTests(WLTestCase):
254     """ tests the /katalog/lektura/book/ page for related tags """
255
256     def setUp(self):
257         WLTestCase.setUp(self)
258         author1 = PersonStub(("Common",), "Man")
259         author2 = PersonStub(("Jim",), "Lazy")
260
261         child_info = BookInfoStub(authors=(author1, author2), genre="ChildGenre", epoch='Epoch', kind="ChildKind",
262                                    **info_args(u"Child"))
263         parent_info = BookInfoStub(author=author1, genre="Genre", epoch='Epoch', kind="Kind",
264                                    parts=[child_info.url],
265                                    **info_args(u"Parent"))
266
267         for info in child_info, parent_info:
268             book_text = """<utwor><opowiadanie><akap>
269                 <begin id="m01" />
270                     <motyw id="m01">Theme, %sTheme</motyw>
271                     Ala ma kota
272                 <end id="m01" />
273                 </akap></opowiadanie></utwor>
274                 """ % info.title.encode('utf-8')
275             models.Book.from_text_and_meta(ContentFile(book_text), info)
276
277     def test_book_tags(self):
278         """ book should have own tags and whole tree's themes """
279
280         book = models.Book.objects.get(slug='parent')
281         related_themes = book.related_themes()
282
283         self.assertEqual([t.slug for t in book.tags.filter(category='author')],
284                          ['common-man'])
285         self.assertEqual([t.slug for t in book.tags.filter(category='kind')],
286                          ['kind'])
287         self.assertEqual([(tag.name, tag.count) for tag in related_themes],
288                          [('ChildTheme', 1), ('ParentTheme', 1), ('Theme', 2)])
289
290     def test_catalogue_tags(self):
291         """ test main page tags and counts """
292         context = self.client.get('/katalog/').context
293         self.assertEqual([(tag.name, tag.count) for tag in context['categories']['author']],
294                          [('Jim Lazy', 1), ('Common Man', 1)])
295         self.assertEqual([(tag.name, tag.count) for tag in context['categories']['theme']],
296                          [('ChildTheme', 1), ('ParentTheme', 1), ('Theme', 2)])
297