File: test_proxy.py

package info (click to toggle)
python-openstacksdk 4.4.0-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 13,352 kB
  • sloc: python: 122,960; sh: 153; makefile: 23
file content (726 lines) | stat: -rw-r--r-- 23,192 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
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
261
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
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
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
487
488
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
542
543
544
545
546
547
548
549
550
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
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
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
688
689
690
691
692
693
694
695
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
721
722
723
724
725
726
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

from hashlib import sha1
import random
import string
import tempfile
import time
from unittest import mock

import requests_mock
from testscenarios import load_tests_apply_scenarios as load_tests  # noqa

from openstack.object_store.v1 import account
from openstack.object_store.v1 import container
from openstack.object_store.v1 import obj
from openstack.tests.unit.cloud import test_object as base_test_object
from openstack.tests.unit import test_proxy_base


class FakeResponse:
    def __init__(self, response, status_code=200, headers=None):
        self.body = response
        self.status_code = status_code
        self.headers = headers if headers else {}

    def json(self):
        return self.body


class TestObjectStoreProxy(test_proxy_base.TestProxyBase):
    kwargs_to_path_args = False

    def setUp(self):
        super().setUp()
        self.proxy = self.cloud.object_store
        self.container = self.getUniqueString()
        self.endpoint = self.cloud.object_store.get_endpoint() + '/'
        self.container_endpoint = f'{self.endpoint}{self.container}'

    def test_account_metadata_get(self):
        self.verify_head(
            self.proxy.get_account_metadata, account.Account, method_args=[]
        )

    def test_container_metadata_get(self):
        self.verify_head(
            self.proxy.get_container_metadata,
            container.Container,
            method_args=["container"],
        )

    def test_container_delete(self):
        self.verify_delete(
            self.proxy.delete_container, container.Container, False
        )

    def test_container_delete_ignore(self):
        self.verify_delete(
            self.proxy.delete_container, container.Container, True
        )

    def test_container_create_attrs(self):
        self.verify_create(
            self.proxy.create_container,
            container.Container,
            method_args=['container_name'],
            expected_args=[],
            expected_kwargs={'name': 'container_name', "x": 1, "y": 2, "z": 3},
        )

    def test_object_metadata_get(self):
        self._verify(
            "openstack.proxy.Proxy._head",
            self.proxy.get_object_metadata,
            method_args=['object'],
            method_kwargs={'container': 'container'},
            expected_args=[obj.Object, 'object'],
            expected_kwargs={'container': 'container'},
        )

    def _test_object_delete(self, ignore):
        expected_kwargs = {
            "ignore_missing": ignore,
            "container": "name",
        }

        self._verify(
            "openstack.proxy.Proxy._delete",
            self.proxy.delete_object,
            method_args=["resource"],
            method_kwargs=expected_kwargs,
            expected_args=[obj.Object, "resource"],
            expected_kwargs=expected_kwargs,
        )

    def test_object_delete(self):
        self._test_object_delete(False)

    def test_object_delete_ignore(self):
        self._test_object_delete(True)

    def test_object_create_attrs(self):
        kwargs = {
            "name": "test",
            "data": "data",
            "container": "name",
            "metadata": {},
        }

        self._verify(
            "openstack.proxy.Proxy._create",
            self.proxy.upload_object,
            method_kwargs=kwargs,
            expected_args=[obj.Object],
            expected_kwargs=kwargs,
        )

    def test_object_create_no_container(self):
        self.assertRaises(TypeError, self.proxy.upload_object)

    def test_object_get(self):
        with requests_mock.Mocker() as m:
            m.get(f"{self.endpoint}container/object", text="data")
            res = self.proxy.get_object("object", container="container")
            self.assertIsNone(res.data)

    def test_object_get_write_file(self):
        with requests_mock.Mocker() as m:
            m.get(f"{self.endpoint}container/object", text="data")
            with tempfile.NamedTemporaryFile() as f:
                self.proxy.get_object(
                    "object", container="container", outfile=f.name
                )
                dt = open(f.name).read()
                self.assertEqual(dt, "data")

    def test_object_get_remember_content(self):
        with requests_mock.Mocker() as m:
            m.get(f"{self.endpoint}container/object", text="data")
            res = self.proxy.get_object(
                "object", container="container", remember_content=True
            )
            self.assertEqual(res.data, "data")

    def test_set_temp_url_key(self):
        key = 'super-secure-key'

        self.register_uris(
            [
                dict(
                    method='POST',
                    uri=self.endpoint,
                    status_code=204,
                    validate=dict(
                        headers={'x-account-meta-temp-url-key': key}
                    ),
                ),
                dict(
                    method='HEAD',
                    uri=self.endpoint,
                    headers={'x-account-meta-temp-url-key': key},
                ),
            ]
        )
        self.proxy.set_account_temp_url_key(key)
        self.assert_calls()

    def test_set_account_temp_url_key_second(self):
        key = 'super-secure-key'

        self.register_uris(
            [
                dict(
                    method='POST',
                    uri=self.endpoint,
                    status_code=204,
                    validate=dict(
                        headers={'x-account-meta-temp-url-key-2': key}
                    ),
                ),
                dict(
                    method='HEAD',
                    uri=self.endpoint,
                    headers={'x-account-meta-temp-url-key-2': key},
                ),
            ]
        )
        self.proxy.set_account_temp_url_key(key, secondary=True)
        self.assert_calls()

    def test_set_container_temp_url_key(self):
        key = 'super-secure-key'

        self.register_uris(
            [
                dict(
                    method='POST',
                    uri=self.container_endpoint,
                    status_code=204,
                    validate=dict(
                        headers={'x-container-meta-temp-url-key': key}
                    ),
                ),
                dict(
                    method='HEAD',
                    uri=self.container_endpoint,
                    headers={'x-container-meta-temp-url-key': key},
                ),
            ]
        )
        self.proxy.set_container_temp_url_key(self.container, key)
        self.assert_calls()

    def test_set_container_temp_url_key_second(self):
        key = 'super-secure-key'

        self.register_uris(
            [
                dict(
                    method='POST',
                    uri=self.container_endpoint,
                    status_code=204,
                    validate=dict(
                        headers={'x-container-meta-temp-url-key-2': key}
                    ),
                ),
                dict(
                    method='HEAD',
                    uri=self.container_endpoint,
                    headers={'x-container-meta-temp-url-key-2': key},
                ),
            ]
        )
        self.proxy.set_container_temp_url_key(
            self.container, key, secondary=True
        )
        self.assert_calls()

    def test_copy_object(self):
        self.assertRaises(NotImplementedError, self.proxy.copy_object)

    def test_file_segment(self):
        file_size = 4200
        content = ''.join(
            random.choice(string.ascii_uppercase + string.digits)
            for _ in range(file_size)
        ).encode('latin-1')
        self.imagefile = tempfile.NamedTemporaryFile(delete=False)
        self.imagefile.write(content)
        self.imagefile.close()

        segments = self.proxy._get_file_segments(
            endpoint='test_container/test_image',
            filename=self.imagefile.name,
            file_size=file_size,
            segment_size=1000,
        )
        self.assertEqual(len(segments), 5)
        segment_content = b''
        for index, (name, segment) in enumerate(segments.items()):
            self.assertEqual(
                f'test_container/test_image/{index:0>6}',
                name,
            )
            segment_content += segment.read()
        self.assertEqual(content, segment_content)


