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