Skip to content

Commit

Permalink
[s3] raise FileNotFoundError on .size for non-existent files (#1309)
Browse files Browse the repository at this point in the history
Closes #1022
  • Loading branch information
sevdog committed Sep 29, 2023
1 parent c766248 commit cf33d69
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
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

0 comments on commit cf33d69

Please sign in to comment.