raise APIError if service is not available (#14596)

This commit is contained in:
Serghei Mihai 2017-01-13 11:13:09 +01:00
parent b3995eaebd
commit 41e33bbc98
2 changed files with 32 additions and 6 deletions

View File

@ -5,6 +5,7 @@ from django.db import models
from django.utils.translation import ugettext_lazy as _
from passerelle.base.models import BaseResource
from passerelle.utils.jsonresponse import APIError
class MontpellierSig(BaseResource):
@ -40,12 +41,13 @@ class MontpellierSig(BaseResource):
kwargs['verify'] = False
if self.username:
kwargs['auth'] = (self.username, self.password)
resp = requests.get(self.service_url + '/adresse/rest/' + endpoint, **kwargs)
if resp.status_code != 200:
logger.warning('endpoint %r returned(%r): %r', endpoint,
resp.status_code, resp.content)
return []
try:
resp = requests.get(self.service_url + '/adresse/rest/' + endpoint, **kwargs)
except requests.exceptions.RequestException as e:
raise APIError('SIG error: %s' % e)
if not resp.ok:
raise APIError('endpoint %r returned status code: %r' % (endpoint,
resp.status_code))
try:
return resp.json()
except Exception, e:

View File

@ -1,4 +1,5 @@
import json
import httmock
from django.test import TestCase
from django.test.client import Client
@ -7,6 +8,7 @@ from django.core.urlresolvers import reverse
from passerelle_montpellier_sig.models import MontpellierSig
from passerelle_montpellier_sig.views import prefix_cleanup, split_street
from passerelle.utils.jsonresponse import APIError
class PrefixCleanupTestCase(TestCase):
@ -70,3 +72,25 @@ class ReverseGeolocTest(TestCase):
def test_split_avenue(self):
self.assertEqual(split_street('42 AV RAYMOND DUGRAND '), ('42', 'AVENUE RAYMOND DUGRAND'))
class ConnectionTest(TestCase):
def setUp(self):
self.connector, created = MontpellierSig.objects.get_or_create(title='hebe',
slug='hebe', description='hebe',
service_url='http://hebe.montpellier3m.fr')
@httmock.all_requests
def hebe_connection_failed(url, request, *args, **kwargs):
raise httmock.requests.exceptions.RequestException('connection error')
@httmock.all_requests
def hebe_http_error(url, request, *args, **kwargs):
return httmock.response(500, 'Internal Error')
def test_connection_fail(self):
with self.assertRaises(APIError) as e:
with httmock.HTTMock(self.hebe_http_error):
self.connector.sig_request('commune')
self.assertEqual(e.exception.message, "endpoint 'commune' returned status code: 500")