Dodanie biblioteki vstorage (pierwszy commit zmierzajÄ…cy do uliniowienia historii...
[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
23         @wraps(func)
24         def decorated(self, *args, **kwargs):
25             clean = False
26             try:
27                 temp = tempfile.mkdtemp("-test", func.__name__)
28                 shutil.copytree(join(REPO_TEMPLATES, name), join(temp, 'repo'), False)
29                 settings.REPOSITORY_PATH = join(temp, 'repo')
30                 func(self, *args, **kwargs)
31                 clean = True
32             finally:
33                 if not clean and self.response:
34                     print "RESULT", func.__name__, ">>>"
35                     print self.response.content
36                     print "<<<"
37                 else:
38                     shutil.rmtree(temp, True)
39                 
40                 settings.REPOSITORY_PATH = ''
41            
42         return decorated
43     return decorator   
44     
45
46 class SimpleTest(TestCase):
47
48     def setUp(self):
49         self.response = None
50         u = User.objects.create_user('admin', 'test@localhost', 'admin')
51         u.save()        
52
53     @temprepo('clean')
54     def test_documents_get_anonymous(self):
55         self.response = self.client.get( reverse("document_list_view") )
56         self.assert_json_response({            
57             u'documents': [],            
58         })
59
60     @temprepo('clean')
61     def test_documents_get_with_login(self):
62         self.assertTrue(self.client.login(username='admin', password='admin'))
63         
64         self.response = self.client.get( reverse("document_list_view") )
65         self.assert_json_response({                        
66             u'documents': [],            
67         })    
68     
69     @temprepo('clean')
70     def test_document_creation(self):
71         self.assertTrue(self.client.login(username='admin', password='admin'))
72
73         infile = tempfile.NamedTemporaryFile("w+")
74         infile.write('012340123456789')
75         infile.flush()
76         infile.seek(0)
77
78         self.response = self.client.post( reverse("document_list_view"),
79         data = {
80              'bookname': 'testbook',
81              'ocr_file': infile,
82              'generate_dc': False,
83         })
84
85         r = self.assert_json_response( {
86             'url': reverse('document_view', args=['testbook']),
87             'name': 'testbook',            
88             # can't test revision number, 'cause it's random
89         }, code=201)
90
91         created_rev = r['revision']
92         self.response = self.client.get(r['url'])
93         
94         result = self.assert_json_response({
95             u'public_revision': created_rev,
96             # u'size': 15,
97         })
98
99
100     @temprepo('simple')
101     def test_document_meta_get_with_login(self):
102         self.assertTrue(self.client.login(username='admin', password='admin'))
103
104         self.response = self.client.get( reverse("document_list_view") )
105         self.assert_json_response({
106             # u'latest_rev': u'f94a263812dbe46a3a13d5209bb119988d0078d5',
107             u'documents': [
108                 {u'url': u'/api/documents/sample', u'name': u'sample', u'parts': []},
109                 {u'url': u'/api/documents/sample_pl', u'name': u'sample_pl', u'parts': []}
110             ],
111         })
112
113         self.response = self.client.get( \
114             reverse("document_view", args=['sample']) )
115
116         self.assert_json_response({
117             #u'latest_shared_rev': u'f94a263812dbe46a3a13d5209bb119988d0078d5',
118             #u'text_url': reverse("doctext_view", args=[u'sample']),
119             #u'dc_url': reverse("docdc_view", args=[u'sample']),
120             # u'parts_url': reverse("docparts_view", args=[u'sample']),
121             u'name': u'sample',
122             # u'size': 20,
123         })
124
125
126     @temprepo('simple')
127     def test_document_text_with_login(self):
128         self.assertTrue(self.client.login(username='admin', password='admin'))
129
130         self.response = self.client.get( \
131             reverse("document_view", args=['sample']) )
132
133         resp = self.assert_json_response({
134             #u'latest_shared_rev': u'f94a263812dbe46a3a13d5209bb119988d0078d5',
135             #u'text_url': reverse("doctext_view", args=[u'sample']),
136             #u'dc_url': reverse("docdc_view", args=[u'sample']),
137             # u'parts_url': reverse("docparts_view", args=[u'sample']),
138             u'name': u'sample',
139             # u'size': 20,
140         })
141
142         self.response = self.client.get(resp['text_url'])
143         self.assertEqual(self.response.status_code, 200)
144         self.assertEqual(self.response.content, "Ala ma kota\n")
145
146
147     @temprepo('simple')
148     def test_document_text_save(self):
149         self.assertTrue(self.client.login(username='admin', password='admin'))
150         TEXT = u"Ala ma kota i psa"
151
152         self.response = self.client.get(
153             reverse("document_view", args=['sample']) )
154             
155         resp = self.assert_json_response()
156
157         self.response = self.client.post(resp['text_url'], {
158             'revision': resp['user_revision'] ,'contents': TEXT })
159         result = self.assert_json_response(must_have={u'document': u'sample'} )
160         
161         #self.response = self.client.get(result['url'])
162         #self.assertEqual(self.response.content, TEXT)
163
164     def assert_json_response(self, must_have={}, exclude=[], code=200):
165         self.assertEqual(self.response.status_code, code)        
166         result = json.loads(self.response.content)
167
168         for (k,v) in must_have.items():
169             self.assertTrue(result.has_key(k), "Required field '%s' missing in response." % k)
170             self.assertEqual(result[k], v)
171
172         if exclude is True:
173             for (k,v) in result.items():
174                 self.assertTrue(must_have.has_key(k))
175                 self.assertEqual(must_have[k], v)
176
177         for key in exclude:
178             self.assertFalse(result.has_key(key))
179             
180         return result   
181