From bacabbe767de3e453774b87f4d8706b55f5c762a Mon Sep 17 00:00:00 2001 From: Gabriel Simonetto <42247511+GabrielSimonetto@users.noreply.github.com> Date: Thu, 6 Feb 2020 07:21:21 -0300 Subject: [PATCH] fix download without path arguments (#1591) * fix download without path arguments * fix download without path arguments * solved downloading a file without file_path or custom_path * if no file_path, download as file_id * Add test case * Elaborate doc string Co-authored-by: Bibo-Joshi --- telegram/files/file.py | 12 ++++++++---- tests/test_file.py | 16 ++++++++++++++++ 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/telegram/files/file.py b/telegram/files/file.py index 77944666b..285b54f03 100644 --- a/telegram/files/file.py +++ b/telegram/files/file.py @@ -19,6 +19,7 @@ """This module contains an object that represents a Telegram File.""" from base64 import b64decode from os.path import basename +import os from future.backports.urllib import parse as urllib_parse @@ -76,9 +77,10 @@ class File(TelegramObject): def download(self, custom_path=None, out=None, timeout=None): """ Download this file. By default, the file is saved in the current working directory with its - original filename as reported by Telegram. If a :attr:`custom_path` is supplied, it will be - saved to that path instead. If :attr:`out` is defined, the file contents will be saved to - that object using the ``out.write`` method. + original filename as reported by Telegram. If the file has no filename, it the file ID will + be used as filename. If a :attr:`custom_path` is supplied, it will be saved to that path + instead. If :attr:`out` is defined, the file contents will be saved to that object using + the ``out.write`` method. Note: :attr:`custom_path` and :attr:`out` are mutually exclusive. @@ -116,8 +118,10 @@ class File(TelegramObject): else: if custom_path: filename = custom_path - else: + elif self.file_path: filename = basename(self.file_path) + else: + filename = os.path.join(os.getcwd(), self.file_id) buf = self.bot.request.retrieve(url, timeout=timeout) if self._credentials: diff --git a/tests/test_file.py b/tests/test_file.py index 9402522e6..49855b2d6 100644 --- a/tests/test_file.py +++ b/tests/test_file.py @@ -96,6 +96,22 @@ class TestFile(object): os.close(file_handle) os.unlink(custom_path) + def test_download_no_filename(self, monkeypatch, file): + def test(*args, **kwargs): + return self.file_content + + file.file_path = None + + monkeypatch.setattr('telegram.utils.request.Request.retrieve', test) + out_file = file.download() + + assert out_file[-len(file.file_id):] == file.file_id + try: + with open(out_file, 'rb') as fobj: + assert fobj.read() == self.file_content + finally: + os.unlink(out_file) + def test_download_file_obj(self, monkeypatch, file): def test(*args, **kwargs): return self.file_content