Search in sources :

Example 31 with LogEvent

use of com.optimizely.ab.event.LogEvent in project java-sdk by optimizely.

the class OptimizelyTest method activateWithListenerNullAttributes.

@Test
@SuppressFBWarnings(value = "NP_NONNULL_PARAM_VIOLATION", justification = "testing nullness contract violation")
public void activateWithListenerNullAttributes() throws Exception {
    final Experiment activatedExperiment = noAudienceProjectConfig.getExperiments().get(0);
    final Variation bucketedVariation = activatedExperiment.getVariations().get(0);
    // setup a mock event builder to return expected impression params
    EventBuilder mockEventBuilder = mock(EventBuilder.class);
    Optimizely optimizely = Optimizely.builder(noAudienceDatafile, mockEventHandler).withBucketing(mockBucketer).withEventBuilder(mockEventBuilder).withConfig(noAudienceProjectConfig).withErrorHandler(mockErrorHandler).build();
    Map<String, String> testParams = new HashMap<String, String>();
    testParams.put("test", "params");
    LogEvent logEventToDispatch = new LogEvent(RequestMethod.GET, "test_url", testParams, "");
    when(mockEventBuilder.createImpressionEvent(eq(noAudienceProjectConfig), eq(activatedExperiment), eq(bucketedVariation), eq(testUserId), eq(Collections.<String, String>emptyMap()))).thenReturn(logEventToDispatch);
    when(mockBucketer.bucket(activatedExperiment, testUserId)).thenReturn(bucketedVariation);
    ActivateNotificationListener activateNotification = new ActivateNotificationListener() {

        @Override
        public void onActivate(@Nonnull Experiment experiment, @Nonnull String userId, @Nonnull Map<String, String> attributes, @Nonnull Variation variation, @Nonnull LogEvent event) {
            assertEquals(experiment.getKey(), activatedExperiment.getKey());
            assertEquals(bucketedVariation.getKey(), variation.getKey());
            assertEquals(userId, testUserId);
            assertTrue(attributes.isEmpty());
            assertEquals(event.getRequestMethod(), RequestMethod.GET);
        }
    };
    int notificationId = optimizely.notificationCenter.addNotificationListener(NotificationCenter.NotificationType.Activate, activateNotification);
    // activate the experiment
    Map<String, String> attributes = null;
    Variation actualVariation = optimizely.activate(activatedExperiment.getKey(), testUserId, attributes);
    optimizely.notificationCenter.removeNotificationListener(notificationId);
    logbackVerifier.expectMessage(Level.WARN, "Attributes is null when non-null was expected. Defaulting to an empty attributes map.");
    // verify that the bucketing algorithm was called correctly
    verify(mockBucketer).bucket(activatedExperiment, testUserId);
    assertThat(actualVariation, is(bucketedVariation));
    // setup the attribute map captor (so we can verify its content)
    ArgumentCaptor<Map> attributeCaptor = ArgumentCaptor.forClass(Map.class);
    verify(mockEventBuilder).createImpressionEvent(eq(noAudienceProjectConfig), eq(activatedExperiment), eq(bucketedVariation), eq(testUserId), attributeCaptor.capture());
    Map<String, String> actualValue = attributeCaptor.getValue();
    assertThat(actualValue, is(Collections.<String, String>emptyMap()));
    // verify that dispatchEvent was called with the correct LogEvent object
    verify(mockEventHandler).dispatchEvent(logEventToDispatch);
}
Also used : HashMap(java.util.HashMap) LogEvent(com.optimizely.ab.event.LogEvent) Nonnull(javax.annotation.Nonnull) Experiment(com.optimizely.ab.config.Experiment) Matchers.anyString(org.mockito.Matchers.anyString) EventBuilder(com.optimizely.ab.event.internal.EventBuilder) ActivateNotificationListener(com.optimizely.ab.notification.ActivateNotificationListener) Variation(com.optimizely.ab.config.Variation) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) HashMap(java.util.HashMap) EventBuilderTest.createExperimentVariationMap(com.optimizely.ab.event.internal.EventBuilderTest.createExperimentVariationMap) Test(org.junit.Test) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 32 with LogEvent

