Merge branch 'master' of https://github.com/fnp/wolnelektury
[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_SEARCH_INDEX = 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._CACHES, settings.CACHES = settings.CACHES, {
17             'default': {
18                 'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
19             }
20         }
21
22     def tearDown(self):
23         shutil.rmtree(settings.MEDIA_ROOT, True)
24         settings.MEDIA_ROOT = self._MEDIA_ROOT
25         settings.CACHES = self._CACHES
26
27 class PersonStub(object):
28
29     def __init__(self, first_names, last_name):
30         self.first_names = first_names
31         self.last_name = last_name
32
33     def readable(self):
34         return " ".join(self.first_names + (self.last_name,))
35
36
37 class BookInfoStub(object):
38     _empty_fields = ['cover_url', 'variant_of']
39     # allow single definition for multiple-value fields
40     _salias = {
41         'authors': 'author',
42     }
43
44     def __init__(self, **kwargs):
45         self.__dict = kwargs
46
47     def __setattr__(self, key, value):
48         if not key.startswith('_'):
49             self.__dict[key] = value
50         return object.__setattr__(self, key, value)
51
52     def __getattr__(self, key):
53         try:
54             return self.__dict[key]
55         except KeyError:
56             if key in self._empty_fields:
57                 return None
58             elif key in self._salias:
59                 return [getattr(self, self._salias[key])]
60             else:
61                 raise
62
63     def to_dict(self):
64         return dict((key, unicode(value)) for key, value in self.__dict.items())
65
66
67 def info_args(title, language=None):
68     """ generate some keywords for comfortable BookInfoCreation  """
69     slug = unicode(slughifi(title))
70     if language is None:
71         language = u'pol'
72     return {
73         'title': unicode(title),
74         'url': WLURI.from_slug(slug),
75         'about': u"http://wolnelektury.pl/example/URI/%s" % slug,
76         'language': language,
77     }