From cd5922e306fe78153c3c083a76f4b3cb079602d9 Mon Sep 17 00:00:00 2001 From: Gernot Hillier Date: Sun, 30 Jul 2023 21:41:47 +0200 Subject: [PATCH] fix(attachments): raise SW360Error on failed downloads Fixes #20 --- ChangeLog.md | 2 ++ sw360/attachments.py | 5 ++++- tests/test_sw360_attachments.py | 31 +++++++++++++++++++++++++++++++ 3 files changed, 37 insertions(+), 1 deletion(-) diff --git a/ChangeLog.md b/ChangeLog.md index 2cae2cc..7ab2dce 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -7,6 +7,8 @@ ## NEXT +* fix: download_xxx_attachment now raises an SW360Error for failed downloads + instead of silently creating a file containing the JSON answer * dependency updates to fix requests CVE-2023-32681. * be REUSE compliant. * get rid of json_params_matcher deprecation warning. diff --git a/sw360/attachments.py b/sw360/attachments.py index fa07c03..39afd46 100644 --- a/sw360/attachments.py +++ b/sw360/attachments.py @@ -169,7 +169,10 @@ def download_attachment(self, filename, download_url): hdr = self.api_headers.copy() hdr["Accept"] = "application/*" req = requests.get(download_url, allow_redirects=True, headers=hdr) - open(filename, "wb").write(req.content) + if req.ok: + open(filename, "wb").write(req.content) + else: + raise SW360Error(req, download_url) def _upload_resource_attachment(self, resource_type, resource_id, upload_file, upload_type="SOURCE", upload_comment=""): diff --git a/tests/test_sw360_attachments.py b/tests/test_sw360_attachments.py index 6341cd3..4b9125d 100644 --- a/tests/test_sw360_attachments.py +++ b/tests/test_sw360_attachments.py @@ -216,6 +216,37 @@ def test_download_release_attachment(self): os.remove(filename) os.removedirs(tmpdir) + @responses.activate + def test_download_release_attachment_404(self): + lib = SW360(self.MYURL, self.MYTOKEN, False) + lib.force_no_session = True + self._add_login_response() + actual = lib.login_api() + self.assertTrue(actual) + + url = self.MYURL + "resource/api/releases/1234/attachments/5678" + responses.add( + method=responses.GET, + url=url, + body='xxxx', + status=404, + content_type="application/text", + adding_headers={"Authorization": "Token " + self.MYTOKEN}, + ) + + tmpdir = tempfile.mkdtemp() + filename = os.path.join(tmpdir, "test_attachment.txt") + if os.path.exists(filename): + os.remove(filename) + + self.assertFalse(os.path.exists(filename)) + with self.assertRaises(SW360Error) as context: + lib.download_release_attachment(filename, "1234", "5678") + self.assertFalse(os.path.exists(filename)) + self.assertEqual(context.exception.url, url) + self.assertEqual(context.exception.response.status_code, 404) + os.removedirs(tmpdir) + @responses.activate def test_download_project_attachment(self): lib = SW360(self.MYURL, self.MYTOKEN, False)