Skip to content

Commit

Permalink
Merge pull request #21 from gernot-h/fix-download-attachment-404
Browse files Browse the repository at this point in the history
fix(attachments): raise SW360Error on failed downloads
  • Loading branch information
tngraf authored Aug 7, 2023
2 parents aae5144 + cd5922e commit d79a3c4
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
2 changes: 2 additions & 0 deletions ChangeLog.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
5 changes: 4 additions & 1 deletion sw360/attachments.py
Original file line number Diff line number Diff line change
Expand Up @@ -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=""):
Expand Down
31 changes: 31 additions & 0 deletions tests/test_sw360_attachments.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit d79a3c4

Please sign in to comment.