Skip to content

feat(event_processor): add forwarding event processor and integrate with optimizely #205

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 126 commits into from
Oct 14, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
126 commits
Select commit Hold shift + click to select a range
232f0a0
feat: Add event_batch datamodels.
Jul 19, 2019
2320939
fix: unit test fixes.
Jul 22, 2019
fbb5a68
Merge branch 'master' into epmodels
mnoman09 Jul 22, 2019
c162465
feat: add event_factory and user_event_factory for event processing.
Jul 24, 2019
633b095
Removed third party dependency
msohailhussain Jul 26, 2019
8a5f531
Merge branch 'master' into sohail/pr-189
mnoman09 Aug 1, 2019
35fcd82
Merge remote-tracking branch 'origin/sohail/pr-189' into sohail/pr-193
mnoman09 Aug 1, 2019
d7201cb
Removed HasAttr
mnoman09 Aug 1, 2019
c829fca
Merge branch 'master' into sohail/pr-189
mnoman09 Aug 16, 2019
1d858b7
feat(eventProcessor): Adds EventProcessor and BatchEventProcessor
mnoman09 Aug 16, 2019
c3c9d46
Addressed feedback. Restructured classes.
msohailhussain Aug 20, 2019
a2eeb85
Merge branch 'sohail/pr-189' into sohail/pr-193
mnoman09 Aug 20, 2019
a045291
update: structural changes.
Aug 20, 2019
f70a1c9
Merge branch 'sohail/pr-193' into mnoman/AddBatchEP
mnoman09 Aug 20, 2019
faff070
update: add check for integer values and insert logs for default values.
mnoman09 Aug 20, 2019
c931956
replaced comma with as
mnoman09 Aug 20, 2019
2dea7fe
conditions reordered
mnoman09 Aug 20, 2019
d7f69ec
Added Log event notification
mnoman09 Aug 20, 2019
8853cb3
fix: fix imports in test_event_processor.
mnoman09 Aug 21, 2019
5934764
fix: linter issues
mnoman09 Aug 21, 2019
23ab6ce
fix: addressed more feedback
Aug 21, 2019
6474e98
update: removed print statements.
mnoman09 Aug 21, 2019
1184568
merged PR 189
mnoman09 Aug 21, 2019
592a306
fix: use VisitorAttribute class to create visitor attributes list.
Aug 21, 2019
c4a412a
fix: fix log_event payload.
Aug 22, 2019
2a3374c
removed commented code
mnoman09 Aug 22, 2019
ce44c11
fix linter error.
mnoman09 Aug 22, 2019
00efd1b
Merge branch 'sohail/pr-193' into mnoman/AddBatchEP
mnoman09 Aug 22, 2019
54333d7
update: log_event params.
mnoman09 Aug 22, 2019
af497f9
Merge branch 'mnoman/AddBatchEP' into mnoman/log_event_notification
mnoman09 Aug 22, 2019
d2f7126
fix: update module names according to structural changes.
Aug 22, 2019
f21c94b
Merge remote-tracking branch 'remotes/main_origin/mnoman/AddBatchEP' …
Aug 22, 2019
3fd5788
fix: update module names according to structural changes.
Aug 22, 2019
ebe833c
Merge branch 'mnoman/AddBatchEP' of github.com:optimizely/python-sdk …
Aug 22, 2019
ddef208
fix: remove print statement.
Aug 23, 2019
e964048
fix: remove print statement.
Aug 23, 2019
8953a43
Merge branch 'mnoman/log_event_notification' of github.com:optimizely…
Aug 23, 2019
b1388da
feat(event_processor): add forwarding event processor and integrate w…
rashidsp Aug 23, 2019
535e624
fixes exception syntax
rashidsp Aug 23, 2019
d4f2c66
Merge branch 'master' into sohail/pr-189
rashidsp Aug 28, 2019
80b0963
fix: addressed minor feedback.
Aug 28, 2019
071460a
fix: addressed minor feedback.
Aug 28, 2019
900d96d
Merge branch 'sohail/pr-189' of github.com:optimizely/python-sdk into…
Aug 28, 2019
8cd8547
Merge branch 'sohail/pr-189' into sohail/pr-193
Aug 28, 2019
b730bfd
Merge branch 'sohail/pr-193' into mnoman/AddBatchEP
Aug 28, 2019
752e35f
Merge branch 'mnoman/AddBatchEP' into mnoman/log_event_notification
Aug 28, 2019
f9a2cb6
Merge branch 'mnoman/AddBatchEP' into mnoman/log_event_notification
Aug 28, 2019
54446b9
Merge branch 'mnoman/log_event_notification' of github.com:optimizely…
Aug 28, 2019
aedccc8
Merge branch 'mnoman/log_event_notification' into rashid/forwarding_e…
Aug 28, 2019
e628e0f
fix: addressed review comments.
mariamjamal94 Sep 2, 2019
855c73f
Merge branch 'sohail/pr-193' into mnoman/AddBatchEP
mariamjamal94 Sep 2, 2019
c92f79d
Merge branch 'mnoman/AddBatchEP' into mnoman/log_event_notification
mariamjamal94 Sep 2, 2019
63c1b21
Merge branch 'mnoman/log_event_notification' into rashid/forwarding_e…
mariamjamal94 Sep 2, 2019
c18e359
Merge branch 'sohail/pr-193' into mnoman/AddBatchEP
mariamjamal94 Sep 2, 2019
56408dc
Merge branches 'mnoman/AddBatchEP' and 'mnoman/AddBatchEP' of github.…
mariamjamal94 Sep 2, 2019
f851754
fix: addresses review comments.
mariamjamal94 Sep 4, 2019
8f7be2b
Merge branch 'sohail/pr-193' into mnoman/AddBatchEP
mariamjamal94 Sep 4, 2019
1486fa4
Merge branch 'sohail/pr-193' into mnoman/AddBatchEP
mariamjamal94 Sep 4, 2019
b9d5fd9
Merge branch 'mnoman/AddBatchEP' of github.com:optimizely/python-sdk …
mariamjamal94 Sep 4, 2019
d42d14b
Merge branch 'mnoman/AddBatchEP' into mnoman/log_event_notification
mariamjamal94 Sep 4, 2019
6366d59
Merge branch 'mnoman/log_event_notification' into rashid/forwarding_e…
mariamjamal94 Sep 4, 2019
65a752b
fix: addresses review comment.
mariamjamal94 Sep 5, 2019
ab192a0
Merge branch 'sohail/pr-193' into mnoman/AddBatchEP
mariamjamal94 Sep 5, 2019
06ac3f0
Merge branch 'mnoman/AddBatchEP' into mnoman/log_event_notification
mariamjamal94 Sep 5, 2019
8e4c118
Merge branch 'mnoman/log_event_notification' into rashid/forwarding_e…
mariamjamal94 Sep 5, 2019
641d09a
update: allow float values for intervals.
mariamjamal94 Sep 5, 2019
9630139
Merge branch 'mnoman/AddBatchEP' into mnoman/log_event_notification
mariamjamal94 Sep 5, 2019
3e40044
Merge branch 'mnoman/log_event_notification' into rashid/forwarding_e…
mariamjamal94 Sep 5, 2019
8998580
fix: updated docstring for LogEvent.
mariamjamal94 Sep 6, 2019
a89a5bf
Merge branch 'sohail/pr-193' into mnoman/AddBatchEP
mariamjamal94 Sep 6, 2019
2582fb7
Merge branch 'mnoman/AddBatchEP' into mnoman/log_event_notification
mariamjamal94 Sep 6, 2019
41d44e6
Merge branch 'mnoman/log_event_notification' into rashid/forwarding_e…
mariamjamal94 Sep 6, 2019
cfb2d74
fix: restore config_manager and remove unnecessary warnings from tox.…
mariamjamal94 Sep 6, 2019
75725bd
Merge branch 'mnoman/AddBatchEP' into mnoman/log_event_notification
mariamjamal94 Sep 6, 2019
42a90f0
Merge branch 'mnoman/log_event_notification' into rashid/forwarding_e…
mariamjamal94 Sep 6, 2019
751ee64
fix: remove closeable and introduce stop method.
mariamjamal94 Sep 6, 2019
cb07348
fix: address review comments.
mariamjamal94 Sep 12, 2019
c3d5b07
Merge branch 'master' into sohail/pr-193
mariamjamal94 Sep 12, 2019
2d37cbe
update: add docstring and split imports in separate lines.
mariamjamal94 Sep 12, 2019
f50e053
Merge branch 'mnoman/AddBatchEP' into mnoman/log_event_notification
mariamjamal94 Sep 13, 2019
bb3f738
fix: remove close method from test_notification_center.
mariamjamal94 Sep 13, 2019
b5d461b
Merge branch 'master' into sohail/pr-193
aliabbasrizvi Sep 16, 2019
ca208a6
Merge remote-tracking branch 'remotes/main_origin/master' into mnoman…
mariamjamal94 Sep 17, 2019
2c33344
update: update documentation and set default time interval unit to sec.
mariamjamal94 Sep 17, 2019
46cc51d
Merge branch 'mnoman/AddBatchEP' into mnoman/log_event_notification
mariamjamal94 Sep 17, 2019
1ab8b32
fix: linting error.
mariamjamal94 Sep 17, 2019
67e0424
fix: compare times directly in seconds.
mariamjamal94 Sep 17, 2019
f0dd1fd
Merge branch 'mnoman/AddBatchEP' into mnoman/log_event_notification
mariamjamal94 Sep 17, 2019
4d4e7d1
update: update documentation for event_processor.
mariamjamal94 Sep 17, 2019
477bbd5
Merge branch 'sohail/pr-193' into mnoman/AddBatchEP
oakbani Sep 17, 2019
e299dce
update: update sleeping time to 5sec.
mariamjamal94 Sep 17, 2019
758ffc2
Merge branch 'mnoman/AddBatchEP' of github.com:optimizely/python-sdk …
mariamjamal94 Sep 17, 2019
304ac00
update: update sleeping time to 5 sec.
mariamjamal94 Sep 17, 2019
cbd918a
Merge branch 'mnoman/AddBatchEP' into mnoman/log_event_notification
mariamjamal94 Sep 17, 2019
5ef24de
fix: address import order issues.
mariamjamal94 Sep 18, 2019
1edb7c2
Merge branch 'sohail/pr-193' into mnoman/AddBatchEP
mariamjamal94 Sep 18, 2019
4c8b7f3
Merge branch 'mnoman/AddBatchEP' into mnoman/log_event_notification
mariamjamal94 Sep 18, 2019
9d917a4
Merge branch 'mnoman/log_event_notification' into rashid/forwarding_e…
mariamjamal94 Sep 18, 2019
443b7aa
update: add documentation.
mariamjamal94 Sep 18, 2019
3b2cb4a
Merge branch 'mnoman/AddBatchEP' into mnoman/log_event_notification
mariamjamal94 Sep 18, 2019
dcca0ec
Merge branch 'mnoman/log_event_notification' into rashid/forwarding_e…
mariamjamal94 Sep 18, 2019
dea337b
update: update parent class name for ForwardingEventProcessor.
mariamjamal94 Sep 18, 2019
1d5aeca
Merge branch 'master' into sohail/pr-193
oakbani Sep 20, 2019
b3883d6
Merge remote-tracking branch 'remotes/origin/sohail/pr-193' into mnom…
oakbani Sep 20, 2019
655a859
Merge branch 'mnoman/AddBatchEP' of github.com:optimizely/python-sdk …
oakbani Sep 20, 2019
4753c0b
Merge branch 'mnoman/AddBatchEP' into mnoman/log_event_notification
oakbani Sep 20, 2019
86e4b7f
Merge branch 'master' into mnoman/AddBatchEP
msohailhussain Sep 20, 2019
65fb6fa
fix: address review comments.
mariamjamal94 Sep 24, 2019
01a8ea1
Merge branch 'mnoman/AddBatchEP' of github.com:optimizely/python-sdk …
mariamjamal94 Sep 24, 2019
3baf024
Merge branch 'mnoman/AddBatchEP' into mnoman/log_event_notification
mariamjamal94 Sep 24, 2019
7e20be7
Merge branch 'mnoman/log_event_notification' of github.com:optimizely…
mariamjamal94 Sep 24, 2019
15e0c8f
Merge branch 'mnoman/log_event_notification' into rashid/forwarding_e…
mariamjamal94 Sep 24, 2019
498db55
update: add docstring.
mariamjamal94 Sep 25, 2019
614a3d4
Merge branch 'mnoman/AddBatchEP' into mnoman/log_event_notification
mariamjamal94 Sep 25, 2019
ee89a1f
Merge branch 'mnoman/log_event_notification' into rashid/forwarding_e…
mariamjamal94 Sep 25, 2019
2c67253
fix: address review comments.
mariamjamal94 Sep 25, 2019
6e4d431
Merge branch 'mnoman/log_event_notification' into rashid/forwarding_e…
mariamjamal94 Sep 25, 2019
02c9e53
fix: address review comments.
mariamjamal94 Sep 25, 2019
9ebf1a4
fix notification center impoer
oakbani Oct 3, 2019
34e3cf5
Merge branch 'mnoman/log_event_notification' into rashid/forwarding_e…
oakbani Oct 3, 2019
d241a2f
fix: another instance
oakbani Oct 3, 2019
dc53d39
fix: Allow floating values less than 1 and wait only for 50ms
oakbani Oct 3, 2019
8956cba
Merge remote-tracking branch 'remotes/origin/master' into rashid/forw…
oakbani Oct 7, 2019
c6a2c18
Make logger optional
oakbani Oct 7, 2019
41516f0
Merge branch 'master' into rashid/forwarding_event_processor
aliabbasrizvi Oct 9, 2019
ac8663a
address comment
oakbani Oct 11, 2019
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 52 additions & 4 deletions optimizely/event/event_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,11 +117,11 @@ def _validate_intantiation_props(self, prop, prop_name):
prop_name: Property name.

