Skip to content

Commit

Permalink
Merge e6e94fc into f3e395a
Browse files Browse the repository at this point in the history
  • Loading branch information
oakbani committed Sep 11, 2018
2 parents f3e395a + e6e94fc commit ecf4964
Show file tree
Hide file tree
Showing 6 changed files with 217 additions and 118 deletions.
109 changes: 57 additions & 52 deletions optimizely/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,52 +1,57 @@
# Copyright 2016-2017, 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


class InvalidAttributeException(Exception):
""" Raised when provided attribute is invalid. """
pass


class InvalidAudienceException(Exception):
""" Raised when provided audience is invalid. """
pass


class InvalidEventTagException(Exception):
""" Raised when provided event tag is invalid. """
pass


class InvalidExperimentException(Exception):
""" Raised when provided experiment key is invalid. """
pass


class InvalidEventException(Exception):
""" Raised when provided event key is invalid. """
pass


class InvalidGroupException(Exception):
""" Raised when provided group ID is invalid. """
pass


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


class InvalidVariationException(Exception):
""" Raised when provided variation is invalid. """
pass
# Copyright 2016-2018, 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


class InvalidAttributeException(Exception):
""" Raised when provided attribute is invalid. """
pass


class InvalidAudienceException(Exception):
""" Raised when provided audience is invalid. """
pass


class InvalidEventException(Exception):
""" Raised when provided event key is invalid. """
pass


class InvalidEventTagException(Exception):
""" Raised when provided event tag is invalid. """
pass


class InvalidExperimentException(Exception):
""" Raised when provided experiment key is invalid. """
pass


class InvalidGroupException(Exception):
""" Raised when provided group ID is invalid. """
pass


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


class InvalidVariationException(Exception):
""" Raised when provided variation is invalid. """
pass


class UnsupportedDatafileVersionException(Exception):
""" Raised when provided version in datafile is not supported. """
pass
41 changes: 23 additions & 18 deletions optimizely/helpers/enums.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,16 @@
import logging


class HTTPVerbs(object):
GET = 'GET'
POST = 'POST'
class ControlAttributes(object):
BOT_FILTERING = '$opt_bot_filtering'
BUCKETING_ID = '$opt_bucketing_id'
USER_AGENT = '$opt_user_agent'


class LogLevels(object):
NOTSET = logging.NOTSET
DEBUG = logging.DEBUG
INFO = logging.INFO
WARNING = logging.WARNING
ERROR = logging.ERROR
CRITICAL = logging.CRITICAL
class DatafileVersions(object):
V2 = '2'
V3 = '3'
V4 = '4'


class Errors(object):
Expand All @@ -44,8 +42,21 @@ class Errors(object):
NONE_FEATURE_KEY_PARAMETER = '"None" is an invalid value for feature key.'
NONE_USER_ID_PARAMETER = '"None" is an invalid value for user ID.'
NONE_VARIABLE_KEY_PARAMETER = '"None" is an invalid value for variable key.'
UNSUPPORTED_DATAFILE_VERSION = 'Provided datafile has unsupported version. ' \
'Please use SDK version 1.1.0 or earlier for datafile version 1.'
UNSUPPORTED_DATAFILE_VERSION = 'This version of the Python SDK does not support the given datafile version: "{}".'


class HTTPVerbs(object):
GET = 'GET'
POST = 'POST'


class LogLevels(object):
NOTSET = logging.NOTSET
DEBUG = logging.DEBUG
INFO = logging.INFO
WARNING = logging.WARNING
ERROR = logging.ERROR
CRITICAL = logging.CRITICAL


