public void AnonymousFalseIsSerializedAsFalse()
        {
            var user     = User.Builder(key).Anonymous(false).Build();
            var expected = $"{{\"key\":\"{key}\",\"anonymous\":false}}";

            TestUtil.AssertJsonEquals(expected, LdJsonSerialization.SerializeObject(user));
        }
        public void CustomAttributesAndPrivateAttributesOmittedIfEmpty()
        {
            var user     = User.WithKey(key);
            var expected = $"{{\"key\":\"{key}\"}}";

            TestUtil.AssertJsonEquals(expected, LdJsonSerialization.SerializeObject(user));
        }
        public void AllFlagsStateReturnsStateWithReasons()
        {
            var flag1 = new FeatureFlagBuilder("key1").Version(100)
                        .OffVariation(0).Variations(LdValue.Of("value1"))
                        .Build();
            var flag2 = new FeatureFlagBuilder("key2").Version(200)
                        .OffVariation(1).Variations(LdValue.Of("x"), LdValue.Of("value2"))
                        .TrackEvents(true).DebugEventsUntilDate(UnixMillisecondTime.OfMillis(1000))
                        .Build();

            testData.UsePreconfiguredFlag(flag1);
            testData.UsePreconfiguredFlag(flag2);

            var state = client.AllFlagsState(user, FlagsStateOption.WithReasons);

            Assert.True(state.Valid);

            var expectedString = @"{""key1"":""value1"",""key2"":""value2"",
                ""$flagsState"":{
                  ""key1"":{
                    ""variation"":0,""version"":100,""reason"":{""kind"":""OFF""}
                  },""key2"":{
                    ""variation"":1,""version"":200,""reason"":{""kind"":""OFF""},""trackEvents"":true,""debugEventsUntilDate"":1000
                  }
                },
                ""$valid"":true
            }";
            var actualString   = LdJsonSerialization.SerializeObject(state);

            AssertHelpers.JsonEqual(expectedString, actualString);
        }
        public void CanSerializeStringProperty(StringPropertyDesc p)
        {
            var value = "x";
            var user  = p.Setter(User.Builder(key))(value).Build();
            var json  = LdValue.Parse(LdJsonSerialization.SerializeObject(user));

            Assert.Equal(LdValue.Of(value), json.Get(p.Name));
        }
Exemplo n.º 5
0
        public void SerializeUser()
        {
            var user = User.Builder("user-key")
                       .FirstName("Lucy").LastName("Cat").Build();

            AssertJsonEqual(LdJsonSerialization.SerializeObject(user),
                            DataModelSerialization.SerializeUser(user));
        }
        public void CustomAttributesAreSerialized()
        {
            LdValue value1 = LdValue.Of("hi");
            LdValue value2 = LdValue.Of(2);
            var     user   = User.Builder(key).Custom("name1", value1).Custom("name2", value2).Build();
            var     json   = LdValue.Parse(LdJsonSerialization.SerializeObject(user));

            Assert.Equal(LdValue.Of("hi"), json.Get("custom").Get("name1"));
            Assert.Equal(LdValue.Of(2), json.Get("custom").Get("name2"));
        }
Exemplo n.º 7
0
        public void CanDeserializeFromJson()
        {
            var state = FeatureFlagsState.Builder(FlagsStateOption.WithReasons)
                        .AddFlag("key1", LdValue.Of("value1"), 0, EvaluationReason.OffReason, 100, false, null)
                        .AddFlag("key2", LdValue.Of("value2"), 1, EvaluationReason.FallthroughReason, 200, true, UnixMillisecondTime.OfMillis(1000))
                        .Build();

            var jsonString = LdJsonSerialization.SerializeObject(state);
            var state1     = LdJsonSerialization.DeserializeObject <FeatureFlagsState>(jsonString);

            Assert.Equal(state, state1);
        }
