Search in sources :

Example 6 with LogEvent

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

the class OptimizelyTest method trackEventWithListenerNullAttributes.

/**
 * Track with listener and verify that {@link Optimizely#track(String, String)} ignores null attributes.
 */
@Test
@SuppressFBWarnings(value = "NP_NONNULL_PARAM_VIOLATION", justification = "testing nullness contract violation")
public void trackEventWithListenerNullAttributes() throws Exception {
    final 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<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()), eq(Collections.<String, String>emptyMap()), eq(Collections.<String, Object>emptyMap()))).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 \"\"");
    TrackNotificationListener trackNotification = new TrackNotificationListener() {

        @Override
        public void onTrack(@Nonnull String eventKey, @Nonnull String userId, @Nonnull Map<String, String> attributes, @Nonnull Map<String, ?> eventTags, @Nonnull LogEvent event) {
            assertEquals(eventType.getKey(), eventKey);
            assertEquals(genericUserId, userId);
            assertTrue(attributes.isEmpty());
            assertTrue(eventTags.isEmpty());
        }
    };
    int notificationId = optimizely.notificationCenter.addNotificationListener(NotificationCenter.NotificationType.Track, trackNotification);
    // call track
    Map<String, String> attributes = null;
    optimizely.track(eventType.getKey(), genericUserId, attributes);
    optimizely.notificationCenter.removeNotificationListener(notificationId);
    logbackVerifier.expectMessage(Level.WARN, "Attributes is null when non-null was expected. Defaulting to an empty attributes map.");
    // setup the attribute map captor (so we can verify its content)
    ArgumentCaptor<Map> attributeCaptor = 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()), attributeCaptor.capture(), eq(Collections.<String, Object>emptyMap()));
    Map<String, String> actualValue = attributeCaptor.getValue();
    assertThat(actualValue, is(Collections.<String, String>emptyMap()));
    verify(mockEventHandler).dispatchEvent(logEventToDispatch);
}
Also used : EventType(com.optimizely.ab.config.EventType) 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) TrackNotificationListener(com.optimizely.ab.notification.TrackNotificationListener) 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 7 with LogEvent

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

the class OptimizelyTest method activateWithUnknownAttribute.

/**
 * Verify that {@link Optimizely#activate(String, String, Map<String, String>)} handles the case
 * where an unknown attribute (i.e., not in the config) is passed through.
 *
 * In this case, the activate call should remove the unknown attribute from the given map.
 */
@Test
@SuppressWarnings("unchecked")
public void activateWithUnknownAttribute() throws Exception {
    Experiment activatedExperiment = validProjectConfig.getExperiments().get(0);
    Variation bucketedVariation = activatedExperiment.getVariations().get(0);
    // setup a mock event builder to return mock params and endpoint
    EventBuilder mockEventBuilder = mock(EventBuilder.class);
    Optimizely optimizely = Optimizely.builder(validDatafile, mockEventHandler).withBucketing(mockBucketer).withEventBuilder(mockEventBuilder).withConfig(validProjectConfig).withErrorHandler(new RaiseExceptionErrorHandler()).build();
    Map<String, String> testUserAttributes = new HashMap<String, String>();
    if (datafileVersion >= 4) {
        testUserAttributes.put(ATTRIBUTE_HOUSE_KEY, AUDIENCE_GRYFFINDOR_VALUE);
    } else {
        testUserAttributes.put("browser_type", "chrome");
    }
    testUserAttributes.put("unknownAttribute", "dimValue");
    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(bucketedVariation), eq(testUserId), anyMapOf(String.class, String.class))).thenReturn(logEventToDispatch);
    when(mockBucketer.bucket(activatedExperiment, testUserId)).thenReturn(bucketedVariation);
    logbackVerifier.expectMessage(Level.INFO, "Activating user \"userId\" in experiment \"" + activatedExperiment.getKey() + "\".");
    logbackVerifier.expectMessage(Level.WARN, "Attribute(s) [unknownAttribute] not in the datafile.");
    logbackVerifier.expectMessage(Level.DEBUG, "Dispatching impression event to URL test_url with params " + testParams + " and payload \"\"");
    // Use an immutable map to also check that we're not attempting to change the provided attribute map
    Variation actualVariation = optimizely.activate(activatedExperiment.getKey(), testUserId, testUserAttributes);
    assertThat(actualVariation, is(bucketedVariation));
    // setup the attribute map captor (so we can verify its content)
    ArgumentCaptor<Map> attributeCaptor = ArgumentCaptor.forClass(Map.class);
    // verify that the event builder was called with the expected attributes
    verify(mockEventBuilder).createImpressionEvent(eq(validProjectConfig), eq(activatedExperiment), eq(bucketedVariation), eq(testUserId), attributeCaptor.capture());
    Map<String, String> actualValue = attributeCaptor.getValue();
    assertThat(actualValue, not(hasKey("unknownAttribute")));
    // verify that dispatchEvent was called with the correct LogEvent object.
    verify(mockEventHandler).dispatchEvent(logEventToDispatch);
}
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) RaiseExceptionErrorHandler(com.optimizely.ab.error.RaiseExceptionErrorHandler) Matchers.anyString(org.mockito.Matchers.anyString) 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)

Example 8 with LogEvent

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

