Skip to content

Commit

Permalink
Updating error handler to itself handle exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
aliabbasrizvi committed Sep 30, 2016
1 parent 2db23ae commit bd03dc3
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
15 changes: 11 additions & 4 deletions optimizely/event_dispatcher.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import json
import logging
import requests

from requests import exceptions as request_exception

from .helpers import enums

REQUEST_TIMEOUT = 10
Expand All @@ -15,7 +18,11 @@ def dispatch_event(event):
Args:
event: Object holding information about the request to be dispatched to the Optimizely backend.
"""
if event.http_verb == enums.HTTPVerbs.GET:
requests.get(event.url, params=event.params, timeout=REQUEST_TIMEOUT)
elif event.http_verb == enums.HTTPVerbs.POST:
requests.post(event.url, data=json.dumps(event.params), headers=event.headers, timeout=REQUEST_TIMEOUT)

try:
if event.http_verb == enums.HTTPVerbs.GET:
requests.get(event.url, params=event.params, timeout=REQUEST_TIMEOUT)
elif event.http_verb == enums.HTTPVerbs.POST:
requests.post(event.url, data=json.dumps(event.params), headers=event.headers, timeout=REQUEST_TIMEOUT)
except request_exception.RequestException as error:
logging.error('Dispatch event failed. Error: %s' % str(error))
23 changes: 23 additions & 0 deletions tests/test_event_dispatcher.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import mock
import json
import unittest
from requests import exceptions as request_exception

from optimizely import event_builder
from optimizely import event_dispatcher
Expand Down Expand Up @@ -43,3 +44,25 @@ def test_dispatch_event__post_request(self):
mock_request_post.assert_called_once_with(url, data=json.dumps(params),
headers={'Content-Type': 'application/json'},
timeout=event_dispatcher.REQUEST_TIMEOUT)

def test_dispatch_event__handle_request_exception(self):
""" Test that dispatch event handles exceptions and logs error. """

url = 'https://www.optimizely.com'
params = {
'accountId': '111001',
'eventName': 'test_event',
'eventEntityId': '111028',
'visitorId': 'oeutest_user'
}
event = event_builder.Event(url, params, http_verb='POST', headers={'Content-Type': 'application/json'})

with mock.patch('requests.post',
side_effect=request_exception.RequestException('Failed Request')) as mock_request_post,\
mock.patch('logging.error') as mock_log_error:
event_dispatcher.EventDispatcher.dispatch_event(event)

mock_request_post.assert_called_once_with(url, data=json.dumps(params),
headers={'Content-Type': 'application/json'},
timeout=event_dispatcher.REQUEST_TIMEOUT)
mock_log_error.assert_called_once_with('Dispatch event failed. Error: Failed Request')

0 comments on commit bd03dc3

Please sign in to comment.