Skip to content

Commit 2c6d029

Browse files
authored
fix: MediaFileUpload error if file does not exist (#1127)
Thank you for opening a Pull Request! Before submitting your PR, there are a few things you can do to make sure it goes smoothly: - [x] Make sure to open an issue as a [bug/issue](https://github.com/googleapis/google-api-python-client/issues/new/choose) before writing your code! That way we can discuss the change, evaluate designs, and agree on the general idea - [x] Ensure the tests and linter pass - [x] Code coverage does not decrease (if any source code was changed) - [x] Appropriate docs were updated (if necessary) Fixes #798 🦕
1 parent e6a1da3 commit 2c6d029

File tree

2 files changed

+9
-3
lines changed

2 files changed

+9
-3
lines changed

googleapiclient/http.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -573,20 +573,22 @@ def __init__(
573573
resumable: bool, True if this is a resumable upload. False means upload
574574
in a single request.
575575
"""
576+
self._fd = None
576577
self._filename = filename
577-
fd = open(self._filename, "rb")
578+
self._fd = open(self._filename, "rb")
578579
if mimetype is None:
579580
# No mimetype provided, make a guess.
580581
mimetype, _ = mimetypes.guess_type(filename)
581582
if mimetype is None:
582583
# Guess failed, use octet-stream.
583584
mimetype = "application/octet-stream"
584585
super(MediaFileUpload, self).__init__(
585-
fd, mimetype, chunksize=chunksize, resumable=resumable
586+
self._fd, mimetype, chunksize=chunksize, resumable=resumable
586587
)
587588

588589
def __del__(self):
589-
self._fd.close()
590+
if self._fd:
591+
self._fd.close()
590592

591593
def to_json(self):
592594
"""Creating a JSON representation of an instance of MediaFileUpload.

tests/test_http.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,10 @@ def test_media_file_upload_to_from_json(self):
248248
self.assertEqual(500, new_upload.chunksize())
249249
self.assertEqual(b"PNG", new_upload.getbytes(1, 3))
250250

251+
def test_media_file_upload_raises_on_file_not_found(self):
252+
with self.assertRaises(FileNotFoundError):
253+
MediaFileUpload(datafile("missing.png"))
254+
251255
def test_media_file_upload_raises_on_invalid_chunksize(self):
252256
self.assertRaises(
253257
InvalidChunkSizeError,

0 commit comments

Comments
 (0)