def test_log__deprecation_warning(self): """Test that SimpleLogger now outputs a deprecation warning on ``.log`` calls.""" simple_logger = _logger.SimpleLogger() actual_log_patch = mock.patch.object(simple_logger, 'logger') warnings_patch = mock.patch('warnings.warn') with warnings_patch as patched_warnings, actual_log_patch as log_patch: simple_logger.log(logging.INFO, 'Message') msg = "<class 'optimizely.logger.SimpleLogger'> is deprecated. " "Please use standard python loggers." patched_warnings.assert_called_once_with(msg, DeprecationWarning) log_patch.log.assert_called_once_with(logging.INFO, 'Message')
def is_feature_enabled(self, *args): logger = optimizely_logging.SimpleLogger(min_level=self.log_level) UNIINITIALIZED_ERROR = """Optimizely: is_feature_enabled called but Optimizely not yet initialized. If you just started a web application or app server, try the request again. OR use the optimizely.fetch_configuration(timeout_ms=500) method to block initialization until the application is ready OR try moving your OptimizelyManager initialization higher in your application startup code OR move your is_feature_enabled call later in your application lifecycle. If this error persists, contact Optimizely! """ logger.log(logging.INFO, UNIINITIALIZED_ERROR)
def configure(self, sdk_key=None, log_level=None, **kwargs): """ Initialize the datafile manager with settings that are also passed to the core Optimizely SDK Parameters: sdk_key (string): Key specific to your Optimizely project and environment for fetching the correct datafile log_level (string): Log level for the SDK to log to console. **kwargs: See Optimizely SDK create_instance parameters """ self.current_datafile = { 'revision': '0' } self.sdk_key = sdk_key self.log_level = log_level or logging.DEBUG self.sdkParameters = kwargs self.optimizely_client_instance = _UinintializedClient(log_level=log_level) self.logger = optimizely_logging.SimpleLogger(min_level=log_level)
def before_request(): global user_profile_service_instance global optimizely_instance user_profile_service_instance = None optimizely_instance = None request.payload = request.get_json() user_profile_service_instance = request.payload.get('user_profile_service') if user_profile_service_instance: ups_class = getattr(user_profile_service, request.payload.get('user_profile_service')) user_profile_service_instance = ups_class(request.payload.get('user_profiles')) with_listener = request.payload.get('with_listener') log_level = environ.get('OPTIMIZELY_SDK_LOG_LEVEL', 'DEBUG') min_level = getattr(logging, log_level) optimizely_instance = optimizely.Optimizely( datafile_content, logger=logger.SimpleLogger(min_level=min_level), user_profile_service=user_profile_service_instance, ) if with_listener is not None: for listener_add in with_listener: if listener_add['type'] == 'Activate': count = int(listener_add['count']) for i in range(count): # make a value copy so that we can add multiple callbacks. a_cb = copy_func(on_activate) optimizely_instance.notification_center.add_notification_listener( enums.NotificationTypes.ACTIVATE, a_cb ) if listener_add['type'] == 'Track': count = int(listener_add['count']) for i in range(count): # make a value copy so that we can add multiple callbacks. t_cb = copy_func(on_track) optimizely_instance.notification_center.add_notification_listener( enums.NotificationTypes.TRACK, t_cb )
def test_adapt_logger__simple(self): """Test that adapt_logger returns a standard python logger from a SimpleLogger.""" simple_logger = _logger.SimpleLogger() standard_logger = _logger.adapt_logger(simple_logger) # adapt_logger knows about the loggers attached to this class. self.assertIs(simple_logger.logger, standard_logger) # Verify the standard properties of the logger. self.assertIsInstance(standard_logger, logging.Logger) self.assertEqual('optimizely.logger.SimpleLogger', standard_logger.name) self.assertEqual(logging.INFO, standard_logger.level) # Should have a single StreamHandler with our default formatting. self.assertEqual(1, len(standard_logger.handlers)) handler = standard_logger.handlers[0] self.assertIsInstance(handler, logging.StreamHandler) self.assertEqual( '%(levelname)-8s %(asctime)s %(filename)s:%(lineno)s:%(message)s', handler.formatter._fmt)
def main(datafile): optimizely_client_instance = optimizely.Optimizely( datafile=datafile, logger=logger.SimpleLogger(min_level=logging.INFO)) visitors = [ { 'userId': 'alice1' }, { 'userId': 'alice2' }, { 'userId': 'alice3' }, { 'userId': 'alice4' }, { 'userId': 'alice5' }, { 'userId': 'alice6' }, { 'userId': 'alice7' }, { 'userId': 'alice8' }, ] print("\n\nWelcome to Daily Deal, we have great deals for YOU!") print("Let's see what the visitors experience!\n") deals = [ get_daily_deal(optimizely_client_instance, visitor) for visitor in visitors ] on_variations = [deal for deal in deals if deal['is_enabled']] if len(on_variations) > 0: experiences = [ 'Visitor #%s: %s %s' % (i, deal['debug_text'], deal['text']) for i, deal in enumerate(deals) ] else: experiences = [ 'Visitor #%s: %s' % (i, deal['text']) for i, deal in enumerate(deals) ] print("\n".join(experiences)) print() def count_frequency(accum, value): text = value['text'] accum[text] = accum[text] + 1 if text in accum.keys() else 1 return accum frequency_map = reduce(count_frequency, deals, {}) num_on_variations = len(on_variations) total = len(visitors) if len(on_variations) > 0: print( "{0} out of {1} visitors (~{2}%) had the feature enabled\n".format( num_on_variations, total, round(num_on_variations / total * 100))) total = len(visitors) for text, _ in frequency_map.items(): perc = round(frequency_map[text] / total * 100) print("%s visitors (~%s%%) got the experience: '%s'" % (frequency_map[text], perc, text))
def test_get_numeric_metric__value_tag(self): """ Test that the correct numeric value is returned. """ # An integer should be cast to a float self.assertEqual( 12345.0, event_tag_utils.get_numeric_value({'value': 12345}, logger=logger.SimpleLogger())) # A string should be cast to a float self.assertEqual( 12345.0, event_tag_utils.get_numeric_value({'value': '12345'}, logger=logger.SimpleLogger())) # Valid float values some_float = 1.2345 self.assertEqual( some_float, event_tag_utils.get_numeric_value({'value': some_float}, logger=logger.SimpleLogger())) max_float = sys.float_info.max self.assertEqual( max_float, event_tag_utils.get_numeric_value({'value': max_float}, logger=logger.SimpleLogger())) min_float = sys.float_info.min self.assertEqual( min_float, event_tag_utils.get_numeric_value({'value': min_float}, logger=logger.SimpleLogger())) # Invalid values self.assertIsNone( event_tag_utils.get_numeric_value({'value': False}, logger=logger.SimpleLogger())) self.assertIsNone( event_tag_utils.get_numeric_value({'value': None}, logger=logger.SimpleLogger())) numeric_value_nan = event_tag_utils.get_numeric_value( {'value': float('nan')}, logger=logger.SimpleLogger()) self.assertIsNone(numeric_value_nan, 'nan numeric value is {}'.format(numeric_value_nan)) numeric_value_array = event_tag_utils.get_numeric_value( {'value': []}, logger=logger.SimpleLogger()) self.assertIsNone( numeric_value_array, 'Array numeric value is {}'.format(numeric_value_array)) numeric_value_dict = event_tag_utils.get_numeric_value( {'value': []}, logger=logger.SimpleLogger()) self.assertIsNone( numeric_value_dict, 'Dict numeric value is {}'.format(numeric_value_dict)) numeric_value_none = event_tag_utils.get_numeric_value( {'value': None}, logger=logger.SimpleLogger()) self.assertIsNone( numeric_value_none, 'None numeric value is {}'.format(numeric_value_none)) numeric_value_invalid_literal = event_tag_utils.get_numeric_value( {'value': '1,234'}, logger=logger.SimpleLogger()) self.assertIsNone( numeric_value_invalid_literal, 'Invalid string literal value is {}'.format( numeric_value_invalid_literal)) numeric_value_overflow = event_tag_utils.get_numeric_value( {'value': sys.float_info.max * 10}, logger=logger.SimpleLogger()) self.assertIsNone( numeric_value_overflow, 'Max numeric value is {}'.format(numeric_value_overflow)) numeric_value_inf = event_tag_utils.get_numeric_value( {'value': float('inf')}, logger=logger.SimpleLogger()) self.assertIsNone( numeric_value_inf, 'Infinity numeric value is {}'.format(numeric_value_inf)) numeric_value_neg_inf = event_tag_utils.get_numeric_value( {'value': float('-inf')}, logger=logger.SimpleLogger()) self.assertIsNone( numeric_value_neg_inf, 'Negative infinity numeric value is {}'.format( numeric_value_neg_inf)) self.assertEqual( 0.0, event_tag_utils.get_numeric_value({'value': 0.0}, logger=logger.SimpleLogger()))
from optimizely import logger import logging #actually teh SDK_KEY SDK_KEY = 'PnsTgkYA2fJUhHZRnZ9S5f' CONF_MANAGER = PollingConfigManager(sdk_key=SDK_KEY, update_interval=10) from flask import Flask, render_template, request application = Flask(__name__, static_folder='images') application.secret_key = os.urandom(24) optimizely_client = optimizely.Optimizely( config_manager=CONF_MANAGER, logger=logger.SimpleLogger(min_level=logging.INFO)) #optimizely_client = optimizely.Optimizely(datafile, logger=logger.SimpleLogger(min_level=logging.INFO)) def build_items(): items = [] reader = csv.reader(open('items.csv', 'r')) for line in reader: items.append({ 'name': line[0], 'color': line[1], 'category': line[2], 'price': int(line[3][1:]), 'imageUrl': line[4] }) return items
def setUp(self, *args, **kwargs): base.BaseTest.setUp(self) self.optimizely = optimizely.Optimizely(json.dumps(self.config_dict), logger=logger.SimpleLogger()) self.bucketer = bucketer.Bucketer()
def setUp(self): base.BaseTest.setUp(self) self.optimizely = optimizely.Optimizely(json.dumps(self.config_dict), logger=logger.SimpleLogger()) self.project_config = self.optimizely.config
def setUp(self): self.config_dict = { 'revision': '42', 'version': '2', 'events': [{ 'key': 'test_event', 'experimentIds': ['111127'], 'id': '111095' }, { 'key': 'Total Revenue', 'experimentIds': ['111127'], 'id': '111096' }], 'experiments': [{ 'key': 'test_experiment', 'status': 'Running', 'forcedVariations': { 'user_1': 'control', 'user_2': 'control' }, 'layerId': '111182', 'audienceIds': ['11154'], 'trafficAllocation': [{ 'entityId': '111128', 'endOfRange': 4000 }, { 'entityId': '', 'endOfRange': 5000 }, { 'entityId': '111129', 'endOfRange': 9000 }], 'id': '111127', 'variations': [{ 'key': 'control', 'id': '111128' }, { 'key': 'variation', 'id': '111129' }] }], 'groups': [{ 'id': '19228', 'policy': 'random', 'experiments': [{ 'id': '32222', 'key': 'group_exp_1', 'status': 'Running', 'audienceIds': [], 'layerId': '111183', 'variations': [{ 'key': 'group_exp_1_control', 'id': '28901' }, { 'key': 'group_exp_1_variation', 'id': '28902' }], 'forcedVariations': { 'user_1': 'group_exp_1_control', 'user_2': 'group_exp_1_control' }, 'trafficAllocation': [{ 'entityId': '28901', 'endOfRange': 3000 }, { 'entityId': '28902', 'endOfRange': 9000 }] }, { 'id': '32223', 'key': 'group_exp_2', 'status': 'Running', 'audienceIds': [], 'layerId': '111184', 'variations': [{ 'key': 'group_exp_2_control', 'id': '28905' }, { 'key': 'group_exp_2_variation', 'id': '28906' }], 'forcedVariations': { 'user_1': 'group_exp_2_control', 'user_2': 'group_exp_2_control' }, 'trafficAllocation': [{ 'entityId': '28905', 'endOfRange': 8000 }, { 'entityId': '28906', 'endOfRange': 10000 }] }], 'trafficAllocation': [{ 'entityId': '32222', "endOfRange": 3000 }, { 'entityId': '32223', 'endOfRange': 7500 }] }], 'accountId': '12001', 'attributes': [{ 'key': 'test_attribute', 'id': '111094' }], 'audiences': [{ 'name': 'Test attribute users', 'conditions': '["and", ["or", ["or", ' '{"name": "test_attribute", "type": "custom_attribute", "value": "test_value"}]]]', 'id': '11154' }], 'projectId': '111001' } # datafile version 4 self.config_dict_with_features = { 'revision': '1', 'accountId': '12001', 'projectId': '111111', 'version': '4', 'events': [{ 'key': 'test_event', 'experimentIds': ['111127'], 'id': '111095' }], 'experiments': [{ 'key': 'test_experiment', 'status': 'Running', 'forcedVariations': {}, 'layerId': '111182', 'audienceIds': [], 'trafficAllocation': [{ 'entityId': '111128', 'endOfRange': 5000 }, { 'entityId': '111129', 'endOfRange': 9000 }], 'id': '111127', 'variations': [{ 'key': 'control', 'id': '111128', 'variables': [{ 'id': '127', 'value': 'false' }, { 'id': '128', 'value': 'prod' }] }, { 'key': 'variation', 'id': '111129' }] }], 'groups': [], 'attributes': [{ 'key': 'test_attribute', 'id': '111094' }], 'audiences': [{ 'name': 'Test attribute users', 'conditions': '["and", ["or", ["or", ' '{"name": "test_attribute", "type": "custom_attribute", "value": "test_value"}]]]', 'id': '11154' }], 'layers': [{ 'id': '211111', 'policy': 'ordered', 'experiments': [{ 'key': 'test_rollout_exp_1', 'status': 'Running', 'forcedVariations': {}, 'layerId': '211111', 'audienceIds': ['11154'], 'trafficAllocation': [{ 'entityId': '211128', 'endOfRange': 5000 }, { 'entityId': '211129', 'endOfRange': 9000 }], 'id': '211127', 'variations': [{ 'key': 'control', 'id': '211128' }, { 'key': 'variation', 'id': '211129' }] }] }], 'features': [{ 'id': '91111', 'key': 'test_feature_1', 'experimentIds': ['111127'], 'layerId': '', 'variables': [{ 'id': '127', 'key': 'is_working', 'defaultValue': 'true', 'type': 'boolean', }, { 'id': '128', 'key': 'environment', 'defaultValue': 'devel', 'type': 'string', }] }, { 'id': '91112', 'key': 'test_feature_2', 'experimentIds': [], 'layerId': '211111', 'variables': [], }] } self.optimizely = optimizely.Optimizely(json.dumps(self.config_dict)) self.config = project_config.ProjectConfig( json.dumps(self.config_dict), logger.SimpleLogger(), error_handler.NoOpErrorHandler()) self.optimizely.event_builder = event_builder.EventBuilderV3( self.config) self.project_config = self.optimizely.config