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