test.py 73.7 KB
Newer Older
1
# Copyright 2013-2014 GRNET S.A. All rights reserved.
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
#
# 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.

34
from unittest import TestCase
35
from mock import patch, call
36 37
from tempfile import NamedTemporaryFile
from os import urandom
38
from itertools import product
39
from random import randint
40

41
from kamaki.clients import pithos, ClientError
42

43 44

rest_pkg = 'kamaki.clients.pithos.rest_api.PithosRestClient'
45 46
pithos_pkg = 'kamaki.clients.pithos.PithosClient'

47
user_id = 'ac0un7-1d-5tr1ng'
48
obj = 'obj3c7N4m3'
49 50 51 52 53 54 55 56 57 58 59 60

account_info = {
    'content-language': 'en-us',
    'content-type': 'text/html; charset=utf-8',
    'date': 'Wed, 06 Mar 2013 13:25:51 GMT',
    'last-modified': 'Mon, 04 Mar 2013 18:22:31 GMT',
    'server': 'gunicorn/0.14.5',
    'vary': 'Accept-Language',
    'x-account-bytes-used': '751615526',
    'x-account-container-count': 7,
    'x-account-policy-quota': 53687091200,
    'x-account-policy-versioning': 'auto'}
61 62 63 64 65 66 67 68 69 70 71 72 73 74
container_info = {
    'content-language': 'en-us',
    'content-type': 'text/html; charset=utf-8',
    'date': 'Wed, 06 Mar 2013 15:11:05 GMT',
    'last-modified': 'Wed, 27 Feb 2013 15:56:13 GMT',
    'server': 'gunicorn/0.14.5',
    'vary': 'Accept-Language',
    'x-container-block-hash': 'sha256',
    'x-container-block-size': 4194304,
    'x-container-bytes-used': 309528938,
    'x-container-object-count': 14,
    'x-container-object-meta': '',
    'x-container-policy-quota': 53687091200,
    'x-container-policy-versioning': 'auto'}
75 76 77 78 79 80 81 82 83 84 85 86
object_info = {
    'content-language': 'en-us',
    'content-length': 254965,
    'content-type': 'application/octet-stream',
    'date': 'Thu, 07 Mar 2013 13:27:43 GMT',
    'etag': '',
    'last-modified': 'Mon, 04 Mar 2013 18:22:31 GMT',
    'server': 'gunicorn/0.14.5',
    'vary': 'Accept-Language',
    'x-object-hash': 'obj3c7h45h1s0bj3c7h45h411r34dY',
    'x-object-uuid': 'd0c747ca-34bd-49e0-8e98-1d07d8b0cbc7',
    'x-object-version': '525996',
87 88 89
    'x-object-version-timestamp': 'Mon, 04 Mar 2013 18:22:31 GMT',
    'x-object-meta-k1': 'v1',
    'x-object-meta-k2': 'v2'}
90 91 92 93 94 95 96 97 98 99 100 101 102
container_list = [
    dict(
        count=2,
        last_modified="2013-02-27T11:56:09.893033+00:00",
        bytes=677076979,
        name="pithos",
        x_container_policy=dict(quota="21474836480", versioning="auto")),
    dict(
        count=0,
        last_modified="2012-10-23T12:25:17.229187+00:00",
        bytes=0,
        name="trash",
        x_container_policy=dict(quota="21474836480", versioning="auto"))]
103
object_list = [
104 105
    dict(
        hash="",
106 107 108 109 110 111 112 113 114 115
        name="The_Secret_Garden.zip",
        x_object_public="/public/wdp9p",
        bytes=203304947,
        x_object_version_timestamp="1360237915.7027509",
        x_object_uuid="s0m3uu1df0r0bj0n3",
        last_modified="2013-02-07T11:51:55.702751+00:00",
        content_type="application/octet-stream",
        x_object_hash="0afdf29f71cd53126225c3f54ca",
        x_object_version=17737,
        x_object_modified_by=user_id),
116 117
    dict(
        hash="",
118 119 120 121 122 123 124 125 126 127
        name="The_Revealed_Garden.zip",
        x_object_public="/public/wpd7p",
        bytes=20330947,
        x_object_version_timestamp="13602915.7027509",
        x_object_uuid="s0m3uu1df0r0bj70w",
        last_modified="2013-02-07T11:51:55.702751+00:00",
        content_type="application/octet-stream",
        x_object_hash="0afdf29f71cd53126225c3f54ca",
        x_object_version=17737,
        x_object_modified_by=user_id)]
128 129 130 131 132 133 134 135 136 137 138
object_hashmap = dict(
    block_hash="sha256", block_size=4194304, bytes=33554432,
    hashes=[
        "4988438cc1c0292c085d289649b28cf547ba3db71c6efaac9f2df7e193d4d0af",
        "b214244aa56df7d1df7c6cac066e7cef268d9c2beb4dcf7ce68af667b0626f91",
        "17f365f25e0682565ded30576066bb13377a3d306967e4d74e06bb6bbc20f75f",
        "2524ae208932669fff89adf8a2fc0df3b67736ca0d3aadce7a2ce640f142af37",
        "5d807a2129d2fcd3c221c3da418ed52af3fc48d0817b62e0bb437acffccd3514",
        "609de22ce842d997f645fc49d5f14e0e3766dd51a6cbe66383b2bab82c8dfcd0",
        "3102851ac168c78be70e35ff5178c7b1ebebd589e5106d565ca1094d1ca8ff59",
        "bfe306dd24e92a8d85caf7055643f250fd319e8c4cdd4755ddabbf3ff97e83c7"])
139 140 141 142
sharers = [
    dict(last_modified="2013-01-29T16:50:06.084674+00:00", name="0b1a-82d5"),
    dict(last_modified="2013-01-29T16:50:06.084674+00:00", name="0b2a-f2d5"),
    dict(last_modified="2013-01-29T16:50:06.084674+00:00", name="2b1a-82d6")]
143

Stavros Sachtouris's avatar
Stavros Sachtouris committed
144

145 146 147 148 149 150 151 152
class FR(object):
    """FR stands for Fake Response"""
    json = dict()
    headers = dict()
    content = json
    status = None
    status_code = 200

153

154
class PithosRestClient(TestCase):
155 156 157 158

    def setUp(self):
        self.url = 'https://www.example.com/pithos'
        self.token = 'p17h0570k3n'
159
        self.client = pithos.PithosRestClient(self.url, self.token)