Exemplo n.º 8
0
        private void VerifySerializeAndParse(LdValue value, string expectedJson)
        {
            var json1 = LdJsonSerialization.SerializeObject(value);
            var json2 = value.ToJsonString();

            Assert.Equal(expectedJson, json1);
            Assert.Equal(json1, json2);
            var parsed1 = LdJsonSerialization.DeserializeObject <LdValue>(expectedJson);
            var parsed2 = LdValue.Parse(expectedJson);

            Assert.Equal(value, parsed1);
            Assert.Equal(value, parsed2);
        }
 private void CheckFeatureOrDebugEvent(string kind, LdValue t, TestFlagProperties f, TestEvalProperties e,
                                       LdValue userJson)
 {
     Assert.Equal(LdValue.Of(kind), t.Get("kind"));
     Assert.Equal(LdValue.Of(e.Timestamp.Value), t.Get("creationDate"));
     Assert.Equal(LdValue.Of(f.Key), t.Get("key"));
     Assert.Equal(LdValue.Of(f.Version), t.Get("version"));
     Assert.Equal(e.Variation.HasValue ? LdValue.Of(e.Variation.Value) : LdValue.Null, t.Get("variation"));
     Assert.Equal(e.Value, t.Get("value"));
     CheckEventUserOrKey(t, e.User, userJson);
     Assert.Equal(e.Reason.HasValue ?
                  LdValue.Parse(LdJsonSerialization.SerializeObject(e.Reason.Value)) : LdValue.Null,
                  t.Get("reason"));
 }
        public void PrivateAttributeNamesAreSerialized()
        {
            var user = User.Builder(key)
                       .Name("user-name").AsPrivateAttribute()
                       .Email("*****@*****.**").AsPrivateAttribute()
                       .Build();
            var json  = LdValue.Parse(LdJsonSerialization.SerializeObject(user));
            var names = new List <string>(json.Get("privateAttributeNames").AsList(LdValue.Convert.String));

            names.Sort();
            Assert.Equal(new List <string> {
                "email", "name"
            }, names);
        }
Exemplo n.º 11
0
        public void ParsePatchData()
        {
            var flag        = new FeatureFlagBuilder("flagkey").Version(2).On(true).Build();
            var segment     = new SegmentBuilder("segmentkey").Version(3).Included("x").Build();
            var flagJson    = LdJsonSerialization.SerializeObject(flag);
            var segmentJson = LdJsonSerialization.SerializeObject(segment);

            var validFlagInput  = @"{""path"": ""/flags/flagkey"", ""data"": " + flagJson + "}";
            var validFlagResult = StreamProcessorEvents.ParsePatchData(Utf8Bytes(validFlagInput));

            Assert.Equal(DataModel.Features, validFlagResult.Kind);
            Assert.Equal("flagkey", validFlagResult.Key);
            AssertHelpers.DataItemsEqual(DataModel.Features, new ItemDescriptor(flag.Version, flag),
                                         validFlagResult.Item);

            var validSegmentInput  = @"{""path"": ""/segments/segmentkey"", ""data"": " + segmentJson + "}";
            var validSegmentResult = StreamProcessorEvents.ParsePatchData(Utf8Bytes(validSegmentInput));

            Assert.Equal(DataModel.Segments, validSegmentResult.Kind);
            Assert.Equal("segmentkey", validSegmentResult.Key);
            AssertHelpers.DataItemsEqual(DataModel.Segments, new ItemDescriptor(segment.Version, segment),
                                         validSegmentResult.Item);

            var validFlagInputWithDataBeforePath  = @"{""data"": " + flagJson + @", ""path"": ""/flags/flagkey""}";
            var validFlagResultWithDataBeforePath = StreamProcessorEvents.ParsePatchData(Utf8Bytes(validFlagInputWithDataBeforePath));

            Assert.Equal(DataModel.Features, validFlagResultWithDataBeforePath.Kind);
            Assert.Equal("flagkey", validFlagResultWithDataBeforePath.Key);
            AssertHelpers.DataItemsEqual(DataModel.Features, new ItemDescriptor(flag.Version, flag),
                                         validFlagResultWithDataBeforePath.Item);

            var inputWithUnrecognizedPath  = @"{""path"": ""/cats/lucy"", ""data"": " + flagJson + "}";
            var resultWithUnrecognizedPath = StreamProcessorEvents.ParsePatchData(Utf8Bytes(inputWithUnrecognizedPath));

            Assert.Null(resultWithUnrecognizedPath.Kind);
            Assert.Null(resultWithUnrecognizedPath.Key);

            var inputWithMissingPath = @"{""data"": " + flagJson + "}";

            Assert.ThrowsAny <JsonReadException>(() => StreamProcessorEvents.ParsePatchData(Utf8Bytes(inputWithMissingPath)));

            var inputWithMissingData = @"{""path"": ""/flags/flagkey""}";

            Assert.ThrowsAny <JsonReadException>(() => StreamProcessorEvents.ParsePatchData(Utf8Bytes(inputWithMissingData)));

            var malformedJsonInput = @"{no";

            Assert.ThrowsAny <JsonReadException>(() => StreamProcessorEvents.ParsePatchData(Utf8Bytes(malformedJsonInput)));
        }
