2292e7dd9a51707d71dc52fcbdf43ab0cde0200a
[redakcja.git] / apps / api / tests / __init__.py
1 from django.test import TestCase
2 from django.test.client import Client
3 from django.core.urlresolvers import reverse
4
5 from django.utils import simplejson as json
6
7 from django.contrib.auth.models import User
8
9 import settings
10 from os.path import join, dirname
11 from StringIO import StringIO
12 import shutil
13 import tempfile
14
15 REPO_TEMPLATES = join(dirname(__file__), 'data')
16
17 def temprepo(name):
18     from functools import wraps
19
20     def decorator(func):
21
22         @wraps(func)
23         def decorated(self, *args, **kwargs):
24             clean = False
25             try:
26                 temp = tempfile.mkdtemp("-test", func.__name__)
27                 shutil.copytree(join(REPO_TEMPLATES, name), join(temp, 'repo'), False)
28                 settings.REPOSITORY_PATH = join(temp, 'repo')
29                 func(self, *args, **kwargs)
30                 clean = True
31             finally:
32                 if not clean and self.response:
33                     print "RESULT", func.__name__, ">>>"
34                     print self.response
35                     print "<<<"
36
37                 # shutil.rmtree(temp, True)
38                 settings.REPOSITORY_PATH = ''
39            
40         return decorated
41     return decorator   
42     
43
44 class SimpleTest(TestCase):
45
46     def setUp(self):
47         self.response = None
48         u = User.objects.create_user('admin', 'test@localhost', 'admin')
49         u.save()        
50
51     @temprepo('clean')
52     def test_documents_get_anonymous(self):
53         self.response = self.client.get( reverse("document_list_view") )
54         self.assert_json_response({            
55             u'documents': [],            
56         })
57
58     @temprepo('clean')
59     def test_documents_get_with_login(self):
60         self.assertTrue(self.client.login(username='admin', password='admin'))
61         
62         self.response = self.client.get( reverse("document_list_view") )
63         self.assert_json_response({                        
64             u'documents': [],            
65         })    
66
67     @temprepo('clean')
68     def test_documents_post(self):
69         self.assertTrue(self.client.login(username='admin', password='admin'))
70
71         infile = tempfile.NamedTemporaryFile("w+")
72         infile.write('0123456789')
73         infile.flush()
74         infile.seek(0)
75
76         self.response = self.client.post( reverse("document_list_view"),
77         data = {
78              'bookname': 'testbook',
79              'ocr': infile,
80              'generate_dc': False,
81         })
82
83         infile.close()
84
85         self.assert_json_response({
86             'url': reverse('document_view', args=['testbook']),
87             'name': 'testbook',
88             # 'size': 10,
89             # can't test revision number, 'cause it's random
90         },)
91
92     @temprepo('clean')
93     def test_document_creation(self):
94         self.assertTrue(self.client.login(username='admin', password='admin'))
95
96         infile = tempfile.NamedTemporaryFile("w+")
97         infile.write('012340123456789')
98         infile.flush()
99         infile.seek(0)
100
101         self.response = self.client.post( reverse("document_list_view"),
102         data = {
103              'bookname': 'testbook',
104              'ocr': infile,
105              'generate_dc': False,
106         })
107
108         r = self.assert_json_response({
109             'url': reverse('document_view', args=['testbook']),
110             'name': 'testbook',            
111             # can't test revision number, 'cause it's random
112         })
113
114         created_rev = r['revision']
115
116         self.response = self.client.get( \
117             reverse("document_view", args=["testbook"]) )
118
119         result = self.assert_json_response({
120             u'latest_shared_rev': created_rev,
121             # u'size': 15,
122         })
123
124
125     @temprepo('simple')
126     def test_document_meta_get_with_login(self):
127         self.assertTrue(self.client.login(username='admin', password='admin'))
128
129         self.response = self.client.get( reverse("document_list_view") )
130         self.assert_json_response({
131             # u'latest_rev': u'f94a263812dbe46a3a13d5209bb119988d0078d5',
132             u'documents': [{u'url': u'/api/documents/sample', u'name': u'sample'},
133                 {u'url': u'/api/documents/sample_pl', u'name': u'sample_pl'}],
134         })
135
136         self.response = self.client.get( \
137             reverse("document_view", args=['sample']) )
138
139         self.assert_json_response({
140             #u'latest_shared_rev': u'f94a263812dbe46a3a13d5209bb119988d0078d5',
141             u'text_url': reverse("doctext_view", args=[u'sample']),
142             u'dc_url': reverse("docdc_view", args=[u'sample']),
143             # u'parts_url': reverse("docparts_view", args=[u'sample']),
144             u'name': u'sample',
145             # u'size': 20,
146         })
147
148
149     @temprepo('simple')
150     def test_document_text_with_login(self):
151         self.assertTrue(self.client.login(username='admin', password='admin'))
152
153         self.response = self.client.get( \
154             reverse("document_view", args=['sample']) )
155
156         resp = self.assert_json_response({
157             #u'latest_shared_rev': u'f94a263812dbe46a3a13d5209bb119988d0078d5',
158             u'text_url': reverse("doctext_view", args=[u'sample']),
159             u'dc_url': reverse("docdc_view", args=[u'sample']),
160             # u'parts_url': reverse("docparts_view", args=[u'sample']),
161             u'name': u'sample',
162             # u'size': 20,
163         })
164
165         self.response = self.client.get(resp['text_url'])
166         self.assertEqual(self.response.status_code, 200)
167         self.assertEqual(self.response.content, "Ala ma kota\n")
168 #
169 #
170 #    @temprepo('simple')
171 #    def test_document_text_update(self):
172 #        self.assertTrue(self.client.login(username='admin', password='admin'))
173 #        TEXT = u"Ala ma kota i psa"
174 #
175 #        self.response = self.client.put( \
176 #            reverse("doctext_view", args=['testfile']), {'contents': TEXT })
177 #        self.assertEqual(self.response.status_code, 200)
178 #
179 #        self.response = self.client.get( \
180 #            reverse("doctext_view", args=['testfile']) )
181 #        self.assertEqual(self.response.status_code, 200)
182 #        self.assertEqual(self.response.content, TEXT)
183
184     def assert_json_response(self, must_have={}, exclude=[]):
185         self.assertEqual(self.response.status_code, 200)
186         result = json.loads(self.response.content)
187
188         for (k,v) in must_have.items():
189             self.assertTrue(result.has_key(k), "Required field '%s' missing in response." % k)
190             self.assertEqual(result[k], v)
191
192         if exclude is True:
193             for (k,v) in result.items():
194                 self.assertTrue(must_have.has_key(k))
195                 self.assertEqual(must_have[k], v)
196
197         for key in exclude:
198             self.assertFalse(result.has_key(key))
199             
200         return result   
201