160 161 162 163 164 165 166
        self.client.account = user_id
        self.client.container = 'c0nt@1n3r_i'

    def tearDown(self):
        FR.headers = dict()
        FR.json = dict()
        FR.content = FR.json
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191

    @patch('%s.set_param' % rest_pkg)
    @patch('%s.set_header' % rest_pkg)
    @patch('%s.head' % rest_pkg, return_value=FR())
    def test_account_head(self, head, SH, SP):
        for params in product(
                (None, '50m3-d473'),
                (None, '50m3-07h3r-d473'),
                (None, 'y37-4n7h3r-d473'),
                ((), ('someval',), ('v1', 'v2',)),
                (dict(), dict(success=200), dict(k='v', v='k'))):
            args, kwargs = params[-2], params[-1]
            params = params[:-2]
            self.client.account_head(*(params + args), **kwargs)
            unt = params[0]
            self.assertEqual(SP.mock_calls[-1], call('until', unt, iff=unt))
            IMS, IUS = params[1], params[2]
            self.assertEqual(SH.mock_calls[-2:], [
                call('If-Modified-Since', IMS),
                call('If-Unmodified-Since', IUS)])
            self.assertEqual(head.mock_calls[-1], call(
                '/%s' % self.client.account,
                *args,
                success=kwargs.pop('success', 204),
                **kwargs))
192

193 194 195 196
    @patch('%s.set_param' % rest_pkg)
    @patch('%s.set_header' % rest_pkg)
    @patch('%s.get' % rest_pkg, return_value=FR())
    def test_account_get(self, get, SH, SP):
197
        keys = ('limit', 'marker', 'format', 'shared', 'public', 'until')
198 199 200 201 202
        for params in product(
                (None, 42),
                (None, 'X'),
                ('json', 'xml'),
                (False, True),
203
                (False, True),
204 205 206 207 208 209 210 211
                (None, '50m3-d473'),
                (None, '50m3-07h3r-d473'),
                (None, 'y37-4n7h3r-d473'),
                ((), ('someval',), ('v1', 'v2',)),
                (dict(), dict(success=200), dict(k='v', v='k'))):
            args, kwargs = params[-2], params[-1]
            params = params[:-2]
            self.client.account_get(*(params + args), **kwargs)
212 213
            self.assertEqual(SP.mock_calls[-6:], [
                call(keys[i], iff=X) if (i in (3, 4)) else call(
214 215
                    keys[i], X, iff=X) for i, X in enumerate(params[:6])])
            IMS, IUS = params[6], params[7]
216 217 218 219 220 221 222 223 224
            self.assertEqual(SH.mock_calls[-2:], [
                call('If-Modified-Since', IMS),
                call('If-Unmodified-Since', IUS)])
            self.assertEqual(get.mock_calls[-1], call(
                '/%s' % self.client.account,
                *args,
                success=kwargs.pop('success', (200, 204)),
                **kwargs))

225 226 227 228 229 230 231 232 233 234 235 236
    @patch('%s.set_param' % rest_pkg)
    @patch('%s.set_header' % rest_pkg)
    @patch('%s.post' % rest_pkg, return_value=FR())
    def test_account_post(self, post, SH, SP):
        for pm in product(
                (True, False),
                ({}, dict(g=['u1', 'u2']), dict(g1=[], g2=['u1', 'u2'])),
                (None, dict(k1='v1', k2='v2', k3='v2'), dict(k='v')),
                (None, 42),
                (None, 'v3r510n1ng'),
                ((), ('someval',), ('v1', 'v2',)),
                (dict(), dict(success=200), dict(k='v', v='k'))):
237
            args, kwargs = pm[-2:]
238 239 240
            pm = pm[:-2]
            self.client.account_post(*(pm + args), **kwargs)
            upd = pm[0]
241
            self.assertEqual(SP.mock_calls[-1], call('update', '', iff=upd))
242 243
            expected = []
            if pm[1]:
244 245
                expected += [call(
                    'X-Account-Group-%s' % k, v) for k, v in pm[1].items()]
246
            if pm[2]:
247 248
                expected = [call(
                    'X-Account-Meta-%s' % k, v) for k, v in pm[2].items()]
249 250 251 252 253 254 255 256 257 258
            expected = [
                call('X-Account-Policy-Quota', pm[3]),
                call('X-Account-Policy-Versioning', pm[4])]
            self.assertEqual(SH.mock_calls[- len(expected):], expected)
            self.assertEqual(post.mock_calls[-1], call(
                '/%s' % self.client.account,
                *args,
                success=kwargs.pop('success', 202),
                **kwargs))

259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
    @patch('%s.set_param' % rest_pkg)
    @patch('%s.set_header' % rest_pkg)
    @patch('%s.head' % rest_pkg, return_value=FR())
    def test_container_head(self, head, SH, SP):
        for pm in product(
                (None, '4-d473'),
                (None, '47h3r-d473'),
                (None, 'y37-4n47h3r'),
                ((), ('someval',)),
                (dict(), dict(success=200), dict(k='v', v='k'))):
            args, kwargs = pm[-2:]
            pm = pm[:-2]
            self.client.container_head(*(pm + args), **kwargs)
            unt, ims, ius = pm[0:3]
            self.assertEqual(SP.mock_calls[-1], call('until', unt, iff=unt))
            self.assertEqual(SH.mock_calls[-2:], [
                call('If-Modified-Since', ims),
                call('If-Unmodified-Since', ius)])
            self.assertEqual(head.mock_calls[-1], call(
                '/%s/%s' % (self.client.account, self.client.container),
                *args,
                success=kwargs.pop('success', 204),
                **kwargs))

283 284 285 286 287 288 289 290 291 292 293 294 295
    @patch('%s.set_param' % rest_pkg)
    @patch('%s.set_header' % rest_pkg)
    @patch('%s.get' % rest_pkg, return_value=FR())
    def test_container_get(self, get, SH, SP):
        for pm in product(
                (None, 42),
                (None, 'X'),
                (None, 'some/prefix'),
                (None, 'delimiter'),
                (None, '/some/path'),
                ('json', 'some-format'),
                ([], ['k1', 'k2', 'k3']),
                (False, True),
296
                (False, True),
297 298 299 300 301 302 303 304
                (None, 'unt1l-d473'),
                (None, 'y37-4n47h3r'),
                (None, '4n47h3r-d473'),
                ((), ('someval',)),
                (dict(), dict(success=400), dict(k='v', v='k'))):
            args, kwargs = pm[-2:]
            pm = pm[:-2]
            self.client.container_get(*(pm + args), **kwargs)
305
            lmt, mrk, prfx, dlm, path, frmt, meta, shr, pbl, unt = pm[:-2]
306 307 308 309
            exp = [call('limit', lmt, iff=lmt), call('marker', mrk, iff=mrk)]
            exp += [call('path', path)] if path else [
                call('prefix', prfx, iff=prfx),
                call('delimiter', dlm, iff=dlm)]
310 311 312 313
            exp += [
                call('format', frmt, iff=frmt),
                call('shared', iff=shr),
                call('public', iff=pbl)]