Exemplo n.º 12
0
        public void PatchUpdatesSegment()
        {
            StreamProcessor sp = CreateAndStartProcessor();

            SimulateMessageReceived("put", EmptyPutData);

            string path = "/segments/" + SEGMENT_KEY;
            string data = LdValue.BuildObject()
                          .Add("path", path)
                          .Add("data", LdValue.Parse(LdJsonSerialization.SerializeObject(SEGMENT)))
                          .Build().ToJsonString();

            SimulateMessageReceived("patch", data);

            AssertSegmentInStore(SEGMENT);
        }
Exemplo n.º 13
0
        public void PutCausesFeatureToBeStored()
        {
            StreamProcessor sp   = CreateAndStartProcessor();
            string          data = LdValue.BuildObject()
                                   .Add("data", LdValue.BuildObject()
                                        .Add("flags", LdValue.BuildObject()
                                             .Add(FEATURE_KEY, LdValue.Parse(LdJsonSerialization.SerializeObject(FEATURE)))
                                             .Build())
                                        .Add("segments", LdValue.BuildObject().Build())
                                        .Build())
                                   .Build().ToJsonString();

            SimulateMessageReceived("put", data);

            AssertFeatureInStore(FEATURE);
        }
Exemplo n.º 14
0
        public void PatchUpdatesFeature()
        {
            StreamProcessor sp = CreateAndStartProcessor();

            SimulateMessageReceived("put", EmptyPutData);

            string path = "/flags/" + FEATURE_KEY;
            string data = LdValue.BuildObject()
                          .Add("path", path)
                          .Add("data", LdValue.Parse(LdJsonSerialization.SerializeObject(FEATURE)))
                          .Build().ToJsonString();

            SimulateMessageReceived("patch", data);

            AssertFeatureInStore(FEATURE);
        }
 public void TestBigSegmentsStatusSerializationDeserialization()
 {
     foreach (var test in new KeyValuePair <BigSegmentsStatus, string>[]
     {
         new KeyValuePair <BigSegmentsStatus, string>(BigSegmentsStatus.Healthy, "HEALTHY"),
         new KeyValuePair <BigSegmentsStatus, string>(BigSegmentsStatus.Stale, "STALE"),
         new KeyValuePair <BigSegmentsStatus, string>(BigSegmentsStatus.NotConfigured, "NOT_CONFIGURED"),
         new KeyValuePair <BigSegmentsStatus, string>(BigSegmentsStatus.StoreError, "STORE_ERROR"),
     })
     {
         var reason     = EvaluationReason.FallthroughReason.WithBigSegmentsStatus(test.Key);
         var reasonJson = LdJsonSerialization.SerializeObject(reason);
         Assert.Equal(LdValue.Parse(reasonJson).Get("bigSegmentsStatus"), LdValue.Of(test.Value));
         var reason1 = LdJsonSerialization.DeserializeObject <EvaluationReason>(reasonJson);
         Assert.Equal(test.Key, reason1.BigSegmentsStatus);
     }
 }
 public void TestErrorKindSerializationDeserialization()
 {
     foreach (var test in new KeyValuePair <EvaluationErrorKind, string>[]
     {
         new KeyValuePair <EvaluationErrorKind, string>(EvaluationErrorKind.ClientNotReady, "CLIENT_NOT_READY"),
         new KeyValuePair <EvaluationErrorKind, string>(EvaluationErrorKind.Exception, "EXCEPTION"),
         new KeyValuePair <EvaluationErrorKind, string>(EvaluationErrorKind.FlagNotFound, "FLAG_NOT_FOUND"),
         new KeyValuePair <EvaluationErrorKind, string>(EvaluationErrorKind.MalformedFlag, "MALFORMED_FLAG"),
         new KeyValuePair <EvaluationErrorKind, string>(EvaluationErrorKind.UserNotSpecified, "USER_NOT_SPECIFIED"),
         new KeyValuePair <EvaluationErrorKind, string>(EvaluationErrorKind.WrongType, "WRONG_TYPE"),
     })
     {
         var reason     = EvaluationReason.ErrorReason(test.Key);
         var reasonJson = LdJsonSerialization.SerializeObject(reason);
         Assert.Equal(LdValue.Parse(reasonJson).Get("errorKind"), LdValue.Of(test.Value));
         var reason1 = LdJsonSerialization.DeserializeObject <EvaluationReason>(reasonJson);
         Assert.Equal(test.Key, reason1.ErrorKind);
     }
 }
