acf92f5ca943d7724df01b8d5d2a5f49cddd3e9b
[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_document_creation(self):
69         self.assertTrue(self.client.login(username='admin', password='admin'))
70
71         infile = tempfile.NamedTemporaryFile("w+")
72         infile.write('012340123456789')
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_file': infile,
80              'generate_dc': False,
81         })
82
83         r = self.assert_json_response( {
84             'url': reverse('document_view', args=['testbook']),
85             'name': 'testbook',            
86             # can't test revision number, 'cause it's random
87         }, code=201)
88
89         created_rev = r['revision']
90         self.response = self.client.get(r['url'])
91         
92         result = self.assert_json_response({
93             u'public_revision': created_rev,
94             # u'size': 15,
95         })
96
97
98     @temprepo('simple')
99     def test_document_meta_get_with_login(self):
100         self.assertTrue(self.client.login(username='admin', password='admin'))
101
102         self.response = self.client.get( reverse("document_list_view") )
103         self.assert_json_response({
104             # u'latest_rev': u'f94a263812dbe46a3a13d5209bb119988d0078d5',
105             u'documents': [
106                 {u'url': u'/api/documents/sample', u'name': u'sample'},
107                 {u'url': u'/api/documents/sample_pl', u'name': u'sample_pl'}
108             ],
109         })
110
111         self.response = self.client.get( \
112             reverse("document_view", args=['sample']) )
113
114         self.assert_json_response({
115             #u'latest_shared_rev': u'f94a263812dbe46a3a13d5209bb119988d0078d5',
116             #u'text_url': reverse("doctext_view", args=[u'sample']),
117             #u'dc_url': reverse("docdc_view", args=[u'sample']),
118             # u'parts_url': reverse("docparts_view", args=[u'sample']),
119             u'name': u'sample',
120             # u'size': 20,
121         })
122
123
124     @temprepo('simple')
125     def test_document_text_with_login(self):
126         self.assertTrue(self.client.login(username='admin', password='admin'))
127
128         self.response = self.client.get( \
129             reverse("document_view", args=['sample']) )
130
131         resp = self.assert_json_response({
132             #u'latest_shared_rev': u'f94a263812dbe46a3a13d5209bb119988d0078d5',
133             #u'text_url': reverse("doctext_view", args=[u'sample']),
134             #u'dc_url': reverse("docdc_view", args=[u'sample']),
135             # u'parts_url': reverse("docparts_view", args=[u'sample']),
136             u'name': u'sample',
137             # u'size': 20,
138         })
139
140         self.response = self.client.get(resp['text_url'])
141         self.assertEqual(self.response.status_code, 200)
142         self.assertEqual(self.response.content, "Ala ma kota\n")
143 #
144 #
145 #    @temprepo('simple')
146 #    def test_document_text_update(self):
147 #        self.assertTrue(self.client.login(username='admin', password='admin'))
148 #        TEXT = u"Ala ma kota i psa"
149 #
150 #        self.response = self.client.put( \
151 #            reverse("doctext_view", args=['testfile']), {'contents': TEXT })
152 #        self.assertEqual(self.response.status_code, 200)
153 #
154 #        self.response = self.client.get( \
155 #            reverse("doctext_view", args=['testfile']) )
156 #        self.assertEqual(self.response.status_code, 200)
157 #        self.assertEqual(self.response.content, TEXT)
158
159     def assert_json_response(self, must_have={}, exclude=[], code=200):
160         self.assertEqual(self.response.status_code, code)
161         result = json.loads(self.response.content)
162
163         for (k,v) in must_have.items():
164             self.assertTrue(result.has_key(k), "Required field '%s' missing in response." % k)
165             self.assertEqual(result[k], v)
166
167         if exclude is True:
168             for (k,v) in result.items():
169                 self.assertTrue(must_have.has_key(k))
170                 self.assertEqual(must_have[k], v)
171
172         for key in exclude:
173             self.assertFalse(result.has_key(key))
174             
175         return result   
176