314 315 316 317 318 319 320 321 322 323 324 325 326 327
            if meta:
                exp += [call('meta', ','.join(meta))]
            exp += [call('until', unt, iff=unt)]
            self.assertEqual(SP.mock_calls[- len(exp):], exp)
            ims, ius = pm[-2:]
            self.assertEqual(SH.mock_calls[-2:], [
                call('If-Modified-Since', ims),
                call('If-Unmodified-Since', ius)])
            self.assertEqual(get.mock_calls[-1], call(
                '/%s/%s' % (self.client.account, self.client.container),
                *args,
                success=kwargs.pop('success', 200),
                **kwargs))

328 329 330 331 332 333
    @patch('%s.set_header' % rest_pkg)
    @patch('%s.put' % rest_pkg, return_value=FR())
    def test_container_put(self, put, SH):
        for pm in product(
                (None, 42),
                (None, 'v3r51on1ng'),
334 335
                (None, 'project id'),
                (None, dict(k1='v2'), dict(k2='v2', k3='v3')),
336 337 338 339 340
                ((), ('someval',)),
                (dict(), dict(success=400), dict(k='v', v='k'))):
            args, kwargs = pm[-2:]
            pm = pm[:-2]
            self.client.container_put(*(pm + args), **kwargs)
341 342
            quota, versioning, project_id = pm[-4:-1]
            metas = pm[-1] or dict()
343 344
            exp = [
                call('X-Container-Policy-Quota', quota),
345 346 347
                call('X-Container-Policy-Versioning', versioning)] + (
                    [call('X-Container-Policy-Project', project_id)] if (
                        project_id is not None) else []) + [
348 349 350 351 352 353 354 355
                call('X-Container-Meta-%s' % k, v) for k, v in metas.items()]
            self.assertEqual(SH.mock_calls[- len(exp):], exp)
            self.assertEqual(put.mock_calls[-1], call(
                '/%s/%s' % (self.client.account, self.client.container),
                *args,
                success=kwargs.pop('success', (201, 202)),
                **kwargs))

356 357 358 359 360 361 362 363 364
    @patch('%s.set_param' % rest_pkg)
    @patch('%s.set_header' % rest_pkg)
    @patch('%s.post' % rest_pkg, return_value=FR())
    def test_container_post(self, post, SH, SP):
        for pm in product(
                (True, False),
                ('json', 'some-format'),
                (None, 'quota'),
                (None, 'v3r51on1ng'),
365
                (None, 'project id'),
366 367 368 369 370 371 372 373 374 375 376
                (dict(), dict(k1='v2'), dict(k2='v2', k3='v3')),
                (None, 'content-type'),
                (None, 42),
                (None, 'transfer-encoding'),
                ((), ('someval',)),
                (dict(), dict(success=400), dict(k='v', v='k'))):
            args, kwargs = pm[-2:]
            pm = pm[:-2]
            self.client.container_post(*(pm + args), **kwargs)
            upd, frmt = pm[:2]
            self.assertEqual(SP.mock_calls[-2:], [
377
                call('update', '', iff=upd),
378
                call('format', frmt, iff=frmt)])
379
            qta, vrs, project_id, metas, ctype, clen, trenc = pm[2:]
380 381 382
            prfx = 'X-Container-Meta-'
            exp = [
                call('X-Container-Policy-Quota', qta),
383 384 385
                call('X-Container-Policy-Versioning', vrs)] + ([
                    call('X-Container-Policy-Project', project_id)] if (
                        project_id is not None) else []) + [
386 387 388 389 390 391 392 393 394 395 396 397
                call('%s%s' % (prfx, k), v) for k, v in metas.items()] + [
                call('Content-Type', ctype),
                call('Content-Length', clen),
                call('Transfer-Encoding', trenc)]
            self.assertEqual(SH.mock_calls[- len(exp):], exp)
            ims, ius = pm[-2:]
            self.assertEqual(post.mock_calls[-1], call(
                '/%s/%s' % (self.client.account, self.client.container),
                *args,
                success=kwargs.pop('success', 202),
                **kwargs))

398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
    @patch('%s.set_param' % rest_pkg)
    @patch('%s.delete' % rest_pkg, return_value=FR())
    def test_container_delete(self, delete, SP):
        for pm in product(
                (None, 'd473'),
                (None, 'd3l1m'),
                ((), ('someval',)),
                (dict(), dict(success=400), dict(k='v', v='k'))):
            args, kwargs = pm[-2:]
            pm = pm[:-2]
            self.client.container_delete(*(pm + args), **kwargs)
            unt, dlm = pm[-2:]
            self.assertEqual(SP.mock_calls[-2:], [
                call('until', unt, iff=unt),
                call('delimiter', dlm, iff=dlm)])
            self.assertEqual(delete.mock_calls[-1], call(
                '/%s/%s' % (self.client.account, self.client.container),
                *args,
                success=kwargs.pop('success', 204),
                **kwargs))

419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
    @patch('%s.set_param' % rest_pkg)
    @patch('%s.set_header' % rest_pkg)
    @patch('%s.head' % rest_pkg, return_value=FR())
    def test_object_head(self, head, SH, SP):
        for pm in product(
                (None, 'v3r510n'),
                (None, '1f-374g'),
                (None, '1f-n0-74g'),
                (None, '1f-m0d-51nc3'),
                (None, '1f-unm0d-51nc3'),
                ((), ('someval',)),
                (dict(), dict(success=400), dict(k='v', v='k'))):
            args, kwargs = pm[-2:]
            pm = pm[:-2]
            self.client.object_head(obj, *(pm + args), **kwargs)
            vrs, etag, netag, ims, ius = pm[:5]
            self.assertEqual(
                SP.mock_calls[-1],
                call('version', vrs, iff=vrs))
            self.assertEqual(SH.mock_calls[-4:], [
                call('If-Match', etag),
                call('If-None-Match', netag),
                call('If-Modified-Since', ims),
                call('If-Unmodified-Since', ius)])
            acc, cont = self.client.account, self.client.container
            self.assertEqual(head.mock_calls[-1], call(
                '/%s/%s/%s' % (acc, cont, obj),
                *args,
                success=kwargs.pop('success', 200),
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
                **kwargs))

    @patch('%s.set_param' % rest_pkg)
    @patch('%s.set_header' % rest_pkg)
    @patch('%s.get' % rest_pkg, return_value=FR())
    def test_object_get(self, get, SH, SP):
        for pm in product(
                ('json', 'f0rm47'),
                (False, True),
                (None, 'v3r510n'),
                (None, 'range=74-63'),
                (False, True),
                (None, '3746'),
                (None, 'non-3746'),
                (None, '1f-m0d'),
                (None, '1f-unm0d'),
                ((), ('someval',)),
                (dict(), dict(success=400), dict(k='v', v='k'))):
            args, kwargs = pm[-2:]
            pm = pm[:-2]
            self.client.object_get(obj, *(pm + args), **kwargs)
            format, hashmap, version = pm[:3]
            self.assertEqual(SP.mock_calls[-3:], [
                call('format', format, iff=format),
                call('hashmap', hashmap, iff=hashmap),
                call('version', version, iff=version)])
            rng, ifrng, im, inm, ims, ius = pm[-6:]
            self.assertEqual(SH.mock_calls[-6:], [
                call('Range', rng),
                call('If-Range', '', ifrng and rng),
                call('If-Match', im),
                call('If-None-Match', inm),
                call('If-Modified-Since', ims),
                call('If-Unmodified-Since', ius)])
            acc, cont = self.client.account, self.client.container
            self.assertEqual(get.mock_calls[-1], call(
                '/%s/%s/%s' % (acc, cont, obj),
                *args,
                success=kwargs.pop('success', 200),
487 488
                **kwargs))

