Skip to content

feat(api): Accepting all types for attributes values #102

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Sep 14, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions OptimizelySDK.Tests/DecisionServiceTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,14 @@ public void TestGetVariationWithBucketingId()
{ControlAttributes.BUCKETING_ID_ATTRIBUTE, testBucketingIdVariation}
};

var userAttributesWithInvalidBucketingId = new UserAttributes
{
{"device_type", "iPhone"},
{"company", "Optimizely"},
{"location", "San Francisco"},
{ControlAttributes.BUCKETING_ID_ATTRIBUTE, 1.59}
};

var invalidUserAttributesWithBucketingId = new UserAttributes
{
{"company", "Optimizely"},
Expand All @@ -407,6 +415,12 @@ public void TestGetVariationWithBucketingId()
// confirm valid bucketing with bucketing ID set in attributes
actualVariation = optlyObject.GetVariation(experimentKey, userId, userAttributesWithBucketingId);
Assert.IsTrue(TestData.CompareObjects(VariationWithKeyVariation, actualVariation));
LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, $"BucketingId is valid: \"{testBucketingIdVariation}\""));

// check audience with invalid bucketing Id
actualVariation = optlyObject.GetVariation(experimentKey, userId, userAttributesWithInvalidBucketingId);
Assert.IsTrue(TestData.CompareObjects(VariationWithKeyControl, actualVariation));
LoggerMock.Verify(l => l.Log(LogLevel.WARN, "BucketingID attribute is not a string. Defaulted to userId"));

// check invalid audience with bucketing ID
actualVariation = optlyObject.GetVariation(experimentKey, userId, invalidUserAttributesWithBucketingId);
Expand Down
113 changes: 113 additions & 0 deletions OptimizelySDK.Tests/EventTests/EventBuilderTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,119 @@ public void TestCreateImpressionEventWithAttributes()
Assert.IsTrue(TestData.CompareObjects(expectedLogEvent, logEvent));
}

[Test]
public void TestCreateImpressionEventWithTypedAttributes()
{
var guid = Guid.NewGuid();
var timeStamp = TestData.SecondsSince1970();

var payloadParams = new Dictionary<string, object>
{
{ "visitors", new object[]
{
new Dictionary<string, object>()
{
{ "snapshots", new object[]
{
new Dictionary<string, object>
{
{ "decisions", new object[]
{
new Dictionary<string, object>
{
{"campaign_id", "7719770039" },
{"experiment_id", "7716830082" },
{"variation_id", "7722370027" }
}
}
},
{ "events", new object[]
{
new Dictionary<string, object>
{
{"entity_id", "7719770039" },
{"timestamp", timeStamp },
{"uuid", guid },
{"key", "campaign_activated" }
}
}
}
}
}
},
{"attributes", new object[]
{
new Dictionary<string, object>
{
{"entity_id", "7723280020" },
{"key", "device_type" },
{"type", "custom" },
{"value", "iPhone"}
},
new Dictionary<string, object>
{
{"entity_id", "323434545" },
{"key", "boolean_key" },
{"type", "custom" },
{"value", true}
},
new Dictionary<string, object>
{
{"entity_id", "616727838" },
{"key", "integer_key" },
{"type", "custom" },
{"value", 15}
},
new Dictionary<string, object>
{
{"entity_id", "808797686" },
{"key", "double_key" },
{"type", "custom" },
{"value", 3.14}
},
new Dictionary<string, object>
{
{"entity_id", ControlAttributes.BOT_FILTERING_ATTRIBUTE},
{"key", ControlAttributes.BOT_FILTERING_ATTRIBUTE},
{"type", "custom" },
{"value", true }
}
}
},
{ "visitor_id", TestUserId }
}
}
},
{"project_id", "7720880029" },
{"account_id", "1592310167" },
{"client_name", "csharp-sdk" },
{"client_version", Optimizely.SDK_VERSION },
{"revision", "15" },
{"anonymize_ip", false}
};

var expectedLogEvent = new LogEvent("https://logx.optimizely.com/v1/events",
payloadParams,
"POST",
new Dictionary<string, string>
{
{ "Content-Type", "application/json" }
});

var userAttributes = new UserAttributes
{
{"device_type", "iPhone" },
{"boolean_key", true },
{"integer_key", 15 },
{"double_key", 3.14 }
};

var logEvent = EventBuilder.CreateImpressionEvent(Config, Config.GetExperimentFromKey("test_experiment"), "7722370027", TestUserId, userAttributes);
TestData.ChangeGUIDAndTimeStamp(logEvent.Params, timeStamp, guid);

Assert.IsTrue(TestData.CompareObjects(expectedLogEvent, logEvent));
}

