Merge pull request #1592 from alphagov/load-service-err

make sure load_service_before_request handles 404s
This commit is contained in:
Leo Hemsted
2017-11-01 16:47:25 +00:00
committed by GitHub
2 changed files with 31 additions and 3 deletions

View File

@@ -406,10 +406,23 @@ def load_service_before_request():
if '/static/' in request.url:
_request_ctx_stack.top.service = None
return
service_id = request.view_args.get('service_id', session.get('service_id')) if request.view_args \
else session.get('service_id')
if _request_ctx_stack.top is not None:
_request_ctx_stack.top.service = service_api_client.get_service(service_id)['data'] if service_id else None
_request_ctx_stack.top.service = None
if request.view_args:
service_id = request.view_args.get('service_id', session.get('service_id'))
else:
service_id = session.get('service_id')
if service_id:
try:
_request_ctx_stack.top.service = service_api_client.get_service(service_id)['data']
except HTTPError as exc:
# if service id isn't real, then 404 rather than 500ing later because we expect service to be set
if exc.status_code == 404:
abort(404)
else:
raise
def save_service_after_request(response):

View File

@@ -1,5 +1,7 @@
from flask import Response
import pytest
from bs4 import BeautifulSoup
from notifications_python_client.errors import HTTPError
def test_bad_url_returns_page_not_found(client):
@@ -9,6 +11,19 @@ def test_bad_url_returns_page_not_found(client):
assert page.h1.string.strip() == 'Page could not be found'
def test_load_service_before_request_handles_404(client_request, mocker):
exc = HTTPError(Response(status=404), 'Not found')
get_service = mocker.patch('app.service_api_client.get_service', side_effect=exc)
client_request.get(
'main.service_dashboard',
service_id='00000000-0000-0000-0000-000000000000',
_expected_status=404
)
get_service.assert_called_once_with('00000000-0000-0000-0000-000000000000')
@pytest.mark.parametrize('url', [
'/invitation/MALFORMED_TOKEN',
'/new-password/MALFORMED_TOKEN',