views.py 17.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/usr/bin/env python
#coding=utf8

# Copyright 2011-2013 GRNET S.A. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
#   1. Redistributions of source code must retain the above
#      copyright notice, this list of conditions and the following
#      disclaimer.
#
#   2. Redistributions in binary form must reproduce the above
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials
#      provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.

from pithos.api import settings as pithos_settings
from pithos.api.test import PithosAPITest, DATE_FORMATS
from pithos.api.test.util import (md5_hash, get_random_data, get_random_name)
from pithos.api.test.objects import merkle

from synnefo.lib.services import get_service_path
from synnefo.lib import join_urls

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
45
#from mock import patch
46
47
48
49
50
51
52
53
from urllib import quote

import django.utils.simplejson as json

import re
import datetime
import time as _time
import random
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
54
55
import urllib
import urlparse
56
57


Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
58
59
60
61
62
63
64
65
66
def add_url_params(url, **kwargs):
    if not kwargs:
        return url
    parts = list(urlparse.urlsplit(url))
    params = dict(urlparse.parse_qsl(parts[3], keep_blank_values=True))
    params.update(kwargs)
    parts[3] = urllib.urlencode(params)
    return urlparse.urlunsplit(parts)

67

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
68
class NotAllowedView(PithosAPITest):
69
70
71
72
73
74
75
    def test_not_allowed(self):
        self.view_path = join_urls(get_service_path(
            pithos_settings.pithos_services, 'pithos_ui'), 'view')
        self.view_url = join_urls(self.view_path, self.user, get_random_name(),
                                  get_random_name())

        r = self.delete(self.view_url)
76
77
78
        self.assertEqual(r.status_code, 405)
        self.assertTrue('Allow' in r)
        self.assertEqual(r['Allow'],  'GET')
79
80

        r = self.post(self.view_url)
81
82
83
        self.assertEqual(r.status_code, 405)
        self.assertTrue('Allow' in r)
        self.assertEqual(r['Allow'],  'GET')
84
85

        r = self.put(self.view_url)
86
87
88
        self.assertEqual(r.status_code, 405)
        self.assertTrue('Allow' in r)
        self.assertEqual(r['Allow'],  'GET')
89
90

        r = self.copy(self.view_url)
91
92
93
        self.assertEqual(r.status_code, 405)
        self.assertTrue('Allow' in r)
        self.assertEqual(r['Allow'],  'GET')
94
95

        r = self.move(self.view_url)
96
97
98
        self.assertEqual(r.status_code, 405)
        self.assertTrue('Allow' in r)
        self.assertEqual(r['Allow'],  'GET')
99
100


101
102
103
104
105
106
107
108
109
110
111
112
113
class ObjectGetView(PithosAPITest):
    def setUp(self):
        PithosAPITest.setUp(self)
        self.cname = self.create_container()[0]
        self.oname, self.odata = self.upload_object(self.cname)[:-1]

        self.view_path = join_urls(get_service_path(
            pithos_settings.pithos_services, 'pithos_ui'), 'view')
        self.view_url = join_urls(self.view_path, self.user, self.cname,
                                  self.oname)
        self.api_url = join_urls(self.pithos_path, self.user, self.cname,
                                 self.oname)

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
114
115
116
117
118
119
120
121
    def view(self, url, access_token='valid_token', user='user', *args,
             **kwargs):

        params = {}
        if access_token is not None:
            params['access_token'] = access_token
        return self.get(add_url_params(url, **params), user, *args,
                        **kwargs)
122

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
123
124
    def test_no_authorization_granted(self):
        r = self.get(self.view_url)
125
126
        self.assertEqual(r.status_code, 302)
        self.assertTrue('Location' in r)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
127
128
        p = urlparse.urlparse(r['Location'])
        self.assertEqual(p.netloc, 'testserver')
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
129
        self.assertEqual(p.path, '/astakos/oauth2/auth')
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175

        r = self.get(add_url_params(self.view_url, code='valid_code'),
                     follow=True)
        self.assertEqual(r.status_code, 200)
        self.assertTrue(r.content, self.odata)
        intermidiate_url = r.redirect_chain[0][0]
        p = urlparse.urlparse(intermidiate_url)
        params = urlparse.parse_qs(p.query)
        self.assertTrue('access_token' in params)

        r = self.get(add_url_params(self.view_url, access_token='valid_token'))
        self.assertEqual(r.status_code, 200)
        self.assertTrue(r.content, self.odata)

    def test_forbidden(self):
        container = self.create_container(user='alice')[0]
        obj = self.upload_object(container, user='alice')[0]

        url = join_urls(self.view_path, 'alice', container, obj)
        r = self.view(url)
        self.assertEqual(r.status_code, 403)

    def test_shared_with_me(self):
        container = self.create_container(user='alice')[0]
        obj, data = self.upload_object(container, user='alice')[:-1]

        # share object
        url = join_urls(self.pithos_path, 'alice', container, obj)
        self.post(url, user='alice', content_type='',
                  HTTP_CONTENT_RANGE='bytes */*',
                  HTTP_X_OBJECT_SHARING='read=user')

        url = join_urls(self.view_path, 'alice', container, obj)
        r = self.view(url)
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.content, data)

    def test_view(self):
        r = self.view(self.view_url)
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.content, self.odata)

    def test_not_existing(self):
        url = self.view_url[:-1]
        r = self.view(url)
        self.assertEqual(r.status_code, 404)