Returns:
False if property value is None or less than 1 or not a finite number.
False if property value is None or less than or equal to 0 or not a finite number.
False if property name is batch_size and value is a floating point number.
True otherwise.
"""
if (prop_name == 'batch_size' and not isinstance(prop, int)) or prop is None or prop < 1 or \
if (prop_name == 'batch_size' and not isinstance(prop, int)) or prop is None or prop <= 0 or \
not validator.is_finite_number(prop):
self.logger.info('Using default value for {}.'.format(prop_name))
return False
Expand Down Expand Up @@ -159,11 +159,11 @@ def _run(self):
"""
try:
while True:
if self._get_time() > self.flushing_interval_deadline:
if self._get_time() >= self.flushing_interval_deadline:
self._flush_queue()

try:
item = self.event_queue.get(True, 0.05)
item = self.event_queue.get(False)

except queue.Empty:
time.sleep(0.05)
Expand Down Expand Up @@ -283,3 +283,51 @@ def stop(self):

if self.is_running:
self.logger.error('Timeout exceeded while attempting to close for ' + str(self.timeout_interval) + ' ms.')


class ForwardingEventProcessor(BaseEventProcessor):
"""
ForwardingEventProcessor serves as the default EventProcessor.

The ForwardingEventProcessor sends the LogEvent to EventDispatcher as soon as it is received.
"""