the class OptimizelyTest method activateDispatchEventThrowsException.

/**
 * Verify that {@link Optimizely#activate(String, String)} handles exceptions thrown by
 * {@link EventHandler#dispatchEvent(LogEvent)} gracefully.
 */
@Test
public void activateDispatchEventThrowsException() throws Exception {
    Experiment experiment = noAudienceProjectConfig.getExperiments().get(0);
    doThrow(new Exception("Test Exception")).when(mockEventHandler).dispatchEvent(any(LogEvent.class));
    Optimizely optimizely = Optimizely.builder(noAudienceDatafile, mockEventHandler).withConfig(noAudienceProjectConfig).build();
    logbackVerifier.expectMessage(Level.ERROR, "Unexpected exception in event dispatcher");
    optimizely.activate(experiment.getKey(), testUserId);
}
Also used : LogEvent(com.optimizely.ab.event.LogEvent) Experiment(com.optimizely.ab.config.Experiment) ConfigParseException(com.optimizely.ab.config.parser.ConfigParseException) IOException(java.io.IOException) ExpectedException(org.junit.rules.ExpectedException) Test(org.junit.Test)

Example 9 with LogEvent

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

the class EventBuilderTest method createImpressionEventIgnoresUnknownAttributes.

/**
 * Verify that passing through an unknown attribute causes that attribute to be ignored, rather than
 * causing an exception to be thrown.
 */
@Test
public void createImpressionEventIgnoresUnknownAttributes() throws Exception {
    // use the "valid" project config and its associated experiment, variation, and attributes
    ProjectConfig projectConfig = validProjectConfigV2();
    Experiment activatedExperiment = projectConfig.getExperiments().get(0);
    Variation bucketedVariation = activatedExperiment.getVariations().get(0);
    LogEvent impressionEvent = builder.createImpressionEvent(projectConfig, activatedExperiment, bucketedVariation, "userId", Collections.singletonMap("unknownAttribute", "blahValue"));
    EventBatch impression = gson.fromJson(impressionEvent.getBody(), EventBatch.class);
    // verify that no Feature is created for "unknownAtrribute" -> "blahValue"
    for (com.optimizely.ab.event.internal.payload.Attribute feature : impression.getVisitors().get(0).getAttributes()) {
        assertFalse(feature.getKey() == "unknownAttribute");
        assertFalse(feature.getValue() == "blahValue");
    }
}
Also used : ProjectConfig(com.optimizely.ab.config.ProjectConfig) LogEvent(com.optimizely.ab.event.LogEvent) Experiment(com.optimizely.ab.config.Experiment) Variation(com.optimizely.ab.config.Variation) EventBatch(com.optimizely.ab.event.internal.payload.EventBatch) Test(org.junit.Test)

Example 10 with LogEvent

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

the class EventBuilderTest method createConversionEventAndroidClientEngineClientVersion.

/**
 * Verify that supplying {@link EventBuilder} with a custom client engine and client version results in conversion
 * events being sent with the overriden values.
 */
@Test
public void createConversionEventAndroidClientEngineClientVersion() throws Exception {
    EventBuilder builder = new EventBuilder(EventBatch.ClientEngine.ANDROID_SDK, "0.0.0");
    Attribute attribute = validProjectConfig.getAttributes().get(0);
    EventType eventType = validProjectConfig.getEventTypes().get(0);
    Bucketer mockBucketAlgorithm = mock(Bucketer.class);
    for (Experiment experiment : validProjectConfig.getExperiments()) {
        when(mockBucketAlgorithm.bucket(experiment, userId)).thenReturn(experiment.getVariations().get(0));
    }
    DecisionService decisionService = new DecisionService(mockBucketAlgorithm, mock(ErrorHandler.class), validProjectConfig, mock(UserProfileService.class));
    Map<String, String> attributeMap = Collections.singletonMap(attribute.getKey(), "value");
    Map<Experiment, Variation> experimentVariationMap = createExperimentVariationMap(validProjectConfig, decisionService, eventType.getKey(), userId, attributeMap);
    LogEvent conversionEvent = builder.createConversionEvent(validProjectConfig, experimentVariationMap, userId, eventType.getId(), eventType.getKey(), attributeMap, Collections.<String, Object>emptyMap());
    EventBatch conversion = gson.fromJson(conversionEvent.getBody(), EventBatch.class);
    assertThat(conversion.getClientName(), is(EventBatch.ClientEngine.ANDROID_SDK.getClientEngineValue()));
    assertThat(conversion.getClientVersion(), is("0.0.0"));
}
Also used : NoOpErrorHandler(com.optimizely.ab.error.NoOpErrorHandler) ErrorHandler(com.optimizely.ab.error.ErrorHandler) Attribute(com.optimizely.ab.config.Attribute) EventType(com.optimizely.ab.config.EventType) LogEvent(com.optimizely.ab.event.LogEvent) Experiment(com.optimizely.ab.config.Experiment) UserProfileService(com.optimizely.ab.bucketing.UserProfileService) DecisionService(com.optimizely.ab.bucketing.DecisionService) Variation(com.optimizely.ab.config.Variation) EventBatch(com.optimizely.ab.event.internal.payload.EventBatch) Bucketer(com.optimizely.ab.bucketing.Bucketer) 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