pep8 and other code-style changes
[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}, {}, 'tags related to empty tag')
108
109     def test_has_related(self):
110         """ related own and descendants' tags should be generated """
111
112         cats = self.client.get('/katalog/rodzaj/kind/').context['categories']
113         self.assertTrue('Common Man' in [tag.name for tag in cats['author']],
114                         'missing `author` related tag')
115         self.assertTrue('Epoch' in [tag.name for tag in cats['epoch']],
116                         'missing `epoch` related tag')
117         self.assertFalse(cats.get("kind", False),
118                          "There should be no child-only related `kind` tags")
119         self.assertTrue("Genre" in [tag.name for tag in cats['genre']],
120                         'missing `genre` related tag')
121         self.assertFalse("ChildGenre" in [tag.name for tag in cats['genre']],
122                          "There should be no child-only related `genre` tags")
123         self.assertTrue("GchildGenre" in [tag.name for tag in cats['genre']],
124                         "missing grandchild's related tag")
125         self.assertTrue('Theme' in [tag.name for tag in cats['theme']],
126                         "missing related theme")
127         self.assertFalse('Child1Theme' in [tag.name for tag in cats['theme']],
128                          "There should be no child-only related `theme` tags")
129         self.assertTrue('GChildTheme' in [tag.name for tag in cats['theme']],
130                         "missing grandchild's related theme")
131
132     def test_related_differ(self):
133         """ related tags shouldn't include filtering tags """
134
135         response = self.client.get('/katalog/rodzaj/kind/')
136         cats = response.context['categories']
137         self.assertFalse(cats.get('kind', False),
138                          'filtering tag wrongly included in related')
139         cats = self.client.get('/katalog/motyw/theme/').context['categories']
140         self.assertFalse('Theme' in [tag.name for tag in cats['theme']],
141                          'filtering theme wrongly included in related')
142
143     def test_parent_tag_once(self):
144         """ if parent and descendants have a common tag, count it only once """
145
146         cats = self.client.get('/katalog/rodzaj/kind/').context['categories']
147         self.assertEqual([(tag.name, tag.count) for tag in cats['epoch']],
148                          [('Epoch', 1)],
149                          'wrong related tag epoch tag on tag page')
150
151     def test_siblings_tags_count(self):
152         """ if children have tags and parent hasn't, count the children """
153
154         cats = self.client.get('/katalog/epoka/epoch/').context['categories']
155         self.assertTrue(
156             ('ChildKind', 2) in [(tag.name, tag.count) for tag in cats['kind']],
157             'wrong related kind tags on tag page, got: ' +
158             unicode([(tag.name, tag.count) for tag in cats['kind']]))
159
160         # all occurencies of theme should be counted
161         self.assertTrue(('Theme', 4) in [(tag.name, tag.count) for tag in cats['theme']],
162                         'wrong related theme count')
163
164     def test_query_child_tag(self):
165         """
166         If child and parent have a common tag, but parent isn't included
167         in the result, child should still count.
168         """
169         cats = self.client.get('/katalog/gatunek/childgenre/').context['categories']
170         self.assertTrue(('Epoch', 2) in [(tag.name, tag.count) for tag in cats['epoch']],
171                         'wrong related kind tags on tag page, got: ' +
172                         unicode([(tag.name, tag.count) for tag in cats['epoch']]))
173
174
175 class CleanTagRelationTests(WLTestCase):
176     """ tests for tag relations cleaning after deleting things """
177
178     def setUp(self):
179         WLTestCase.setUp(self)
180         author = PersonStub(("Common",), "Man")
181
182         book_info = BookInfoStub(author=author, genre="G", epoch='E', kind="K", **info_args(u"Book"))
183         book_text = """<utwor><opowiadanie><akap>
184             <begin id="m01" /><motyw id="m01">Theme</motyw>Ala ma kota
185             <end id="m01" />
186             </akap></opowiadanie></utwor>
187             """
188         self.book = models.Book.from_text_and_meta(ContentFile(book_text), book_info)
189
190     def test_delete_objects(self):
191         """ there should be no related tags left after deleting some objects """
192
193         models.Book.objects.all().delete()
194         cats = self.client.get('/katalog/rodzaj/k/').context['categories']
195         self.assertEqual({k: v for (k, v) in cats.items() if v}, {})
196         self.assertEqual(models.Fragment.objects.all().count(), 0,
197                          "orphaned fragments left")
198         self.assertEqual(models.Tag.intermediary_table_model.objects.all().count(), 0,
199                          "orphaned TagRelation objects left")
200
201     def test_deleted_tag(self):
202         """ there should be no tag relations left after deleting tags """
203
204         models.Tag.objects.all().delete()
205         self.assertEqual(len(self.book.related_themes()), 0)
206         self.assertEqual(models.Tag.intermediary_table_model.objects.all().count(), 0,
207                          "orphaned TagRelation objects left")
208
209
210 class TestIdenticalTag(WLTestCase):
211
212     def setUp(self):
213         WLTestCase.setUp(self)
214         author = PersonStub((), "Tag")
215
216         self.book_info = BookInfoStub(author=author, genre="tag", epoch='tag', kind="tag", **info_args(u"tag"))
217         self.book_text = """<utwor>
218             <opowiadanie>
219             <akap>
220                 <begin id="m01" /><motyw id="m01">tag</motyw>Ala ma kota<end id="m01" />
221             </akap>
222             </opowiadanie>
223             </utwor>
224         """
225
226     def test_book_tags(self):
227         """ there should be all related tags in relevant categories """
228         book = models.Book.from_text_and_meta(ContentFile(self.book_text), self.book_info)
229
230         related_themes = book.related_themes()
231         for category in 'author', 'kind', 'genre', 'epoch':
232             self.assertTrue('tag' in [tag.slug for tag in book.tags.filter(category=category)],
233                             'missing related tag for %s' % category)
234         self.assertTrue('tag' in [tag.slug for tag in related_themes])
235
236     def test_qualified_url(self):
237         models.Book.from_text_and_meta(ContentFile(self.book_text), self.book_info)
238         categories = {'author': 'autor', 'theme': 'motyw', 'epoch': 'epoka', 'kind': 'rodzaj', 'genre': 'gatunek'}
239         for cat, localcat in categories.iteritems():
240             context = self.client.get('/katalog/%s/tag/' % localcat).context
241             self.assertEqual(1, len(context['object_list']))
242             self.assertNotEqual({}, context['categories'])
243             self.assertFalse(context['categories'].get(cat, False))
244
245
246 class BookTagsTests(WLTestCase):
247     """ tests the /katalog/lektura/book/ page for related tags """
248
249     def setUp(self):
250         WLTestCase.setUp(self)
251         author1 = PersonStub(("Common",), "Man")
252         author2 = PersonStub(("Jim",), "Lazy")
253
254         child_info = BookInfoStub(authors=(author1, author2), genre="ChildGenre", epoch='Epoch', kind="ChildKind",
255                                   **info_args(u"Child"))
256         parent_info = BookInfoStub(author=author1, genre="Genre", epoch='Epoch', kind="Kind",
257                                    parts=[child_info.url],
258                                    **info_args(u"Parent"))
259
260         for info in child_info, parent_info:
261             book_text = """<utwor><opowiadanie><akap>
262                 <begin id="m01" />
263                     <motyw id="m01">Theme, %sTheme</motyw>
264                     Ala ma kota
265                 <end id="m01" />
266                 </akap></opowiadanie></utwor>
267                 """ % info.title.encode('utf-8')
268             models.Book.from_text_and_meta(ContentFile(book_text), info)
269
270     def test_book_tags(self):
271         """ book should have own tags and whole tree's themes """
272
273         book = models.Book.objects.get(slug='parent')
274         related_themes = book.related_themes()
275
276         self.assertEqual([t.slug for t in book.tags.filter(category='author')],
277                          ['common-man'])
278         self.assertEqual([t.slug for t in book.tags.filter(category='kind')],
279                          ['kind'])
280         self.assertEqual([(tag.name, tag.count) for tag in related_themes],
281                          [('ChildTheme', 1), ('ParentTheme', 1), ('Theme', 2)])