176
177
178
179
180
181
182
183
184

    def test_versions(self):
        c = self.cname
        o = self.oname

        meta = {'HTTP_X_OBJECT_META_QUALITY': 'AAA'}
        r = self.post(self.api_url, content_type='', **meta)
        self.assertEqual(r.status_code, 202)

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
185
        r = self.view('%s?version=list&format=json' % self.view_url)
186
187
188
189
190
191
192
193
194
195
196
        self.assertEqual(r.status_code, 200)
        l1 = json.loads(r.content)['versions']
        self.assertEqual(len(l1), 2)

        # update meta
        meta = {'HTTP_X_OBJECT_META_QUALITY': 'AB',
                'HTTP_X_OBJECT_META_STOCK': 'True'}
        r = self.post(self.api_url, content_type='', **meta)
        self.assertEqual(r.status_code, 202)

        # assert a newly created version has been created
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
197
        r = self.view('%s?version=list&format=json' % self.view_url)
198
199
200
201
202
203
204
        self.assertEqual(r.status_code, 200)
        l2 = json.loads(r.content)['versions']
        self.assertEqual(len(l2), len(l1) + 1)
        self.assertEqual(l2[:-1], l1)

        vserial, _ = l2[-2]
        self.assertEqual(self.get_object_meta(c, o, version=vserial),
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
205
                         {'Quality': 'AAA'})
206
207
208
209
210

        # update data
        self.append_object_data(c, o)

        # assert a newly created version has been created
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
211
        r = self.view('%s?version=list&format=json' % self.view_url)
212
213
214
215
216
217
218
219
        self.assertEqual(r.status_code, 200)
        l3 = json.loads(r.content)['versions']
        self.assertEqual(len(l3), len(l2) + 1)
        self.assertEqual(l3[:-1], l2)

    def test_objects_with_trailing_spaces(self):
        cname = self.cname

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
220
        r = self.view(quote('%s ' % self.view_url))
221
222
223
224
225
        self.assertEqual(r.status_code, 404)

        # delete object
        self.delete(self.api_url)

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
226
        r = self.view(self.view_url)
227
228
229
230
231
232
        self.assertEqual(r.status_code, 404)

        # upload object with trailing space
        oname = self.upload_object(cname, quote('%s ' % get_random_name()))[0]

        view_url = join_urls(self.view_path, self.user, cname, oname)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
233
        r = self.view(view_url)
234
235
236
        self.assertEqual(r.status_code, 200)

        view_url = join_urls(self.view_path, self.user, cname, oname[:-1])
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
237
        r = self.view(view_url)
238
239
240
241
        self.assertEqual(r.status_code, 404)

    def test_get_partial(self):
        limit = pithos_settings.BACKEND_BLOCK_SIZE + 1
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
242
        r = self.view(self.view_url, HTTP_RANGE='bytes=0-%d' % limit)
243
244
245
246
247
248
249
250
251
252
        self.assertEqual(r.status_code, 206)
        self.assertEqual(r.content, self.odata[:limit + 1])
        self.assertTrue('Content-Range' in r)
        self.assertEqual(r['Content-Range'], 'bytes 0-%d/%d' % (
            limit, len(self.odata)))
        self.assertTrue('Content-Type' in r)
        self.assertTrue(r['Content-Type'], 'application/octet-stream')

    def test_get_range_not_satisfiable(self):
        # TODO
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
253
        #r = self.view(self.view_url, HTTP_RANGE='bytes=50-10')
254
255
256
        #self.assertEqual(r.status_code, 416)

        offset = len(self.odata) + 1
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
257
        r = self.view(self.view_url, HTTP_RANGE='bytes=0-%s' % offset)
258
259
260
261
262
        self.assertEqual(r.status_code, 416)

    def test_multiple_range(self):
        l = ['0-499', '-500', '1000-']
        ranges = 'bytes=%s' % ','.join(l)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