class TestDownloadObject(base_test_object.BaseTestObject):
    def setUp(self):
        super().setUp()
        self.the_data = b'test body'
        self.register_uris(
            [
                dict(
                    method='GET',
                    uri=self.object_endpoint,
                    headers={
                        'Content-Length': str(len(self.the_data)),
                        'Content-Type': 'application/octet-stream',
                        'Accept-Ranges': 'bytes',
                        'Last-Modified': 'Thu, 15 Dec 2016 13:34:14 GMT',
                        'Etag': '"b5c454b44fbd5344793e3fb7e3850768"',
                        'X-Timestamp': '1481808853.65009',
                        'X-Trans-Id': 'tx68c2a2278f0c469bb6de1-005857ed80dfw1',
                        'Date': 'Mon, 19 Dec 2016 14:24:00 GMT',
                        'X-Static-Large-Object': 'True',
                        'X-Object-Meta-Mtime': '1481513709.168512',
                    },
                    content=self.the_data,
                )
            ]
        )

    def test_download(self):
        data = self.cloud.object_store.download_object(
            self.object, container=self.container
        )

        self.assertEqual(data, self.the_data)
        self.assert_calls()

    def test_stream(self):
        chunk_size = 2
        for index, chunk in enumerate(
            self.cloud.object_store.stream_object(
                self.object, container=self.container, chunk_size=chunk_size
            )
        ):
            chunk_len = len(chunk)
            start = index * chunk_size
            end = start + chunk_len
            self.assertLessEqual(chunk_len, chunk_size)
            self.assertEqual(chunk, self.the_data[start:end])
        self.assert_calls()


