Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Raise not exists error when attempting to get size for unexisting S3 file #1309

Merged
merged 1 commit into from
Sep 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion storages/backends/s3.py
Original file line number Diff line number Diff line change
Expand Up @@ -535,7 +535,12 @@ def listdir(self, name):

def size(self, name):
name = self._normalize_name(clean_name(name))
return self.bucket.Object(name).content_length
try:
return self.bucket.Object(name).content_length
except ClientError as err:
if err.response["ResponseMetadata"]["HTTPStatusCode"] == 404:
raise FileNotFoundError("File does not exist: %s" % name)
raise # Let it bubble up if it was some other error

def _get_write_parameters(self, name, content=None):
params = self.get_object_parameters(name)
Expand Down
11 changes: 11 additions & 0 deletions tests/test_s3.py
Original file line number Diff line number Diff line change
Expand Up @@ -647,6 +647,17 @@ def test_storage_size(self):
name = "file.txt"
self.assertEqual(self.storage.size(name), obj.content_length)

def test_storage_size_not_exists(self):
self.storage.bucket.Object.side_effect = ClientError(
{"Error": {}, "ResponseMetadata": {"HTTPStatusCode": 404}},
"HeadObject",
)
name = "file.txt"
with self.assertRaisesMessage(
FileNotFoundError, "File does not exist: file.txt"
):
self.storage.size(name)

def test_storage_mtime(self):
# Test both USE_TZ cases
for use_tz in (True, False):
Expand Down