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