datablob 0.9.3__tar.gz → 0.10.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: datablob
3
- Version: 0.9.3
3
+ Version: 0.10.0
4
4
  Summary: Client for Updating a Simple Data Warehouse on Blob Storage
5
5
  Home-page: https://github.com/gocarta/datablob
6
6
  Download-URL: https://github.com/gocarta/datablob/tarball/download
@@ -20,6 +20,10 @@ Requires-Dist: pandas
20
20
  Requires-Dist: pyarrow
21
21
  Requires-Dist: shapely
22
22
  Requires-Dist: tzdata
23
+ Provides-Extra: gcs
24
+ Requires-Dist: google-cloud-storage; extra == "gcs"
25
+ Provides-Extra: dev
26
+ Requires-Dist: pytest; extra == "dev"
23
27
  Dynamic: author
24
28
  Dynamic: author-email
25
29
  Dynamic: classifier
@@ -29,6 +33,7 @@ Dynamic: download-url
29
33
  Dynamic: home-page
30
34
  Dynamic: keywords
31
35
  Dynamic: license-file
36
+ Dynamic: provides-extra
32
37
  Dynamic: requires-dist
33
38
  Dynamic: summary
34
39
 
@@ -49,6 +54,11 @@ Client for Updating a Simple Data Warehouse on Blob Storage
49
54
  pip install datablob
50
55
  ```
51
56
 
57
+ To include Google Cloud Storage (GCS) support:
58
+ ```sh
59
+ pip install datablob[gcs]
60
+ ```
61
+
52
62
  ## supported formats
53
63
  - csv
54
64
  - [geojson (points and polygons)](https://geojson.org/)
@@ -63,10 +73,16 @@ pip install datablob
63
73
  ```py
64
74
  from datablob import DataBlobClient
65
75
 
76
+ # AWS S3 (default)
66
77
  client = DataBlobClient(
67
78
  bucket_name="example-test-bucket-123", bucket_path="prefix/to/dataportal"
68
79
  )
69
80
 