use of com.optimizely.ab.event.LogEvent in project java-sdk by optimizely.

the class OptimizelyTest method trackEventEndToEnd.

/**
 * Verify that the {@link Optimizely#track(String, String)} call correctly builds a V2 event and passes it
 * through {@link EventHandler#dispatchEvent(LogEvent)}.
 */
@Test
public void trackEventEndToEnd() throws Exception {
    EventType eventType;
    String datafile;
    ProjectConfig config;
    if (datafileVersion >= 4) {
        config = spy(validProjectConfig);
        eventType = validProjectConfig.getEventNameMapping().get(EVENT_BASIC_EVENT_KEY);
        datafile = validDatafile;
    } else {
        config = spy(noAudienceProjectConfig);
        eventType = noAudienceProjectConfig.getEventTypes().get(0);
        datafile = noAudienceDatafile;
    }
    List<Experiment> allExperiments = config.getExperiments();
    EventBuilder eventBuilder = new EventBuilder();
    DecisionService spyDecisionService = spy(new DecisionService(mockBucketer, mockErrorHandler, config, null));
    Optimizely optimizely = Optimizely.builder(datafile, mockEventHandler).withDecisionService(spyDecisionService).withEventBuilder(eventBuilder).withConfig(noAudienceProjectConfig).withErrorHandler(mockErrorHandler).build();
    // call the bucket function.
    for (Experiment experiment : allExperiments) {
        when(mockBucketer.bucket(experiment, testUserId)).thenReturn(experiment.getVariations().get(0));
    }
    // call track
    optimizely.track(eventType.getKey(), testUserId);
    // verify that the bucketing algorithm was called only on experiments corresponding to the specified goal.
    List<Experiment> experimentsForEvent = config.getExperimentsForEventKey(eventType.getKey());
    for (Experiment experiment : allExperiments) {
        if (experiment.isRunning() && experimentsForEvent.contains(experiment)) {
            verify(spyDecisionService).getVariation(experiment, testUserId, Collections.<String, String>emptyMap());
            verify(config).getForcedVariation(experiment.getKey(), testUserId);
        } else {
            verify(spyDecisionService, never()).getVariation(experiment, testUserId, Collections.<String, String>emptyMap());
        }
    }
    // verify that dispatchEvent was called
    verify(mockEventHandler).dispatchEvent(any(LogEvent.class));
}
Also used : ProjectConfig(com.optimizely.ab.config.ProjectConfig) EventBuilder(com.optimizely.ab.event.internal.EventBuilder) EventType(com.optimizely.ab.config.EventType) LogEvent(com.optimizely.ab.event.LogEvent) Experiment(com.optimizely.ab.config.Experiment) Matchers.anyString(org.mockito.Matchers.anyString) DecisionService(com.optimizely.ab.bucketing.DecisionService) Test(org.junit.Test)

Example 33 with LogEvent

use of com.optimizely.ab.event.LogEvent in project java-sdk by optimizely.

the class OptimizelyTest method addNotificationListenerFromNotificationCenter.

/**
 * Verify that {@link com.optimizely.ab.notification.NotificationCenter#addNotificationListener(
 * com.optimizely.ab.notification.NotificationCenter.NotificationType,
 * com.optimizely.ab.notification.NotificationListener)} properly used
 *  and the listener is
 * added and notified when an experiment is activated.
 */
