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
|
# Copyright 2010 Google Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
Provides basic mocks of core storage service classes, for unit testing:
ACL, Key, Bucket, Connection, and StorageUri. We implement a subset of
the interfaces defined in the real boto classes, but don't handle most
of the optional params (which we indicate with the constant "NOT_IMPL").
"""
import copy
import boto
import base64
import re
import locale
from hashlib import md5
from boto.utils import compute_md5
from boto.utils import find_matching_headers
from boto.utils import merge_headers_by_name
from boto.s3.prefix import Prefix
from boto.compat import six
NOT_IMPL = None
class MockAcl(object):
def __init__(self, parent=NOT_IMPL):
pass
def startElement(self, name, attrs, connection):
pass
def endElement(self, name, value, connection):
pass
def to_xml(self):
return '<mock_ACL_XML/>'
class MockKey(object):
def __init__(self, bucket=None, name=None):
self.bucket = bucket
self.name = name
self.data = None
self.etag = None
self.size = None
self.closed = True
self.content_encoding = None
self.content_language = None
self.content_type = None
self.last_modified = 'Wed, 06 Oct 2010 05:11:54 GMT'
self.BufferSize = 8192
def __repr__(self):
if self.bucket:
return '<MockKey: %s,%s>' % (self.bucket.name, self.name)
else:
return '<MockKey: %s>' % self.name
def get_contents_as_string(self, headers=NOT_IMPL,
cb=NOT_IMPL, num_cb=NOT_IMPL,
torrent=NOT_IMPL,
version_id=NOT_IMPL):
return self.data
def get_contents_to_file(self, fp, headers=NOT_IMPL,
cb=NOT_IMPL, num_cb=NOT_IMPL,
torrent=NOT_IMPL,
version_id=NOT_IMPL,
res_download_handler=NOT_IMPL):
if isinstance(self.data, six.binary_type):
if 'b' in fp.mode:
# data is bytes, and fp is binary
fp.write(self.data)
elif hasattr(fp, 'buffer'):
# data is bytes, but fp is text - try the underlying buffer
fp.buffer.write(self.data)
else:
# data is bytes, but fp is text - try to decode bytes
fp.write(
self.data.decode(locale.getpreferredencoding(False)))
elif 'b' in fp.mode:
# data is not bytes, but fp is binary
fp.write(self.data.encode(locale.getpreferredencoding(False)))
else:
# data is not bytes, and fp is text
fp.write(self.data)
def get_file(self, fp, headers=NOT_IMPL, cb=NOT_IMPL, num_cb=NOT_IMPL,
torrent=NOT_IMPL, version_id=NOT_IMPL,
override_num_retries=NOT_IMPL):
fp.write(self.data)
def _handle_headers(self, headers):
if not headers:
return
if find_matching_headers('Content-Encoding', headers):
self.content_encoding = merge_headers_by_name('Content-Encoding',
headers)
if find_matching_headers('Content-Type', headers):
self.content_type = merge_headers_by_name('Content-Type', headers)
if find_matching_headers('Content-Language', headers):
self.content_language = merge_headers_by_name('Content-Language',
headers)
# Simplistic partial implementation for headers: Just supports range GETs
# of flavor 'Range: bytes=xyz-'.
def open_read(self, headers=None, query_args=NOT_IMPL,
override_num_retries=NOT_IMPL):
if self.closed:
self.read_pos = 0
self.closed = False
if headers and 'Range' in headers:
match = re.match('bytes=([0-9]+)-$', headers['Range'])
if match:
self.read_pos = int(match.group(1))
def close(self, fast=NOT_IMPL):
self.closed = True
def read(self, size=0):
self.open_read()
if size == 0:
data = self.data[self.read_pos:]
self.read_pos = self.size
else:
data = self.data[self.read_pos:self.read_pos+size]
self.read_pos += size
if not data:
self.close()
return data
def set_contents_from_file(self, fp, headers=None, replace=NOT_IMPL,
cb=NOT_IMPL, num_cb=NOT_IMPL,
policy=NOT_IMPL, md5=NOT_IMPL,
res_upload_handler=NOT_IMPL):
self.data = fp.read()
self.set_etag()
self.size = len(self.data)
self._handle_headers(headers)
def set_contents_from_stream(self, fp, headers=None, replace=NOT_IMPL,
cb=NOT_IMPL, num_cb=NOT_IMPL, policy=NOT_IMPL,
reduced_redundancy=NOT_IMPL, query_args=NOT_IMPL,
size=NOT_IMPL):
self.data = b''
chunk = fp.read(self.BufferSize)
while chunk:
self.data += chunk
chunk = fp.read(self.BufferSize)
self.set_etag()
self.size = len(self.data)
self._handle_headers(headers)
def set_contents_from_string(self, s, headers=NOT_IMPL, replace=NOT_IMPL,
cb=NOT_IMPL, num_cb=NOT_IMPL, policy=NOT_IMPL,
md5=NOT_IMPL, reduced_redundancy=NOT_IMPL):
self.data = copy.copy(s)
self.set_etag()
self.size = len(s)
self._handle_headers(headers)
def set_contents_from_filename(self, filename, headers=None,
replace=NOT_IMPL, cb=NOT_IMPL,
num_cb=NOT_IMPL, policy=NOT_IMPL,
md5=NOT_IMPL, res_upload_handler=NOT_IMPL):
fp = open(filename, 'rb')
self.set_contents_from_file(fp, headers, replace, cb, num_cb,
policy, md5, res_upload_handler)
fp.close()
def copy(self, dst_bucket_name, dst_key, metadata=NOT_IMPL,
reduced_redundancy=NOT_IMPL, preserve_acl=NOT_IMPL):
dst_bucket = self.bucket.connection.get_bucket(dst_bucket_name)
return dst_bucket.copy_key(dst_key, self.bucket.name,
self.name, metadata)
@property
def provider(self):
provider = None
if self.bucket and self.bucket.connection:
provider = self.bucket.connection.provider
return provider
def set_etag(self):
"""
Set etag attribute by generating hex MD5 checksum on current
contents of mock key.
"""
m = md5()
if not isinstance(self.data, bytes):
m.update(self.data.encode('utf-8'))
else:
m.update(self.data)
hex_md5 = m.hexdigest()
self.etag = hex_md5
def compute_md5(self, fp):
"""
:type fp: file
:param fp: File pointer to the file to MD5 hash. The file pointer
will be reset to the beginning of the file before the
method returns.
:rtype: tuple
:return: A tuple containing the hex digest version of the MD5 hash
as the first element and the base64 encoded version of the
plain digest as the second element.
"""
tup = compute_md5(fp)
# Returned values are MD5 hash, base64 encoded MD5 hash, and file size.
# The internal implementation of compute_md5() needs to return the
# file size but we don't want to return that value to the external
# caller because it changes the class interface (i.e. it might
# break some code) so we consume the third tuple value here and
# return the remainder of the tuple to the caller, thereby preserving
# the existing interface.
self.size = tup[2]
return tup[0:2]
class MockBucket(object):
def __init__(self, connection=None, name=None, key_class=NOT_IMPL):
self.name = name
self.keys = {}
self.acls = {name: MockAcl()}
# default object ACLs are one per bucket and not supported for keys
self.def_acl = MockAcl()
self.subresources = {}
self.connection = connection
self.logging = False
def __repr__(self):
return 'MockBucket: %s' % self.name
def copy_key(self, new_key_name, src_bucket_name,
src_key_name, metadata=NOT_IMPL, src_version_id=NOT_IMPL,
storage_class=NOT_IMPL, preserve_acl=NOT_IMPL,
encrypt_key=NOT_IMPL, headers=NOT_IMPL, query_args=NOT_IMPL):
new_key = self.new_key(key_name=new_key_name)
src_key = self.connection.get_bucket(
src_bucket_name).get_key(src_key_name)
new_key.data = copy.copy(src_key.data)
new_key.size = len(new_key.data)
return new_key
def disable_logging(self):
self.logging = False
def enable_logging(self, target_bucket_prefix):
self.logging = True
def get_logging_config(self):
return {"Logging": {}}
def get_versioning_status(self, headers=NOT_IMPL):
return False
def get_acl(self, key_name='', headers=NOT_IMPL, version_id=NOT_IMPL):
if key_name:
# Return ACL for the key.
return self.acls[key_name]
else:
# Return ACL for the bucket.
return self.acls[self.name]
def get_def_acl(self, key_name=NOT_IMPL, headers=NOT_IMPL,
version_id=NOT_IMPL):
# Return default ACL for the bucket.
return self.def_acl
def get_subresource(self, subresource, key_name=NOT_IMPL, headers=NOT_IMPL,
version_id=NOT_IMPL):
if subresource in self.subresources:
return self.subresources[subresource]
else:
return '<Subresource/>'
def new_key(self, key_name=None):
mock_key = MockKey(self, key_name)
self.keys[key_name] = mock_key
self.acls[key_name] = MockAcl()
return mock_key
def delete_key(self, key_name, headers=NOT_IMPL,
version_id=NOT_IMPL, mfa_token=NOT_IMPL):
if key_name not in self.keys:
raise boto.exception.StorageResponseError(404, 'Not Found')
del self.keys[key_name]
def get_all_keys(self, headers=NOT_IMPL):
return six.itervalues(self.keys)
def get_key(self, key_name, headers=NOT_IMPL, version_id=NOT_IMPL):
# Emulate behavior of boto when get_key called with non-existent key.
if key_name not in self.keys:
return None
return self.keys[key_name]
def list(self, prefix='', delimiter='', marker=NOT_IMPL,
headers=NOT_IMPL):
prefix = prefix or '' # Turn None into '' for prefix match.
# Return list instead of using a generator so we don't get
# 'dictionary changed size during iteration' error when performing
# deletions while iterating (e.g., during test cleanup).
result = []
key_name_set = set()
for k in six.itervalues(self.keys):
if k.name.startswith(prefix):
k_name_past_prefix = k.name[len(prefix):]
if delimiter:
pos = k_name_past_prefix.find(delimiter)
else:
pos = -1
if (pos != -1):
key_or_prefix = Prefix(
bucket=self, name=k.name[:len(prefix)+pos+1])
else:
key_or_prefix = MockKey(bucket=self, name=k.name)
if key_or_prefix.name not in key_name_set:
key_name_set.add(key_or_prefix.name)
result.append(key_or_prefix)
return result
def set_acl(self, acl_or_str, key_name='', headers=NOT_IMPL,
version_id=NOT_IMPL):
# We only handle setting ACL XML here; if you pass a canned ACL
# the get_acl call will just return that string name.
if key_name:
# Set ACL for the key.
self.acls[key_name] = MockAcl(acl_or_str)
else:
# Set ACL for the bucket.
self.acls[self.name] = MockAcl(acl_or_str)
def set_def_acl(self, acl_or_str, key_name=NOT_IMPL, headers=NOT_IMPL,
version_id=NOT_IMPL):
# We only handle setting ACL XML here; if you pass a canned ACL
# the get_acl call will just return that string name.
# Set default ACL for the bucket.
self.def_acl = acl_or_str
def set_subresource(self, subresource, value, key_name=NOT_IMPL,
headers=NOT_IMPL, version_id=NOT_IMPL):
self.subresources[subresource] = value
class MockProvider(object):
def __init__(self, provider):
self.provider = provider
def get_provider_name(self):
return self.provider
class MockConnection(object):
def __init__(self, aws_access_key_id=NOT_IMPL,
aws_secret_access_key=NOT_IMPL, is_secure=NOT_IMPL,
port=NOT_IMPL, proxy=NOT_IMPL, proxy_port=NOT_IMPL,
proxy_user=NOT_IMPL, proxy_pass=NOT_IMPL,
host=NOT_IMPL, debug=NOT_IMPL,
https_connection_factory=NOT_IMPL,
calling_format=NOT_IMPL,
path=NOT_IMPL, provider='s3',
bucket_class=NOT_IMPL):
self.buckets = {}
self.provider = MockProvider(provider)
def create_bucket(self, bucket_name, headers=NOT_IMPL, location=NOT_IMPL,
policy=NOT_IMPL, storage_class=NOT_IMPL):
if bucket_name in self.buckets:
raise boto.exception.StorageCreateError(
409, 'BucketAlreadyOwnedByYou',
"<Message>Your previous request to create the named bucket "
"succeeded and you already own it.</Message>")
mock_bucket = MockBucket(name=bucket_name, connection=self)
self.buckets[bucket_name] = mock_bucket
return mock_bucket
def delete_bucket(self, bucket, headers=NOT_IMPL):
if bucket not in self.buckets:
raise boto.exception.StorageResponseError(
404, 'NoSuchBucket', '<Message>no such bucket</Message>')
del self.buckets[bucket]
def get_bucket(self, bucket_name, validate=NOT_IMPL, headers=NOT_IMPL):
if bucket_name not in self.buckets:
raise boto.exception.StorageResponseError(404, 'NoSuchBucket',
'Not Found')
return self.buckets[bucket_name]
def get_all_buckets(self, headers=NOT_IMPL):
return six.itervalues(self.buckets)
# We only mock a single provider/connection.
mock_connection = MockConnection()
class MockBucketStorageUri(object):
delim = '/'
def __init__(self, scheme, bucket_name=None, object_name=None,
debug=NOT_IMPL, suppress_consec_slashes=NOT_IMPL,
version_id=None, generation=None, is_latest=False):
self.scheme = scheme
self.bucket_name = bucket_name
self.object_name = object_name
self.suppress_consec_slashes = suppress_consec_slashes
if self.bucket_name and self.object_name:
self.uri = ('%s://%s/%s' % (self.scheme, self.bucket_name,
self.object_name))
elif self.bucket_name:
self.uri = ('%s://%s/' % (self.scheme, self.bucket_name))
else:
self.uri = ('%s://' % self.scheme)
self.version_id = version_id
self.generation = generation and int(generation)
self.is_version_specific = (bool(self.generation)
or bool(self.version_id))
self.is_latest = is_latest
if bucket_name and object_name:
self.versionless_uri = '%s://%s/%s' % (scheme, bucket_name,
object_name)
def __repr__(self):
"""Returns string representation of URI."""
return self.uri
def acl_class(self):
return MockAcl
def canned_acls(self):
return boto.provider.Provider('aws').canned_acls
def clone_replace_name(self, new_name):
return self.__class__(self.scheme, self.bucket_name, new_name)
def clone_replace_key(self, key):
return self.__class__(
key.provider.get_provider_name(),
bucket_name=key.bucket.name,
object_name=key.name,
suppress_consec_slashes=self.suppress_consec_slashes,
version_id=getattr(key, 'version_id', None),
generation=getattr(key, 'generation', None),
is_latest=getattr(key, 'is_latest', None))
def connect(self, access_key_id=NOT_IMPL, secret_access_key=NOT_IMPL):
return mock_connection
def create_bucket(self, headers=NOT_IMPL, location=NOT_IMPL,
policy=NOT_IMPL, storage_class=NOT_IMPL):
return self.connect().create_bucket(self.bucket_name)
def delete_bucket(self, headers=NOT_IMPL):
return self.connect().delete_bucket(self.bucket_name)
def get_versioning_config(self, headers=NOT_IMPL):
self.get_bucket().get_versioning_status(headers)
def has_version(self):
return (issubclass(type(self), MockBucketStorageUri)
and ((self.version_id is not None)
or (self.generation is not None)))
def delete_key(self, validate=NOT_IMPL, headers=NOT_IMPL,
version_id=NOT_IMPL, mfa_token=NOT_IMPL):
self.get_bucket().delete_key(self.object_name)
def disable_logging(self, validate=NOT_IMPL, headers=NOT_IMPL,
version_id=NOT_IMPL):
self.get_bucket().disable_logging()
def enable_logging(self, target_bucket, target_prefix, validate=NOT_IMPL,
headers=NOT_IMPL, version_id=NOT_IMPL):
self.get_bucket().enable_logging(target_bucket)
def get_logging_config(self, validate=NOT_IMPL, headers=NOT_IMPL,
version_id=NOT_IMPL):
return self.get_bucket().get_logging_config()
def equals(self, uri):
return self.uri == uri.uri
def get_acl(self, validate=NOT_IMPL, headers=NOT_IMPL, version_id=NOT_IMPL):
return self.get_bucket().get_acl(self.object_name)
def get_def_acl(self, validate=NOT_IMPL, headers=NOT_IMPL,
version_id=NOT_IMPL):
return self.get_bucket().get_def_acl(self.object_name)
def get_subresource(self, subresource, validate=NOT_IMPL, headers=NOT_IMPL,
version_id=NOT_IMPL):
return self.get_bucket().get_subresource(subresource, self.object_name)
def get_all_buckets(self, headers=NOT_IMPL):
return self.connect().get_all_buckets()
def get_all_keys(self, validate=NOT_IMPL, headers=NOT_IMPL):
return self.get_bucket().get_all_keys(self)
def list_bucket(self, prefix='', delimiter='', headers=NOT_IMPL,
all_versions=NOT_IMPL):
return self.get_bucket().list(prefix=prefix, delimiter=delimiter)
def get_bucket(self, validate=NOT_IMPL, headers=NOT_IMPL):
return self.connect().get_bucket(self.bucket_name)
def get_key(self, validate=NOT_IMPL, headers=NOT_IMPL,
version_id=NOT_IMPL):
return self.get_bucket().get_key(self.object_name)
def is_file_uri(self):
return False
def is_cloud_uri(self):
return True
def names_container(self):
return bool(not self.object_name)
def names_singleton(self):
return bool(self.object_name)
def names_directory(self):
return False
def names_provider(self):
return bool(not self.bucket_name)
def names_bucket(self):
return self.names_container()
def names_file(self):
return False
def names_object(self):
return not self.names_container()
def is_stream(self):
return False
def new_key(self, validate=NOT_IMPL, headers=NOT_IMPL):
bucket = self.get_bucket()
return bucket.new_key(self.object_name)
def set_acl(self, acl_or_str, key_name='', validate=NOT_IMPL,
headers=NOT_IMPL, version_id=NOT_IMPL):
self.get_bucket().set_acl(acl_or_str, key_name)
def set_def_acl(self, acl_or_str, key_name=NOT_IMPL, validate=NOT_IMPL,
headers=NOT_IMPL, version_id=NOT_IMPL):
self.get_bucket().set_def_acl(acl_or_str)
def set_subresource(self, subresource, value, validate=NOT_IMPL,
headers=NOT_IMPL, version_id=NOT_IMPL):
self.get_bucket().set_subresource(subresource, value, self.object_name)
def copy_key(self, src_bucket_name, src_key_name, metadata=NOT_IMPL,
src_version_id=NOT_IMPL, storage_class=NOT_IMPL,
preserve_acl=NOT_IMPL, encrypt_key=NOT_IMPL, headers=NOT_IMPL,
query_args=NOT_IMPL, src_generation=NOT_IMPL):
dst_bucket = self.get_bucket()
return dst_bucket.copy_key(new_key_name=self.object_name,
src_bucket_name=src_bucket_name,
src_key_name=src_key_name)
def set_contents_from_string(self, s, headers=NOT_IMPL, replace=NOT_IMPL,
cb=NOT_IMPL, num_cb=NOT_IMPL, policy=NOT_IMPL,
md5=NOT_IMPL, reduced_redundancy=NOT_IMPL):
key = self.new_key()
key.set_contents_from_string(s)
def set_contents_from_file(self, fp, headers=None, replace=NOT_IMPL,
cb=NOT_IMPL, num_cb=NOT_IMPL, policy=NOT_IMPL,
md5=NOT_IMPL, size=NOT_IMPL, rewind=NOT_IMPL,
res_upload_handler=NOT_IMPL):
key = self.new_key()
return key.set_contents_from_file(fp, headers=headers)
def set_contents_from_stream(self, fp, headers=NOT_IMPL, replace=NOT_IMPL,
cb=NOT_IMPL, num_cb=NOT_IMPL, policy=NOT_IMPL,
reduced_redundancy=NOT_IMPL,
query_args=NOT_IMPL, size=NOT_IMPL):
dst_key.set_contents_from_stream(fp)
def get_contents_to_file(self, fp, headers=NOT_IMPL, cb=NOT_IMPL,
num_cb=NOT_IMPL, torrent=NOT_IMPL,
version_id=NOT_IMPL, res_download_handler=NOT_IMPL,
response_headers=NOT_IMPL):
key = self.get_key()
key.get_contents_to_file(fp)
def get_contents_to_stream(self, fp, headers=NOT_IMPL, cb=NOT_IMPL,
num_cb=NOT_IMPL, version_id=NOT_IMPL):
key = self.get_key()
return key.get_contents_to_file(fp)
|