263
        r = self.view(self.view_url, HTTP_RANGE=ranges)
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
        self.assertEqual(r.status_code, 206)
        self.assertTrue('content-type' in r)
        p = re.compile(
            'multipart/byteranges; boundary=(?P<boundary>[0-9a-f]{32}\Z)',
            re.I)
        m = p.match(r['content-type'])
        if m is None:
            self.fail('Invalid multiple range content type')
        boundary = m.groupdict()['boundary']
        cparts = r.content.split('--%s' % boundary)[1:-1]

        # assert content parts length
        self.assertEqual(len(cparts), len(l))

        # for each content part assert headers
        i = 0
        for cpart in cparts:
            content = cpart.split('\r\n')
            headers = content[1:3]
            content_range = headers[0].split(': ')
            self.assertEqual(content_range[0], 'Content-Range')

            r = l[i].split('-')
            if not r[0] and not r[1]:
                pass
            elif not r[0]:
                start = len(self.odata) - int(r[1])
                end = len(self.odata)
            elif not r[1]:
                start = int(r[0])
                end = len(self.odata)
            else:
                start = int(r[0])
                end = int(r[1]) + 1
            fdata = self.odata[start:end]
            sdata = '\r\n'.join(content[4:-1])
            self.assertEqual(len(fdata), len(sdata))
            self.assertEquals(fdata, sdata)
            i += 1

    def test_multiple_range_not_satisfiable(self):
        # perform get with multiple range
        out_of_range = len(self.odata) + 1
        l = ['0-499', '-500', '%d-' % out_of_range]
        ranges = 'bytes=%s' % ','.join(l)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
309
        r = self.view(self.view_url, HTTP_RANGE=ranges)
310
311
312
313
314
315
316
317
        self.assertEqual(r.status_code, 416)

    def test_get_if_match(self):
        if pithos_settings.UPDATE_MD5:
            etag = md5_hash(self.odata)
        else:
            etag = merkle(self.odata)

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
318
        r = self.view(self.view_url, HTTP_IF_MATCH=etag)
319
320
321
322
323
324
325
326

        # assert get success
        self.assertEqual(r.status_code, 200)

        # assert response content
        self.assertEqual(r.content, self.odata)

    def test_get_if_match_star(self):
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
327
        r = self.view(self.view_url, HTTP_IF_MATCH='*')
328
329
330
331
332
333
334
335
336
337
338
339
340
341

        # assert get success
        self.assertEqual(r.status_code, 200)

        # assert response content
        self.assertEqual(r.content, self.odata)

    def test_get_multiple_if_match(self):
        if pithos_settings.UPDATE_MD5:
            etag = md5_hash(self.odata)
        else:
            etag = merkle(self.odata)

        quoted = lambda s: '"%s"' % s
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
342
        r = self.view(self.view_url, HTTP_IF_MATCH=','.join(
343
344
345
346
347
348
349
350
351
            [quoted(etag), quoted(get_random_data(64))]))

        # assert get success
        self.assertEqual(r.status_code, 200)

        # assert response content
        self.assertEqual(r.content, self.odata)

    def test_if_match_precondition_failed(self):
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
352
        r = self.view(self.view_url, HTTP_IF_MATCH=get_random_name())
353
354
355
356
357
358
359
360
361
        self.assertEqual(r.status_code, 412)

    def test_if_none_match(self):
        if pithos_settings.UPDATE_MD5:
            etag = md5_hash(self.odata)
        else:
            etag = merkle(self.odata)

        # perform get with If-None-Match
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
362
        r = self.view(self.view_url, HTTP_IF_NONE_MATCH=etag)
363
364
365
366
367
368
369
370
371

        # assert precondition_failed
        self.assertEqual(r.status_code, 304)

        # update object data
        r = self.append_object_data(self.cname, self.oname)[-1]
        self.assertTrue(etag != r['ETag'])

        # perform get with If-None-Match
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
372
        r = self.view(self.view_url, HTTP_IF_NONE_MATCH=etag)
373
374
375
376
377
378

        # assert get success
        self.assertEqual(r.status_code, 200)

    def test_if_none_match_star(self):
        # perform get with If-None-Match with star
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
379
        r = self.view(self.view_url, HTTP_IF_NONE_MATCH='*')
380
381
382
383
384
385
386
387
388
389
390
        self.assertEqual(r.status_code, 304)

    def test_if_modified_since(self):
        # upload object
        object_info = self.get_object_info(self.cname, self.oname)
        last_modified = object_info['Last-Modified']
        t1 = datetime.datetime.strptime(last_modified, DATE_FORMATS[-1])
        t1_formats = map(t1.strftime, DATE_FORMATS)

        # Check not modified since
        for t in t1_formats:
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
391
            r = self.view(self.view_url, HTTP_IF_MODIFIED_SINCE=t)
