From 86d8788ee8a766ca6818620f3fd2899be0e44190 Mon Sep 17 00:00:00 2001 From: Bu Sun Kim <8822365+busunkim96@users.noreply.github.com> Date: Thu, 22 Oct 2020 08:51:16 -0600 Subject: [PATCH] fix: don't raise when downloading zero byte files (#1074) --- googleapiclient/http.py | 12 ++++++++++-- tests/test_http.py | 20 ++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/googleapiclient/http.py b/googleapiclient/http.py index a87575184a7..00467747fd3 100644 --- a/googleapiclient/http.py +++ b/googleapiclient/http.py @@ -745,8 +745,16 @@ def next_chunk(self, num_retries=0): if self._total_size is None or self._progress == self._total_size: self._done = True return MediaDownloadProgress(self._progress, self._total_size), self._done - else: - raise HttpError(resp, content, uri=self._uri) + elif resp.status == 416: + # 416 is Range Not Satisfiable + # This typically occurs with a zero byte file + content_range = resp["content-range"] + length = content_range.rsplit("/", 1)[1] + self._total_size = int(length) + if self._total_size == 0: + self._done = True + return MediaDownloadProgress(self._progress, self._total_size), self._done + raise HttpError(resp, content, uri=self._uri) class _StreamSlice(object): diff --git a/tests/test_http.py b/tests/test_http.py index c7d9cc35df7..00db06eee39 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -672,6 +672,26 @@ def test_media_io_base_download_empty_file(self): self.assertEqual(0, download._total_size) self.assertEqual(0, status.progress()) + def test_media_io_base_download_empty_file_416_response(self): + self.request.http = HttpMockSequence( + [({"status": "416", "content-range": "0-0/0"}, b"")] + ) + + download = MediaIoBaseDownload(fd=self.fd, request=self.request, chunksize=3) + + self.assertEqual(self.fd, download._fd) + self.assertEqual(0, download._progress) + self.assertEqual(None, download._total_size) + self.assertEqual(False, download._done) + self.assertEqual(self.request.uri, download._uri) + + status, done = download.next_chunk() + + self.assertEqual(True, done) + self.assertEqual(0, download._progress) + self.assertEqual(0, download._total_size) + self.assertEqual(0, status.progress()) + def test_media_io_base_download_unknown_media_size(self): self.request.http = HttpMockSequence([({"status": "200"}, b"123")])