Raise Exception if letter PDF not in S3

Previously, the function would just return a presumed filename. Now that
it actually checks s3, if the file doesn't exist it'll raise an
exception. By default that's a StopIteration at the end of the bucket
iterator, which isn't ideal as this will get supressed if the function
is called within a generator loop further up or anything.

There are a couple of places where we expect the file may not exist, so
we define a custom exception to rescue specifically here. I did consider
subclassing boto's ClientError, but this wasn't straightforward as the
constructor expects to know the operation that failed, which for me is a
signal that it's not an appropriate (re-)use of the class.
This commit is contained in:
Leo Hemsted
2021-03-08 18:09:16 +00:00
committed by Ben Thorner
parent b43a367d5f
commit 6784ae62a6
4 changed files with 32 additions and 4 deletions

View File

@@ -8,6 +8,7 @@ from freezegun import freeze_time
from moto import mock_s3
from app.letters.utils import (
LetterPDFNotFound,
ScanErrorType,
find_letter_pdf_filename,
generate_letter_pdf_filename,
@@ -62,6 +63,19 @@ def test_find_letter_pdf_filename_returns_filename(sample_notification):
assert find_letter_pdf_filename(sample_notification) == f'{prefix}-and-then-some'
@mock_s3
def test_find_letter_pdf_filename_raises_if_not_found(sample_notification):
bucket_name = current_app.config['LETTERS_PDF_BUCKET_NAME']
s3 = boto3.client('s3', region_name='eu-west-1')
s3.create_bucket(
Bucket=bucket_name,
CreateBucketConfiguration={'LocationConstraint': 'eu-west-1'}
)
with pytest.raises(LetterPDFNotFound):
find_letter_pdf_filename(sample_notification)
@pytest.mark.parametrize('created_at,folder', [
(datetime(2017, 1, 1, 17, 29), '2017-01-01'),
(datetime(2017, 1, 1, 17, 31), '2017-01-02'),