81
+ # Google Cloud Storage (GCS)
82
+ client = DataBlobClient(
83
+ bucket_name="example-gcs-bucket-123", bucket_path="prefix/to/dataportal", provider="gcs"
84
+ )
85
+
70
86
  rows = [
71
87
  {
72
88
  "name": "Random Building",
@@ -81,7 +97,7 @@ client.update_dataset(
81
97
  version="2", # version of the dataset. It's a string, so you can version as you like.
82
98
  data=rows, # list of dictionaries. Each row is a dictionary.
83
99
  latitude_key="@lat", # name of the latitude column
84
- longitude="@lon", # name of the longitude column
100
+ longitude_key="@lon", # name of the longitude column
85
101
  polygon_key="@geom", # name of the column with a polygon geometry in it (if applicable)
86
102
  xlsx=True # set to True to include an Excel file in output
87
103
  )
@@ -15,6 +15,11 @@ Client for Updating a Simple Data Warehouse on Blob Storage
15
15
  pip install datablob
16
16
  ```
17
17
 
18
+ To include Google Cloud Storage (GCS) support:
19
+ ```sh
20
+ pip install datablob[gcs]
21
+ ```
22
+
18
23
  ## supported formats
19
24
  - csv
20
25
  - [geojson (points and polygons)](https://geojson.org/)
@@ -29,10 +34,16 @@ pip install datablob
29
34
  ```py
30
35
  from datablob import DataBlobClient
31
36
 
37
+ # AWS S3 (default)
32
38
  client = DataBlobClient(
33
39
  bucket_name="example-test-bucket-123", bucket_path="prefix/to/dataportal"
34
40
  )
35
41
 
42
+ # Google Cloud Storage (GCS)
43
+ client = DataBlobClient(
44
+ bucket_name="example-gcs-bucket-123", bucket_path="prefix/to/dataportal", provider="gcs"
45
+ )
46
+
36
47
  rows = [
37
48
  {
38
49
  "name": "Random Building",
@@ -47,7 +58,7 @@ client.update_dataset(
47
58
  version="2", # version of the dataset. It's a string, so you can version as you like.
48
59
  data=rows, # list of dictionaries. Each row is a dictionary.
49
60
  latitude_key="@lat", # name of the latitude column
50
- longitude="@lon", # name of the longitude column
61
+ longitude_key="@lon", # name of the longitude column
51
62
  polygon_key="@geom", # name of the column with a polygon geometry in it (if applicable)
52
63
  xlsx=True # set to True to include an Excel file in output
53
64
  )
@@ -1,4 +1,3 @@
1
- import boto3
2
1
  import csv
3
2
  from datetime import datetime
4
3
  import geopandas as gpd
@@ -10,10 +9,16 @@ import os
10
9
  import pandas as pd
11
10
  from shapely.geometry import shape
12
11
  import tempfile
13
- import tzdata
12
+ from typing import Literal, TypeAlias
14
13
  import zipfile
15
14
  from zoneinfo import ZoneInfo
16
15
 
16
+ from datablob.storage_client import (
17
+ GcsClient as GcsClient,
18
+ S3Client,
19
+ StorageClientProtocol,
20
+ )
21
+
17
22
  POSSIBLE_LATITUDE_KEYS = [
18
23
  "LATITUDE",
19
24
  "Latitude",
@@ -37,12 +42,41 @@ POSSIBLE_LONGITUDE_KEYS = [
37
42
  "@lon",
38
43
  ]
39
44
 
45
+ Provider: TypeAlias = Literal["s3", "gcs"]
46
+ VALID_PROVIDERS: tuple[Provider, ...] = ("s3", "gcs")
47
+
40
48
 
41
49
  class DataBlobClient:
42
- def __init__(self, bucket_name, bucket_path, timezones=None):
50
+ storage_client: StorageClientProtocol
51
+
52
+ def __init__(
53
+ self,
54
+ bucket_name,
55
+ bucket_path,
56
+ timezones=None,
57
+ provider: Provider = "s3",
58
+ storage_client: StorageClientProtocol | None = None,
59
+ ):
60
+ if provider not in VALID_PROVIDERS:
61
+ raise ValueError(
62
+ f"Unsupported provider '{provider}'. Must be 's3' or 'gcs'."
63
+ )
64
+
43
65
  self.bucket_name = bucket_name
44
66
  self.bucket_path = bucket_path.rstrip("/")
45
67
  self.timezones = timezones or ["UTC"]
68
+ self.provider = provider
69
+
70
+ if storage_client is not None:
71
+ self.storage_client = storage_client
72
+ elif self.provider == "s3":
73
+ self.storage_client = S3Client(self.bucket_name)
74
+ elif self.provider == "gcs":
75
+ self.storage_client = GcsClient(self.bucket_name)
76
+ else:
77
+ raise ValueError(
78
+ f"Unsupported provider '{self.provider}'. Must be 's3' or 'gcs'."
79
+ )
46
80
 
47
81
  def _get_unique_keys(self, rows):
48
82
  columns = set()
@@ -64,23 +98,21 @@ class DataBlobClient:
64
98
 
65
99
  def get_filenames_by_dataset_and_version(self):
66
100
  results = {}
67
- response = boto3.client("s3").list_objects_v2(
68
- Bucket=self.bucket_name, Prefix=self.bucket_path
69
- )
70
- if "Contents" in response:
71
- for obj in response["Contents"]:
72
- key = obj["Key"][len(self.bucket_path) + 1 :]
73
-
74
- if len(key.split("/")) == 3:
75
- [dataset_id, version, filename] = key.split("/")
76
- if version.startswith("v"):
77
- version = version[1:]
78
- if filename:
79
- if dataset_id not in results:
80
- results[dataset_id] = {}
81
- if version not in results[dataset_id]:
82
- results[dataset_id][version] = []
83
- results[dataset_id][version].append(filename)
101
+ keys = self.storage_client.list_keys(prefix=self.bucket_path)
102
+ prefix_len = len(self.bucket_path) + 1 if self.bucket_path else 0
103
+ for full_key in keys:
104
+ key = full_key[prefix_len:] if prefix_len else full_key
105
+
106
+ if len(key.split("/")) == 3:
107
+ [dataset_id, version, filename] = key.split("/")
108
+ if version.startswith("v"):
109
+ version = version[1:]
110
+ if filename:
111
+ if dataset_id not in results:
112
+ results[dataset_id] = {}
113
+ if version not in results[dataset_id]:
114
+ results[dataset_id][version] = []
115
+ results[dataset_id][version].append(filename)
84
116
 
85
117
  for dataset_id, subdict in results.items():
86
118
  versions = list(subdict.keys())
@@ -96,48 +128,36 @@ class DataBlobClient:
96
128
  key = (
97
129
  self.bucket_path + "/" + dataset_name + "/v" + dataset_version + "/data.csv"
98
130
  )
99
- boto3.client("s3").put_object(
100
- Bucket=self.bucket_name,
101
- Key=key,
102
- Body=data,
103
- )
131
+ self.storage_client.put_object(key, data)
104
132
 
105
133
  def upload_tsv(self, dataset_name, dataset_version, data):
106
134
  key = (
107
135
  self.bucket_path + "/" + dataset_name + "/v" + dataset_version + "/data.tsv"
108
136
  )
109
- boto3.client("s3").put_object(
110
- Bucket=self.bucket_name,
111
- Key=key,
112
- Body=data,
113
- )
137
+ self.storage_client.put_object(key, data)
114
138
 
115
139
  def get_dataset_as_csv(self, name, version, remove_bom=True):
116
140
  key = self.bucket_path + "/" + name + "/v" + version + "/data.csv"
117
- response = boto3.client("s3").get_object(Bucket=self.bucket_name, Key=key)
118
- object_content = response["Body"].read().decode("utf-8")
141
+ object_content = self.storage_client.get_object_bytes(key).decode("utf-8")
119
142
  if remove_bom:
120
143
  object_content = object_content.lstrip("\ufeff")
121
144
  return object_content
122
145
 
123
146
  def get_dataset_as_tsv(self, name, version, remove_bom=True):
124
147
  key = self.bucket_path + "/" + name + "/v" + version + "/data.tsv"
125
- response = boto3.client("s3").get_object(Bucket=self.bucket_name, Key=key)
126
- object_content = response["Body"].read().decode("utf-8")
148
+ object_content = self.storage_client.get_object_bytes(key).decode("utf-8")
127
149
  if remove_bom:
128
150
  object_content = object_content.lstrip("\ufeff")
129
151
  return object_content
130
152
 
131
153
  def get_dataset_as_json(self, name, version):
132
154
  key = self.bucket_path + "/" + name + "/v" + version + "/data.json"
133
- response = boto3.client("s3").get_object(Bucket=self.bucket_name, Key=key)
134
- object_content = response["Body"].read().decode("utf-8")
155
+ object_content = self.storage_client.get_object_bytes(key).decode("utf-8")
135
156
  return json_loads(object_content)
136
157
 
137
158
  def get_dataset_metadata(self, name: str, version: str):
138
159
  key = self.bucket_path + "/" + name + "/v" + version + "/meta.json"
139
- response = boto3.client("s3").get_object(Bucket=self.bucket_name, Key=key)
140
- object_content = response["Body"].read().decode("utf-8")
160
+ object_content = self.storage_client.get_object_bytes(key).decode("utf-8")
141
161
  return json_loads(object_content)
142
162
 
143
163
  def upload_geojson_points(self, dataset_name, dataset_version, data):
@@ -149,10 +169,9 @@ class DataBlobClient:
149
169
  + dataset_version
150
170
  + "/data.points.geojson"
151
171
  )
152
- boto3.client("s3").put_object(
153
- Bucket=self.bucket_name,
154
- Key=key,
155
- Body=data if isinstance(data, str) else json_dumps(data),
172
+ self.storage_client.put_object(
173
+ key,
174
+ data if isinstance(data, str) else json_dumps(data),
156
175
  )
157
176
 
158
177
  def upload_geojson_polygons(self, dataset_name, dataset_version, data):
@@ -164,10 +183,9 @@ class DataBlobClient:
164
183
  + dataset_version
165
184
  + "/data.polygons.geojson"
166
185
  )
167
- boto3.client("s3").put_object(
168
- Bucket=self.bucket_name,
169
- Key=key,
170
- Body=data if isinstance(data, str) else json_dumps(data),
186
+ self.storage_client.put_object(
187
+ key,
188
+ data if isinstance(data, str) else json_dumps(data),
171
189
  )
172
190
 
173
191
  def upload_shapefile_points(self, dataset_name, dataset_version, blob):
@@ -179,11 +197,7 @@ class DataBlobClient:
179
197
  + dataset_version
180
198
  + "/data.points.shp.zip"
181
199
  )
182
- boto3.client("s3").put_object(
183
- Bucket=self.bucket_name,
184
- Key=key,
185
- Body=blob,
186
- )
200
+ self.storage_client.put_object(key, blob)
187
201
 
188
202
  def upload_shapefile_polygons(self, dataset_name, dataset_version, blob):
189
203
  key = (
@@ -194,11 +208,7 @@ class DataBlobClient:
194
208
  + dataset_version
195
209
  + "/data.polygons.shp.zip"
196
210
  )
197
- boto3.client("s3").put_object(
198
- Bucket=self.bucket_name,
199
- Key=key,
200
- Body=blob,
201
- )
211
+ self.storage_client.put_object(key, blob)
202
212
 
203
213
  def upload_jsonl(self, dataset_name, dataset_version, data):
204
214
  key = (
@@ -214,11 +224,7 @@ class DataBlobClient:
214
224
  for row in data:
215
225
  results += json_dumps(row) + "\n"
216
226
 
217
- boto3.client("s3").put_object(
218
- Bucket=self.bucket_name,
219
- Key=key,
220
- Body=results,
221
- )
227
+ self.storage_client.put_object(key, results)
222
228
 
223
229
  def upload_json(self, dataset_name, dataset_version, data):
224
230
  key = (
@@ -229,10 +235,9 @@ class DataBlobClient:
229
235
  + dataset_version
230
236
  + "/data.json"
231
237
  )
232
- boto3.client("s3").put_object(
233
- Bucket=self.bucket_name,
234
- Key=key,
235
- Body=data if isinstance(data, str) else json_dumps(data),
238
+ self.storage_client.put_object(
239
+ key,
240
+ data if isinstance(data, str) else json_dumps(data),
236
241
  )
237
242
 
238
243
  def upload_parquet(self, dataset_name, dataset_version, data):
@@ -244,11 +249,7 @@ class DataBlobClient:
244
249
  + dataset_version
245
250
  + "/data.parquet"
246
251
  )
247
- boto3.client("s3").put_object(
248
- Bucket=self.bucket_name,
249
- Key=key,
250
- Body=data,
251
- )
252
+ self.storage_client.put_object(key, data)
252
253
 
253
254
  def upload_xlsx(self, dataset_name, dataset_version, data):
254
255
  key = (
@@ -259,11 +260,7 @@ class DataBlobClient:
259
260
  + dataset_version
260
261
  + "/data.xlsx"
261
262
  )
262
- boto3.client("s3").put_object(
263
- Bucket=self.bucket_name,
264
- Key=key,
265
- Body=data,
266
- )
263
+ self.storage_client.put_object(key, data)
267
264
 
268
265
  def upload_metadata(self, dataset_name, dataset_version, data):
269
266
  key = (
@@ -274,17 +271,16 @@ class DataBlobClient:
274
271
  + dataset_version
275
272
  + "/meta.json"
276
273
  )
277
- boto3.client("s3").put_object(
278
- Bucket=self.bucket_name,
279
- Key=key,
280
- Body=data if isinstance(data, str) else json_dumps(data, indent=4),
274
+ self.storage_client.put_object(
275
+ key,
276
+ data if isinstance(data, str) else json_dumps(data, indent=4),
281
277
  )
282
278
 
283
279
  def convert_gdf_to_shapefile(self, gdf):
284
280
  buf = io.BytesIO()
285
281
 
286
282
  with tempfile.TemporaryDirectory() as tmpdir:
287
- path = os.path.join(tmpdir, f"data.shp")
283
+ path = os.path.join(tmpdir, "data.shp")
288
284
  gdf.to_file(path, driver="ESRI Shapefile")
289
285
 
290
286
  # copy temp files into in-memory zip file
@@ -0,0 +1,77 @@
1
+ import io
2
+ from typing import Protocol
3
+
4
+ import boto3
5
+
6
+ BlobBody = str | bytes | io.BytesIO | io.StringIO
7
+
8
+
9
+ class StorageClientProtocol(Protocol):
10
+ def put_object(self, key: str, body: BlobBody) -> None: ...
11
+
12
+ def get_object_bytes(self, key: str) -> bytes: ...
13
+
14
+ def list_keys(self, prefix: str) -> list[str]: ...
15
+
16
+
17
+ class S3Client:
18
+ def __init__(self, bucket_name: str):
19
+ self.bucket_name = bucket_name
20
+ self.client = boto3.client("s3")
21
+
22
+ def put_object(self, key: str, body: BlobBody) -> None:
23
+ if isinstance(body, (io.BytesIO, io.StringIO)):
24
+ data = body.getvalue()
25
+ else:
26
+ data = body
27
+ self.client.put_object(
28
+ Bucket=self.bucket_name,
29
+ Key=key,
30
+ Body=data,
31
+ )
32
+
33
+ def get_object_bytes(self, key: str) -> bytes:
34
+ response = self.client.get_object(Bucket=self.bucket_name, Key=key)
35
+ return response["Body"].read()
36
+
37
+ def list_keys(self, prefix: str) -> list[str]:
38
+ keys = []
39
+ response = self.client.list_objects_v2(Bucket=self.bucket_name, Prefix=prefix)
40
+ if "Contents" in response:
41
+ for obj in response["Contents"]:
42
+ keys.append(obj["Key"])
43
+ return keys
44
+
45
+
46
+ class GcsClient:
47
+ def __init__(self, bucket_name: str):
48
+ self.bucket_name = bucket_name
49
+ try:
50
+ from google.cloud import storage
51
+ except ImportError:
52
+ raise ImportError(
53
+ "google-cloud-storage is required to use GCS with datablob. "
54
+ "Install it with 'pip install datablob[gcs]'"
55
+ )
56
+ self.client = storage.Client()
57
+
58
+ def put_object(self, key: str, body: BlobBody) -> None:
59
+ bucket = self.client.bucket(self.bucket_name)
60
+ blob = bucket.blob(key)
61
+ if isinstance(body, (io.BytesIO, io.StringIO)):
62
+ data = body.getvalue()
63
+ else:
64
+ data = body
65
+ blob.upload_from_string(data)
66
+
67
+ def get_object_bytes(self, key: str) -> bytes:
68
+ bucket = self.client.bucket(self.bucket_name)
69
+ blob = bucket.blob(key)
70
+ return blob.download_as_bytes()
71
+
72
+ def list_keys(self, prefix: str) -> list[str]:
73
+ keys = []
74
+ blobs = self.client.list_blobs(self.bucket_name, prefix=prefix)
75
+ for blob in blobs:
76
+ keys.append(blob.name)
77
+ return keys
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: datablob
3
- Version: 0.9.3
3
+ Version: 0.10.0
4
4
  Summary: Client for Updating a Simple Data Warehouse on Blob Storage
5
5
  Home-page: https://github.com/gocarta/datablob
6
6
  Download-URL: https://github.com/gocarta/datablob/tarball/download
@@ -20,6 +20,10 @@ Requires-Dist: pandas
20
20
  Requires-Dist: pyarrow
21
21
  Requires-Dist: shapely
22
22
  Requires-Dist: tzdata
23
+ Provides-Extra: gcs
24
+ Requires-Dist: google-cloud-storage; extra == "gcs"
25
+ Provides-Extra: dev
26
+ Requires-Dist: pytest; extra == "dev"
23
27
  Dynamic: author
24
28
  Dynamic: author-email
25
29
  Dynamic: classifier
@@ -29,6 +33,7 @@ Dynamic: download-url
29
33
  Dynamic: home-page
30
34
  Dynamic: keywords
31
35
  Dynamic: license-file
36
+ Dynamic: provides-extra
32
37
  Dynamic: requires-dist
33
38
  Dynamic: summary
34
39
 
@@ -49,6 +54,11 @@ Client for Updating a Simple Data Warehouse on Blob Storage
49
54
  pip install datablob
50
55
  ```
51
56
 
57
+ To include Google Cloud Storage (GCS) support:
58
+ ```sh
59
+ pip install datablob[gcs]
60
+ ```
61
+
52
62
  ## supported formats
53
63
  - csv
54
64
  - [geojson (points and polygons)](https://geojson.org/)
@@ -63,10 +73,16 @@ pip install datablob
63
73
  ```py
64
74
  from datablob import DataBlobClient
65
75
 
76
+ # AWS S3 (default)
66
77
  client = DataBlobClient(
67
78
  bucket_name="example-test-bucket-123", bucket_path="prefix/to/dataportal"
68
79
  )
69
80
 
81
+ # Google Cloud Storage (GCS)
82
+ client = DataBlobClient(
83
+ bucket_name="example-gcs-bucket-123", bucket_path="prefix/to/dataportal", provider="gcs"
84
+ )
85
+
70
86
  rows = [
71
87
  {
72
88
  "name": "Random Building",
@@ -81,7 +97,7 @@ client.update_dataset(
81
97
  version="2", # version of the dataset. It's a string, so you can version as you like.
82
98
  data=rows, # list of dictionaries. Each row is a dictionary.
83
99
  latitude_key="@lat", # name of the latitude column
84
- longitude="@lon", # name of the longitude column
100
+ longitude_key="@lon", # name of the longitude column
85
101
  polygon_key="@geom", # name of the column with a polygon geometry in it (if applicable)
86
102
  xlsx=True # set to True to include an Excel file in output
87
103
  )
@@ -3,8 +3,11 @@ README.md
3
3
  setup.cfg
4
4
  setup.py
5
5
  datablob/__init__.py
6
+ datablob/storage_client.py
6
7
  datablob.egg-info/PKG-INFO
7
8
  datablob.egg-info/SOURCES.txt
8
9
  datablob.egg-info/dependency_links.txt
9
10
  datablob.egg-info/requires.txt
10
- datablob.egg-info/top_level.txt
11
+ datablob.egg-info/top_level.txt
12
+ tests/test_client.py
13
+ tests/test_storage_client.py
@@ -5,3 +5,9 @@ pandas
5
5
  pyarrow
6
6
  shapely
7
7
  tzdata
8
+
9
+ [dev]
10
+ pytest
11
+
12
+ [gcs]
13
+ google-cloud-storage
@@ -15,7 +15,7 @@ setup(
15
15
  "__init__.py",
16
16
  ]
17
17
  },
18
- version="0.9.3",
18
+ version="0.10.0",
19
19
  description="Client for Updating a Simple Data Warehouse on Blob Storage",
20
20
  long_description=long_description,
21
21
  long_description_content_type="text/markdown",
@@ -39,4 +39,12 @@ setup(
39
39
  "shapely",
40
40
  "tzdata",
41
41
  ],
42
+ extras_require={
43
+ "gcs": [
44
+ "google-cloud-storage",
45
+ ],
46
+ "dev": [
47
+ "pytest",
48
+ ],
49
+ },
42
50
  )
@@ -0,0 +1,28 @@
1
+ import pytest
2
+
3
+ from datablob import DataBlobClient
4
+ from datablob.storage_client import GcsClient, S3Client
5
+
6
+
7
+ def test_init_with_providers():
8
+ # s3 (default)
9
+ client = DataBlobClient(bucket_name="my-bucket", bucket_path="path/to/data")
10
+ assert client.bucket_name == "my-bucket"
11
+ assert client.bucket_path == "path/to/data"
12
+ assert client.provider == "s3"
13
+ assert isinstance(client.storage_client, S3Client)
14
+
15
+ # gcs provider
16
+ client = DataBlobClient(
17
+ bucket_name="my-gcs-bucket", bucket_path="path/to/data", provider="gcs"
18
+ )
19
+ assert client.bucket_name == "my-gcs-bucket"
20
+ assert client.provider == "gcs"
21
+ assert isinstance(client.storage_client, GcsClient)
22
+
23
+ # Invalid providers should be rejected explicitly
24
+ with pytest.raises(ValueError, match="Unsupported provider 'azure'"):
25
+ DataBlobClient(bucket_name="my-bucket", bucket_path="path", provider="azure")
26
+
27
+ with pytest.raises(ValueError, match="Unsupported provider 'GCS'"):
28
+ DataBlobClient(bucket_name="my-bucket", bucket_path="path", provider="GCS")
@@ -0,0 +1,103 @@
1
+ import io
2
+ import pytest
3
+ from unittest.mock import MagicMock, patch
4
+
5
+ from datablob.storage_client import GcsClient, S3Client
6
+
7
+
8
+ @patch("boto3.client")
9
+ def test_s3_client_put_object(mock_boto3_client):
10
+ s3_client = S3Client("my-s3-bucket")
11
+
12
+ s3_client.put_object("path/to/file.txt", "hello world")
13
+ mock_boto3_client.return_value.put_object.assert_called_with(
14
+ Bucket="my-s3-bucket",
15
+ Key="path/to/file.txt",
16
+ Body="hello world",
17
+ )
18
+
19
+ bytes_io = io.BytesIO(b"binary data")
20
+ s3_client.put_object("path/to/binary.dat", bytes_io)
21
+ mock_boto3_client.return_value.put_object.assert_called_with(
22
+ Bucket="my-s3-bucket",
23
+ Key="path/to/binary.dat",
24
+ Body=b"binary data",
25
+ )
26
+
27
+
28
+ @patch("boto3.client")
29
+ def test_s3_client_get_object(mock_boto3_client):
30
+ mock_body = MagicMock()
31
+ mock_body.read.return_value = b"sample content"
32
+ mock_boto3_client.return_value.get_object.return_value = {"Body": mock_body}
33
+
34
+ s3_client = S3Client("my-s3-bucket")
35
+ content = s3_client.get_object_bytes("path/to/file.txt")
36
+
37
+ assert content == b"sample content"
38
+ mock_boto3_client.return_value.get_object.assert_called_once_with(
39
+ Bucket="my-s3-bucket",
40
+ Key="path/to/file.txt",
41
+ )
42
+
43
+
44
+ @patch("boto3.client")
45
+ def test_s3_client_list_keys(mock_boto3):
46
+ mock_boto3_client = mock_boto3.return_value
47
+ mock_boto3_client.list_objects_v2.return_value = {
48
+ "Contents": [
49
+ {"Key": "prefix/ds1/v1/meta.json"},
50
+ {"Key": "prefix/ds1/v1/data.csv"},
51
+ ]
52
+ }
53
+
54
+ s3_client = S3Client("my-s3-bucket")
55
+ keys = s3_client.list_keys("prefix")
56
+
57
+ assert keys == ["prefix/ds1/v1/meta.json", "prefix/ds1/v1/data.csv"]
58
+ mock_boto3_client.list_objects_v2.assert_called_once_with(
59
+ Bucket="my-s3-bucket",
60
+ Prefix="prefix",
61
+ )
62
+
63
+
64
+ @patch.dict("sys.modules", {"google.cloud": None})
65
+ def test_gcs_client_missing_import():
66
+ with pytest.raises(ImportError, match="google-cloud-storage is required"):
67
+ GcsClient("my-gcs-bucket")
68
+
69
+
70
+ @patch("google.cloud.storage.Client")
71
+ def test_gcs_client_operations(mock_gcs_client_cls):
72
+ mock_client_instance = mock_gcs_client_cls.return_value
73
+ mock_bucket = MagicMock()
74
+ mock_blob = MagicMock()
75
+ mock_client_instance.bucket.return_value = mock_bucket
76
+ mock_bucket.blob.return_value = mock_blob
77
+
78
+ gcs_client = GcsClient("my-gcs-bucket")
79
+
80
+ gcs_client.put_object("path/to/file.txt", "hello gcs")
81
+ mock_client_instance.bucket.assert_called_with("my-gcs-bucket")
82
+ mock_bucket.blob.assert_called_with("path/to/file.txt")
83
+ mock_blob.upload_from_string.assert_called_with("hello gcs")
84
+
85
+ bytes_io = io.BytesIO(b"gcs binary")
86
+ gcs_client.put_object("path/to/binary.dat", bytes_io)
87
+ mock_blob.upload_from_string.assert_called_with(b"gcs binary")
88
+
89
+ mock_blob.download_as_bytes.return_value = b"retrieved gcs bytes"
90
+ content = gcs_client.get_object_bytes("path/to/file.txt")
91
+ assert content == b"retrieved gcs bytes"
92
+
93
+ blob1 = MagicMock()
94
+ blob1.name = "prefix/file1.csv"
95
+ blob2 = MagicMock()
96
+ blob2.name = "prefix/file2.csv"
97
+ mock_client_instance.list_blobs.return_value = [blob1, blob2]
98
+
99
+ keys = gcs_client.list_keys("prefix")
100
+ assert keys == ["prefix/file1.csv", "prefix/file2.csv"]
101
+ mock_client_instance.list_blobs.assert_called_once_with(
102
+ "my-gcs-bucket", prefix="prefix"
103
+ )
File without changes
File without changes