class NotificationTypes(object):
Expand All @@ -59,9 +70,3 @@ class NotificationTypes(object):
"""
ACTIVATE = "ACTIVATE:experiment, user_id, attributes, variation, event"
TRACK = "TRACK:event_key, user_id, attributes, event_tags, event"


class ControlAttributes(object):
BOT_FILTERING = '$opt_bot_filtering'
BUCKETING_ID = '$opt_bucketing_id'
USER_AGENT = '$opt_user_agent'
29 changes: 15 additions & 14 deletions optimizely/optimizely.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,23 +61,24 @@ def __init__(self,
self.logger.exception(str(error))
return

error_msg = None
try:
self.config = project_config.ProjectConfig(datafile, self.logger, self.error_handler)
except exceptions.UnsupportedDatafileVersionException as error:
error_msg = error.args[0]
error_to_handle = error
except:
self.is_valid = False
self.config = None
# We actually want to log this error to stderr, so make sure the logger
# has a handler capable of doing that.
self.logger = _logging.reset_logger(self.logger_name)
self.logger.error(enums.Errors.INVALID_INPUT_ERROR.format('datafile'))
return

if not self.config.was_parsing_successful():
self.is_valid = False
# We actually want to log this error to stderr, so make sure the logger
# has a handler capable of doing that.
self.logger.error(enums.Errors.UNSUPPORTED_DATAFILE_VERSION)
return
error_msg = enums.Errors.INVALID_INPUT_ERROR.format('datafile')
error_to_handle = exceptions.InvalidInputException(error_msg)
finally:
if error_msg:
self.is_valid = False
# We actually want to log this error to stderr, so make sure the logger
# has a handler capable of doing that.
self.logger = _logging.reset_logger(self.logger_name)
self.logger.exception(error_msg)
self.error_handler.handle_error(error_to_handle)
return

self.event_builder = event_builder.EventBuilder(self.config)
self.decision_service = decision_service.DecisionService(self.config, user_profile_service)
Expand Down
26 changes: 6 additions & 20 deletions optimizely/project_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,7 @@
from . import entities
from . import exceptions

REVENUE_GOAL_KEY = 'Total Revenue'
V1_CONFIG_VERSION = '1'
V2_CONFIG_VERSION = '2'

SUPPORTED_VERSIONS = [V2_CONFIG_VERSION]
UNSUPPORTED_VERSIONS = [V1_CONFIG_VERSION]
SUPPORTED_VERSIONS = [enums.DatafileVersions.V2, enums.DatafileVersions.V3, enums.DatafileVersions.V4]

RESERVED_ATTRIBUTE_PREFIX = '$opt_'

Expand All @@ -41,12 +36,14 @@ def __init__(self, datafile, logger, error_handler):
"""

config = json.loads(datafile)
self.parsing_succeeded = False
self.logger = logger
self.error_handler = error_handler
self.version = config.get('version')
if self.version in UNSUPPORTED_VERSIONS:
return
if self.version not in SUPPORTED_VERSIONS:
raise exceptions.UnsupportedDatafileVersionException(
enums.Errors.UNSUPPORTED_DATAFILE_VERSION.format(self.version)
)

self.account_id = config.get('accountId')
self.project_id = config.get('projectId')
self.revision = config.get('revision')
Expand Down Expand Up @@ -109,8 +106,6 @@ def __init__(self, datafile, logger, error_handler):
# Experiments in feature can only belong to one mutex group
break

self.parsing_succeeded = True

# Map of user IDs to another map of experiments to variations.
# This contains all the forced variations set by the user
# by calling set_forced_variation (it is not the same as the
Expand Down Expand Up @@ -176,15 +171,6 @@ def get_typecast_value(self, value, type):
else:
return value

def was_parsing_successful(self):
""" Helper method to determine if parsing the datafile was successful.
Returns:
Boolean depending on whether parsing the datafile succeeded or not.
"""

return self.parsing_succeeded

def get_version(self):
""" Get version of the datafile.
Expand Down
50 changes: 50 additions & 0 deletions tests/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -521,6 +521,56 @@ def setUp(self, config_dict='config_dict'):
'projectId': '111001'
}

self.config_dict_with_unsupported_version = {
'version': '5',
'rollouts': [],
'projectId': '10431130345',
'variables': [],
'featureFlags': [],
'experiments': [
{
'status': 'Running',
'key': 'ab_running_exp_untargeted',
'layerId': '10417730432',
'trafficAllocation': [
{
'entityId': '10418551353',
'endOfRange': 10000
}
],
'audienceIds': [],
'variations': [
{
'variables': [],
'id': '10418551353',
'key': 'all_traffic_variation'
},
{
'variables': [],
'id': '10418510624',
'key': 'no_traffic_variation'
}
],
'forcedVariations': {},
'id': '10420810910'
}
],
'audiences': [],
'groups': [],
'attributes': [],
'accountId': '10367498574',
'events': [
{
'experimentIds': [
'10420810910'
],
'id': '10404198134',
'key': 'winning'
}
],
'revision': '1337'
}

config = getattr(self, config_dict)
self.optimizely = optimizely.Optimizely(json.dumps(config))
self.project_config = self.optimizely.config

0 comments on commit ecf4964

Please sign in to comment.