@Test
public void addNotificationListenerFromNotificationCenter() throws Exception {
    Experiment activatedExperiment;
    EventType eventType;
    if (datafileVersion >= 4) {
        activatedExperiment = validProjectConfig.getExperimentKeyMapping().get(EXPERIMENT_BASIC_EXPERIMENT_KEY);
        eventType = validProjectConfig.getEventNameMapping().get(EVENT_BASIC_EVENT_KEY);
    } else {
        activatedExperiment = validProjectConfig.getExperiments().get(0);
        eventType = validProjectConfig.getEventTypes().get(0);
    }
    Variation bucketedVariation = activatedExperiment.getVariations().get(0);
    EventBuilder mockEventBuilder = mock(EventBuilder.class);
    Optimizely optimizely = Optimizely.builder(validDatafile, mockEventHandler).withDecisionService(mockDecisionService).withEventBuilder(mockEventBuilder).withConfig(validProjectConfig).withErrorHandler(mockErrorHandler).build();
    Map<String, String> attributes = Collections.emptyMap();
    Map<String, String> testParams = new HashMap<String, String>();
    testParams.put("test", "params");
    LogEvent logEventToDispatch = new LogEvent(RequestMethod.GET, "test_url", testParams, "");
    when(mockEventBuilder.createImpressionEvent(validProjectConfig, activatedExperiment, bucketedVariation, genericUserId, attributes)).thenReturn(logEventToDispatch);
    when(mockDecisionService.getVariation(eq(activatedExperiment), eq(genericUserId), eq(Collections.<String, String>emptyMap()))).thenReturn(bucketedVariation);
    // Add listener
    ActivateNotificationListener listener = mock(ActivateNotificationListener.class);
    optimizely.notificationCenter.addNotificationListener(NotificationCenter.NotificationType.Activate, listener);
    // Check if listener is notified when experiment is activated
    Variation actualVariation = optimizely.activate(activatedExperiment, genericUserId, attributes);
    verify(listener, times(1)).onActivate(activatedExperiment, genericUserId, attributes, bucketedVariation, logEventToDispatch);
    assertEquals(actualVariation.getKey(), bucketedVariation.getKey());
    // Check if listener is notified after an event is tracked
    String eventKey = eventType.getKey();
    Map<Experiment, Variation> experimentVariationMap = createExperimentVariationMap(validProjectConfig, mockDecisionService, eventType.getKey(), genericUserId, attributes);
    when(mockEventBuilder.createConversionEvent(eq(validProjectConfig), eq(experimentVariationMap), eq(genericUserId), eq(eventType.getId()), eq(eventKey), eq(attributes), anyMapOf(String.class, Object.class))).thenReturn(logEventToDispatch);
    TrackNotificationListener trackNotification = mock(TrackNotificationListener.class);
    optimizely.notificationCenter.addNotificationListener(NotificationCenter.NotificationType.Track, trackNotification);
    optimizely.track(eventKey, genericUserId, attributes);
    verify(trackNotification, times(1)).onTrack(eventKey, genericUserId, attributes, Collections.EMPTY_MAP, logEventToDispatch);
}
Also used : EventType(com.optimizely.ab.config.EventType) HashMap(java.util.HashMap) LogEvent(com.optimizely.ab.event.LogEvent) Experiment(com.optimizely.ab.config.Experiment) Matchers.anyString(org.mockito.Matchers.anyString) EventBuilder(com.optimizely.ab.event.internal.EventBuilder) TrackNotificationListener(com.optimizely.ab.notification.TrackNotificationListener) ActivateNotificationListener(com.optimizely.ab.notification.ActivateNotificationListener) Variation(com.optimizely.ab.config.Variation) Test(org.junit.Test)

Example 34 with LogEvent

use of com.optimizely.ab.event.LogEvent in project java-sdk by optimizely.

the class OptimizelyTest method isFeatureEnabledWithExperimentKeyForced.

/**
 * Verify that the {@link Optimizely#activate(String, String, Map<String, String>)} call
 * uses forced variation to force the user into the second variation.  The mock bucket returns
 * the first variation. Then remove the forced variation and confirm that the forced variation is null.
 */