489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
    @patch('%s.set_param' % rest_pkg)
    @patch('%s.set_header' % rest_pkg)
    @patch('%s.put' % rest_pkg, return_value=FR())
    def test_object_put(self, put, SH, SP):
        for pm in product(
                ('json', 'f0rm47'),
                (False, True),
                (None, 'delim',),
                (dict(), dict(read=['u1', 'g2'], write=['u1'])),
                (False, True),
                (dict(), dict(k2='v2', k3='v3')),
                ((), ('someval',)),
                (dict(), dict(success=400), dict(k='v', v='k'))):
            args, kwargs = pm[-2:]
            pm = pm[:-2]
            terms = [None] * 13
            for i in range(len(terms)):
                if randint(0, 2):
                    terms[i] = 'val_%s' % randint(13, 1024)
            self.client.object_put(
                obj,
                *(pm[:3] + tuple(terms) + pm[3:] + args),
                **kwargs)
            format, hashmap, delimiter = pm[:3]
            self.assertEqual(SP.mock_calls[-3:], [
                call('format', format, iff=format),
                call('hashmap', hashmap, iff=hashmap),
                call('delimiter', delimiter, iff=delimiter)])
            (
                im, inm, etag, clen, ctype, trenc,
                cp, mv, srcacc, srcvrs, conenc, condis, mnf) = terms
            perms, public, metas = pm[3:]
            exp = [
                call('If-Match', im),
                call('If-None-Match', inm),
                call('ETag', etag),
                call('Content-Length', clen),
                call('Content-Type', ctype),
                call('Transfer-Encoding', trenc),
                call('X-Copy-From', cp),
                call('X-Move-From', mv),
                call('X-Source-Account', srcacc),
                call('X-Source-Version', srcvrs),
                call('Content-Encoding', conenc),
                call('Content-Disposition', condis),
                call('X-Object-Manifest', mnf)]
            if perms:
                perm_str = ''
                for ptype, pval in perms.items():
                    if pval:
                        perm_str += ';' if perm_str else ''
                        perm_str += '%s=%s' % (ptype, ','.join(pval))
                exp += [call('X-Object-Sharing', perm_str)]
542
            exp += [call('X-Object-Public', public, public is not None)]
543 544 545 546 547 548 549 550
            for k, v in metas.items():
                exp += [call('X-Object-Meta-%s' % k, v)]
            self.assertEqual(SH.mock_calls[- len(exp):], exp)
            acc, cont = self.client.account, self.client.container
            self.assertEqual(put.mock_calls[-1], call(
                '/%s/%s/%s' % (acc, cont, obj),
                *args,
                success=kwargs.pop('success', 201),
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
                **kwargs))

    @patch('%s.set_param' % rest_pkg)
    @patch('%s.set_header' % rest_pkg)
    @patch('%s.copy' % rest_pkg, return_value=FR())
    def test_object_copy(self, copy, SH, SP):
        dest = 'dest1n4710n'
        for pm in product(
                ('json', 'f0rm47'),
                (False, True),
                (None, 'ifmatch'),
                (None, 'ifnonematch'),
                (None, 'destinationaccount'),
                (None, 'content-type'),
                (None, 'content-encoding'),
                (None, 'content-disp'),
                (None, 'source-version'),
                (dict(), dict(read=['u1', 'g2'], write=['u1'])),
                (False, True),
                (dict(), dict(k2='v2', k3='v3')),
                ((), ('someval',)),
                (dict(), dict(success=400), dict(k='v', v='k'))):
            args, kwargs = pm[-2:]
            pm = pm[:-2]
            self.client.object_copy(obj, dest, *(pm + args), **kwargs)
            format, ict = pm[:2]
            self.assertEqual(SP.mock_calls[-2:], [
                call('format', format, iff=format),
                call('ignore_content_type', iff=ict)])
            im, inm, da, ct, ce, cd, sv, perms, public, metas = pm[2:]
581 582
            exp = [
                call('If-Match', im),
583 584 585 586 587 588 589 590 591 592 593 594 595 596
                call('If-None-Match', inm),
                call('Destination', dest),
                call('Destination-Account', da),
                call('Content-Type', ct),
                call('Content-Encoding', ce),
                call('Content-Disposition', cd),
                call('X-Source-Version', sv)]
            if perms:
                perm_str = ''
                for ptype, pval in perms.items():
                    if pval:
                        perm_str += ';' if perm_str else ''
                        perm_str += '%s=%s' % (ptype, ','.join(pval))
                exp += [call('X-Object-Sharing', perm_str)]
597
            exp += [call('X-Object-Public', public, public is not None)]
598 599 600 601 602 603 604 605
            for k, v in metas.items():
                exp += [call('X-Object-Meta-%s' % k, v)]
            self.assertEqual(SH.mock_calls[- len(exp):], exp)
            acc, cont = self.client.account, self.client.container
            self.assertEqual(copy.mock_calls[-1], call(
                '/%s/%s/%s' % (acc, cont, obj),
                *args,
                success=kwargs.pop('success', 201),
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
                **kwargs))

    @patch('%s.set_param' % rest_pkg)
    @patch('%s.set_header' % rest_pkg)
    @patch('%s.move' % rest_pkg, return_value=FR())
    def test_object_move(self, move, SH, SP):
        for pm in product(
                ('json', 'f0rm47'),
                (False, True),
                (None, 'ifmatch'),
                (None, 'ifnonematch'),
                (None, 'destination'),
                (None, 'destinationaccount'),
                (None, 'content-type'),
                (None, 'content-encoding'),
                (None, 'content-disp'),
                (dict(), dict(read=['u1', 'g2'], write=['u1'])),
                (False, True),
                (dict(), dict(k2='v2', k3='v3')),
                ((), ('someval',)),
                (dict(), dict(success=400), dict(k='v', v='k'))):
            args, kwargs = pm[-2:]
            pm = pm[:-2]
            self.client.object_move(obj, *(pm + args), **kwargs)
            format, ict = pm[:2]
            self.assertEqual(SP.mock_calls[-2:], [
                call('format', format, iff=format),
                call('ignore_content_type', iff=ict)])
            im, inm, d, da, ct, ce, cd, perms, public, metas = pm[2:]
