objects.py 50.6 KB
Newer Older
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
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
#!/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 collections import defaultdict
from urllib import quote
39
from functools import partial
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
40
41
42

from pithos.api.test import (PithosAPITest, pithos_settings,
                             AssertMappingInvariant, AssertUUidInvariant,
43
                             TEST_BLOCK_SIZE, TEST_HASH_ALGORITHM,
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
44
                             DATE_FORMATS)
45
46
from pithos.api.test.util import (md5_hash, merkle, strnextling,
                                  get_random_data, get_random_name)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
47
48
49
50
51
52
53
54

from synnefo.lib import join_urls

import django.utils.simplejson as json

import random
import re
import datetime
55
56
57
58
59
import time as _time

merkle = partial(merkle,
                 blocksize=TEST_BLOCK_SIZE,
                 blockhash=TEST_HASH_ALGORITHM)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
60
61


Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
class ObjectHead(PithosAPITest):
    def setUp(self):
        cname = self.create_container()[0]
        oname, odata = self.upload_object(cname)[:-1]

        url = join_urls(self.pithos_path, cname, oname)
        r = self.head(url)
        map(lambda i: self.assertTrue(i in r),
            ['Etag',
             'Content-Length',
             'Content-Type',
             'Last-Modified',
             'Content-Encoding',
             'Content-Disposition',
             'X-Object-Hash',
             'X-Object-UUID',
             'X-Object-Version',
             'X-Object-Version-Timestamp',
             'X-Object-Modified-By',
             'X-Object-Manifest'])


Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
class ObjectGet(PithosAPITest):
    def setUp(self):
        PithosAPITest.setUp(self)
        self.containers = ['c1', 'c2']

        # create some containers
        for c in self.containers:
            self.create_container(c)

        # upload files
        self.objects = defaultdict(list)
        self.objects['c1'].append(self.upload_object('c1')[0])

    def test_versions(self):
        c = 'c1'
        o = self.objects[c][0]
        url = join_urls(self.pithos_path, self.user, c, o)

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

        url = join_urls(self.pithos_path, self.user, c, o)
        r = self.get('%s?version=list&format=json' % url)
        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(url, content_type='', **meta)
        self.assertEqual(r.status_code, 202)

        # assert a newly created version has been created
        r = self.get('%s?version=list&format=json' % url)
        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),
                         {'X-Object-Meta-Quality': 'AAA'})

        # update data
        self.append_object_data(c, o)

        # assert a newly created version has been created
        r = self.get('%s?version=list&format=json' % url)
        self.assertEqual(r.status_code, 200)
        l3 = json.loads(r.content)['versions']
        self.assertEqual(len(l3), len(l2) + 1)
        self.assertEqual(l3[:-1], l2)

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
176
177
178
    def test_get_version(self):
        c = 'c1'
        o = self.objects[c][0]
        url = join_urls(self.pithos_path, self.user, c, o)

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

        url = join_urls(self.pithos_path, self.user, c, o)
        r = self.get('%s?version=list&format=json' % url)
        self.assertEqual(r.status_code, 200)
        l = json.loads(r.content)['versions']
        self.assertEqual(len(l), 2)

        r = self.head('%s?version=%s' % (url, l[0][0]))
        self.assertEqual(r.status_code, 200)
        self.assertTrue('X-Object-Meta-Quality' not in r)

        r = self.head('%s?version=%s' % (url, l[1][0]))
        self.assertEqual(r.status_code, 200)
        self.assertTrue('X-Object-Meta-Quality' in r)

        # test invalid version
        r = self.head('%s?version=-1' % url)
        self.assertEqual(r.status_code, 404)

        other_name, other_data, r = self.upload_object(c)
        self.assertTrue('X-Object-Version' in r)
        other_version = r['X-Object-Version']

        self.assertTrue(o != other_name)

        r = self.get('%s?version=%s' % (url, other_version))
        self.assertEqual(r.status_code, 403)

        r = self.head('%s?version=%s' % (url, other_version))
        self.assertEqual(r.status_code, 403)

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
    def test_objects_with_trailing_spaces(self):
        # create object
        oname = self.upload_object('c1')[0]
        url = join_urls(self.pithos_path, self.user, 'c1', oname)

        r = self.get(quote('%s ' % url))
        self.assertEqual(r.status_code, 404)

        # delete object
        self.delete(url)

        r = self.get(url)
        self.assertEqual(r.status_code, 404)

        # upload object with trailing space