Exemplo n.º 17
0
        public void CanSerializeToJson()
        {
            var state = FeatureFlagsState.Builder(FlagsStateOption.WithReasons)
                        .AddFlag("key1", LdValue.Of("value1"), 0, EvaluationReason.OffReason, 100, false, null)
                        .AddFlag("key2", LdValue.Of("value2"), 1, EvaluationReason.FallthroughReason, 200, true, UnixMillisecondTime.OfMillis(1000))
                        .Build();

            var expectedString = @"{""key1"":""value1"",""key2"":""value2"",
                ""$flagsState"":{
                  ""key1"":{
                    ""variation"":0,""version"":100,""reason"":{""kind"":""OFF""}
                  },""key2"":{
                    ""variation"":1,""version"":200,""reason"":{""kind"":""FALLTHROUGH""},""trackEvents"":true,""debugEventsUntilDate"":1000
                  }
                },
                ""$valid"":true
            }";
            var actualString   = LdJsonSerialization.SerializeObject(state);

            AssertHelpers.JsonEqual(expectedString, actualString);
        }
 public void RequestHasCorrectUriAndMethodAndBodyInReportMode(
     string baseUriExtraPath,
     bool withReasons,
     string expectedPath,
     string expectedQuery
     )
 {
     using (var server = HttpServer.Start(StreamWithEmptyData))
     {
         var baseUri = new Uri(server.Uri.ToString().TrimEnd('/') + baseUriExtraPath);
         using (var dataSource = MakeDataSource(baseUri, simpleUser,
                                                c => c.EvaluationReasons(withReasons)
                                                .Http(Components.HttpConfiguration().UseReport(true))))
         {
             dataSource.Start();
             var req = server.Recorder.RequireRequest();
             Assert.Equal(expectedPath, req.Path);
             Assert.Equal(expectedQuery, req.Query);
             Assert.Equal("REPORT", req.Method);
             AssertJsonEqual(LdJsonSerialization.SerializeObject(simpleUser), req.Body);
         }
     }
 }
        public async Task GetFlagsUsesCorrectUriAndMethodInReportModeAsync(
            string baseUriExtraPath,
            bool withReasons,
            string expectedPath,
            string expectedQuery
            )
        {
            using (var server = HttpServer.Start(Handlers.BodyJson(_allDataJson)))
            {
                var baseUri = new Uri(server.Uri.ToString().TrimEnd('/') + baseUriExtraPath);

                var config = Configuration.Builder(_mobileKey)
                             .Http(Components.HttpConfiguration().UseReport(true))
                             .Build();

                using (var requestor = new FeatureFlagRequestor(
                           baseUri,
                           _user,
                           withReasons,
                           new LdClientContext(config).Http,
                           testLogger))
                {
                    var resp = await requestor.FeatureFlagsAsync();

                    Assert.Equal(200, resp.statusCode);
                    Assert.Equal(_allDataJson, resp.jsonResponse);

                    var req = server.Recorder.RequireRequest();
                    Assert.Equal("REPORT", req.Method);
                    Assert.Equal(expectedPath, req.Path);
                    Assert.Equal(expectedQuery, req.Query);
                    Assert.Equal(_mobileKey, req.Headers["Authorization"]);
                    AssertJsonEqual(LdJsonSerialization.SerializeObject(_user),
                                    TestUtil.NormalizeJsonUser(LdValue.Parse(req.Body)));
                }
            }
        }
