eeda03f04303018ff9c4737faf774f59cf5d434c
[wolnelektury.git] / apps / catalogue / test_utils.py
1 from django.conf import settings
2 from django.test import TestCase
3 import shutil
4 import tempfile
5 from slughifi import slughifi
6 from librarian import WLURI
7
8 class WLTestCase(TestCase):
9     """
10         Generic base class for tests. Adds settings freeze and clears MEDIA_ROOT.
11     """
12     def setUp(self):
13         self._MEDIA_ROOT, settings.MEDIA_ROOT = settings.MEDIA_ROOT, tempfile.mkdtemp(prefix='djangotest_')
14         settings.NO_BUILD_PDF = settings.NO_BUILD_MOBI = settings.NO_BUILD_EPUB = settings.NO_BUILD_TXT = True
15         settings.CELERY_ALWAYS_EAGER = True
16         self._CACHE_BACKEND, settings.CACHE_BACKEND = settings.CACHE_BACKEND, 'dummy://'
17
18     def tearDown(self):
19         shutil.rmtree(settings.MEDIA_ROOT, True)
20         settings.MEDIA_ROOT = self._MEDIA_ROOT
21         settings.CACHE_BACKEND = self._CACHE_BACKEND
22
23 class PersonStub(object):
24
25     def __init__(self, first_names, last_name):
26         self.first_names = first_names
27         self.last_name = last_name
28
29     def readable(self):
30         return " ".join(self.first_names + (self.last_name,))
31
32
33 class BookInfoStub(object):
34     _empty_fields = ['cover_url', 'variant_of']
35     # allow single definition for multiple-value fields
36     _salias = {
37         'authors': 'author',
38     }
39
40     def __init__(self, **kwargs):
41         self.__dict = kwargs
42
43     def __setattr__(self, key, value):
44         if not key.startswith('_'):
45             self.__dict[key] = value
46         return object.__setattr__(self, key, value)
47
48     def __getattr__(self, key):
49         try:
50             return self.__dict[key]
51         except KeyError:
52             if key in self._empty_fields:
53                 return None
54             elif key in self._salias:
55                 return [getattr(self, self._salias[key])]
56             else:
57                 raise
58
59     def to_dict(self):
60         return dict((key, unicode(value)) for key, value in self.__dict.items())
61
62
63 def info_args(title, language=None):
64     """ generate some keywords for comfortable BookInfoCreation  """
65     slug = unicode(slughifi(title))
66     if language is None:
67         language = u'pol'
68     return {
69         'title': unicode(title),
70         'url': WLURI.from_slug(slug),
71         'about': u"http://wolnelektury.pl/example/URI/%s" % slug,
72         'language': language,
73     }