[Test]
public void TestCreateConversionEventNoAttributesNoValue()
{
Expand Down
38 changes: 35 additions & 3 deletions OptimizelySDK.Tests/OptimizelyTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ public class OptimizelyTest
private Mock<IErrorHandler> ErrorHandlerMock;
private Mock<IEventDispatcher> EventDispatcherMock;
private Optimizely Optimizely;
private IEventDispatcher EventDispatcher;
private const string TestUserId = "testUserId";
private OptimizelyHelper Helper;
private Mock<Optimizely> OptimizelyMock;
Expand Down Expand Up @@ -458,6 +457,39 @@ public void TestActivateExperimentNotRunning()

Assert.IsNull(variationkey);
}

[Test]
public void TestActivateWithTypedAttributes()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test case is not verifying the payload generated from EventBuilder is returned correctly or not.
Create an expectedEventBuilder class and call EventBuilder, and compare it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added payload comparison test case for typed attributes in EventBuilderTest.cs.

{
var userAttributes = new UserAttributes
{
{"device_type", "iPhone" },
{"location", "San Francisco" },
{"boolean_key", true },
{"integer_key", 15 },
{"double_key", 3.14 }
};

EventBuilderMock.Setup(b => b.CreateImpressionEvent(It.IsAny<ProjectConfig>(), It.IsAny<Experiment>(),
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<UserAttributes>()))
.Returns(new LogEvent("logx.optimizely.com/decision", OptimizelyHelper.SingleParameter, "POST", new Dictionary<string, string> { }));

var optly = Helper.CreatePrivateOptimizely();
optly.SetFieldOrProperty("EventBuilder", EventBuilderMock.Object);

var variation = (Variation)optly.Invoke("Activate", "test_experiment", "test_user", userAttributes);

EventBuilderMock.Verify(b => b.CreateImpressionEvent(It.IsAny<ProjectConfig>(), Config.GetExperimentFromKey("test_experiment"),
"7722370027", "test_user", userAttributes), Times.Once);

LoggerMock.Verify(l => l.Log(It.IsAny<LogLevel>(), It.IsAny<string>()), Times.Exactly(6));
LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, "Assigned bucket [3037] to user [test_user] with bucketing ID [test_user]."), Times.Once);
LoggerMock.Verify(l => l.Log(LogLevel.INFO, "User [test_user] is in variation [control] of experiment [test_experiment]."), Times.Once);
LoggerMock.Verify(l => l.Log(LogLevel.INFO, "Activating user test_user in experiment test_experiment."), Times.Once);
LoggerMock.Verify(l => l.Log(LogLevel.DEBUG, @"Dispatching impression event to URL logx.optimizely.com/decision with params {""param1"":""val1""}."), Times.Once);

Assert.IsTrue(TestData.CompareObjects(VariationWithKeyControl, variation));
}
#endregion

