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