def __init__(self, event_dispatcher, logger=None, notification_center=None):
""" ForwardingEventProcessor init method to configure event dispatching.

Args:
event_dispatcher: Provides a dispatch_event method which if given a URL and params sends a request to it.
logger: Optional component which provides a log method to log messages. By default nothing would be logged.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You say it is optional, but it is not so in practice.

notification_center: Optional instance of notification_center.NotificationCenter.
"""
self.event_dispatcher = event_dispatcher
self.logger = _logging.adapt_logger(logger or _logging.NoOpLogger())
self.notification_center = notification_center
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similar to feedback in #204 shouldn't we validate that notification_center is an instance of notification_center.NotificationCenter


if not validator.is_notification_center_valid(self.notification_center):
self.logger.error(enums.Errors.INVALID_INPUT.format('notification_center'))
self.notification_center = _notification_center.NotificationCenter()

def process(self, user_event):
""" Method to process the user_event by dispatching it.
Args:
user_event: UserEvent Instance.
"""
if not isinstance(user_event, UserEvent):
self.logger.error('Provided event is in an invalid format.')
return

self.logger.debug('Received user_event: ' + str(user_event))

log_event = EventFactory.create_log_event(user_event, self.logger)

if self.notification_center is not None:
self.notification_center.send_notifications(
enums.NotificationTypes.LOG_EVENT,
log_event
)

