From 432782b33e412bad6e7722a65e3fb1db34c6b474 Mon Sep 17 00:00:00 2001 From: Rebecca Cremona Date: Tue, 3 Dec 2024 17:56:25 -0500 Subject: [PATCH] Add handling for requests to download unavilable formats. --- perma_web/api/tests/test_link_resource.py | 12 ++++++++++++ perma_web/perma/utils.py | 19 ++++++++++++------- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/perma_web/api/tests/test_link_resource.py b/perma_web/api/tests/test_link_resource.py index c08eb04be..e08313ec0 100644 --- a/perma_web/api/tests/test_link_resource.py +++ b/perma_web/api/tests/test_link_resource.py @@ -185,6 +185,18 @@ def test_public_download_wacz(self, get_wacz): def test_public_download_unsupported_format(self): self.rejected_get(f"{self.public_link_download_url}?file_format=asdf", expected_status_code=400) + @patch('perma.models.Link.get_warc', autospec=True) + def test_download_nonexistent_warc(self, get_warc): + get_warc.side_effect = RuntimeError + self.rejected_get(self.public_link_download_url, expected_status_code=404) + self.assertEqual(get_warc.call_count, 1) + + @patch('perma.models.Link.get_wacz', autospec=True) + def test_download_nonexistent_wacz(self, get_wacz): + get_wacz.side_effect = RuntimeError + self.rejected_get(f"{self.public_link_download_url}?file_format=wacz", expected_status_code=404) + self.assertEqual(get_wacz.call_count, 1) + def test_private_download_at_public_url(self): self.rejected_get(self.public_link_download_url_for_private_link, expected_status_code=404) diff --git a/perma_web/perma/utils.py b/perma_web/perma/utils.py index a52754dce..ba31a4255 100644 --- a/perma_web/perma/utils.py +++ b/perma_web/perma/utils.py @@ -632,13 +632,18 @@ def stream_archive(link, stream=True, file_format='warc'): if link.user_deleted or not link.can_play_back(): raise Http404 - match file_format: - case 'warc': - return get_warc_stream(link, stream) - case 'wacz': - return get_wacz_stream(link, stream) - case _: - raise NotImplementedError("Unsupported file format.") + try: + match file_format: + case 'warc': + return get_warc_stream(link, stream) + case 'wacz': + return get_wacz_stream(link, stream) + case _: + raise NotImplementedError("Unsupported file format.") + except RuntimeError: + # If the requested format is not available, return 404 + # just like with deleted and failed Perma Links + raise Http404 def stream_archive_if_permissible(link, user, stream=True, file_format='warc'):