#region Test GetVariation
Expand Down Expand Up @@ -765,7 +797,7 @@ public void TestTrackNoAttributesWithDeprecatedEventValue()
[Test]
public void TestForcedVariationPreceedsWhitelistedVariation()
{
var optimizely = new Optimizely(TestData.Datafile, EventDispatcher, LoggerMock.Object, ErrorHandlerMock.Object);
var optimizely = new Optimizely(TestData.Datafile, EventDispatcherMock.Object, LoggerMock.Object, ErrorHandlerMock.Object);
var projectConfig = ProjectConfig.Create(TestData.Datafile, LoggerMock.Object, ErrorHandlerMock.Object);
Variation expectedVariation1 = projectConfig.GetVariationFromKey("etag3", "vtag5");
Variation expectedVariation2 = projectConfig.GetVariationFromKey("etag3", "vtag6");
Expand Down Expand Up @@ -813,7 +845,7 @@ public void TestForcedVariationPreceedsUserProfile()

userProfileServiceMock.Setup(_ => _.Lookup(userId)).Returns(userProfile.ToMap());

var optimizely = new Optimizely(TestData.Datafile, EventDispatcher, LoggerMock.Object, ErrorHandlerMock.Object, userProfileServiceMock.Object);
var optimizely = new Optimizely(TestData.Datafile, EventDispatcherMock.Object, LoggerMock.Object, ErrorHandlerMock.Object, userProfileServiceMock.Object);
var projectConfig = ProjectConfig.Create(TestData.Datafile, LoggerMock.Object, ErrorHandlerMock.Object);
Variation expectedFbVariation = projectConfig.GetVariationFromKey(experimentKey, fbVariationKey);
Variation expectedVariation = projectConfig.GetVariationFromKey(experimentKey, variationKey);
Expand Down
5 changes: 4 additions & 1 deletion OptimizelySDK.Tests/ProjectConfigTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,10 @@ public void TestInit()
{
{ "device_type", Config.GetAttribute("device_type") },
{ "location", Config.GetAttribute("location")},
{ "browser_type", Config.GetAttribute("browser_type")}
{ "browser_type", Config.GetAttribute("browser_type")},
{ "boolean_key", Config.GetAttribute("boolean_key")},
{ "integer_key", Config.GetAttribute("integer_key")},
{ "double_key", Config.GetAttribute("double_key")}
};
Assert.IsTrue(TestData.CompareObjects(attributeKeyMap, Config.AttributeKeyMap));

Expand Down
12 changes: 12 additions & 0 deletions OptimizelySDK.Tests/TestData.json
Original file line number Diff line number Diff line change
Expand Up @@ -785,6 +785,18 @@
{
"id": "134",
"key": "browser_type"
},
{
"id": "323434545",
"key": "boolean_key"
},
{
"id": "616727838",
"key": "integer_key"
},
{
"id": "808797686",
"key": "double_key"
}
],
"projectId": "7720880029",
Expand Down
17 changes: 16 additions & 1 deletion OptimizelySDK.Tests/UtilsTests/ConditionEvaluatorTest.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2017, Optimizely
* Copyright 2017-2018, Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -83,5 +83,20 @@ public void TestEvaluateNullUserAttributes()
Assert.IsFalse(ConditionEvaluator.Evaluate(Conditions, userAttributes));
}