194
        oname = self.upload_object('c1', quote('%s ' % get_random_name()))[0]
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260

        url = join_urls(self.pithos_path, self.user, 'c1', oname)
        r = self.get(url)
        self.assertEqual(r.status_code, 200)

        url = join_urls(self.pithos_path, self.user, 'c1', oname[:-1])
        r = self.get(url)
        self.assertEqual(r.status_code, 404)

    def test_get_partial(self):
        cname = self.containers[0]
        oname, odata = self.upload_object(cname, length=512)[:-1]
        url = join_urls(self.pithos_path, self.user, cname, oname)
        r = self.get(url, HTTP_RANGE='bytes=0-499')
        self.assertEqual(r.status_code, 206)
        data = r.content
        self.assertEqual(data, odata[:500])
        self.assertTrue('Content-Range' in r)
        self.assertEqual(r['Content-Range'], 'bytes 0-499/%s' % len(odata))
        self.assertTrue('Content-Type' in r)
        self.assertTrue(r['Content-Type'], 'application/octet-stream')

    def test_get_final_500(self):
        cname = self.containers[0]
        oname, odata = self.upload_object(cname, length=512)[:-1]
        size = len(odata)
        url = join_urls(self.pithos_path, self.user, cname, oname)
        r = self.get(url, HTTP_RANGE='bytes=-500')
        self.assertEqual(r.status_code, 206)
        self.assertEqual(r.content, odata[-500:])
        self.assertTrue('Content-Range' in r)
        self.assertEqual(r['Content-Range'],
                         'bytes %s-%s/%s' % (size - 500, size - 1, size))
        self.assertTrue('Content-Type' in r)
        self.assertTrue(r['Content-Type'], 'application/octet-stream')

    def test_get_rest(self):
        cname = self.containers[0]
        oname, odata = self.upload_object(cname, length=512)[:-1]
        size = len(odata)
        url = join_urls(self.pithos_path, self.user, cname, oname)
        offset = len(odata) - random.randint(1, 512)
        r = self.get(url, HTTP_RANGE='bytes=%s-' % offset)
        self.assertEqual(r.status_code, 206)
        self.assertEqual(r.content, odata[offset:])
        self.assertTrue('Content-Range' in r)
        self.assertEqual(r['Content-Range'],
                         'bytes %s-%s/%s' % (offset, size - 1, size))
        self.assertTrue('Content-Type' in r)
        self.assertTrue(r['Content-Type'], 'application/octet-stream')

    def test_get_range_not_satisfiable(self):
        cname = self.containers[0]
        oname, odata = self.upload_object(cname, length=512)[:-1]
        url = join_urls(self.pithos_path, self.user, cname, oname)

        # TODO
        #r = self.get(url, HTTP_RANGE='bytes=50-10')
        #self.assertEqual(r.status_code, 416)

        offset = len(odata) + 1
        r = self.get(url, HTTP_RANGE='bytes=0-%s' % offset)
        self.assertEqual(r.status_code, 416)

    def test_multiple_range(self):
        cname = self.containers[0]
261
        oname, odata = self.upload_object(cname)[:-1]
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
262
263
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
309
        url = join_urls(self.pithos_path, self.user, cname, oname)

        l = ['0-499', '-500', '1000-']
        ranges = 'bytes=%s' % ','.join(l)
        r = self.get(url, HTTP_RANGE=ranges)
        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(odata) - int(r[1])
                end = len(odata)
            elif not r[1]:
                start = int(r[0])
                end = len(odata)
            else:
                start = int(r[0])
                end = int(r[1]) + 1
            fdata = 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
        cname = self.containers[0]
310
        oname, odata = self.upload_object(cname)[:-1]
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
311
312
313
314
315
316
317
        out_of_range = len(odata) + 1
        l = ['0-499', '-500', '%d-' % out_of_range]
        ranges = 'bytes=%s' % ','.join(l)
        url = join_urls(self.pithos_path, self.user, cname, oname)
        r = self.get(url, HTTP_RANGE=ranges)
        self.assertEqual(r.status_code, 416)

318
    def test_get_if_match(self):
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
319
        cname = self.containers[0]
320
        oname, odata = self.upload_object(cname)[:-1]
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
321
322
323
324
325

        # perform get with If-Match
        url = join_urls(self.pithos_path, self.user, cname, oname)

        if pithos_settings.UPDATE_MD5:
326
            etag = md5_hash(odata)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
327
328
329
330
331
332
333
334
335
336
337
        else:
            etag = merkle(odata)

        r = self.get(url, HTTP_IF_MATCH=etag)

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

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

338
    def test_get_if_match_star(self):
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
339
        cname = self.containers[0]
340
        oname, odata = self.upload_object(cname)[:-1]
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
341
342
343
344
345
346
347
348
349
350
351

        # perform get with If-Match *
        url = join_urls(self.pithos_path, self.user, cname, oname)
        r = self.get(url, HTTP_IF_MATCH='*')

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

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

352
    def test_get_multiple_if_match(self):
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
353
        cname = self.containers[0]
354
        oname, odata = self.upload_object(cname)[:-1]
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
355
356
357
358
359

        # perform get with If-Match
        url = join_urls(self.pithos_path, self.user, cname, oname)

        if pithos_settings.UPDATE_MD5:
360
            etag = md5_hash(odata)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
361
362
363
        else:
            etag = merkle(odata)

364
365
366
        quoted = lambda s: '"%s"' % s
        r = self.get(url, HTTP_IF_MATCH=','.join(
            [quoted(etag), quoted(get_random_data(64))]))
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
367
368
369
370
371
372
373
374
375

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

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

    def test_if_match_precondition_failed(self):
        cname = self.containers[0]
376
        oname, odata = self.upload_object(cname)[:-1]
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
377
378
379

        # perform get with If-Match
        url = join_urls(self.pithos_path, self.user, cname, oname)
380
        r = self.get(url, HTTP_IF_MATCH=get_random_name())
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
381
382
        self.assertEqual(r.status_code, 412)

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
383
    def test_if_none_match(self):
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
384
385
        # upload object
        cname = self.containers[0]
386
        oname, odata = self.upload_object(cname)[:-1]
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
387
388

        if pithos_settings.UPDATE_MD5:
389
            etag = md5_hash(odata)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
        else:
            etag = merkle(odata)

        # perform get with If-None-Match
        url = join_urls(self.pithos_path, self.user, cname, oname)
        r = self.get(url, HTTP_IF_NONE_MATCH=etag)

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

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

        # perform get with If-None-Match
        url = join_urls(self.pithos_path, self.user, cname, oname)
        r = self.get(url, HTTP_IF_NONE_MATCH=etag)

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

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
411
    def test_if_none_match_star(self):
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
412
413
        # upload object
        cname = self.containers[0]
414
        oname, odata = self.upload_object(cname)[:-1]
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
415
416
417
418
419
420
421
422
423
424

        # perform get with If-None-Match with star
        url = join_urls(self.pithos_path, self.user, cname, oname)
        r = self.get(url, HTTP_IF_NONE_MATCH='*')

        self.assertEqual(r.status_code, 304)

    def test_if_modified_since(self):
        # upload object
        cname = self.containers[0]