try:
self.event_dispatcher.dispatch_event(log_event)
except Exception as e:
self.logger.exception('Error dispatching event: ' + str(log_event) + ' ' + str(e))
4 changes: 2 additions & 2 deletions optimizely/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Copyright 2016-2018, Optimizely
# Copyright 2016-2019, Optimizely
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
Expand Down Expand Up @@ -43,7 +43,7 @@ class InvalidGroupException(Exception):


class InvalidInputException(Exception):
""" Raised when provided datafile, event dispatcher, logger or error handler is invalid. """
""" Raised when provided datafile, event dispatcher, logger, event processor or error handler is invalid. """
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit. Year in header needs to be updated.

pass


Expand Down
15 changes: 14 additions & 1 deletion optimizely/helpers/validator.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Copyright 2016-2018, Optimizely
# Copyright 2016-2019, Optimizely
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
Expand Down Expand Up @@ -72,6 +72,19 @@ def is_config_manager_valid(config_manager):
return _has_method(config_manager, 'get_config')


def is_event_processor_valid(event_processor):
""" Given an event_processor, determine if it is valid or not i.e. provides a process method.

Args:
event_processor: Provides a process method to create user events and then send requests.

Returns:
Boolean depending upon whether event_processor is valid or not.
"""

return _has_method(event_processor, 'process')