@Test
public void isFeatureEnabledWithExperimentKeyForced() throws Exception {
    assumeTrue(datafileVersion >= Integer.parseInt(ProjectConfig.Version.V4.toString()));
    Experiment activatedExperiment = validProjectConfig.getExperimentKeyMapping().get(EXPERIMENT_MULTIVARIATE_EXPERIMENT_KEY);
    Variation forcedVariation = activatedExperiment.getVariations().get(1);
    EventBuilder mockEventBuilder = mock(EventBuilder.class);
    Optimizely optimizely = Optimizely.builder(validDatafile, mockEventHandler).withBucketing(mockBucketer).withEventBuilder(mockEventBuilder).withConfig(validProjectConfig).withErrorHandler(mockErrorHandler).build();
    optimizely.setForcedVariation(activatedExperiment.getKey(), testUserId, forcedVariation.getKey());
    Map<String, String> testUserAttributes = new HashMap<String, String>();
    if (datafileVersion < 4) {
        testUserAttributes.put("browser_type", "chrome");
    }
    Map<String, String> testParams = new HashMap<String, String>();
    testParams.put("test", "params");
    LogEvent logEventToDispatch = new LogEvent(RequestMethod.GET, "test_url", testParams, "");
    when(mockEventBuilder.createImpressionEvent(eq(validProjectConfig), eq(activatedExperiment), eq(forcedVariation), eq(testUserId), eq(testUserAttributes))).thenReturn(logEventToDispatch);
    // activate the experiment
    assertTrue(optimizely.isFeatureEnabled(FEATURE_FLAG_MULTI_VARIATE_FEATURE.getKey(), testUserId));
    verify(mockEventHandler).dispatchEvent(logEventToDispatch);
    assertTrue(optimizely.setForcedVariation(activatedExperiment.getKey(), testUserId, null));
    assertNull(optimizely.getForcedVariation(activatedExperiment.getKey(), testUserId));
    assertFalse(optimizely.isFeatureEnabled(FEATURE_FLAG_MULTI_VARIATE_FEATURE.getKey(), testUserId));
}
Also used : EventBuilder(com.optimizely.ab.event.internal.EventBuilder) HashMap(java.util.HashMap) LogEvent(com.optimizely.ab.event.LogEvent) Experiment(com.optimizely.ab.config.Experiment) Matchers.anyString(org.mockito.Matchers.anyString) Variation(com.optimizely.ab.config.Variation) Test(org.junit.Test)

Example 35 with LogEvent

use of com.optimizely.ab.event.LogEvent in project java-sdk by optimizely.

the class OptimizelyTest method trackEventWithEventTags.

/**
 * Verify that {@link Optimizely#track(String, String, Map, Map)} passes event features to
 * {@link EventBuilder#createConversionEvent(ProjectConfig, Map, String, String, String, Map, Map)}
 */