425
        oname, odata = self.upload_object(cname)[:-1]
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
        object_info = self.get_object_info(cname, 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
        url = join_urls(self.pithos_path, self.user, cname, oname)
        for t in t1_formats:
            r = self.get(url, HTTP_IF_MODIFIED_SINCE=t)
            self.assertEqual(r.status_code, 304)

        _time.sleep(1)

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

        # Check modified since
        url = join_urls(self.pithos_path, self.user, cname, oname)
        for t in t1_formats:
            r = self.get(url, HTTP_IF_MODIFIED_SINCE=t)
            self.assertEqual(r.status_code, 200)
            self.assertEqual(r.content, odata + appended_data)

    def test_if_modified_since_invalid_date(self):
        cname = self.containers[0]
451
        oname, odata = self.upload_object(cname)[:-1]
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
452
453
454
455
456
457
458
        url = join_urls(self.pithos_path, self.user, cname, oname)
        r = self.get(url, HTTP_IF_MODIFIED_SINCE='Monday')
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.content, odata)

    def test_if_not_modified_since(self):
        cname = self.containers[0]
459
        oname, odata = self.upload_object(cname)[:-1]
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
460
461
462
463
464
465
466
467
468
469
470
        url = join_urls(self.pithos_path, self.user, cname, oname)
        object_info = self.get_object_info(cname, 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:
            r = self.get(url, HTTP_IF_UNMODIFIED_SINCE=t)
            self.assertEqual(r.status_code, 200)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
471
            self.assertEqual(r.content, odata)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
472
473
474
475
476
477
478
479
480
481
482

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

        object_info = self.get_object_info(cname, 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)

483
        # check modified
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
484
485
486
487
        for t in t2_formats:
            r = self.get(url, HTTP_IF_UNMODIFIED_SINCE=t)
            self.assertEqual(r.status_code, 412)

488
        # modify account: update object meta
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
489
490
491
492
493
494
495
496
497
        _time.sleep(1)
        self.update_object_meta(cname, oname, {'foo': 'bar'})

        object_info = self.get_object_info(cname, 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)

498
        # check modified
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
499
500
501
502
503
504
        for t in t3_formats:
            r = self.get(url, HTTP_IF_UNMODIFIED_SINCE=t)
            self.assertEqual(r.status_code, 412)

    def test_if_unmodified_since(self):
        cname = self.containers[0]
505
        oname, odata = self.upload_object(cname)[:-1]
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
506
507
508
509
510
511
512
513
514
515
516
517
518
519
        url = join_urls(self.pithos_path, self.user, cname, oname)
        object_info = self.get_object_info(cname, 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:
            r = self.get(url, HTTP_IF_UNMODIFIED_SINCE=tf)
            self.assertEqual(r.status_code, 200)
            self.assertEqual(r.content, odata)

    def test_if_unmodified_since_precondition_failed(self):
        cname = self.containers[0]
520
        oname, odata = self.upload_object(cname)[:-1]
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
        url = join_urls(self.pithos_path, self.user, cname, oname)
        object_info = self.get_object_info(cname, 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:
            r = self.get(url, HTTP_IF_UNMODIFIED_SINCE=tf)
            self.assertEqual(r.status_code, 412)

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

        url = join_urls(self.pithos_path, self.user, cname, oname)
        r = self.get('%s?format=json&hashmap' % url)
        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
552
            hash = merkle(odata[start:end])
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
553
554
555
556
557
558
559
            self.assertEqual(h, hash)
            i += 1


class ObjectPut(PithosAPITest):
    def setUp(self):
        PithosAPITest.setUp(self)
560
        self.container = get_random_name()
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
561
562
563
564
        self.create_container(self.container)

    def test_upload(self):
        cname = self.container
565
        oname = get_random_name()
566
        data = get_random_data()
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
        meta = {'test': 'test1'}
        headers = dict(('HTTP_X_OBJECT_META_%s' % k.upper(), v)
                       for k, v in meta.iteritems())
        url = join_urls(self.pithos_path, self.user, cname, oname)
        r = self.put(url, data=data, content_type='application/pdf', **headers)
        self.assertEqual(r.status_code, 201)
        self.assertTrue('ETag' in r)
        self.assertTrue('X-Object-Version' in r)

        info = self.get_object_info(cname, oname)

        # assert object meta
        self.assertTrue('X-Object-Meta-Test' in info)
        self.assertEqual(info['X-Object-Meta-Test'], 'test1')

        # assert content-type
        self.assertEqual(info['content-type'], 'application/pdf')

        # assert uploaded content
        r = self.get(url)
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.content, data)

    def test_maximum_upload_size_exceeds(self):
        cname = self.container
592
        oname = get_random_name()
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608

        # set container quota to 100
        url = join_urls(self.pithos_path, self.user, cname)
        r = self.post(url, HTTP_X_CONTAINER_POLICY_QUOTA='100')
        self.assertEqual(r.status_code, 202)

        info = self.get_container_info(cname)
        length = int(info['X-Container-Policy-Quota']) + 1

        data = get_random_data(length)
        url = join_urls(self.pithos_path, self.user, cname, oname)
        r = self.put(url, data=data)
        self.assertEqual(r.status_code, 413)

    def test_upload_with_name_containing_slash(self):
        cname = self.container
609
        oname = '/%s' % get_random_name()
610
        data = get_random_data()
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
611
612
613
614
615
616
617
618
619
620
621
622
        url = join_urls(self.pithos_path, self.user, cname, oname)
        r = self.put(url, data=data)
        self.assertEqual(r.status_code, 201)
        self.assertTrue('ETag' in r)
        self.assertTrue('X-Object-Version' in r)

        r = self.get(url)
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.content, data)

    def test_upload_unprocessable_entity(self):
        cname = self.container
623
        oname = get_random_name()
624
        data = get_random_data()
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
625
626
627
628
629
630
        url = join_urls(self.pithos_path, self.user, cname, oname)
        r = self.put(url, data=data, HTTP_ETAG='123')
        self.assertEqual(r.status_code, 422)

#    def test_chunked_transfer(self):
#        cname = self.container
631
#        oname = '/%s' % get_random_name()
632
#        data = get_random_data()
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
#        url = join_urls(self.pithos_path, self.user, cname, oname)
#        r = self.put(url, data=data, HTTP_TRANSFER_ENCODING='chunked')
#        self.assertEqual(r.status_code, 201)
#        self.assertTrue('ETag' in r)
#        self.assertTrue('X-Object-Version' in r)

    def test_manifestation(self):
        cname = self.container
        prefix = 'myobject/'
        data = ''
        for i in range(random.randint(2, 10)):
            part = '%s%d' % (prefix, i)
            data += self.upload_object(cname, oname=part)[1]

        manifest = '%s/%s' % (cname, prefix)
648
        oname = get_random_name()
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
649
650
651
652
653
654
655
656
657
658
659
660
        url = join_urls(self.pithos_path, self.user, cname, oname)
        r = self.put(url, data='', HTTP_X_OBJECT_MANIFEST=manifest)
        self.assertEqual(r.status_code, 201)

        # assert object exists
        r = self.get(url)
        self.assertEqual(r.status_code, 200)

        # assert its content
        self.assertEqual(r.content, data)

        # invalid manifestation
661
        invalid_manifestation = '%s/%s' % (cname, get_random_name())
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
662
663
664
665
666
667
        self.put(url, data='', HTTP_X_OBJECT_MANIFEST=invalid_manifestation)
        r = self.get(url)
        self.assertEqual(r.content, '')

    def test_create_zero_length_object(self):
        cname = self.container
668
        oname = get_random_name()
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
669
670
671
672
673
674
675
676
677
678
679
680
681
        url = join_urls(self.pithos_path, self.user, cname, oname)
        r = self.put(url, data='')
        self.assertEqual(r.status_code, 201)

        r = self.get(url)
        self.assertEqual(r.status_code, 200)
        self.assertEqual(int(r['Content-Length']), 0)
        self.assertEqual(r.content, '')

        r = self.get('%s?hashmap=&format=json' % url)
        self.assertEqual(r.status_code, 200)
        body = json.loads(r.content)
        hashes = body['hashes']
682
        hash = merkle('')
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
683
684
685
686
687
688
689
690
691
692
693
694
        self.assertEqual(hashes, [hash])

    def test_create_object_by_hashmap(self):
        cname = self.container
        block_size = pithos_settings.BACKEND_BLOCK_SIZE

        # upload an object
        oname, data = self.upload_object(cname, length=block_size + 1)[:-1]
        # get it hashmap
        url = join_urls(self.pithos_path, self.user, cname, oname)
        r = self.get('%s?hashmap=&format=json' % url)

695
        oname = get_random_name()
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
        url = join_urls(self.pithos_path, self.user, cname, oname)
        r = self.put('%s?hashmap=' % url, data=r.content)
        self.assertEqual(r.status_code, 201)

        r = self.get(url)
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.content, data)


