1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 from base64 import b64encode
11 from unittest.mock import patch
12 from urllib.parse import quote, urlencode, parse_qs
14 from django.contrib.auth.models import User
15 from django.core.files.uploadedfile import SimpleUploadedFile
16 from django.test import TestCase
17 from django.test.utils import override_settings
19 from catalogue.models import Book, Tag
20 from picture.forms import PictureImportForm
21 from picture.models import Picture
23 from api.models import Consumer, Token
29 'BACKEND': 'django.core.cache.backends.dummy.DummyCache'}},
31 class ApiTest(TestCase):
34 def load_json(self, url):
35 content = self.client.get(url).content
37 data = json.loads(content)
39 self.fail('No JSON could be decoded: %s' % content)
42 def assert_response(self, url, name):
43 content = self.client.get(url).content.decode('utf-8').rstrip()
44 filename = path.join(path.dirname(__file__), 'res', 'responses', name)
45 with open(filename) as f:
46 good_content = f.read().rstrip()
47 self.assertEqual(content, good_content, content)
49 def assert_json_response(self, url, name):
50 data = self.load_json(url)
51 filename = path.join(path.dirname(__file__), 'res', 'responses', name)
52 with open(filename) as f:
53 good_data = json.load(f)
54 self.assertEqual(data, good_data, json.dumps(data, indent=4))
56 def assert_slugs(self, url, slugs):
57 have_slugs = [x['slug'] for x in self.load_json(url)]
58 self.assertEqual(have_slugs, slugs, have_slugs)
61 class BookTests(ApiTest):
64 self.tag = Tag.objects.create(category='author', slug='joe')
65 self.book = Book.objects.create(title='A Book', slug='a-book')
66 self.book_tagged = Book.objects.create(
67 title='Tagged Book', slug='tagged-book')
68 self.book_tagged.tags = [self.tag]
69 self.book_tagged.save()
71 def test_book_list(self):
72 books = self.load_json('/api/books/')
73 self.assertEqual(len(books), 2,
76 def test_tagged_books(self):
77 books = self.load_json('/api/authors/joe/books/')
79 self.assertEqual([b['title'] for b in books], [self.book_tagged.title],
80 'Wrong tagged book list.')
82 def test_detail(self):
83 book = self.load_json('/api/books/a-book/')
84 self.assertEqual(book['title'], self.book.title,
85 'Wrong book details.')
88 class TagTests(ApiTest):
91 self.tag = Tag.objects.create(
92 category='author', slug='joe', name='Joe')
93 self.book = Book.objects.create(title='A Book', slug='a-book')
94 self.book.tags = [self.tag]
97 def test_tag_list(self):
98 tags = self.load_json('/api/authors/')
99 self.assertEqual(len(tags), 1,
102 def test_tag_detail(self):
103 tag = self.load_json('/api/authors/joe/')
104 self.assertEqual(tag['name'], self.tag.name,
105 'Wrong tag details.')
108 class PictureTests(ApiTest):
109 def test_publish(self):
110 slug = "kandinsky-composition-viii"
112 picture.tests.__path__[0], "files", slug + ".xml"
114 xml = SimpleUploadedFile(
118 picture.tests.__path__[0], "files", slug + ".png"
120 img = SimpleUploadedFile(
124 import_form = PictureImportForm({}, {
125 'picture_xml_file': xml,
126 'picture_image_file': img
129 assert import_form.is_valid()
130 if import_form.is_valid():
133 Picture.objects.get(slug=slug)
136 class BooksTests(ApiTest):
137 fixtures = ['test-books.yaml']
139 def test_books(self):
140 self.assert_json_response('/api/books/', 'books.json')
141 self.assert_json_response('/api/books/?new_api=true', 'books.json')
142 self.assert_response('/api/books/?format=xml', 'books.xml')
144 self.assert_slugs('/api/audiobooks/', ['parent'])
145 self.assert_slugs('/api/daisy/', ['parent'])
146 self.assert_slugs('/api/newest/', ['parent'])
147 self.assert_slugs('/api/parent_books/', ['parent'])
148 self.assert_slugs('/api/recommended/', ['parent'])
151 self.assert_slugs('/api/books/after/grandchild/count/1/', ['parent'])
153 '/api/books/?new_api=true&after=$grandchild$3&count=1', ['parent'])
156 self.assert_slugs('/api/authors/john-doe/books/', ['parent'])
158 '/api/genres/sonet/books/?authors=john-doe',
160 # It is probably a mistake that this doesn't filter:
162 '/api/books/?authors=john-doe',
163 ['child', 'grandchild', 'parent'])
165 # Parent books by tag.
166 # Notice this contains a grandchild, if a child doesn't have the tag.
167 # This probably isn't really intended behavior and should be redefined.
169 '/api/genres/sonet/parent_books/',
170 ['grandchild', 'parent'])
172 def test_ebooks(self):
173 self.assert_json_response('/api/ebooks/', 'ebooks.json')
175 def test_filter_books(self):
176 self.assert_json_response('/api/filter-books/', 'filter-books.json')
178 '/api/filter-books/?lektura=false',
179 ['child', 'grandchild', 'parent'])
181 '/api/filter-books/?lektura=true',
184 Book.objects.filter(slug='grandchild').update(preview=True)
185 # Skipping: we don't allow previewed books in filtered list.
187 # '/api/filter-books/?preview=true',
190 '/api/filter-books/?preview=false',
192 Book.objects.filter(slug='grandchild').update(preview=False)
195 '/api/filter-books/?audiobook=true',
198 '/api/filter-books/?audiobook=false',
199 ['child', 'grandchild'])
201 self.assert_slugs('/api/filter-books/?genres=wiersz', ['child'])
203 self.assert_slugs('/api/filter-books/?search=parent', ['parent'])
205 def test_collections(self):
206 self.assert_json_response('/api/collections/', 'collections.json')
207 self.assert_json_response(
208 '/api/collections/a-collection/',
212 self.assert_json_response('/api/books/parent/', 'books-parent.json')
213 self.assert_json_response('/api/books/child/', 'books-child.json')
214 self.assert_json_response(
215 '/api/books/grandchild/',
216 'books-grandchild.json')
219 # List of tags by category.
220 self.assert_json_response('/api/genres/', 'tags.json')
222 def test_fragments(self):
223 # This is not supported, though it probably should be.
224 # self.assert_json_response(
225 # '/api/books/child/fragments/',
228 self.assert_json_response(
229 '/api/genres/wiersz/fragments/',
231 self.assert_json_response(
232 '/api/books/child/fragments/an-anchor/',
236 class BlogTests(ApiTest):
238 self.assertEqual(self.load_json('/api/blog'), [])
241 class OAuth1Tests(ApiTest):
244 cls.user = User.objects.create(username='test')
245 cls.user.set_password('test')
247 cls.consumer_secret = 'len(quote(consumer secret))>=32'
248 Consumer.objects.create(
250 secret=cls.consumer_secret
254 def tearDownClass(cls):
255 User.objects.all().delete()
257 def test_create_token(self):
258 # Fetch request token.
259 base_query = ("oauth_consumer_key=client&oauth_nonce=12345678&"
260 "oauth_signature_method=HMAC-SHA1&oauth_timestamp={}&"
261 "oauth_version=1.0".format(int(time())))
264 quote('http://testserver/api/oauth/request_token/', safe=''),
265 quote(base_query, safe='')
268 (quote(self.consumer_secret) + '&').encode('latin1'),
269 raw.encode('latin1'),
272 h = b64encode(h).rstrip(b'\n')
274 query = "{}&oauth_signature={}".format(base_query, sign)
275 response = self.client.get('/api/oauth/request_token/?' + query)
276 request_token_data = parse_qs(response.content.decode('latin1'))
277 request_token = request_token_data['oauth_token'][0]
278 request_token_secret = request_token_data['oauth_token_secret'][0]
280 # Request token authorization.
281 self.client.login(username='test', password='test')
282 response = self.client.get(
283 '/api/oauth/authorize/?oauth_token=%s&oauth_callback=test://oauth.callback/' % (
287 post_data = response.context['form'].initial
289 response = self.client.post('/api/oauth/authorize/?' + urlencode(post_data))
291 response['Location'],
292 'test://oauth.callback/?oauth_token=' + request_token
295 # Fetch access token.
296 base_query = ("oauth_consumer_key=client&oauth_nonce=12345678&"
297 "oauth_signature_method=HMAC-SHA1&oauth_timestamp={}&"
298 "oauth_token={}&oauth_version=1.0".format(
299 int(time()), request_token))
302 quote('http://testserver/api/oauth/access_token/', safe=''),
303 quote(base_query, safe='')
306 (quote(self.consumer_secret) + '&' +
307 quote(request_token_secret, safe='')).encode('latin1'),
308 raw.encode('latin1'),
311 h = b64encode(h).rstrip(b'\n')
313 query = "{}&oauth_signature={}".format(base_query, sign)
314 response = self.client.get('/api/oauth/access_token/?' + query)
315 access_token_data = parse_qs(response.content.decode('latin1'))
316 access_token = access_token_data['oauth_token'][0]
319 Token.objects.filter(
321 token_type=Token.ACCESS,
326 class AuthorizedTests(ApiTest):
327 fixtures = ['test-books.yaml']
331 super(AuthorizedTests, cls).setUpClass()
332 cls.user = User.objects.create(username='test')
333 cls.consumer = Consumer.objects.create(
334 key='client', secret='12345678901234567890123456789012')
335 cls.token = Token.objects.create(
336 key='123456789012345678',
337 secret='12345678901234567890123456789012',
339 consumer=cls.consumer,
340 token_type=Token.ACCESS,
342 cls.key = (cls.consumer.secret + '&' + cls.token.secret).encode('latin1')
345 def tearDownClass(cls):
347 cls.consumer.delete()
348 super(AuthorizedTests, cls).tearDownClass()
350 def signed(self, url, method='GET', params=None, data=None):
352 "oauth_consumer_key": self.consumer.key,
353 "oauth_nonce": ("%f" % time()).replace('.', ''),
354 "oauth_signature_method": "HMAC-SHA1",
355 "oauth_timestamp": int(time()),
356 "oauth_token": self.token.key,
357 "oauth_version": "1.0",
362 sign_params.update(params)
364 sign_params.update(data)
365 sign_params.update(auth_params)
368 quote('http://testserver' + url, safe=''),
370 quote(str(k), safe='') + "=" + quote(str(v), safe='')
371 for (k, v) in sorted(sign_params.items())))
373 auth_params["oauth_signature"] = quote(b64encode(hmac.new(
375 raw.encode('latin1'),
377 ).digest()).rstrip(b'\n'))
378 auth = 'OAuth realm="API", ' + ', '.join(
379 '{}="{}"'.format(k, v) for (k, v) in auth_params.items())
382 url = url + '?' + urlencode(params)
383 return getattr(self.client, method.lower())(
385 data=urlencode(data) if data else None,
386 content_type='application/x-www-form-urlencoded',
387 HTTP_AUTHORIZATION=auth,
390 def signed_json(self, url, method='GET', params=None, data=None):
391 return json.loads(self.signed(url, method, params, data).content)
393 def test_books(self):
395 [b['liked'] for b in self.signed_json('/api/books/')],
396 [False, False, False]
398 data = self.signed_json('/api/books/child/')
399 self.assertFalse(data['parent']['liked'])
400 self.assertFalse(data['children'][0]['liked'])
403 self.signed_json('/api/like/parent/'),
406 self.signed('/api/like/parent/', 'POST')
408 self.signed_json('/api/like/parent/'),
411 # There are several endpoints where 'liked' appears.
412 self.assertTrue(self.signed_json('/api/parent_books/')[0]['liked'])
413 self.assertTrue(self.signed_json(
414 '/api/filter-books/', params={"search": "parent"})[0]['liked'])
416 self.assertTrue(self.signed_json(
417 '/api/books/child/')['parent']['liked'])
418 # Liked books go on shelf.
420 [x['slug'] for x in self.signed_json('/api/shelf/likes/')],
423 self.signed('/api/like/parent/', 'POST', {"action": "unlike"})
425 self.signed_json('/api/like/parent/'),
428 self.assertFalse(self.signed_json('/api/parent_books/')[0]['liked'])
430 def test_reading(self):
432 self.signed_json('/api/reading/parent/'),
433 {"state": "not_started"}
435 self.signed('/api/reading/parent/reading/', 'post')
437 self.signed_json('/api/reading/parent/'),
441 [x['slug'] for x in self.signed_json('/api/shelf/reading/')],
444 def test_subscription(self):
445 Book.objects.filter(slug='grandchild').update(preview=True)
447 self.assert_slugs('/api/preview/', ['grandchild'])
449 self.signed_json('/api/username/'),
450 {"username": "test", "premium": False})
452 self.signed('/api/epub/grandchild/').status_code,
455 with patch('club.models.Membership.is_active_for', return_value=True):
457 self.signed_json('/api/username/'),
458 {"username": "test", "premium": True})
459 with patch('django.core.files.storage.Storage.open',
460 return_value=BytesIO(b"<epub>")):
462 self.signed('/api/epub/grandchild/').content,
465 Book.objects.filter(slug='grandchild').update(preview=False)
467 def test_publish(self):
468 response = self.signed('/api/books/',
470 data={"data": json.dumps({})})
471 self.assertEqual(response.status_code, 403)
473 response = self.signed('/api/pictures/',
475 data={"data": json.dumps({})})
476 self.assertEqual(response.status_code, 403)
478 self.user.is_superuser = True
481 with patch('catalogue.models.Book.from_xml_file') as mock:
482 response = self.signed('/api/books/',
484 data={"data": json.dumps({
485 "book_xml": "<utwor/>"
487 self.assertTrue(mock.called)
488 self.assertEqual(response.status_code, 201)
490 with patch('picture.models.Picture.from_xml_file') as mock:
491 response = self.signed('/api/pictures/',
493 data={"data": json.dumps({
494 "picture_xml": "<utwor/>",
495 "picture_image_data": "Kg==",
497 self.assertTrue(mock.called)
498 self.assertEqual(response.status_code, 201)
500 self.user.is_superuser = False