class TestExtractName(TestObjectStoreProxy):
    scenarios = [
        ('discovery', dict(url='/', parts=['account'])),
        ('endpoints', dict(url='/endpoints', parts=['endpoints'])),
        (
            'container',
            dict(url='/AUTH_123/container_name', parts=['container']),
        ),
        ('object', dict(url='/container_name/object_name', parts=['object'])),
        (
            'object_long',
            dict(
                url='/v1/AUTH_123/cnt/path/deep/object_name', parts=['object']
            ),
        ),
    ]

    def test_extract_name(self):
        results = self.proxy._extract_name(self.url, project_id='123')
        self.assertEqual(self.parts, results)


class TestTempURL(TestObjectStoreProxy):
    expires_iso8601_format = '%Y-%m-%dT%H:%M:%SZ'
    short_expires_iso8601_format = '%Y-%m-%d'
    time_errmsg = (
        'time must either be a whole number or in specific ISO 8601 format.'
    )
    path_errmsg = 'path must be full path to an object e.g. /v1/a/c/o'
    url = '/v1/AUTH_account/c/o'
    seconds = 3600
    key = 'correcthorsebatterystaple'
    method = 'GET'
    expected_url = url + (
        '?temp_url_sig=temp_url_signature&temp_url_expires=1400003600'
    )
    expected_body = '\n'.join(
        [
            method,
            '1400003600',
            url,
        ]
    ).encode('utf-8')

    @mock.patch('hmac.HMAC')
    @mock.patch('time.time', return_value=1400000000)
    def test_generate_temp_url(self, time_mock, hmac_mock):
        hmac_mock().hexdigest.return_value = 'temp_url_signature'
        url = self.proxy.generate_temp_url(
            self.url, self.seconds, self.method, temp_url_key=self.key
        )
        key = self.key
        if not isinstance(key, bytes):
            key = key.encode('utf-8')
        self.assertEqual(url, self.expected_url)
        self.assertEqual(
            hmac_mock.mock_calls,
            [
                mock.call(),
                mock.call(key, self.expected_body, sha1),
                mock.call().hexdigest(),
            ],
        )
        self.assertIsInstance(url, type(self.url))

    @mock.patch('hmac.HMAC')
    @mock.patch('time.time', return_value=1400000000)
    def test_generate_temp_url_ip_range(self, time_mock, hmac_mock):
        hmac_mock().hexdigest.return_value = 'temp_url_signature'
        ip_ranges = [
            '1.2.3.4',
            '1.2.3.4/24',
            '2001:db8::',
            b'1.2.3.4',
            b'1.2.3.4/24',
            b'2001:db8::',
        ]
        path = '/v1/AUTH_account/c/o/'
        expected_url = path + (
            '?temp_url_sig=temp_url_signature'
            '&temp_url_expires=1400003600'
            '&temp_url_ip_range='
        )
        for ip_range in ip_ranges:
            hmac_mock.reset_mock()
            url = self.proxy.generate_temp_url(
                path,
                self.seconds,
                self.method,
                temp_url_key=self.key,
                ip_range=ip_range,
            )
            key = self.key
            if not isinstance(key, bytes):
                key = key.encode('utf-8')

            if isinstance(ip_range, bytes):
                ip_range_expected_url = expected_url + ip_range.decode('utf-8')
                expected_body = '\n'.join(
                    [
                        'ip=' + ip_range.decode('utf-8'),
                        self.method,
                        '1400003600',
                        path,
                    ]
                ).encode('utf-8')
            else:
                ip_range_expected_url = expected_url + ip_range
                expected_body = '\n'.join(
                    [
                        'ip=' + ip_range,
                        self.method,
                        '1400003600',
                        path,
                    ]
                ).encode('utf-8')

            self.assertEqual(url, ip_range_expected_url)

            self.assertEqual(
                hmac_mock.mock_calls,
                [
                    mock.call(key, expected_body, sha1),
                    mock.call().hexdigest(),
                ],
            )
            self.assertIsInstance(url, type(path))

    @mock.patch('hmac.HMAC')
    def test_generate_temp_url_iso8601_argument(self, hmac_mock):
        hmac_mock().hexdigest.return_value = 'temp_url_signature'
        url = self.proxy.generate_temp_url(
            self.url,
            '2014-05-13T17:53:20Z',
            self.method,
            temp_url_key=self.key,
        )
        self.assertEqual(url, self.expected_url)

        # Don't care about absolute arg.
        url = self.proxy.generate_temp_url(
            self.url,
            '2014-05-13T17:53:20Z',
            self.method,
            temp_url_key=self.key,
            absolute=True,
        )
        self.assertEqual(url, self.expected_url)

        lt = time.localtime()
        expires = time.strftime(self.expires_iso8601_format[:-1], lt)

        if not isinstance(self.expected_url, str):
            expected_url = self.expected_url.replace(
                b'1400003600',
                bytes(str(int(time.mktime(lt))), encoding='ascii'),
            )
        else:
            expected_url = self.expected_url.replace(
                '1400003600', str(int(time.mktime(lt)))
            )
        url = self.proxy.generate_temp_url(
            self.url, expires, self.method, temp_url_key=self.key
        )
        self.assertEqual(url, expected_url)

        expires = time.strftime(self.short_expires_iso8601_format, lt)
        lt = time.strptime(expires, self.short_expires_iso8601_format)

        if not isinstance(self.expected_url, str):
            expected_url = self.expected_url.replace(
                b'1400003600',
                bytes(str(int(time.mktime(lt))), encoding='ascii'),
            )
        else:
            expected_url = self.expected_url.replace(
                '1400003600', str(int(time.mktime(lt)))
            )
        url = self.proxy.generate_temp_url(
            self.url, expires, self.method, temp_url_key=self.key
        )
        self.assertEqual(url, expected_url)

    @mock.patch('hmac.HMAC')
    @mock.patch('time.time', return_value=1400000000)
    def test_generate_temp_url_iso8601_output(self, time_mock, hmac_mock):
        hmac_mock().hexdigest.return_value = 'temp_url_signature'
        url = self.proxy.generate_temp_url(
            self.url,
            self.seconds,
            self.method,
            temp_url_key=self.key,
            iso8601=True,
        )
        key = self.key
        if not isinstance(key, bytes):
            key = key.encode('utf-8')

        expires = time.strftime(
            self.expires_iso8601_format, time.gmtime(1400003600)
        )
        if not isinstance(self.url, str):
            self.assertTrue(url.endswith(bytes(expires, 'utf-8')))
        else:
            self.assertTrue(url.endswith(expires))
        self.assertEqual(
            hmac_mock.mock_calls,
            [
                mock.call(),
                mock.call(key, self.expected_body, sha1),
                mock.call().hexdigest(),
            ],
        )
        self.assertIsInstance(url, type(self.url))

    @mock.patch('hmac.HMAC')
    @mock.patch('time.time', return_value=1400000000)
    def test_generate_temp_url_prefix(self, time_mock, hmac_mock):
        hmac_mock().hexdigest.return_value = 'temp_url_signature'
        prefixes = ['', 'o', 'p0/p1/']
        for p in prefixes:
            hmac_mock.reset_mock()
            path = '/v1/AUTH_account/c/' + p
            expected_url = path + (
                '?temp_url_sig=temp_url_signature'
                '&temp_url_expires=1400003600'
                '&temp_url_prefix=' + p
            )
            expected_body = '\n'.join(
                [
                    self.method,
                    '1400003600',
                    'prefix:' + path,
                ]
            ).encode('utf-8')
            url = self.proxy.generate_temp_url(
                path,
                self.seconds,
                self.method,
                prefix=True,
                temp_url_key=self.key,
            )
            key = self.key
            if not isinstance(key, bytes):
                key = key.encode('utf-8')
            self.assertEqual(url, expected_url)
            self.assertEqual(
                hmac_mock.mock_calls,
                [
                    mock.call(key, expected_body, sha1),
                    mock.call().hexdigest(),
                ],
            )

            self.assertIsInstance(url, type(path))

    def test_generate_temp_url_invalid_path(self):
        self.assertRaisesRegex(
            ValueError,
            'path must be representable as UTF-8',
            self.proxy.generate_temp_url,
            b'/v1/a/c/\xff',
            self.seconds,
            self.method,
            temp_url_key=self.key,
        )

    @mock.patch('hmac.HMAC.hexdigest', return_value="temp_url_signature")
    def test_generate_absolute_expiry_temp_url(self, hmac_mock):
        if isinstance(self.expected_url, bytes):
            expected_url = self.expected_url.replace(
                b'1400003600', b'2146636800'
            )
        else:
            expected_url = self.expected_url.replace(
                '1400003600', '2146636800'
            )
        url = self.proxy.generate_temp_url(
            self.url,
            2146636800,
            self.method,
            absolute=True,
            temp_url_key=self.key,
        )
        self.assertEqual(url, expected_url)

    def test_generate_temp_url_bad_time(self):
        for bad_time in [
            'not_an_int',
            -1,
            1.1,
            '-1',
            '1.1',
            '2015-05',
            '2015-05-01T01:00',
        ]:
            self.assertRaisesRegex(
                ValueError,
                self.time_errmsg,
                self.proxy.generate_temp_url,
                self.url,
                bad_time,
                self.method,
                temp_url_key=self.key,
            )

    def test_generate_temp_url_bad_path(self):
        for bad_path in [
            '/v1/a/c',
            'v1/a/c/o',
            'blah/v1/a/c/o',
            '/v1//c/o',
            '/v1/a/c/',
            '/v1/a/c',
        ]:
            self.assertRaisesRegex(
                ValueError,
                self.path_errmsg,
                self.proxy.generate_temp_url,
                bad_path,
                60,
                self.method,
                temp_url_key=self.key,
            )