class ObjectCopy(PithosAPITest):
    def setUp(self):
        PithosAPITest.setUp(self)
        self.container = 'c1'
        self.create_container(self.container)
        self.object, self.data = self.upload_object(self.container)[:-1]

        url = join_urls(
            self.pithos_path, self.user, self.container, self.object)
        r = self.head(url)
        self.etag = r['X-Object-Hash']

    def test_copy(self):
        with AssertMappingInvariant(self.get_object_info, self.container,
                                    self.object):
            # copy object
721
            oname = get_random_name()
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
            url = join_urls(self.pithos_path, self.user, self.container, oname)
            r = self.put(url, data='', HTTP_X_OBJECT_META_TEST='testcopy',
                         HTTP_X_COPY_FROM='/%s/%s' % (
                             self.container, self.object))

            # assert copy success
            self.assertEqual(r.status_code, 201)

            # assert access the new object
            r = self.head(url)
            self.assertEqual(r.status_code, 200)
            self.assertTrue('X-Object-Meta-Test' in r)
            self.assertEqual(r['X-Object-Meta-Test'], 'testcopy')

            # assert etag is the same
            self.assertTrue('X-Object-Hash' in r)
            self.assertEqual(r['X-Object-Hash'], self.etag)

    def test_copy_from_different_container(self):
        cname = 'c2'
        self.create_container(cname)
        with AssertMappingInvariant(self.get_object_info, self.container,
                                    self.object):
745
            oname = get_random_name()
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
            url = join_urls(self.pithos_path, self.user, cname, oname)
            r = self.put(url, data='', HTTP_X_OBJECT_META_TEST='testcopy',
                         HTTP_X_COPY_FROM='/%s/%s' % (
                             self.container, self.object))

            # assert copy success
            self.assertEqual(r.status_code, 201)

            # assert access the new object
            r = self.head(url)
            self.assertEqual(r.status_code, 200)
            self.assertTrue('X-Object-Meta-Test' in r)
            self.assertEqual(r['X-Object-Meta-Test'], 'testcopy')

            # assert etag is the same
            self.assertTrue('X-Object-Hash' in r)
            self.assertEqual(r['X-Object-Hash'], self.etag)

    def test_copy_invalid(self):
        # copy from non-existent object
766
        oname = get_random_name()
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
767
768
769
        url = join_urls(self.pithos_path, self.user, self.container, oname)
        r = self.put(url, data='', HTTP_X_OBJECT_META_TEST='testcopy',
                     HTTP_X_COPY_FROM='/%s/%s' % (
770
                         self.container, get_random_name()))
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
771
772
773
        self.assertEqual(r.status_code, 404)

        # copy from non-existent container
