def test_sanitise_letter_calls_template_preview_sanitise_endoint_with_file( mocker): request_mock = mocker.patch('app.template_previews.requests.post') sanitise_letter('pdf_data') request_mock.assert_called_once_with( 'http://localhost:9999/precompiled/sanitise', headers={'Authorization': 'Token my-secret-key'}, data='pdf_data')
def test_sanitise_letter_calls_template_preview_sanitise_endoint_with_file( mocker, allow_international_letters, expected_url, ): request_mock = mocker.patch('app.template_previews.requests.post') sanitise_letter('pdf_data', allow_international_letters=allow_international_letters) request_mock.assert_called_once_with( expected_url, headers={'Authorization': 'Token my-secret-key'}, data='pdf_data')
def upload_letter(service_id): form = PDFUploadForm() error = {} if form.validate_on_submit(): pdf_file_bytes = form.file.data.read() original_filename = form.file.data.filename if current_app.config['ANTIVIRUS_ENABLED']: virus_free = antivirus_client.scan(BytesIO(pdf_file_bytes)) if not virus_free: return invalid_upload_error('Your file contains a virus') if len(pdf_file_bytes) > MAX_FILE_UPLOAD_SIZE: return invalid_upload_error('Your file is too big', 'Files must be smaller than 2MB.') try: # TODO: get page count from the sanitise response once template preview handles malformed files nicely page_count = pdf_page_count(BytesIO(pdf_file_bytes)) except PdfReadError: current_app.logger.info( 'Invalid PDF uploaded for service_id: {}'.format(service_id)) return invalid_upload_error( "There’s a problem with your file", 'Notify cannot read this PDF.<br>Save a new copy of your file and try again.' ) upload_id = uuid.uuid4() file_location = get_transient_letter_file_location( service_id, upload_id) try: response = sanitise_letter( BytesIO(pdf_file_bytes), allow_international_letters=current_service.has_permission( 'international_letters'), ) response.raise_for_status() except RequestException as ex: if ex.response is not None and ex.response.status_code == 400: validation_failed_message = response.json().get('message') invalid_pages = response.json().get('invalid_pages') status = 'invalid' upload_letter_to_s3(pdf_file_bytes, file_location=file_location, status=status, page_count=page_count, filename=original_filename, message=validation_failed_message, invalid_pages=invalid_pages) else: raise ex else: response = response.json() recipient = response['recipient_address'] status = 'valid' file_contents = base64.b64decode(response['file'].encode()) upload_letter_to_s3(file_contents, file_location=file_location, status=status, page_count=page_count, filename=original_filename, recipient=recipient) return redirect( url_for( 'main.uploaded_letter_preview', service_id=current_service.id, file_id=upload_id, )) if form.file.errors: error = _get_error_from_upload_form(form.file.errors[0]) return render_template('views/uploads/choose-file.html', error=error, form=form)