Fundraising in PDF.
[wolnelektury.git] / src / catalogue / test_utils.py
1 # This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
3 #
4 from os.path import abspath, dirname, join
5 import tempfile
6 from traceback import extract_stack
7 from django.conf import settings
8 from django.test import TestCase
9 from django.test.utils import override_settings
10 from slugify import slugify
11 from librarian import WLURI
12
13
14 @override_settings(
15     MEDIA_ROOT=tempfile.mkdtemp(prefix='djangotest_'),
16     CATALOGUE_DONT_BUILD={'pdf', 'mobi', 'epub', 'txt', 'fb2', 'cover'},
17     NO_SEARCH_INDEX=True,
18     CELERY_TASK_ALWAYS_EAGER=True,
19     CACHES={
20         'default': {'BACKEND': 'django.core.cache.backends.dummy.DummyCache'},
21     },
22 )
23 class WLTestCase(TestCase):
24     """
25         Generic base class for tests. Adds settings freeze and clears MEDIA_ROOT.
26     """
27     longMessage = True
28
29
30 class PersonStub:
31
32     def __init__(self, first_names, last_name):
33         self.first_names = first_names
34         self.last_name = last_name
35
36     def readable(self):
37         return " ".join(self.first_names + (self.last_name,))
38
39
40 class BookInfoStub:
41     _empty_fields = ['cover_url', 'variant_of']
42     # allow single definition for multiple-value fields
43     _salias = {
44         'authors': 'author',
45     }
46
47     def __init__(self, **kwargs):
48         self.__dict = kwargs
49
50     def __setattr__(self, key, value):
51         if not key.startswith('_'):
52             self.__dict[key] = value
53         return object.__setattr__(self, key, value)
54
55     def __getattr__(self, key):
56         try:
57             return self.__dict[key]
58         except KeyError as e:
59             if key in self._empty_fields:
60                 return None
61             if key in self._salias:
62                 return [getattr(self, self._salias[key])]
63             raise AttributeError(e)
64
65     def to_dict(self):
66         return dict((key, str(value)) for key, value in self.__dict.items())
67
68
69 def info_args(title, language=None):
70     """ generate some keywords for comfortable BookInfoCreation  """
71     slug = str(slugify(title))
72     if language is None:
73         language = 'pol'
74     return {
75         'title': str(title),
76         'url': WLURI(slug),
77         'about': "http://wolnelektury.pl/example/URI/%s" % slug,
78         'language': language,
79     }
80
81
82 def get_fixture(path, app=None):
83     if app is not None:
84         mod_path = app.__file__
85         f_path = join(dirname(abspath(mod_path)), 'tests/files', path)
86     else:
87         mod_path = extract_stack(limit=2)[0][0]
88         f_path = join(dirname(abspath(mod_path)), 'files', path)
89     return f_path
90
91
92 def get_mp3_length(path):
93     return 60