def is_error_handler_valid(error_handler):
""" Given a error_handler determine if it is valid or not i.e. provides a handle_error method.

Expand Down
57 changes: 30 additions & 27 deletions optimizely/optimizely.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,13 @@
from . import event_builder
from . import exceptions
from . import logger as _logging
from .config_manager import StaticConfigManager
from .config_manager import PollingConfigManager
from .config_manager import StaticConfigManager
from .error_handler import NoOpErrorHandler as noop_error_handler
from .event import event_factory, user_event_factory
from .event.event_processor import ForwardingEventProcessor
from .event_dispatcher import EventDispatcher as default_event_dispatcher
from .helpers import enums
from .helpers import validator
from .helpers import enums, validator
from .notification_center import NotificationCenter


Expand All @@ -38,7 +39,8 @@ def __init__(self,
user_profile_service=None,
sdk_key=None,
config_manager=None,
notification_center=None):
notification_center=None,
event_processor=None):
""" Optimizely init method for managing Custom projects.

Args:
Expand All @@ -56,6 +58,7 @@ def __init__(self,
notification_center: Optional instance of notification_center.NotificationCenter. Useful when providing own
config_manager.BaseConfigManager implementation which can be using the
same NotificationCenter instance.
event_processor: Processes the given event(s) by creating LogEvent(s) and then dispatching it.
"""
self.logger_name = '.'.join([__name__, self.__class__.__name__])
self.is_valid = True
Expand All @@ -64,6 +67,9 @@ def __init__(self,
self.error_handler = error_handler or noop_error_handler
self.config_manager = config_manager
self.notification_center = notification_center or NotificationCenter(self.logger)
self.event_processor = event_processor or ForwardingEventProcessor(self.event_dispatcher,
self.logger,
self.notification_center)

try:
self._validate_instantiation_options()
Expand Down Expand Up @@ -114,6 +120,9 @@ def _validate_instantiation_options(self):
if not validator.is_notification_center_valid(self.notification_center):
raise exceptions.InvalidInputException(enums.Errors.INVALID_INPUT.format('notification_center'))

if not validator.is_event_processor_valid(self.event_processor):
raise exceptions.InvalidInputException(enums.Errors.INVALID_INPUT.format('event_processor'))

def _validate_user_inputs(self, attributes=None, event_tags=None):
""" Helper method to validate user inputs.

Expand Down Expand Up @@ -149,26 +158,23 @@ def _send_impression_event(self, project_config, experiment, variation, user_id,
attributes: Dict representing user attributes and values which need to be recorded.
"""

impression_event = self.event_builder.create_impression_event(
user_event = user_event_factory.UserEventFactory.create_impression_event(
project_config,
experiment,
variation.id,
user_id,
attributes
)

self.logger.debug('Dispatching impression event to URL %s with params %s.' % (
impression_event.url,
impression_event.params
))

try:
self.event_dispatcher.dispatch_event(impression_event)
except:
self.logger.exception('Unable to dispatch impression event!')
self.event_processor.process(user_event)

self.notification_center.send_notifications(enums.NotificationTypes.ACTIVATE,
experiment, user_id, attributes, variation, impression_event)
# Kept for backward compatibility.
# This notification is deprecated and new Decision notifications
# are sent via their respective method calls.
if len(self.notification_center.notification_listeners[enums.NotificationTypes.ACTIVATE]) > 0:
log_event = event_factory.EventFactory.create_log_event(user_event, self.logger)
self.notification_center.send_notifications(enums.NotificationTypes.ACTIVATE, experiment,
user_id, attributes, variation, log_event.__dict__)

def _get_feature_variable_for_type(self,
project_config,
Expand Down Expand Up @@ -359,24 +365,21 @@ def track(self, event_key, user_id, attributes=None, event_tags=None):
self.logger.info('Not tracking user "%s" for event "%s".' % (user_id, event_key))
return

conversion_event = self.event_builder.create_conversion_event(
user_event = user_event_factory.UserEventFactory.create_conversion_event(
project_config,
event_key,
user_id,
attributes,
event_tags
)

self.event_processor.process(user_event)
self.logger.info('Tracking event "%s" for user "%s".' % (event_key, user_id))
self.logger.debug('Dispatching conversion event to URL %s with params %s.' % (
conversion_event.url,
conversion_event.params
))
try:
self.event_dispatcher.dispatch_event(conversion_event)
except:
self.logger.exception('Unable to dispatch conversion event!')
self.notification_center.send_notifications(enums.NotificationTypes.TRACK, event_key, user_id,
attributes, event_tags, conversion_event)

if len(self.notification_center.notification_listeners[enums.NotificationTypes.TRACK]) > 0:
log_event = event_factory.EventFactory.create_log_event(user_event, self.logger)
self.notification_center.send_notifications(enums.NotificationTypes.TRACK, event_key, user_id,
attributes, event_tags, log_event.__dict__)

def get_variation(self, experiment_key, user_id, attributes=None):
""" Gets variation where user will be bucketed.
Expand Down
17 changes: 16 additions & 1 deletion tests/helpers_tests/test_validator.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Copyright 2016-2018, Optimizely
# Copyright 2016-2019, Optimizely
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
Expand All @@ -20,6 +20,7 @@
from optimizely import error_handler
from optimizely import event_dispatcher
from optimizely import logger
from optimizely.event import event_processor
from optimizely.helpers import validator

from tests import base
Expand All @@ -42,6 +43,20 @@ def some_other_method(self):

self.assertFalse(validator.is_config_manager_valid(CustomConfigManager()))

def test_is_event_processor_valid__returns_true(self):
""" Test that valid event_processor returns True. """

self.assertTrue(validator.is_event_processor_valid(event_processor.ForwardingEventProcessor))

def test_is_event_processor_valid__returns_false(self):
""" Test that invalid event_processor returns False. """

class CustomEventProcessor(object):
def some_other_method(self):
pass

self.assertFalse(validator.is_event_processor_valid(CustomEventProcessor))

def test_is_datafile_valid__returns_true(self):
""" Test that valid datafile returns True. """

Expand Down
81 changes: 80 additions & 1 deletion tests/test_event_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@

from . import base
from optimizely.event.payload import Decision, Visitor
from optimizely.event.event_processor import BatchEventProcessor
from optimizely.event.event_processor import BatchEventProcessor, ForwardingEventProcessor
from optimizely.event.event_factory import EventFactory
from optimizely.event.log_event import LogEvent
from optimizely.event.user_event_factory import UserEventFactory
from optimizely.helpers import enums
Expand Down Expand Up @@ -401,3 +402,81 @@ def on_log_event(log_event):
self.assertEqual(1, len(self.optimizely.notification_center.notification_listeners[
enums.NotificationTypes.LOG_EVENT
]))


class TestForwardingEventDispatcher(object):

def __init__(self, is_updated=False):
self.is_updated = is_updated

def dispatch_event(self, log_event):
if log_event.http_verb == 'POST' and log_event.url == EventFactory.EVENT_ENDPOINT:
self.is_updated = True
return self.is_updated


class ForwardingEventProcessorTest(base.BaseTest):

def setUp(self, *args, **kwargs):
base.BaseTest.setUp(self, 'config_dict_with_multiple_experiments')
self.test_user_id = 'test_user'
self.event_name = 'test_event'
self.optimizely.logger = SimpleLogger()
self.notification_center = self.optimizely.notification_center
self.event_dispatcher = TestForwardingEventDispatcher(is_updated=False)

with mock.patch.object(self.optimizely, 'logger') as mock_config_logging:
self._event_processor = ForwardingEventProcessor(self.event_dispatcher,
mock_config_logging,
self.notification_center
)

def _build_conversion_event(self, event_name):
return UserEventFactory.create_conversion_event(self.project_config,
event_name,
self.test_user_id,
{},
{}
)

def test_event_processor__dispatch_raises_exception(self):
""" Test that process logs dispatch failure gracefully. """

user_event = self._build_conversion_event(self.event_name)
log_event = EventFactory.create_log_event(user_event, self.optimizely.logger)

with mock.patch.object(self.optimizely, 'logger') as mock_client_logging, \
mock.patch.object(self.event_dispatcher, 'dispatch_event',
side_effect=Exception('Failed to send.')):

event_processor = ForwardingEventProcessor(self.event_dispatcher, mock_client_logging, self.notification_center)
event_processor.process(user_event)

mock_client_logging.exception.assert_called_once_with(
'Error dispatching event: ' + str(log_event) + ' Failed to send.'
)

def test_event_processor__with_test_event_dispatcher(self):
user_event = self._build_conversion_event(self.event_name)
self._event_processor.process(user_event)
self.assertStrictTrue(self.event_dispatcher.is_updated)

def test_notification_center(self):

callback_hit = [False]

def on_log_event(log_event):
self.assertStrictTrue(isinstance(log_event, LogEvent))
callback_hit[0] = True

self.optimizely.notification_center.add_notification_listener(
enums.NotificationTypes.LOG_EVENT, on_log_event
)

user_event = self._build_conversion_event(self.event_name)
self._event_processor.process(user_event)

self.assertEqual(True, callback_hit[0])
self.assertEqual(1, len(self.optimizely.notification_center.notification_listeners[
enums.NotificationTypes.LOG_EVENT
]))
Loading