[Test]
public void TestTypedUserAttributesEvaluateTrue()
{
var userAttributes = new UserAttributes
{
{"device_type", "iPhone" },
{"is_firefox", false },
{"num_users", 15 },
{"pi_value", 3.14 }
};

string typedConditionStr = @"[""and"", [""or"", [""or"", {""name"": ""device_type"", ""type"": ""custom_attribute"", ""value"": ""iPhone""}]], [""or"", [""or"", {""name"": ""is_firefox"", ""type"": ""custom_attribute"", ""value"": false}]], [""or"", [""or"", {""name"": ""num_users"", ""type"": ""custom_attribute"", ""value"": 15}]], [""or"", [""or"", {""name"": ""pi_value"", ""type"": ""custom_attribute"", ""value"": 3.14}]]]";
var typedConditions = Newtonsoft.Json.JsonConvert.DeserializeObject<object[]>(typedConditionStr);
Assert.IsTrue(ConditionEvaluator.Evaluate(typedConditions, userAttributes));
}
}
}
13 changes: 10 additions & 3 deletions OptimizelySDK/Bucketing/DecisionService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -393,16 +393,23 @@ public virtual FeatureDecision GetVariationForFeature(FeatureFlag featureFlag, s
/// </summary>
/// <param name = "userId" >User Identifier</param>
/// <param name = "filteredAttributes" >The user's attributes.</param>
/// <returns>User ID if bucketing Id is not provided in user attributes, bucketing Id otherwise.</returns>
/// <returns>Bucketing Id if it is a string type in attributes, user Id otherwise.</returns>
private string GetBucketingId(string userId, UserAttributes filteredAttributes)
{
string bucketingId = userId;

// If the bucketing ID key is defined in attributes, then use that in place of the userID for the murmur hash key
if (filteredAttributes != null && filteredAttributes.ContainsKey(ControlAttributes.BUCKETING_ID_ATTRIBUTE))
{
bucketingId = filteredAttributes[ControlAttributes.BUCKETING_ID_ATTRIBUTE];
Logger.Log(LogLevel.DEBUG, string.Format("Setting the bucketing ID to \"{0}\"", bucketingId));
if (filteredAttributes[ControlAttributes.BUCKETING_ID_ATTRIBUTE] is string)
{
bucketingId = (string)filteredAttributes[ControlAttributes.BUCKETING_ID_ATTRIBUTE];
Logger.Log(LogLevel.DEBUG, $"BucketingId is valid: \"{bucketingId}\"");
}
else
{
Logger.Log(LogLevel.WARN, "BucketingID attribute is not a string. Defaulted to userId");
}
}

return bucketingId;
Expand Down
6 changes: 3 additions & 3 deletions OptimizelySDK/Entity/UserAttributes.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2017, Optimizely
* Copyright 2017-2018, Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -18,12 +18,12 @@

namespace OptimizelySDK.Entity
{
public class UserAttributes : Dictionary<string, string>
public class UserAttributes : Dictionary<string, object>
{
public UserAttributes FilterNullValues(ILogger logger)
{
UserAttributes answer = new UserAttributes();
foreach (KeyValuePair<string, string> pair in this) {
foreach (KeyValuePair<string, object> pair in this) {
if (pair.Value != null) {
answer[pair.Key] = pair.Value;
} else {
Expand Down
30 changes: 27 additions & 3 deletions OptimizelySDK/Utils/ConditionEvaluator.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2017, Optimizely
* Copyright 2017-2018, Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -16,6 +16,7 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OptimizelySDK.Entity;
using System;
using System.Linq;

namespace OptimizelySDK.Utils
Expand Down Expand Up @@ -70,8 +71,7 @@ public bool Evaluate(JToken conditions, UserAttributes userAttributes)
}

string conditionName = conditions["name"].ToString();
return userAttributes != null && userAttributes.ContainsKey(conditionName)
&& userAttributes[conditionName] == conditions["value"].ToString();
return userAttributes != null && userAttributes.ContainsKey(conditionName) && CompareValues(userAttributes[conditionName], conditions["value"]);
}

public bool Evaluate(object[] conditions, UserAttributes userAttributes)
Expand All @@ -90,5 +90,29 @@ public static JToken DecodeConditions(string conditions)
{
return JToken.Parse(conditions);
}

private bool CompareValues(object attribute, JToken condition)
{
try
{
switch (condition.Type)
{
case JTokenType.Integer:
return (int)condition == Convert.ToInt32(attribute);
case JTokenType.Float:
return (double)condition == Convert.ToDouble(attribute);
case JTokenType.String:
return (string)condition == Convert.ToString(attribute);
case JTokenType.Boolean:
return (bool)condition == Convert.ToBoolean(attribute);
default:
return false;
}
}
catch (Exception)
{
return false;
}
}
}
}