From a6e651d23a316bafc4ea7119220301ec8486eb78 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Mon, 7 Dec 2020 12:45:13 +0000 Subject: [PATCH 1/2] fix: MediaFileUpload error if file does not exist --- googleapiclient/http.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/googleapiclient/http.py b/googleapiclient/http.py index b8e1b8eaaee..e842bb4c87b 100644 --- a/googleapiclient/http.py +++ b/googleapiclient/http.py @@ -573,8 +573,9 @@ def __init__( resumable: bool, True if this is a resumable upload. False means upload in a single request. """ + self._fd = None self._filename = filename - fd = open(self._filename, "rb") + self._fd = open(self._filename, "rb") if mimetype is None: # No mimetype provided, make a guess. mimetype, _ = mimetypes.guess_type(filename) @@ -582,11 +583,12 @@ def __init__( # Guess failed, use octet-stream. mimetype = "application/octet-stream" super(MediaFileUpload, self).__init__( - fd, mimetype, chunksize=chunksize, resumable=resumable + self._fd, mimetype, chunksize=chunksize, resumable=resumable ) def __del__(self): - self._fd.close() + if self._fd: + self._fd.close() def to_json(self): """Creating a JSON representation of an instance of MediaFileUpload. From 7acba976beaa2652330066a5dc3d045d2c35900c Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Tue, 8 Dec 2020 11:52:18 +0000 Subject: [PATCH 2/2] Add MediaFileUpload test where file does not exist --- tests/test_http.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/test_http.py b/tests/test_http.py index 5293a6a3bfc..9bfae93fd73 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -248,6 +248,10 @@ def test_media_file_upload_to_from_json(self): self.assertEqual(500, new_upload.chunksize()) self.assertEqual(b"PNG", new_upload.getbytes(1, 3)) + def test_media_file_upload_raises_on_file_not_found(self): + with self.assertRaises(FileNotFoundError): + MediaFileUpload(datafile("missing.png")) + def test_media_file_upload_raises_on_invalid_chunksize(self): self.assertRaises( InvalidChunkSizeError,