From cf33d69fdad5e4fcff8e3b23e5aa178433934f46 Mon Sep 17 00:00:00 2001 From: Devid <13779643+sevdog@users.noreply.github.com> Date: Fri, 29 Sep 2023 05:23:36 +0100 Subject: [PATCH] [s3] raise `FileNotFoundError` on `.size` for non-existent files (#1309) Closes #1022 --- storages/backends/s3.py | 7 ++++++- tests/test_s3.py | 11 +++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/storages/backends/s3.py b/storages/backends/s3.py index 3edc3c9a..66f7a0cf 100644 --- a/storages/backends/s3.py +++ b/storages/backends/s3.py @@ -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) diff --git a/tests/test_s3.py b/tests/test_s3.py index 7d1e7f5f..6f43980a 100644 --- a/tests/test_s3.py +++ b/tests/test_s3.py @@ -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):