forked from drivendataorg/cloudpathlib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmock_s3.py
More file actions
278 lines (215 loc) · 8.78 KB
/
Copy pathmock_s3.py
File metadata and controls
278 lines (215 loc) · 8.78 KB
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
import collections
from datetime import datetime
from pathlib import Path, PurePosixPath
import shutil
from tempfile import TemporaryDirectory
from boto3.session import Session
from botocore.exceptions import ClientError
from .utils import delete_empty_parents_up_to_root
TEST_ASSETS = Path(__file__).parent.parent / "assets"
DEFAULT_S3_BUCKET_NAME = "bucket"
# Since we don't contol exactly when the filesystem finishes writing a file
# and the test files are super small, we can end up with race conditions in
# the tests where the updated file is modified before the source file,
# which breaks our caching logic
NoSuchKey = Session().client("s3").exceptions.NoSuchKey
def mocked_session_class_factory(test_dir: str):
class MockBoto3Session:
def __init__(self, *args, **kwargs):
# copy test assets for reference in tests without affecting assets
self.tmp = TemporaryDirectory()
self.tmp_path = Path(self.tmp.name) / "test_case_copy"
shutil.copytree(TEST_ASSETS, self.tmp_path / test_dir)
self.metadata_cache = {}
def __del__(self):
self.tmp.cleanup()
def resource(self, item, endpoint_url, config=None):
return MockBoto3Resource(self.tmp_path, session=self)
def client(self, item, endpoint_url, config=None):
return MockBoto3Client(self.tmp_path, session=self)
return MockBoto3Session
class MockBoto3Resource:
def __init__(self, root, session=None):
self.root = root
self.download_config = None
self.upload_config = None
self.session = session
def Bucket(self, bucket):
return MockBoto3Bucket(self.root, session=self.session)
def ObjectSummary(self, bucket, key):
return MockBoto3ObjectSummary(self.root, key, session=self.session)
def Object(self, bucket, key):
return MockBoto3Object(self.root, key, self)
class MockBoto3Object:
def __init__(self, root, path, resource):
self.root = root
self.path = root / path
self.resource = resource
def get(self):
if not self.path.exists() or self.path.is_dir():
raise NoSuchKey({}, {})
else:
return {"key": str(PurePosixPath(self.path))}
def load(self):
if not self.path.exists() or self.path.is_dir():
raise ClientError({}, {})
else:
return {"key": str(PurePosixPath(self.path))}
@property
def key(self):
return str(PurePosixPath(self.path).relative_to(PurePosixPath(self.root)))
def copy_from(self, CopySource=None, Metadata=None, MetadataDirective=None):
if CopySource["Key"] == str(self.path.relative_to(self.root)):
# same file, touch
self.path.touch()
else:
self.path.write_bytes((self.root / Path(CopySource["Key"])).read_bytes())
def download_file(self, to_path, Config=None, ExtraArgs=None):
to_path = Path(to_path)
to_path.parent.mkdir(parents=True, exist_ok=True)
to_path.write_bytes(self.path.read_bytes())
# track config to make sure it's used in tests
self.resource.download_config = Config
self.resource.download_extra_args = ExtraArgs
def upload_file(self, from_path, Config=None, ExtraArgs=None):
self.path.parent.mkdir(parents=True, exist_ok=True)
self.path.write_bytes(Path(from_path).read_bytes())
self.resource.upload_config = Config
if ExtraArgs is not None:
self.resource.session.metadata_cache[self.path] = ExtraArgs.pop("ContentType", None)
def delete(self):
self.path.unlink()
delete_empty_parents_up_to_root(self.path, self.root)
return {"ResponseMetadata": {"HTTPStatusCode": 204}}
def copy(self, source, ExtraArgs=None, Config=None):
# boto3 is more like "copy from"
source = self.root / source["Key"]
self.path.parent.mkdir(parents=True, exist_ok=True)
return shutil.copy(str(source), str(self.path))
class MockBoto3ObjectSummary:
def __init__(self, root, path, session=None):
self.path = root / path
self.session = session
def get(self):
if not self.path.exists() or self.path.is_dir():
raise NoSuchKey({}, {})
else:
return {
"LastModified": datetime.fromtimestamp(self.path.stat().st_mtime),
"ContentLength": None,
"ETag": hash(str(self.path)),
"ContentType": self.session.metadata_cache.get(self.path, None),
"Metadata": {},
}
class MockBoto3Bucket:
def __init__(self, root, session=None):
self.root = root
self.session = session
@property
def objects(self):
return MockObjects(self.root, session=self.session)
class MockObjects:
def __init__(self, root, session=None):
self.root = root
self.session = session
def filter(self, Prefix=""):
path = self.root / Prefix
if path.is_file():
return MockCollection([PurePosixPath(path)], self.root, session=self.session)
items = [
PurePosixPath(f)
for f in path.glob("**/*")
if f.is_file() and not f.name.startswith(".")
]
return MockCollection(items, self.root, session=self.session)
class MockCollection:
def __init__(self, items, root, session=None):
self.root = root
self.session = session
s3_obj = collections.namedtuple("s3_obj", "key bucket_name")
self.full_paths = items
self.s3_obj_paths = [
s3_obj(bucket_name=DEFAULT_S3_BUCKET_NAME, key=str(i.relative_to(self.root)))
for i in items
]
def __iter__(self):
return iter(self.s3_obj_paths)
def limit(self, n):
return self.s3_obj_paths[:n]
def delete(self):
any_deleted = False
for p in self.full_paths:
if Path(p).exists():
any_deleted = True
Path(p).unlink()
delete_empty_parents_up_to_root(Path(p), self.root)
if not any_deleted:
return []
return [{"ResponseMetadata": {"HTTPStatusCode": 200}}]
class MockBoto3Client:
def __init__(self, root, session=None):
self.root = root
self.session = session
def get_paginator(self, api):
return MockBoto3Paginator(self.root, session=self.session)
def head_bucket(self, Bucket):
if Bucket == DEFAULT_S3_BUCKET_NAME: # used in passing tests
return {"Bucket": Bucket}
else:
raise ClientError(
{
"Error": {
"Message": f"Bucket {Bucket} not expected as mock bucket; only '{DEFAULT_S3_BUCKET_NAME}' exists."
}
},
{},
)
def list_buckets(self):
return {"Buckets": [{"Name": DEFAULT_S3_BUCKET_NAME}]}
def head_object(self, Bucket, Key, **kwargs):
if (
not (self.root / Key).exists()
or (self.root / Key).is_dir()
or Bucket != DEFAULT_S3_BUCKET_NAME
):
raise ClientError({}, {})
else:
return {"key": Key}
@property
def exceptions(self):
Ex = collections.namedtuple("Ex", "NoSuchKey")
return Ex(NoSuchKey=NoSuchKey)
class MockBoto3Paginator:
def __init__(self, root, per_page=2, session=None):
self.root = root
self.per_page = per_page
self.session = session
def paginate(self, Bucket=None, Prefix="", Delimiter=None):
new_dir = self.root / Prefix
if Delimiter == "/":
items = [f for f in new_dir.iterdir() if not f.name.startswith(".")]
else:
items = [f for f in new_dir.rglob("*") if not f.name.startswith(".")]
for ix in range(0, len(items), self.per_page):
page = items[ix : ix + self.per_page]
dirs = [
{"Prefix": str(_.relative_to(self.root).as_posix())} for _ in page if _.is_dir()
]
files = [
{
"Key": str(_.relative_to(self.root).as_posix()),
"Size": 123
if not _.relative_to(self.root).exists()
else _.relative_to(self.root).stat().st_size,
}
for _ in page
if _.is_file()
]
# s3 can have "fake" directories where size is 0, but it is listed in "Contents" (see #198)
# add one in here for testing
if dirs:
fake_dir = dirs.pop(-1)
fake_dir["Size"] = 0
fake_dir["Key"] = fake_dir.pop("Prefix") + "/" # fake dirs have '/' appended
files.append(fake_dir)
yield {"CommonPrefixes": dirs, "Contents": files}