774
        oname = get_random_name()
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
775
776
777
        url = join_urls(self.pithos_path, self.user, self.container, oname)
        r = self.put(url, data='', HTTP_X_OBJECT_META_TEST='testcopy',
                     HTTP_X_COPY_FROM='/%s/%s' % (
778
                         get_random_name(), self.object))
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
779
780
781
782
783
        self.assertEqual(r.status_code, 404)

    def test_copy_dir(self):
        folder = self.create_folder(self.container)[0]
        subfolder = self.create_folder(
784
            self.container, oname='%s/%s' % (folder, get_random_name()))[0]
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
785
786
787
        objects = [subfolder]
        append = objects.append
        append(self.upload_object(self.container,
788
                                  '%s/%s' % (folder, get_random_name()),
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
789
790
                                  HTTP_X_OBJECT_META_DEPTH='1')[0])
        append(self.upload_object(self.container,
791
                                  '%s/%s' % (subfolder, get_random_name()),
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
                                  HTTP_X_OBJECT_META_DEPTH='2')[0])
        other = self.upload_object(self.container, strnextling(folder))[0]

        # copy dir
        copy_folder = self.create_folder(self.container)[0]
        url = join_urls(self.pithos_path, self.user, self.container,
                        copy_folder)
        r = self.put('%s?delimiter=/' % url, data='',
                     HTTP_X_COPY_FROM='/%s/%s' % (self.container, folder))
        self.assertEqual(r.status_code, 201)

        for obj in objects:
            # assert object exists
            url = join_urls(self.pithos_path, self.user, self.container,
                            obj.replace(folder, copy_folder))
            r = self.head(url)
            self.assertEqual(r.status_code, 200)

            # assert metadata
            meta = self.get_object_meta(self.container, obj)
            for k in meta.keys():
                self.assertTrue(k in r)
                self.assertEqual(r[k], meta[k])

        # assert other has not been created under copy folder
        url = join_urls(self.pithos_path, self.user, self.container,
                        '%s/%s' % (copy_folder,
                                   other.replace(folder, copy_folder)))
        r = self.head(url)
        self.assertEqual(r.status_code, 404)


class ObjectMove(PithosAPITest):
    def setUp(self):
        PithosAPITest.setUp(self)
        self.container = 'c1'
        self.create_container(self.container)
        self.object, self.data = self.upload_object(self.container)[:-1]

        url = join_urls(
            self.pithos_path, self.user, self.container, self.object)
        r = self.head(url)
        self.etag = r['X-Object-Hash']

    def test_move(self):
        # move object
838
        oname = get_random_name()
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
        url = join_urls(self.pithos_path, self.user, self.container, oname)
        r = self.put(url, data='', HTTP_X_OBJECT_META_TEST='testcopy',
                     HTTP_X_MOVE_FROM='/%s/%s' % (
                         self.container, self.object))

        # assert move success
        self.assertEqual(r.status_code, 201)

        # assert access the new object
        r = self.head(url)
        self.assertEqual(r.status_code, 200)
        self.assertTrue('X-Object-Meta-Test' in r)
        self.assertEqual(r['X-Object-Meta-Test'], 'testcopy')

        # assert etag is the same
        self.assertTrue('X-Object-Hash' in r)

        # assert the initial object has been deleted
        url = join_urls(self.pithos_path, self.user, self.container,
                        self.object)
        r = self.head(url)
        self.assertEqual(r.status_code, 404)

    def test_move_dir(self):
        folder = self.create_folder(self.container)[0]
        subfolder = self.create_folder(
865
            self.container, oname='%s/%s' % (folder, get_random_name()))[0]
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
866
867
868
869
870
        objects = [subfolder]
        append = objects.append
        meta = {}
        meta[objects[0]] = {}
        append(self.upload_object(self.container,
871
                                  '%s/%s' % (folder, get_random_name()),
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
872
873
874
                                  HTTP_X_OBJECT_META_DEPTH='1')[0])
        meta[objects[1]] = {'X-Object-Meta-Depth': '1'}
        append(self.upload_object(self.container,
875
                                  '%s/%s' % (subfolder, get_random_name()),
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
                                  HTTP_X_OBJECT_META_DEPTH='2')[0])
        meta[objects[1]] = {'X-Object-Meta-Depth': '2'}
        other = self.upload_object(self.container, strnextling(folder))[0]

        # move dir
        copy_folder = self.create_folder(self.container)[0]
        url = join_urls(self.pithos_path, self.user, self.container,
                        copy_folder)
        r = self.put('%s?delimiter=/' % url, data='',
                     HTTP_X_MOVE_FROM='/%s/%s' % (self.container, folder))
        self.assertEqual(r.status_code, 201)

        for obj in objects:
            # assert initial object does not exist
            url = join_urls(self.pithos_path, self.user, self.container, obj)
            r = self.head(url)
            self.assertEqual(r.status_code, 404)

            # assert new object was created
            url = join_urls(self.pithos_path, self.user, self.container,
                            obj.replace(folder, copy_folder))
            r = self.head(url)
            self.assertEqual(r.status_code, 200)

#            # assert metadata
#            for k in meta[obj].keys():
#                self.assertTrue(k in r)
#                self.assertEqual(r[k], meta[obj][k])

        # assert other has not been created under copy folder
        url = join_urls(self.pithos_path, self.user, self.container,
                        '%s/%s' % (copy_folder,
                                   other.replace(folder, copy_folder)))
        r = self.head(url)
        self.assertEqual(r.status_code, 404)