Exemplo n.º 20
0
 public void TestUserInequalityWithModifiedBuilder()
 {
     Func <IUserBuilder, IUserBuilder>[] mods =
     {
         b => b.Secondary("x"),
         b => b.Secondary(null),
         b => b.IPAddress("x"),
         b => b.IPAddress(null),
         b => b.Country("FR"),
         b => b.Country(null),
         b => b.FirstName("x"),
         b => b.FirstName(null),
         b => b.LastName("x"),
         b => b.LastName(null),
         b => b.Name("x"),
         b => b.Name(null),
         b => b.Avatar("x"),
         b => b.Avatar(null),
         b => b.Email("x"),
         b => b.Email(null),
         b => b.Anonymous(true),
         b => b.Custom("c3",                   "v3"),
         b => b.Name("n").AsPrivateAttribute(),
         b => b.Name("o").AsPrivateAttribute()
     };
     foreach (var mod in mods)
     {
         User modUser = mod(User.Builder(UserTest.UserToCopy)).Build();
         Assert.False(UserTest.UserToCopy.Equals(modUser),
                      LdJsonSerialization.SerializeObject(modUser) + " should not equal " +
                      LdJsonSerialization.SerializeObject(UserTest.UserToCopy));
         Assert.False(UserTest.UserToCopy.GetHashCode() == modUser.GetHashCode(),
                      LdJsonSerialization.SerializeObject(modUser) + " should not have same hashCode as " +
                      LdJsonSerialization.SerializeObject(UserTest.UserToCopy));
     }
 }
 public void TestReasonSerializationDeserialization()
 {
     foreach (var test in new ReasonTestCase[]
     {
         new ReasonTestCase {
             Reason = EvaluationReason.OffReason,
             JsonString = @"{""kind"":""OFF""}", ExpectedShortString = "OFF"
         },
         new ReasonTestCase {
             Reason = EvaluationReason.FallthroughReason,
             JsonString = @"{""kind"":""FALLTHROUGH""}", ExpectedShortString = "FALLTHROUGH"
         },
         new ReasonTestCase {
             Reason = EvaluationReason.FallthroughReason.WithInExperiment(true),
             JsonString = @"{""kind"":""FALLTHROUGH"",""inExperiment"":true}",
             ExpectedShortString = "FALLTHROUGH"
         },
         new ReasonTestCase {
             Reason = EvaluationReason.FallthroughReason.WithBigSegmentsStatus(BigSegmentsStatus.Healthy),
             JsonString = @"{""kind"":""FALLTHROUGH"",""bigSegmentsStatus"":""HEALTHY""}", ExpectedShortString = "FALLTHROUGH"
         },
         new ReasonTestCase {
             Reason = EvaluationReason.FallthroughReason.WithInExperiment(true).WithBigSegmentsStatus(BigSegmentsStatus.Healthy),
             JsonString = @"{""kind"":""FALLTHROUGH"",""inExperiment"":true,""bigSegmentsStatus"":""HEALTHY""}",
             ExpectedShortString = "FALLTHROUGH"
         },
         new ReasonTestCase {
             Reason = EvaluationReason.TargetMatchReason,
             JsonString = @"{""kind"":""TARGET_MATCH""}", ExpectedShortString = "TARGET_MATCH"
         },
         new ReasonTestCase {
             Reason = EvaluationReason.RuleMatchReason(1, "id"),
             JsonString = @"{""kind"":""RULE_MATCH"",""ruleIndex"":1,""ruleId"":""id""}",
             ExpectedShortString = "RULE_MATCH(1,id)"
         },
         new ReasonTestCase {
             Reason = EvaluationReason.RuleMatchReason(1, "id").WithInExperiment(true),
             JsonString = @"{""kind"":""RULE_MATCH"",""ruleIndex"":1,""ruleId"":""id"",""inExperiment"":true}",
             ExpectedShortString = "RULE_MATCH(1,id)"
         },
         new ReasonTestCase {
             Reason = EvaluationReason.RuleMatchReason(1, "id").WithBigSegmentsStatus(BigSegmentsStatus.Healthy),
             JsonString = @"{""kind"":""RULE_MATCH"",""ruleIndex"":1,""ruleId"":""id"",""bigSegmentsStatus"":""HEALTHY""}",
             ExpectedShortString = "RULE_MATCH(1,id)"
         },
         new ReasonTestCase {
             Reason = EvaluationReason.RuleMatchReason(1, "id").WithInExperiment(true).WithBigSegmentsStatus(BigSegmentsStatus.Healthy),
             JsonString = @"{""kind"":""RULE_MATCH"",""ruleIndex"":1,""ruleId"":""id"",""inExperiment"":true,""bigSegmentsStatus"":""HEALTHY""}",
             ExpectedShortString = "RULE_MATCH(1,id)"
         },
         new ReasonTestCase {
             Reason = EvaluationReason.PrerequisiteFailedReason("key"),
             JsonString = @"{""kind"":""PREREQUISITE_FAILED"",""prerequisiteKey"":""key""}",
             ExpectedShortString = "PREREQUISITE_FAILED(key)"
         },
         new ReasonTestCase {
             Reason = EvaluationReason.ErrorReason(EvaluationErrorKind.Exception),
             JsonString = @"{""kind"":""ERROR"",""errorKind"":""EXCEPTION""}",
             ExpectedShortString = "ERROR(EXCEPTION)"
         }
     })
     {
         AssertJsonEqual(test.JsonString, LdJsonSerialization.SerializeObject(test.Reason));
         Assert.Equal(test.Reason, LdJsonSerialization.DeserializeObject <EvaluationReason>(test.JsonString));
         Assert.Equal(test.ExpectedShortString, test.Reason.ToString());
     }
 }
 public void JsonConversion()
 {
     Assert.Equal("12345", LdJsonSerialization.SerializeObject(UnixMillisecondTime.OfMillis(12345)));
     Assert.Equal(UnixMillisecondTime.OfMillis(12345),
                  LdJsonSerialization.DeserializeObject <UnixMillisecondTime>("12345"));
 }
Exemplo n.º 23
0
 internal static string SerializeFlag(FeatureFlag flag) =>
 LdJsonSerialization.SerializeObject(flag);
 public static void UsersEqual(User expected, User actual) =>
 AssertJsonEqual(LdJsonSerialization.SerializeObject(expected),
                 LdJsonSerialization.SerializeObject(actual));
Exemplo n.º 25
0
 internal static string SerializeUser(User user) =>
 LdJsonSerialization.SerializeObject(user);