635 636
            exp = [
                call('If-Match', im),
637 638 639 640 641 642 643 644 645 646 647 648
                call('If-None-Match', inm),
                call('Destination', d),
                call('Destination-Account', da),
                call('Content-Type', ct),
                call('Content-Encoding', ce),
                call('Content-Disposition', cd)]
            if perms:
                perm_str = ''
                for ptype, pval in perms.items():
                    if pval:
                        perm_str += ';' if perm_str else ''
                        perm_str += '%s=%s' % (ptype, ','.join(pval))
649 650 651
                exp += [call('X-Object-Sharing', perm_str, iff=perms)]
            else:
                exp += [call('X-Object-Sharing', '', iff={})]
652
            exp += [call('X-Object-Public', public, public is not None)]
653 654 655 656 657 658 659 660
            for k, v in metas.items():
                exp += [call('X-Object-Meta-%s' % k, v)]
            self.assertEqual(SH.mock_calls[- len(exp):], exp)
            acc, cont = self.client.account, self.client.container
            self.assertEqual(move.mock_calls[-1], call(
                '/%s/%s/%s' % (acc, cont, obj),
                *args,
                success=kwargs.pop('success', 201),
661 662
                **kwargs))

663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
    @patch('%s.set_param' % rest_pkg)
    @patch('%s.set_header' % rest_pkg)
    @patch('%s.post' % rest_pkg, return_value=FR())
    def test_object_post(self, post, SH, SP):
        for pm in product(
                ('json', 'f0rm47'),
                (False, True),
                (dict(), dict(read=['u1', 'g2'], write=['u1'])),
                (False, True),
                (dict(), dict(k2='v2', k3='v3')),
                ((), ('someval',)),
                (dict(), dict(success=400), dict(k='v', v='k'))):
            args, kwargs = pm[-2:]
            pm = pm[:-2]
            terms = [None] * 13
            for i in range(len(terms)):
                if randint(0, 2):
                    terms[i] = 'val_%s' % randint(13, 1024)
            self.client.object_post(
                obj,
                *(pm[:2] + tuple(terms) + pm[2:] + args),
                **kwargs)
            format, update = pm[:2]
            self.assertEqual(SP.mock_calls[-2:], [
                call('format', format, iff=format),
688
                call('update', '', iff=update)])
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
            (
                im, inm, clen, ctype, crng, trenc, cenc,
                condis, srcobj, srcacc, srcvrs, obytes, mnfs) = terms
            exp = [
                call('If-Match', im),
                call('If-None-Match', inm),
                call('Content-Length', clen, iff=not trenc),
                call('Content-Type', ctype),
                call('Content-Range', crng),
                call('Transfer-Encoding', trenc),
                call('Content-Encoding', cenc),
                call('Content-Disposition', condis),
                call('X-Source-Object', srcobj),
                call('X-Source-Account', srcacc),
                call('X-Source-Version', srcvrs),
                call('X-Object-Bytes', obytes),
                call('X-Object-Manifest', mnfs)]
            perms, public, metas = pm[2:]
            if perms:
                perm_str = ''
                for ptype, pval in perms.items():
                    if pval:
                        perm_str += ';' if perm_str else ''
                        perm_str += '%s=%s' % (ptype, ','.join(pval))
713 714 715
                exp += [call('X-Object-Sharing', perm_str, iff=perms)]
            else:
                exp += [call('X-Object-Sharing', '', iff={})]
716
            exp += [call('X-Object-Public', public, public is not None)]
717 718 719 720 721 722 723 724 725 726
            for k, v in metas.items():
                exp += [call('X-Object-Meta-%s' % k, v)]
            self.assertEqual(SH.mock_calls[- len(exp):], exp)
            acc, cont = self.client.account, self.client.container
            self.assertEqual(post.mock_calls[-1], call(
                '/%s/%s/%s' % (acc, cont, obj),
                *args,
                success=kwargs.pop('success', (202, 204)),
                **kwargs))

727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
    @patch('%s.set_param' % rest_pkg)
    @patch('%s.delete' % rest_pkg, return_value=FR())
    def test_object_delete(self, delete, SP):
        for pm in product(
                (None, 'until'),
                (None, 'delim'),
                ((), ('someval',)),
                (dict(), dict(success=400), dict(k='v', v='k'))):
            args, kwargs = pm[-2:]
            pm = pm[:-2]
            self.client.object_delete(
                obj,
                *(pm + args),
                **kwargs)
            until, dlm = pm[-2:]
            self.assertEqual(SP.mock_calls[-2:], [
                call('until', until, iff=until),
                call('delimiter', dlm, iff=dlm)])
            acc, cont = self.client.account, self.client.container
            self.assertEqual(delete.mock_calls[-1], call(
                '/%s/%s/%s' % (acc, cont, obj),
                *args,
                success=kwargs.pop('success', 204),
                **kwargs))

752

753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
class PithosMethods(TestCase):

    def test__range_up(self):
        from kamaki.clients.pithos import _range_up
        for args, expected in (
                ((0, 100, 1000, '10'), '0-10'),
                ((0, 100, 1000, '-10'), ''),
                ((900, 1000, 1000, '-10'), '990-1000'),
                ((150, 250, 1000, '10'), ''),
                ((10, 200, 1000, '130-170'), '130-170'),
                ((150, 200, 1000, '130-170'), '150-170'),
                ((100, 150, 1000, '130-170'), '130-150'),
                ((200, 250, 1000, '130-170'), ''),
                ((100, 250, 1000, '30-170,200-270'), '100-170,200-250'),
                ((40, 950, 1000, '-170,200-270,50',), '830-950,200-270,40-50'),
                ((740, 900, 1000, '-170,200-270,50',), '830-900'),
                ((42, 333, 800, '100,50-200,-600',), '42-100,50-200,200-333')):
            self.assertEqual(_range_up(*args), expected)


773
class PithosClient(TestCase):
774

775
    files = []
776

777
    def _create_temp_file(self, num_of_blocks):
778 779 780 781 782 783 784 785 786 787
        self.files.append(NamedTemporaryFile())
        tmpFile = self.files[-1]
        file_size = num_of_blocks * 4 * 1024 * 1024
        print('\n\tCreate tmp file')
        tmpFile.write(urandom(file_size))
        tmpFile.flush()
        tmpFile.seek(0)
        print('\t\tDone')
        return tmpFile

788 789 790 791 792 793 794
    def assert_dicts_are_equal(self, d1, d2):
        for k, v in d1.items():
            self.assertTrue(k in d2)
            if isinstance(v, dict):
                self.assert_dicts_are_equal(v, d2[k])
            else:
                self.assertEqual(unicode(v), unicode(d2[k]))