@Test
public void trackEventWithEventTags() throws Exception {
    EventType eventType;
    if (datafileVersion >= 4) {
        eventType = validProjectConfig.getEventNameMapping().get(EVENT_BASIC_EVENT_KEY);
    } else {
        eventType = validProjectConfig.getEventTypes().get(0);
    }
    // setup a mock event builder to return expected conversion params
    EventBuilder mockEventBuilder = mock(EventBuilder.class);
    Optimizely optimizely = Optimizely.builder(validDatafile, mockEventHandler).withBucketing(mockBucketer).withEventBuilder(mockEventBuilder).withConfig(validProjectConfig).withErrorHandler(mockErrorHandler).build();
    Map<String, String> testParams = new HashMap<String, String>();
    testParams.put("test", "params");
    Map<String, Object> eventTags = new HashMap<String, Object>();
    eventTags.put("int_param", 123);
    eventTags.put("string_param", "123");
    eventTags.put("boolean_param", false);
    eventTags.put("float_param", 12.3f);
    Map<Experiment, Variation> experimentVariationMap = createExperimentVariationMap(validProjectConfig, mockDecisionService, eventType.getKey(), genericUserId, Collections.<String, String>emptyMap());
    LogEvent logEventToDispatch = new LogEvent(RequestMethod.GET, "test_url", testParams, "");
    when(mockEventBuilder.createConversionEvent(eq(validProjectConfig), eq(experimentVariationMap), eq(genericUserId), eq(eventType.getId()), eq(eventType.getKey()), anyMapOf(String.class, String.class), eq(eventTags))).thenReturn(logEventToDispatch);
    logbackVerifier.expectMessage(Level.INFO, "Tracking event \"" + eventType.getKey() + "\" for user \"" + genericUserId + "\".");
    logbackVerifier.expectMessage(Level.DEBUG, "Dispatching conversion event to URL test_url with params " + testParams + " and payload \"\"");
    // call track
    optimizely.track(eventType.getKey(), genericUserId, Collections.<String, String>emptyMap(), eventTags);
    // setup the event map captor (so we can verify its content)
    ArgumentCaptor<Map> eventTagCaptor = ArgumentCaptor.forClass(Map.class);
    // verify that the event builder was called with the expected attributes
    verify(mockEventBuilder).createConversionEvent(eq(validProjectConfig), eq(experimentVariationMap), eq(genericUserId), eq(eventType.getId()), eq(eventType.getKey()), eq(Collections.<String, String>emptyMap()), eventTagCaptor.capture());
    Map<String, ?> actualValue = eventTagCaptor.getValue();
    assertThat(actualValue, hasEntry("int_param", eventTags.get("int_param")));
    assertThat(actualValue, hasEntry("string_param", eventTags.get("string_param")));
    assertThat(actualValue, hasEntry("boolean_param", eventTags.get("boolean_param")));
    assertThat(actualValue, hasEntry("float_param", eventTags.get("float_param")));
    verify(mockEventHandler).dispatchEvent(logEventToDispatch);
}
Also used : EventType(com.optimizely.ab.config.EventType) HashMap(java.util.HashMap) LogEvent(com.optimizely.ab.event.LogEvent) Experiment(com.optimizely.ab.config.Experiment) Matchers.anyString(org.mockito.Matchers.anyString) EventBuilder(com.optimizely.ab.event.internal.EventBuilder) Variation(com.optimizely.ab.config.Variation) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) HashMap(java.util.HashMap) EventBuilderTest.createExperimentVariationMap(com.optimizely.ab.event.internal.EventBuilderTest.createExperimentVariationMap) Test(org.junit.Test)

Aggregations

LogEvent (com.optimizely.ab.event.LogEvent)66 Test (org.junit.Test)58 Experiment (com.optimizely.ab.config.Experiment)37 Variation (com.optimizely.ab.config.Variation)34 EventBatch (com.optimizely.ab.event.internal.payload.EventBatch)32 HashMap (java.util.HashMap)25 EventType (com.optimizely.ab.config.EventType)23 EventBuilder (com.optimizely.ab.event.internal.EventBuilder)21 Matchers.anyString (org.mockito.Matchers.anyString)21 ControlAttribute (com.optimizely.ab.internal.ControlAttribute)17 Map (java.util.Map)14 ImmutableMap (com.google.common.collect.ImmutableMap)11 Bucketer (com.optimizely.ab.bucketing.Bucketer)11 EventBuilderTest.createExperimentVariationMap (com.optimizely.ab.event.internal.EventBuilderTest.createExperimentVariationMap)11 ProjectConfig (com.optimizely.ab.config.ProjectConfig)10 Attribute (com.optimizely.ab.config.Attribute)9 Decision (com.optimizely.ab.event.internal.payload.Decision)9 DecisionService (com.optimizely.ab.bucketing.DecisionService)8 UserProfileService (com.optimizely.ab.bucketing.UserProfileService)6 NoOpErrorHandler (com.optimizely.ab.error.NoOpErrorHandler)6