class ObjectPost(PithosAPITest):
    def setUp(self):
        PithosAPITest.setUp(self)
        self.container = 'c1'
        self.create_container(self.container)
        self.object, self.object_data = self.upload_object(self.container)[:2]

    def test_update_meta(self):
        with AssertUUidInvariant(self.get_object_info,
                                 self.container,
                                 self.object):
            # update metadata
            d = {'a' * 114: 'b' * 256}
            kwargs = dict(('HTTP_X_OBJECT_META_%s' % k, v) for
                          k, v in d.items())
            url = join_urls(self.pithos_path, self.user, self.container,
                            self.object)
            r = self.post(url, content_type='', **kwargs)
            self.assertEqual(r.status_code, 202)

            # assert metadata have been updated
            meta = self.get_object_meta(self.container, self.object)

            for k, v in d.items():
                key = 'X-Object-Meta-%s' % k.title()
                self.assertTrue(key in meta)
                self.assertTrue(meta[key], v)

            # Header key too large
            d = {'a' * 115: 'b' * 256}
            kwargs = dict(('HTTP_X_OBJECT_META_%s' % k, v) for
                          k, v in d.items())
            r = self.post(url, content_type='', **kwargs)
            self.assertEqual(r.status_code, 400)

            # Header value too large
            d = {'a' * 114: 'b' * 257}
            kwargs = dict(('HTTP_X_OBJECT_META_%s' % k, v) for
                          k, v in d.items())
            r = self.post(url, content_type='', **kwargs)
            self.assertEqual(r.status_code, 400)

#            # Check utf-8 meta
#            d = {'α' * (114 / 2): 'β' * (256 / 2)}
#            kwargs = dict(('HTTP_X_OBJECT_META_%s' % quote(k), quote(v)) for
#                          k, v in d.items())
#            url = join_urls(self.pithos_path, self.user, self.container,
#                            self.object)
#            r = self.post(url, content_type='', **kwargs)
#            self.assertEqual(r.status_code, 202)
#
#            # assert metadata have been updated
#            meta = self.get_object_meta(self.container, self.object)
#
#            for k, v in d.items():
#                key = 'X-Object-Meta-%s' % k.title()
#                self.assertTrue(key in meta)
#                self.assertTrue(meta[key], v)
#
#            # Header key too large
#            d = {'α' * 114: 'β' * (256 / 2)}
#            kwargs = dict(('HTTP_X_OBJECT_META_%s' % quote(k), quote(v)) for
#                          k, v in d.items())
#            r = self.post(url, content_type='', **kwargs)
#            self.assertEqual(r.status_code, 400)
#
#            # Header value too large
#            d = {'α' * 114: 'β' * 256}
#            kwargs = dict(('HTTP_X_OBJECT_META_%s' % quote(k), quote(v)) for
#                          k, v in d.items())
#            r = self.udpate(url, content_type='', **kwargs)
#            self.assertEqual(r.status_code, 400)

    def test_update_object(self):
        block_size = pithos_settings.BACKEND_BLOCK_SIZE
        oname, odata = self.upload_object(
            self.container, length=random.randint(
                block_size + 1, 2 * block_size))[:2]

        length = len(odata)
        first_byte_pos = random.randint(1, block_size)
        last_byte_pos = random.randint(block_size + 1, length - 1)
        range = 'bytes %s-%s/%s' % (first_byte_pos, last_byte_pos, length)
        kwargs = {'content_type': 'application/octet-stream',
                  'HTTP_CONTENT_RANGE': range}

        url = join_urls(self.pithos_path, self.user, self.container, oname)
        partial = last_byte_pos - first_byte_pos + 1
        data = get_random_data(partial)
        r = self.post(url, data=data, **kwargs)

        self.assertEqual(r.status_code, 204)
        self.assertTrue('ETag' in r)
        updated_data = odata.replace(odata[first_byte_pos: last_byte_pos + 1],
                                     data)
        if pithos_settings.UPDATE_MD5:
1009
            etag = md5_hash(updated_data)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
        else:
            etag = merkle(updated_data)
        #self.assertEqual(r['ETag'], etag)

        # check modified object
        r = self.get(url)

        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.content, updated_data)
        self.assertEqual(etag, r['ETag'])

    def test_update_object_divided_by_blocksize(self):
        block_size = pithos_settings.BACKEND_BLOCK_SIZE
        oname, odata = self.upload_object(self.container,
                                          length=2 * block_size)[:2]

        length = len(odata)
        first_byte_pos = block_size
        last_byte_pos = 2 * block_size - 1
        range = 'bytes %s-%s/%s' % (first_byte_pos, last_byte_pos, length)
        kwargs = {'content_type': 'application/octet-stream',
                  'HTTP_CONTENT_RANGE': range}

        url = join_urls(self.pithos_path, self.user, self.container, oname)
        partial = last_byte_pos - first_byte_pos + 1
        data = get_random_data(partial)
        r = self.post(url, data=data, **kwargs)

        self.assertEqual(r.status_code, 204)
        self.assertTrue('ETag' in r)
        updated_data = odata.replace(odata[first_byte_pos: last_byte_pos + 1],
                                     data)
        if pithos_settings.UPDATE_MD5:
1043
            etag = md5_hash(updated_data)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
        else:
            etag = merkle(updated_data)
        #self.assertEqual(r['ETag'], etag)

        # check modified object
        r = self.get(url)

        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.content, updated_data)
        self.assertEqual(etag, r['ETag'])

    def test_update_object_invalid_content_length(self):
        block_size = pithos_settings.BACKEND_BLOCK_SIZE
        oname, odata = self.upload_object(
            self.container, length=random.randint(
                block_size + 1, 2 * block_size))[:2]

        length = len(odata)
        first_byte_pos = random.randint(1, block_size)
        last_byte_pos = random.randint(block_size + 1, length - 1)
        partial = last_byte_pos - first_byte_pos + 1
        data = get_random_data(partial)
        range = 'bytes %s-%s/%s' % (first_byte_pos, last_byte_pos, length)
        kwargs = {'content_type': 'application/octet-stream',
                  'HTTP_CONTENT_RANGE': range,
                  'CONTENT_LENGTH': partial + 1}

        url = join_urls(self.pithos_path, self.user, self.container, oname)
        r = self.post(url, data=data, **kwargs)

        self.assertEqual(r.status_code, 400)

    def test_update_object_invalid_range(self):
        block_size = pithos_settings.BACKEND_BLOCK_SIZE
        oname, odata = self.upload_object(
            self.container, length=random.randint(block_size + 1,
                                                  2 * block_size))[:2]

        length = len(odata)
        first_byte_pos = random.randint(1, block_size)
        last_byte_pos = first_byte_pos - 1
        range = 'bytes %s-%s/%s' % (first_byte_pos, last_byte_pos, length)
        kwargs = {'content_type': 'application/octet-stream',
                  'HTTP_CONTENT_RANGE': range}

        url = join_urls(self.pithos_path, self.user, self.container, oname)
1090
        r = self.post(url, data=get_random_data(), **kwargs)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107

        self.assertEqual(r.status_code, 416)

    def test_update_object_out_of_limits(self):
        block_size = pithos_settings.BACKEND_BLOCK_SIZE
        oname, odata = self.upload_object(
            self.container, length=random.randint(block_size + 1,
                                                  2 * block_size))[:2]

        length = len(odata)
        first_byte_pos = random.randint(1, block_size)
        last_byte_pos = length + 1
        range = 'bytes %s-%s/%s' % (first_byte_pos, last_byte_pos, length)
        kwargs = {'content_type': 'application/octet-stream',
                  'HTTP_CONTENT_RANGE': range}

        url = join_urls(self.pithos_path, self.user, self.container, oname)
1108
        r = self.post(url, data=get_random_data(), **kwargs)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
1109
1110
1111
1112

        self.assertEqual(r.status_code, 416)

    def test_append(self):
1113
1114
        data = get_random_data()
        length = len(data)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
        url = join_urls(self.pithos_path, self.user, self.container,
                        self.object)
        r = self.post(url, data=data, content_type='application/octet-stream',
                      HTTP_CONTENT_LENGTH=str(length),
                      HTTP_CONTENT_RANGE='bytes */*')
        self.assertEqual(r.status_code, 204)

        r = self.get(url)
        content = r.content
        self.assertEqual(len(content), len(self.object_data) + length)
        self.assertEqual(content, self.object_data + data)

1127
1128
1129
1130
    # TODO Fix the test
    def _test_update_with_chunked_transfer(self):
        data = get_random_data()
        length = len(data)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146

        url = join_urls(self.pithos_path, self.user, self.container,
                        self.object)
        r = self.post(url, data=data, content_type='application/octet-stream',
                      HTTP_CONTENT_RANGE='bytes 0-/*',
                      HTTP_TRANSFER_ENCODING='chunked')
        self.assertEqual(r.status_code, 204)

        # check modified object
        r = self.get(url)
        content = r.content
        self.assertEqual(content[0:length], data)
        self.assertEqual(content[length:], self.object_data[length:])

    def test_update_from_other_object(self):
        src = self.object
1147
        dest = get_random_name()
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176

        url = join_urls(self.pithos_path, self.user, self.container, src)
        r = self.get(url)
        source_data = r.content
        source_meta = self.get_object_info(self.container, src)

        # update zero length object
        url = join_urls(self.pithos_path, self.user, self.container, dest)
        r = self.put(url, data='')
        self.assertEqual(r.status_code, 201)

        r = self.post(url,
                      HTTP_CONTENT_RANGE='bytes */*',
                      HTTP_X_SOURCE_OBJECT='/%s/%s' % (self.container, src))
        self.assertEqual(r.status_code, 204)

        r = self.get(url)
        dest_data = r.content
        dest_meta = self.get_object_info(self.container, dest)

        self.assertEqual(source_data, dest_data)
        #self.assertEqual(source_meta['ETag'], dest_meta['ETag'])
        self.assertEqual(source_meta['X-Object-Hash'],
                         dest_meta['X-Object-Hash'])
        self.assertTrue(
            source_meta['X-Object-UUID'] != dest_meta['X-Object-UUID'])

    def test_update_range_from_other_object(self):
        src = self.object
1177
        dest = get_random_name()
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
1178
1179
1180
1181
1182
1183
1184

        url = join_urls(self.pithos_path, self.user, self.container, src)
        r = self.get(url)
        source_data = r.content

        # update zero length object
        url = join_urls(self.pithos_path, self.user, self.container, dest)
1185
1186
        initial_data = get_random_data()
        length = len(initial_data)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
1187
        r = self.put(url, data=initial_data)
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
        self.assertEqual(r.status_code, 201)

        offset = random.randint(1, length - 2)
        upto = random.randint(offset, length - 1)
        r = self.post(url,
                      HTTP_CONTENT_RANGE='bytes %s-%s/*' % (offset, upto),
                      HTTP_X_SOURCE_OBJECT='/%s/%s' % (self.container, src))
        self.assertEqual(r.status_code, 204)

        r = self.get(url)
        content = r.content
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
1199
1200
1201
        self.assertEqual(content, (initial_data[:offset] +
                                   source_data[:upto - offset + 1] +
                                   initial_data[upto + 1:]))
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
1202