795

796 797 798
    def setUp(self):
        self.url = 'https://www.example.com/pithos'
        self.token = 'p17h0570k3n'
799
        self.client = pithos.PithosClient(self.url, self.token)
800 801
        self.client.account = user_id
        self.client.container = 'c0nt@1n3r_i'
802 803

    def tearDown(self):
804 805 806 807
        FR.headers = dict()
        FR.status_code = 200
        FR.json = dict()
        FR.content = FR.json
808 809
        for f in self.files:
            f.close()
810

811 812
    #  Pithos+ methods that extend storage API

813
    @patch('%s.account_head' % pithos_pkg, return_value=FR())
814
    def test_get_account_info(self, AH):
815
        FR.headers = account_info
816 817 818 819
        for until in (None, 'un71L-d473'):
            r = self.client.get_account_info(until=until)
            self.assert_dicts_are_equal(r, account_info)
            self.assertEqual(AH.mock_calls[-1], call(until=until))
820 821
        FR.status_code = 401
        self.assertRaises(ClientError, self.client.get_account_info)
822

823
    @patch('%s.account_post' % pithos_pkg, return_value=FR())
824
    def test_del_account_meta(self, AP):
825
        keys = ['k1', 'k2', 'k3']
826 827
        for key in keys:
            self.client.del_account_meta(key)
828 829 830
            self.assertEqual(
                AP.mock_calls[-1],
                call(update=True, metadata={key: ''}))
831 832

    @patch('%s.container_head' % pithos_pkg, return_value=FR())
833
    def test_get_container_info(self, CH):
834
        FR.headers = container_info
835 836 837 838
        r = self.client.get_container_info()
        self.assert_dicts_are_equal(r, container_info)
        u = 'some date'
        r = self.client.get_container_info(until=u)
839
        self.assertEqual(CH.mock_calls, [call(until=None), call(until=u)])
840 841 842

    @patch('%s.account_get' % pithos_pkg, return_value=FR())
    def test_list_containers(self, get):
843
        FR.json = container_list
844
        r = self.client.list_containers()
845
        get.assert_called_once_with()
846 847
        for i in range(len(r)):
            self.assert_dicts_are_equal(r[i], container_list[i])
848

849 850 851
    @patch('%s.get_container_info' % pithos_pkg, return_value=container_info)
    @patch('%s.container_post' % pithos_pkg, return_value=FR())
    @patch('%s.object_put' % pithos_pkg, return_value=FR())
852
    def test_upload_object(self, OP, CP, GCI):
853 854
        num_of_blocks = 8
        tmpFile = self._create_temp_file(num_of_blocks)
855

856
        # Without kwargs
857 858 859 860
        exp_headers = dict(id='container id', name='container name')
        FR.headers = dict(exp_headers)
        r = self.client.upload_object(obj, tmpFile)
        self.assert_dicts_are_equal(r, exp_headers)
861
        self.assertEqual(GCI.mock_calls[-1], call())
862

863
        [call1, call2] = OP.mock_calls
864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
        (args1, kwargs1) = call1[1:3]
        (args2, kwargs2) = call2[1:3]
        self.assertEqual(args1, (obj,))
        expected1 = dict(
            hashmap=True,
            success=(201, 409),
            format='json',
            json=dict(
                hashes=['s0m3h@5h'] * num_of_blocks,
                bytes=num_of_blocks * 4 * 1024 * 1024),
            content_encoding=None,
            content_type='application/octet-stream',
            content_disposition=None,
            public=None,
            permissions=None)
        for k, v in expected1.items():
            if k == 'json':
                self.assertEqual(len(v['hashes']), len(kwargs1[k]['hashes']))
                self.assertEqual(v['bytes'], kwargs1[k]['bytes'])
            else:
                self.assertEqual(v, kwargs1[k])
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
        (args2, kwargs2) = call2[1:3]
        self.assertEqual(args2, (obj,))
        expected2 = dict(
            json=dict(
                hashes=['s0m3h@5h'] * num_of_blocks,
                bytes=num_of_blocks * 4 * 1024 * 1024),
            content_type='application/octet-stream',
            hashmap=True,
            success=201,
            format='json')
        for k, v in expected2.items():
            if k == 'json':
                self.assertEqual(len(v['hashes']), len(kwargs2[k]['hashes']))
                self.assertEqual(v['bytes'], kwargs2[k]['bytes'])
            else:
                self.assertEqual(v, kwargs2[k])

        mock_offset = 2

        #  With progress bars
        try:
            from progress.bar import ShadyBar
            blck_bar = ShadyBar('Mock blck calc.')
            upld_bar = ShadyBar('Mock uplds')
        except ImportError:
            blck_bar = None
            upld_bar = None

        if blck_bar and upld_bar:

            def blck_gen(n):
                for i in blck_bar.iter(range(n)):
                    yield
                yield

            def upld_gen(n):
                for i in upld_bar.iter(range(n)):
                    yield
                yield

            tmpFile.seek(0)
            r = self.client.upload_object(
                obj, tmpFile,
                hash_cb=blck_gen, upload_cb=upld_gen)
            self.assert_dicts_are_equal(r, exp_headers)

            for i, c in enumerate(OP.mock_calls[-mock_offset:]):
                self.assertEqual(OP.mock_calls[i], c)

        #  With content-type
        tmpFile.seek(0)
        ctype = 'video/mpeg'
        sharing = dict(read=['u1', 'g1', 'u2'], write=['u1'])
939 940
        r = self.client.upload_object(
            obj, tmpFile, content_type=ctype, sharing=sharing)
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
        self.assert_dicts_are_equal(r, exp_headers)
        self.assertEqual(OP.mock_calls[-1][2]['content_type'], ctype)
        self.assert_dicts_are_equal(
            OP.mock_calls[-2][2]['permissions'],
            sharing)

        # With other args
        tmpFile.seek(0)
        kwargs = dict(
            etag='s0m3E74g',
            if_etag_match='if etag match',
            if_not_exist=True,
            content_type=ctype,
            content_disposition=ctype + 'd15p051710n',
            public=True,
            content_encoding='802.11',
            container_info_cache={})
        r = self.client.upload_object(obj, tmpFile, **kwargs)
        self.assert_dicts_are_equal(r, exp_headers)

        kwargs.pop('if_not_exist')
        ematch = kwargs.pop('if_etag_match')
        etag = kwargs.pop('etag')
        self.assert_dicts_are_equal(
            kwargs.pop('container_info_cache'),
            {self.client.container: container_info})
        for arg, val in kwargs.items():
            self.assertEqual(OP.mock_calls[-2][2][arg], val)
        self.assertEqual(OP.mock_calls[-1][2]['if_etag_match'], ematch)
        self.assertEqual(OP.mock_calls[-1][2]['if_etag_not_match'], '*')
        self.assertEqual(OP.mock_calls[-1][2]['etag'], etag)

    @patch('%s.get_container_info' % pithos_pkg, return_value=container_info)
    @patch('%s.container_post' % pithos_pkg, return_value=FR())
    @patch('%s.object_put' % pithos_pkg, return_value=FR())
    def test_upload_from_string(self, OP, CP, GCI):
        num_of_blocks = 2
        tmpFile = self._create_temp_file(num_of_blocks)
        tmpFile.seek(0)
        src_str = tmpFile.read()

        exp_headers = dict(id='container id', name='container name')
        FR.headers = dict(exp_headers)
        r = self.client.upload_from_string(obj, src_str)
        self.assert_dicts_are_equal(r, exp_headers)
        self.assertEqual(GCI.mock_calls[-1], call())

        [call1, call2] = OP.mock_calls
