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