class TestTempURLUnicodePathAndKey(TestTempURL):
    url = '/v1/\u00e4/c/\u00f3'
    key = 'k\u00e9y'
    expected_url = (
        f'{url}?temp_url_sig=temp_url_signature&temp_url_expires=1400003600'
    )
    expected_body = '\n'.join(
        [
            'GET',
            '1400003600',
            url,
        ]
    ).encode('utf-8')


class TestTempURLUnicodePathBytesKey(TestTempURL):
    url = '/v1/\u00e4/c/\u00f3'
    key = 'k\u00e9y'.encode()
    expected_url = (
        f'{url}?temp_url_sig=temp_url_signature&temp_url_expires=1400003600'
    )
    expected_body = '\n'.join(
        [
            'GET',
            '1400003600',
            url,
        ]
    ).encode('utf-8')


class TestTempURLBytesPathUnicodeKey(TestTempURL):
    url = '/v1/\u00e4/c/\u00f3'.encode()
    key = 'k\u00e9y'
    expected_url = url + (
        b'?temp_url_sig=temp_url_signature&temp_url_expires=1400003600'
    )
    expected_body = b'\n'.join(
        [
            b'GET',
            b'1400003600',
            url,
        ]
    )


class TestTempURLBytesPathAndKey(TestTempURL):
    url = '/v1/\u00e4/c/\u00f3'.encode()
    key = 'k\u00e9y'.encode()
    expected_url = url + (
        b'?temp_url_sig=temp_url_signature&temp_url_expires=1400003600'
    )
    expected_body = b'\n'.join(
        [
            b'GET',
            b'1400003600',
            url,
        ]
    )


class TestTempURLBytesPathAndNonUtf8Key(TestTempURL):
    url = '/v1/\u00e4/c/\u00f3'.encode()
    key = b'k\xffy'
    expected_url = url + (
        b'?temp_url_sig=temp_url_signature&temp_url_expires=1400003600'
    )
    expected_body = b'\n'.join(
        [
            b'GET',
            b'1400003600',
            url,
        ]
    )