989 990 991 992
        (args1, kwargs1) = call1[1:3]
        (args2, kwargs2) = call2[1:3]
        self.assertEqual(args1, (obj,))
        expected1 = dict(
993 994 995 996 997
            hashmap=True,
            success=(201, 409),
            format='json',
            json=dict(
                hashes=['s0m3h@5h'] * num_of_blocks,
998
                bytes=num_of_blocks * 4 * 1024 * 1024),
999 1000 1001 1002 1003
            content_encoding=None,
            content_type='application/octet-stream',
            content_disposition=None,
            public=None,
            permissions=None)
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
        for k, v in expected1.items():
            if k == 'json':
                self.assertEqual(len(v['hashes']), len(kwargs1[k]['hashes']))
                self.assertEqual(v['bytes'], kwargs1[k]['bytes'])
            else:
                self.assertEqual(v, kwargs1[k])

        (args2, kwargs2) = call2[1:3]
        self.assertEqual(args2, (obj,))
        expected2 = dict(
            json=dict(
                hashes=['s0m3h@5h'] * num_of_blocks,
1016
                bytes=num_of_blocks * 4 * 1024 * 1024),
1017 1018 1019 1020 1021
            content_type='application/octet-stream',
            hashmap=True,
            success=201,
            format='json')
        for k, v in expected2.items():
1022
            if k == 'json':
1023 1024
                self.assertEqual(len(v['hashes']), len(kwargs2[k]['hashes']))
                self.assertEqual(v['bytes'], kwargs2[k]['bytes'])
1025
            else:
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
                self.assertEqual(v, kwargs2[k])

        mock_offset = 2

        #  With progress bars
        try:
            from progress.bar import ShadyBar
            blck_bar = ShadyBar('Mock blck calc.')
            upld_bar = ShadyBar('Mock uplds')
        except ImportError:
            blck_bar = None
            upld_bar = None

        if blck_bar and upld_bar:

            def blck_gen(n):
                for i in blck_bar.iter(range(n)):
                    yield
                yield

            def upld_gen(n):
                for i in upld_bar.iter(range(n)):
                    yield
                yield

            tmpFile.seek(0)
1052
            r = self.client.upload_object(
1053 1054
                obj, tmpFile,
                hash_cb=blck_gen, upload_cb=upld_gen)
1055
            self.assert_dicts_are_equal(r, exp_headers)
1056 1057 1058 1059 1060 1061 1062 1063

            for i, c in enumerate(OP.mock_calls[-mock_offset:]):
                self.assertEqual(OP.mock_calls[i], c)

        #  With content-type
        tmpFile.seek(0)
        ctype = 'video/mpeg'
        sharing = dict(read=['u1', 'g1', 'u2'], write=['u1'])
1064 1065
        r = self.client.upload_object(
            obj, tmpFile,
1066
            content_type=ctype, sharing=sharing)
1067
        self.assert_dicts_are_equal(r, exp_headers)
1068 1069 1070 1071 1072 1073 1074 1075 1076
        self.assertEqual(OP.mock_calls[-1][2]['content_type'], ctype)
        self.assert_dicts_are_equal(
            OP.mock_calls[-2][2]['permissions'],
            sharing)

        # With other args
        tmpFile.seek(0)
        kwargs = dict(
            etag='s0m3E74g',
1077
            if_etag_match='if etag match',
1078
            if_not_exist=True,
1079 1080 1081
            content_type=ctype,
            content_disposition=ctype + 'd15p051710n',
            public=True,
1082 1083
            content_encoding='802.11',
            container_info_cache={})
1084 1085 1086
        r = self.client.upload_object(obj, tmpFile, **kwargs)
        self.assert_dicts_are_equal(r, exp_headers)

1087
        kwargs.pop('if_not_exist')
1088
        ematch = kwargs.pop('if_etag_match')
1089
        etag = kwargs.pop('etag')
1090 1091 1092
        self.assert_dicts_are_equal(
            kwargs.pop('container_info_cache'),
            {self.client.container: container_info})
1093 1094
        for arg, val in kwargs.items():
            self.assertEqual(OP.mock_calls[-2][2][arg], val)
1095
        self.assertEqual(OP.mock_calls[-1][2]['if_etag_match'], ematch)
1096 1097
        self.assertEqual(OP.mock_calls[-1][2]['if_etag_not_match'], '*')
        self.assertEqual(OP.mock_calls[-1][2]['etag'], etag)
1098

1099
    def test_get_object_info(self):
1100
        FR.headers = object_info
1101
        version = 'v3r510n'
1102
        with patch.object(
1103
                pithos.PithosClient, 'object_head',
1104
                return_value=FR()) as head:
1105 1106 1107 1108 1109 1110 1111
            r = self.client.get_object_info(obj)
            self.assertEqual(r, object_info)
            r = self.client.get_object_info(obj, version=version)
            self.assertEqual(head.mock_calls, [
                call(obj, version=None),
                call(obj, version=version)])
        with patch.object(
1112
                pithos.PithosClient, 'object_head',
1113 1114 1115 1116 1117
                side_effect=ClientError('Obj not found', 404)):
            self.assertRaises(
                ClientError,
                self.client.get_object_info,
                obj, version=version)
1118

1119 1120
    @patch('%s.get_object_info' % pithos_pkg, return_value=object_info)
    def test_get_object_meta(self, GOI):
1121 1122 1123 1124 1125 1126
        for version in (None, 'v3r510n'):
            r = self.client.get_object_meta(obj, version)
            for k in [k for k in object_info if k.startswith('x-object-meta')]:
                self.assertEqual(r.pop(k), object_info[k])
            self.assertFalse(len(r))
            self.assertEqual(GOI.mock_calls[-1], call(obj, version=version))
1127

1128 1129
    @patch('%s.object_post' % pithos_pkg, return_value=FR())
    def test_del_object_meta(self, post):
1130
        metakey = '50m3m3t4k3y'
1131
        self.client.del_object_meta(obj, metakey)