392
393
394
395
396
397
398
399
400
            self.assertEqual(r.status_code, 304)

        _time.sleep(1)

        # update object data
        appended_data = self.append_object_data(self.cname, self.oname)[1]

        # Check modified since
        for t in t1_formats:
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
401
            r = self.view(self.view_url, HTTP_IF_MODIFIED_SINCE=t)
402
403
404
405
            self.assertEqual(r.status_code, 200)
            self.assertEqual(r.content, self.odata + appended_data)

    def test_if_modified_since_invalid_date(self):
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
406
        r = self.view(self.view_url, HTTP_IF_MODIFIED_SINCE='Monday')
407
408
409
410
411
412
413
414
415
416
417
418
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.content, self.odata)

    def test_if_not_modified_since(self):
        object_info = self.get_object_info(self.cname, self.oname)
        last_modified = object_info['Last-Modified']
        t = datetime.datetime.strptime(last_modified, DATE_FORMATS[-1])

        # Check unmodified
        t1 = t + datetime.timedelta(seconds=1)
        t1_formats = map(t1.strftime, DATE_FORMATS)
        for t in t1_formats:
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
419
            r = self.view(self.view_url, HTTP_IF_UNMODIFIED_SINCE=t)
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
            self.assertEqual(r.status_code, 200)
            self.assertEqual(r.content, self.odata)

        # modify object
        _time.sleep(2)
        self.append_object_data(self.cname, self.oname)

        object_info = self.get_object_info(self.cname, self.oname)
        last_modified = object_info['Last-Modified']
        t = datetime.datetime.strptime(last_modified, DATE_FORMATS[-1])
        t2 = t - datetime.timedelta(seconds=1)
        t2_formats = map(t2.strftime, DATE_FORMATS)

        # check modified
        for t in t2_formats:
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
435
            r = self.view(self.view_url, HTTP_IF_UNMODIFIED_SINCE=t)
436
437
438
439
440
441
442
443
444
445
446
447
448
449
            self.assertEqual(r.status_code, 412)

        # modify account: update object meta
        _time.sleep(1)
        self.update_object_meta(self.cname, self.oname, {'foo': 'bar'})

        object_info = self.get_object_info(self.cname, self.oname)
        last_modified = object_info['Last-Modified']
        t = datetime.datetime.strptime(last_modified, DATE_FORMATS[-1])
        t3 = t - datetime.timedelta(seconds=1)
        t3_formats = map(t3.strftime, DATE_FORMATS)

        # check modified
        for t in t3_formats:
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
450
            r = self.view(self.view_url, HTTP_IF_UNMODIFIED_SINCE=t)
451
452
453
454
455
456
457
458
459
460
            self.assertEqual(r.status_code, 412)

    def test_if_unmodified_since(self):
        object_info = self.get_object_info(self.cname, self.oname)
        last_modified = object_info['Last-Modified']
        t = datetime.datetime.strptime(last_modified, DATE_FORMATS[-1])
        t = t + datetime.timedelta(seconds=1)
        t_formats = map(t.strftime, DATE_FORMATS)

        for tf in t_formats:
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
461
            r = self.view(self.view_url, HTTP_IF_UNMODIFIED_SINCE=tf)
462
463
464
465
466
467
468
469
470
471
472
            self.assertEqual(r.status_code, 200)
            self.assertEqual(r.content, self.odata)

    def test_if_unmodified_since_precondition_failed(self):
        object_info = self.get_object_info(self.cname, self.oname)
        last_modified = object_info['Last-Modified']
        t = datetime.datetime.strptime(last_modified, DATE_FORMATS[-1])
        t = t - datetime.timedelta(seconds=1)
        t_formats = map(t.strftime, DATE_FORMATS)

        for tf in t_formats:
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
473
            r = self.view(self.view_url, HTTP_IF_UNMODIFIED_SINCE=tf)
474
475
476
477
478
479
480
481
            self.assertEqual(r.status_code, 412)

    def test_hashes(self):
        l = random.randint(2, 5) * pithos_settings.BACKEND_BLOCK_SIZE
        oname, odata = self.upload_object(self.cname, length=l)[:-1]
        size = len(odata)

        view_url = join_urls(self.view_path, self.user, self.cname, oname)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
482
        r = self.view('%s?format=json&hashmap' % view_url)
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
        self.assertEqual(r.status_code, 200)
        body = json.loads(r.content)

        hashes = body['hashes']
        block_size = body['block_size']
        block_num = size / block_size if size / block_size == 0 else\
            size / block_size + 1
        self.assertTrue(len(hashes), block_num)
        i = 0
        for h in hashes:
            start = i * block_size
            end = (i + 1) * block_size
            hash = merkle(odata[start:end])
            self.assertEqual(h, hash)
            i += 1