1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
    def test_update_range_from_invalid_other_object(self):
        src = self.object
        dest = get_random_name()

        url = join_urls(self.pithos_path, self.user, self.container, src)
        r = self.get(url)

        # update zero length object
        url = join_urls(self.pithos_path, self.user, self.container, dest)
        initial_data = get_random_data()
        length = len(initial_data)
        r = self.put(url, data=initial_data)
        self.assertEqual(r.status_code, 201)

        offset = random.randint(1, length - 2)
        upto = random.randint(offset, length - 1)

        # source object does not start with /
        r = self.post(url,
                      HTTP_CONTENT_RANGE='bytes %s-%s/*' % (offset, upto),
                      HTTP_X_SOURCE_OBJECT='%s/%s' % (self.container, src))
        self.assertEqual(r.status_code, 400)

        # source object does not exist
        r = self.post(url,
                      HTTP_CONTENT_RANGE='bytes %s-%s/*' % (offset, upto),
                      HTTP_X_SOURCE_OBJECT='/%s/%s1' % (self.container, src))
        self.assertEqual(r.status_code, 404)

1232
    def test_restore_version(self):
1233
        info = self.get_object_info(self.container, self.object)
1234
1235
1236
1237
1238
        v = []
        append = v.append
        append((info['X-Object-Version'],
                int(info['Content-Length']),
                self.object_data))
1239
1240

        # update object
1241
1242
        data, r = self.upload_object(self.container, self.object,
                                     length=v[0][1] - 1)[1:]
1243
        self.assertTrue('X-Object-Version' in r)
1244
1245
        append((r['X-Object-Version'], len(data), data))
        # v[0][1] > v[1][1]
1246

1247
        # update with the previous version
1248
1249
1250
1251
1252
1253
        url = join_urls(self.pithos_path, self.user, self.container,
                        self.object)
        r = self.post(url,
                      HTTP_CONTENT_RANGE='bytes 0-/*',
                      HTTP_X_SOURCE_OBJECT='/%s/%s' % (self.container,
                                                       self.object),
1254
1255
                      HTTP_X_SOURCE_VERSION=v[0][0],
                      HTTP_X_OBJECT_BYTES=str(v[0][1]))
1256
        self.assertEqual(r.status_code, 204)
1257
        # v[2][1] = v[0][1] > v[1][1]
1258
1259
1260
1261

        # check content
        r = self.get(url)
        content = r.content
1262
        self.assertEqual(len(content), v[0][1])
1263
        self.assertEqual(content, self.object_data)
1264
        append((r['X-Object-Version'], len(content), content))
1265

1266
1267
1268
        # update object content(v4) > content(v2)
        data, r = self.upload_object(self.container, self.object,
                                     length=v[2][1] + 1)[1:]
1269
        self.assertTrue('X-Object-Version' in r)
1270
1271
        append((r['X-Object-Version'], len(data), data))
        # v[3][1] > v[2][1] = v[0][1] > v[1][1]
1272
1273
1274
1275
1276
1277

        # update with the previous version
        r = self.post(url,
                      HTTP_CONTENT_RANGE='bytes 0-/*',
                      HTTP_X_SOURCE_OBJECT='/%s/%s' % (self.container,
                                                       self.object),
1278
1279
                      HTTP_X_SOURCE_VERSION=v[2][0],
                      HTTP_X_OBJECT_BYTES=str(v[2][1]))
1280
        self.assertEqual(r.status_code, 204)
1281
        # v[3][1] > v[4][1] = v[2][1] = v[0][1] > v[1][1]
1282
1283
1284

        # check content
        r = self.get(url)
1285
1286
1287
        data = r.content
        self.assertEqual(data, v[2][2])
        append((r['X-Object-Version'], len(data), data))
1288

Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307

class ObjectDelete(PithosAPITest):
    def setUp(self):
        PithosAPITest.setUp(self)
        self.container = 'c1'
        self.create_container(self.container)
        self.object, self.object_data = self.upload_object(self.container)[:2]

    def test_delete(self):
        url = join_urls(self.pithos_path, self.user, self.container,
                        self.object)
        r = self.delete(url)
        self.assertEqual(r.status_code, 204)

        r = self.head(url)
        self.assertEqual(r.status_code, 404)

    def test_delete_non_existent(self):
        url = join_urls(self.pithos_path, self.user, self.container,
1308
                        get_random_name())
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
1309
1310
1311
1312
1313
1314
        r = self.delete(url)
        self.assertEqual(r.status_code, 404)

    def test_delete_dir(self):
        folder = self.create_folder(self.container)[0]
        subfolder = self.create_folder(
1315
            self.container, oname='%s/%s' % (folder, get_random_name()))[0]
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
1316
1317
1318
1319
1320
        objects = [subfolder]
        append = objects.append
        meta = {}
        meta[objects[0]] = {}
        append(self.upload_object(self.container,
1321
                                  '%s/%s' % (folder, get_random_name()),
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
1322
1323
1324
                                  HTTP_X_OBJECT_META_DEPTH='1')[0])
        meta[objects[1]] = {'X-Object-Meta-Depth': '1'}
        append(self.upload_object(self.container,
1325
                                  '%s/%s' % (subfolder, get_random_name()),
Sofia Papagiannaki's avatar
Sofia Papagiannaki committed
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
                                  HTTP_X_OBJECT_META_DEPTH='2')[0])
        meta[objects[1]] = {'X-Object-Meta-Depth': '2'}
        other = self.upload_object(self.container, strnextling(folder))[0]

        # move dir
        url = join_urls(self.pithos_path, self.user, self.container, folder)
        r = self.delete('%s?delimiter=/' % url)
        self.assertEqual(r.status_code, 204)

        for obj in objects:
            # assert object does not exist
            url = join_urls(self.pithos_path, self.user, self.container, obj)
            r = self.head(url)
            self.assertEqual(r.status_code, 404)

        # assert other has not been deleted
        url = join_urls(self.pithos_path, self.user, self.container, other)
        r = self.head(url)
        self.assertEqual(r.status_code, 200)