use of com.optimizely.ab.event.internal.EventBuilder in project java-sdk by optimizely.
the class OptimizelyTest method trackEventEndToEndForced.
// ======== track tests ========//
/**
* 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 trackEventEndToEndForced() 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 = new ArrayList<Experiment>();
allExperiments.add(config.getExperiments().get(0));
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(null);
}
// call get forced.
for (Experiment experiment : allExperiments) {
optimizely.projectConfig.setForcedVariation(experiment.getKey(), testUserId, experiment.getVariations().get(0).getKey());
}
// 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));
for (Experiment experiment : allExperiments) {
assertEquals(optimizely.projectConfig.getForcedVariation(experiment.getKey(), testUserId), experiment.getVariations().get(0));
optimizely.projectConfig.setForcedVariation(experiment.getKey(), testUserId, null);
assertNull(optimizely.projectConfig.getForcedVariation(experiment.getKey(), testUserId));
}
}
use of com.optimizely.ab.event.internal.EventBuilder in project java-sdk by optimizely.
the class OptimizelyTest method trackEventWithUnknownAttribute.
/**
* Verify that {@link Optimizely#track(String, String)} handles the case where an unknown attribute
* (i.e., not in the config) is passed through.
*
* In this case, the track event call should remove the unknown attribute from the given map.
*/
@Test
@SuppressWarnings("unchecked")
public void trackEventWithUnknownAttribute() 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(new RaiseExceptionErrorHandler()).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()), anyMapOf(String.class, String.class), eq(Collections.<String, Object>emptyMap()))).thenReturn(logEventToDispatch);
logbackVerifier.expectMessage(Level.INFO, "Tracking event \"" + eventType.getKey() + "\" for user \"" + genericUserId + "\".");
logbackVerifier.expectMessage(Level.WARN, "Attribute(s) [unknownAttribute] not in the datafile.");
logbackVerifier.expectMessage(Level.DEBUG, "Dispatching conversion event to URL test_url with params " + testParams + " and payload \"\"");
// call track
optimizely.track(eventType.getKey(), genericUserId, ImmutableMap.of("unknownAttribute", "attributeValue"));
// 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, not(hasKey("unknownAttribute")));
verify(mockEventHandler).dispatchEvent(logEventToDispatch);
}
use of com.optimizely.ab.event.internal.EventBuilder 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);
}
use of com.optimizely.ab.event.internal.EventBuilder 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);
}
use of com.optimizely.ab.event.internal.EventBuilder in project java-sdk by optimizely.
the class OptimizelyTest method clearNotificationListenersNotificationCenter.
/**
* Verify that {@link com.optimizely.ab.notification.NotificationCenter}
* clearAllListerners removes all listeners
* and no longer notified when an experiment is activated.
*/
@Test
public void clearNotificationListenersNotificationCenter() throws Exception {
Experiment activatedExperiment;
Map<String, String> attributes = new HashMap<String, String>();
if (datafileVersion >= 4) {
activatedExperiment = validProjectConfig.getExperimentKeyMapping().get(EXPERIMENT_MULTIVARIATE_EXPERIMENT_KEY);
attributes.put(ATTRIBUTE_HOUSE_KEY, AUDIENCE_GRYFFINDOR_VALUE);
} else {
activatedExperiment = validProjectConfig.getExperiments().get(0);
attributes.put("browser_type", "chrome");
}
Variation bucketedVariation = activatedExperiment.getVariations().get(0);
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");
LogEvent logEventToDispatch = new LogEvent(RequestMethod.GET, "test_url", testParams, "");
when(mockEventBuilder.createImpressionEvent(validProjectConfig, activatedExperiment, bucketedVariation, genericUserId, attributes)).thenReturn(logEventToDispatch);
when(mockBucketer.bucket(activatedExperiment, genericUserId)).thenReturn(bucketedVariation);
// set up argument captor for the attributes map to compare map equality
ArgumentCaptor<Map> attributeCaptor = ArgumentCaptor.forClass(Map.class);
when(mockEventBuilder.createImpressionEvent(eq(validProjectConfig), eq(activatedExperiment), eq(bucketedVariation), eq(genericUserId), attributeCaptor.capture())).thenReturn(logEventToDispatch);
ActivateNotificationListener activateNotification = mock(ActivateNotificationListener.class);
TrackNotificationListener trackNotification = mock(TrackNotificationListener.class);
optimizely.notificationCenter.addNotificationListener(NotificationCenter.NotificationType.Activate, activateNotification);
optimizely.notificationCenter.addNotificationListener(NotificationCenter.NotificationType.Track, trackNotification);
optimizely.notificationCenter.clearAllNotificationListeners();
// Check if listener is notified after an experiment is activated
Variation actualVariation = optimizely.activate(activatedExperiment, genericUserId, attributes);
// check that the argument that was captured by the mockEventBuilder attribute captor,
// was equal to the attributes passed in to activate
assertEquals(attributes, attributeCaptor.getValue());
verify(activateNotification, never()).onActivate(activatedExperiment, genericUserId, attributes, actualVariation, logEventToDispatch);
// Check if listener is notified after a live variable is accessed
boolean activateExperiment = true;
verify(activateNotification, never()).onActivate(activatedExperiment, genericUserId, attributes, actualVariation, logEventToDispatch);
// Check if listener is notified after a event is tracked
EventType eventType = validProjectConfig.getEventTypes().get(0);
String eventKey = eventType.getKey();
Map<Experiment, Variation> experimentVariationMap = createExperimentVariationMap(validProjectConfig, mockDecisionService, eventType.getKey(), OptimizelyTest.genericUserId, attributes);
when(mockEventBuilder.createConversionEvent(eq(validProjectConfig), eq(experimentVariationMap), eq(OptimizelyTest.genericUserId), eq(eventType.getId()), eq(eventKey), eq(attributes), anyMapOf(String.class, Object.class))).thenReturn(logEventToDispatch);
optimizely.track(eventKey, genericUserId, attributes);
verify(trackNotification, never()).onTrack(eventKey, genericUserId, attributes, Collections.EMPTY_MAP, logEventToDispatch);
}
Aggregations