1132
        post.assert_called_once_with(obj, update=True, metadata={metakey: ''})
1133

1134 1135
    @patch('%s.object_put' % pithos_pkg, return_value=FR())
    def test_copy_object(self, put):
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
        src_cont = 'src-c0nt41n3r'
        src_obj = 'src-0bj'
        dst_cont = 'dst-c0nt41n3r'
        dst_obj = 'dst-0bj'
        expected = call(
            src_obj,
            content_length=0,
            source_account=None,
            success=201,
            copy_from='/%s/%s' % (src_cont, src_obj),
            delimiter=None,
            content_type=None,
            source_version=None,
            public=False)
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
        self.client.copy_object(src_cont, src_obj, dst_cont)
        self.assertEqual(put.mock_calls[-1], expected)
        self.client.copy_object(src_cont, src_obj, dst_cont, dst_obj)
        self.assertEqual(put.mock_calls[-1][1], (dst_obj,))
        kwargs = dict(
            source_version='src-v3r510n',
            source_account='src-4cc0un7',
            public=True,
            content_type='c0n73n7Typ3',
            delimiter='5')
        self.client.copy_object(src_cont, src_obj, dst_cont, **kwargs)
        for k, v in kwargs.items():
            self.assertEqual(v, put.mock_calls[-1][2][k])
1163

1164 1165
    @patch('%s.object_put' % pithos_pkg, return_value=FR())
    def test_move_object(self, put):
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
        src_cont = 'src-c0nt41n3r'
        src_obj = 'src-0bj'
        dst_cont = 'dst-c0nt41n3r'
        dst_obj = 'dst-0bj'
        expected = call(
            src_obj,
            content_length=0,
            source_account=None,
            success=201,
            move_from='/%s/%s' % (src_cont, src_obj),
            delimiter=None,
            content_type=None,
            source_version=None,
            public=False)
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
        self.client.move_object(src_cont, src_obj, dst_cont)
        self.assertEqual(put.mock_calls[-1], expected)
        self.client.move_object(src_cont, src_obj, dst_cont, dst_obj)
        self.assertEqual(put.mock_calls[-1][1], (dst_obj,))
        kwargs = dict(
            source_version='src-v3r510n',
            source_account='src-4cc0un7',
            public=True,
            content_type='c0n73n7Typ3',
            delimiter='5')
        self.client.move_object(src_cont, src_obj, dst_cont, **kwargs)
        for k, v in kwargs.items():
            self.assertEqual(v, put.mock_calls[-1][2][k])
1193

1194 1195
    #  Pithos+ only methods

1196 1197 1198 1199 1200 1201 1202
    @patch('%s.container_put' % pithos_pkg, return_value=FR())
    def test_create_container(self, CP):
        FR.headers = container_info
        cont = 'an0th3r_c0n741n3r'

        r = self.client.create_container()
        self.assert_dicts_are_equal(r, container_info)
1203
        CP.assert_called_once_with(
1204
            project_id=None, quota=None, versioning=None, metadata=None)
1205 1206 1207 1208 1209 1210 1211

        bu_cont = self.client.container
        r = self.client.create_container(cont)
        self.assertEqual(self.client.container, bu_cont)
        self.assert_dicts_are_equal(r, container_info)
        self.assertEqual(
            CP.mock_calls[-1],
1212
            call(project_id=None, quota=None, versioning=None, metadata=None))
1213 1214

        meta = dict(k1='v1', k2='v2')
1215
        r = self.client.create_container(cont, 42, 'auto', meta, 'prid')
1216 1217
        self.assertEqual(self.client.container, bu_cont)
        self.assert_dicts_are_equal(r, container_info)
1218 1219
        self.assertEqual(CP.mock_calls[-1], call(
            quota=42, versioning='auto', project_id='prid', metadata=meta))
1220

1221
    @patch('%s.container_delete' % pithos_pkg, return_value=FR())
1222
    def test_purge_container(self, CD):
1223
        self.client.purge_container()
1224
        self.assertTrue('until' in CD.mock_calls[-1][2])
1225 1226 1227
        cont = self.client.container
        self.client.purge_container('another-container')
        self.assertEqual(self.client.container, cont)
1228

1229 1230
    @patch('%s.object_put' % pithos_pkg, return_value=FR())
    def test_upload_object_unchunked(self, put):
1231 1232
        num_of_blocks = 8
        tmpFile = self._create_temp_file(num_of_blocks)
1233
        expected = dict(
1234 1235 1236 1237 1238 1239 1240 1241
            success=201,
            data=num_of_blocks * 4 * 1024 * 1024,
            etag='some-etag',
            content_encoding='some content_encoding',
            content_type='some content-type',
            content_disposition='some content_disposition',
            public=True,
            permissions=dict(read=['u1', 'g1', 'u2'], write=['u1']))
1242 1243
        r = self.client.upload_object_unchunked(obj, tmpFile)
        self.assert_dicts_are_equal(r, FR.headers)
1244 1245 1246 1247 1248 1249 1250 1251 1252
        self.assertEqual(put.mock_calls[-1][1], (obj,))
        self.assertEqual(
            sorted(put.mock_calls[-1][2].keys()),
            sorted(expected.keys()))
        kwargs = dict(expected)
        kwargs.pop('success')
        kwargs['size'] = kwargs.pop('data')
        kwargs['sharing'] = kwargs.pop('permissions')
        tmpFile.seek(0)
1253 1254
        r = self.client.upload_object_unchunked(obj, tmpFile, **kwargs)
        self.assert_dicts_are_equal(r, FR.headers)
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
        pmc = put.mock_calls[-1][2]
        for k, v in expected.items():
            if k == 'data':
                self.assertEqual(len(pmc[k]), v)
            else:
                self.assertEqual(pmc[k], v)
        self.assertRaises(
            ClientError,
            self.client.upload_object_unchunked,
            obj, tmpFile, withHashFile=True)
1265

1266 1267
    @patch('%s.object_put' % pithos_pkg, return_value=FR())
    def test_create_object_by_manifestation(self, put):
1268 1269
        manifest = '%s/%s' % (self.client.container, obj)
        kwargs = dict(
1270 1271 1272 1273 1274 1275
            etag='some-etag',
            content_encoding='some content_encoding',
            content_type='some content-type',
            content_disposition='some content_disposition',
            public=True,
            sharing=dict(read=['u1', 'g1', 'u2'], write=['u1']))
1276 1277
        r = self.client.create_object_by_manifestation(obj)
        self.assert_dicts_are_equal(r, FR.headers)
1278 1279 1280 1281
        expected = dict(content_length=0, manifest=manifest)
        for k in kwargs:
            expected['permissions' if k == 'sharing' else k] = None
        self.assertEqual(put.mock_calls[-1], call(obj, **expected))
1282 1283
        r = self.client.create_object_by_manifestation(