Exemplo n.º 1
0
        public static void Main(string[] args)
        {
            var localhostFilePath = args[0];

            Console.WriteLine($"localhostFilePath: {localhostFilePath}");

            var client = new LocalhostClient(localhostFilePath, new NoOpLogger());

            var factory = new SplitFactory("localhost", new ConfigurationOptions
            {
                LocalhostFilePath = localhostFilePath,
                Ready             = 10000
            });

            Console.WriteLine();
            foreach (var splitName in factory.Manager().SplitNames())
            {
                Console.WriteLine($"Split: {splitName}");
            }

//      var client = factory.Client();
            var treatment = client.GetTreatment("id", "testing_split_on");

            Console.WriteLine();
            Console.WriteLine($"Treatment: {treatment}");
        }
Exemplo n.º 2
0
        public void GetTreatment_WithtBUR_ReturnsTimeOutException()
        {
            // Arrange.
            var httpClientMock = GetHttpClientMock();
            var configurations = GetConfigurationOptions(httpClientMock);

            var apikey = "apikey2";

            var splitFactory = new SplitFactory(apikey, configurations);
            var client       = splitFactory.Client();

            // Act.
            var exceptionMessage = "";
            var isSdkReady       = false;

            try
            {
                client.BlockUntilReady(1);
                isSdkReady = true;
            }
            catch (Exception ex)
            {
                isSdkReady       = false;
                exceptionMessage = ex.Message;
            }

            // Assert.
            Assert.IsFalse(isSdkReady);
            Assert.AreEqual("SDK was not ready in 1 miliseconds", exceptionMessage);

            ShutdownServer(httpClientMock);
        }
Exemplo n.º 3
0
        public void CheckingHeaders_WithIPAddressesEnabled_ReturnsWithIpAndName()
        {
            // Arrange.
            var httpClientMock = GetHttpClientMock();
            var configurations = GetConfigurationOptions(httpClientMock);

            var apikey = "apikey1";

            var splitFactory = new SplitFactory(apikey, configurations);
            var client       = splitFactory.Client();

            client.BlockUntilReady(10000);

            // Act.
            var treatmentResult = client.GetTreatment("nico_test", "FACUNDO_TEST");

            // Assert.
            Assert.AreEqual("on", treatmentResult);

            Thread.Sleep(5000);

            var requests = httpClientMock.GetLogs();

            foreach (var req in requests)
            {
                Assert.IsTrue(req
                              .RequestMessage
                              .Headers
                              .Any(h => h.Key.Equals("SplitSDKMachineIP") || h.Key.Equals("SplitSDKMachineName")));
            }

            ShutdownServer(httpClientMock);
        }
Exemplo n.º 4
0
        public void GetTreatmentWithConfig_WithtBUR_WhenTreatmentDoesntExist_ReturnsControl()
        {
            // Arrange.
            var httpClientMock = GetHttpClientMock();
            var configurations = GetConfigurationOptions(httpClientMock);

            var apikey = "apikey3";

            var splitFactory = new SplitFactory(apikey, configurations);
            var client       = splitFactory.Client();

            client.BlockUntilReady(10000);

            // Act.
            var result = client.GetTreatment("nico_test", "Random_Treatment");

            // Assert.
            Assert.AreEqual("control", result);

            // Validate impressions in listener.
            Thread.Sleep(2000);
            var impressionQueue = ((IntegrationTestsImpressionListener)_impressionListener).GetQueue();
            var keyImpressions  = impressionQueue.FetchAll();

            Assert.AreEqual(0, keyImpressions.Count);

            //Validate impressions sent to the be.
            AssertSentImpressions(0, httpClientMock);

            ShutdownServer(httpClientMock);
        }
Exemplo n.º 5
0
        // todo: make this reliable. The problem:
        // Sometimes an exception is thrown on client.BlockUntilReady.
        // The factory then seems unable to produce a working client
        // until the whole process is restarted. A similar thing is seen
        // if client.Destroy() is called. Do this, then, as per docs, create a new
        // factory and client. This client will _always_ fail on BlockUntilReady
        private static ISplitClient ReliablyCreateSplitClient(string apiKey)
        {
            SplitFactory factory = null;
            ISplitClient client  = null;

            for (var i = 0; i < 5; i++)
            {
                try
                {
                    if (factory == null)
                    {
                        factory = new SplitFactory(apiKey);
                    }
                    client = factory.Client();
                    client.BlockUntilReady(5000);

                    return(client);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Creating client failed:");
                    Console.WriteLine();
                    Console.WriteLine(e);
                    Console.WriteLine();
                    Console.WriteLine("Retrying...");

                    client?.Destroy();
                    factory = null;
                }
            }

            throw new Exception("couldn't initialise client after 5 tries");
        }
Exemplo n.º 6
0
        public void GetTreatmentsWithConfig_WithoutBUR_ReturnsControl()
        {
            // Arrange.
            using (var httpClientMock = GetHttpClientMock())
            {
                var configurations = GetConfigurationOptions(httpClientMock.GetUrl());

                var apikey = "apikey4";

                var splitFactory = new SplitFactory(apikey, configurations);
                var client       = splitFactory.Client();

                // Act.
                var treatmentResults = client.GetTreatmentsWithConfig("nico_test", new List <string> {
                    "FACUNDO_TEST", "MAURO_TEST"
                });

                // Assert.
                Assert.AreEqual("control", treatmentResults["FACUNDO_TEST"].Treatment);
                Assert.AreEqual("control", treatmentResults["MAURO_TEST"].Treatment);
                Assert.IsNull(treatmentResults["FACUNDO_TEST"].Config);
                Assert.IsNull(treatmentResults["MAURO_TEST"].Config);

                client.Destroy();
            }
        }
Exemplo n.º 7
0
        public void CheckingMachineIpAndMachineName_WithIPAddressesDisabled_ReturnsNA()
        {
            // Arrange.
            GetHttpClientMock();
            var configurations = GetConfigurationOptions(ipAddressesEnabled: false);

            var apikey = "apikey1";

            var splitFactory = new SplitFactory(apikey, configurations);
            var client       = splitFactory.Client();

            client.BlockUntilReady(10000);

            // Act.
            var treatmentResult1 = client.GetTreatment("mauro_test", "FACUNDO_TEST");
            var treatmentResult2 = client.GetTreatment("nico_test", "FACUNDO_TEST");
            var treatmentResult3 = client.GetTreatment("redo_test", "FACUNDO_TEST");
            var trackResult1     = client.Track("mauro", "user", "event_type");
            var trackResult2     = client.Track("nicolas", "user_2", "event_type_2");
            var trackResult3     = client.Track("redo", "user_3", "event_type_3");

            // Assert.
            Thread.Sleep(1500);

            // Impressions
            var redisImpressions = _redisAdapter.ListRange("SPLITIO.impressions");

            foreach (var item in redisImpressions)
            {
                var impression = JsonConvert.DeserializeObject <KeyImpressionRedis>(item);

                Assert.AreEqual("NA", impression.M.I);
                Assert.AreEqual("NA", impression.M.N);
            }

            // Events
            var sdkVersion  = string.Empty;
            var redisEvents = _redisAdapter.ListRange("SPLITIO.events");

            foreach (var item in redisEvents)
            {
                var eventRedis = JsonConvert.DeserializeObject <EventRedis>(item);

                Assert.AreEqual("NA", eventRedis.M.I);
                Assert.AreEqual("NA", eventRedis.M.N);

                sdkVersion = eventRedis.M.S;
            }

            // Metrics
            var keys = _redisAdapter.Keys($"SPLITIO/{sdkVersion}/*");

            foreach (var key in keys)
            {
                Assert.IsTrue(key.ToString().Contains("/NA/"));
            }

            ShutdownServer();
        }
Exemplo n.º 8
0
        public void GetTreatments_WithtBUR_WhenTreatmentsDoesntExist_ReturnsTreatments()
        {
            // Arrange.
            using (var httpClientMock = GetHttpClientMock())
            {
                var impressionListener = new IntegrationTestsImpressionListener(50);
                var configurations     = GetConfigurationOptions(httpClientMock?.GetUrl(), impressionListener: impressionListener);

                var apikey = "base-apikey9";

                var splitFactory = new SplitFactory(apikey, configurations);
                var client       = splitFactory.Client();

                client.BlockUntilReady(10000);

                // Act.
                var result = client.GetTreatments("nico_test", new List <string> {
                    "FACUNDO_TEST", "Random_Treatment", "MAURO_TEST", "Test_Save_1", "Random_Treatment_2",
                });

                // Assert.
                Assert.AreEqual("on", result["FACUNDO_TEST"]);
                Assert.AreEqual("control", result["Random_Treatment"]);
                Assert.AreEqual("off", result["MAURO_TEST"]);
                Assert.AreEqual("off", result["Test_Save_1"]);
                Assert.AreEqual("control", result["Random_Treatment_2"]);

                client.Destroy();

                // Validate impressions.
                Thread.Sleep(2000);
                var impressionQueue = impressionListener.GetQueue();
                var keyImpressions  = impressionQueue.FetchAll();

                var impression1 = keyImpressions
                                  .Where(ki => ki.feature.Equals("FACUNDO_TEST"))
                                  .Where(ki => ki.keyName.Equals("nico_test"))
                                  .FirstOrDefault();

                var impression2 = keyImpressions
                                  .Where(ki => ki.feature.Equals("MAURO_TEST"))
                                  .Where(ki => ki.keyName.Equals("nico_test"))
                                  .FirstOrDefault();

                var impression3 = keyImpressions
                                  .Where(ki => ki.feature.Equals("Test_Save_1"))
                                  .Where(ki => ki.keyName.Equals("nico_test"))
                                  .FirstOrDefault();

                AssertImpression(impression1, 1506703262916, "FACUNDO_TEST", "nico_test", "whitelisted", "on");
                AssertImpression(impression2, 1506703262966, "MAURO_TEST", "nico_test", "not in split", "off");
                AssertImpression(impression3, 1503956389520, "Test_Save_1", "nico_test", "in segment all", "off");

                Assert.AreEqual(3, keyImpressions.Count);

                //Validate impressions sent to the be.
                AssertSentImpressions(3, httpClientMock, impression1, impression2, impression3);
            }
        }
Exemplo n.º 9
0
        public void BuildSplitClientWithEmptyApiKeyShouldReturnException()
        {
            //Arrange
            var factory = new SplitFactory(null, null);

            //Act
            var client = factory.Client();
        }
Exemplo n.º 10
0
        public void GetTreatmentWithConfig_WithtInputValidation_ReturnsTreatments()
        {
            // Arrange.
            using (var httpClientMock = GetHttpClientMock())
            {
                var impressionListener = new IntegrationTestsImpressionListener(50);
                var configurations     = GetConfigurationOptions(httpClientMock?.GetUrl(), impressionListener: impressionListener);

                var apikey = "base-apikey5";

                var splitFactory = new SplitFactory(apikey, configurations);
                var client       = splitFactory.Client();

                client.BlockUntilReady(10000);

                // Act.
                var result1 = client.GetTreatmentWithConfig("nico_test", "FACUNDO_TEST");
                var result2 = client.GetTreatmentWithConfig(string.Empty, "FACUNDO_TEST");
                var result3 = client.GetTreatmentWithConfig("test", string.Empty);
                var result4 = client.GetTreatmentWithConfig("mauro", "MAURO_TEST");

                client.Destroy();

                // Assert.
                Assert.AreEqual("on", result1.Treatment);
                Assert.AreEqual("control", result2.Treatment);
                Assert.AreEqual("control", result3.Treatment);
                Assert.AreEqual("on", result4.Treatment);

                Assert.AreEqual("{\"color\":\"green\"}", result1.Config);
                Assert.IsNull(result2.Config);
                Assert.IsNull(result3.Config);
                Assert.AreEqual("{\"version\":\"v2\"}", result4.Config);

                // Validate impressions.
                Thread.Sleep(3000);
                var impressionQueue = impressionListener.GetQueue();
                var keyImpressions  = impressionQueue.FetchAll();

                Assert.AreEqual(2, keyImpressions.Count);

                var impression1 = keyImpressions
                                  .Where(ki => ki.feature.Equals("FACUNDO_TEST"))
                                  .Where(ki => ki.keyName.Equals("nico_test"))
                                  .FirstOrDefault();

                var impression2 = keyImpressions
                                  .Where(ki => ki.feature.Equals("MAURO_TEST"))
                                  .Where(ki => ki.keyName.Equals("mauro"))
                                  .FirstOrDefault();

                AssertImpression(impression1, 1506703262916, "FACUNDO_TEST", "nico_test", "whitelisted", "on");
                AssertImpression(impression2, 1506703262966, "MAURO_TEST", "mauro", "whitelisted", "on");

                //Validate impressions sent to the be.
                AssertSentImpressions(2, httpClientMock, impression1, impression2);
            }
        }
Exemplo n.º 11
0
        public void GetTreatmentsWithConfig_WithtBUR_ReturnsTreatments()
        {
            // Arrange.
            var httpClientMock = GetHttpClientMock();
            var configurations = GetConfigurationOptions(httpClientMock);

            var apikey = "apikey3";

            var splitFactory = new SplitFactory(apikey, configurations);
            var client       = splitFactory.Client();

            client.BlockUntilReady(10000);

            // Act.
            var result = client.GetTreatmentsWithConfig("nico_test", new List <string> {
                "FACUNDO_TEST", "MAURO_TEST", "Test_Save_1"
            });

            // Assert.
            Assert.AreEqual("on", result["FACUNDO_TEST"].Treatment);
            Assert.AreEqual("off", result["MAURO_TEST"].Treatment);
            Assert.AreEqual("off", result["Test_Save_1"].Treatment);

            Assert.AreEqual("{\"color\":\"green\"}", result["FACUNDO_TEST"].Config);
            Assert.AreEqual("{\"version\":\"v1\"}", result["MAURO_TEST"].Config);
            Assert.IsNull(result["Test_Save_1"].Config);

            // Validate impressions.
            Thread.Sleep(2000);
            var impressionQueue = ((IntegrationTestsImpressionListener)_impressionListener).GetQueue();
            var keyImpressions  = impressionQueue.FetchAll();

            Assert.AreEqual(3, keyImpressions.Count);

            var impression1 = keyImpressions
                              .Where(ki => ki.feature.Equals("FACUNDO_TEST"))
                              .Where(ki => ki.keyName.Equals("nico_test"))
                              .First();

            var impression2 = keyImpressions
                              .Where(ki => ki.feature.Equals("MAURO_TEST"))
                              .Where(ki => ki.keyName.Equals("nico_test"))
                              .First();

            var impression3 = keyImpressions
                              .Where(ki => ki.feature.Equals("Test_Save_1"))
                              .Where(ki => ki.keyName.Equals("nico_test"))
                              .First();

            AssertImpression(impression1, 1506703262916, "FACUNDO_TEST", "nico_test", "whitelisted", "on");
            AssertImpression(impression2, 1506703262966, "MAURO_TEST", "nico_test", "not in split", "off");
            AssertImpression(impression3, 1503956389520, "Test_Save_1", "nico_test", "in segment all", "off");

            //Validate impressions sent to the be.
            AssertSentImpressions(3, httpClientMock, impression1, impression2, impression3);

            ShutdownServer(httpClientMock);
        }
Exemplo n.º 12
0
        public async Task Initialize()
        {
            ConfigurationOptions config  = new ConfigurationOptions();
            SplitFactory         factory = new SplitFactory(ApiKey, config);

            _splitClient = factory.Client();
            _splitClient.BlockUntilReady(100000);
            await Task.FromResult(0);
        }
Exemplo n.º 13
0
        public void Telemetry_ValidatesConfigInitAndStats()
        {
            // Arrange.
            using (var httpClientMock = GetHttpClientMock())
            {
                var impressionListener = new IntegrationTestsImpressionListener(50);
                var configurations     = GetConfigurationOptions(httpClientMock.GetUrl(), impressionListener: impressionListener);

                var apikey = "apikey-telemetry";

                var splitFactory = new SplitFactory(apikey, configurations);
                var client       = splitFactory.Client();
                client.Track("test-key", "tt", "test");

                try
                {
                    client.BlockUntilReady(0);
                }
                catch
                {
                    client.BlockUntilReady(10000);
                }

                // Act.
                var result = client.GetTreatment("nico_test", "FACUNDO_TEST");

                Thread.Sleep(3000);

                // Assert.
                Assert.AreEqual("on", result);

                var sentConfig = GetMetricsConfigSentBackend(httpClientMock);
                Assert.IsNotNull(sentConfig);
                Assert.AreEqual(configurations.StreamingEnabled, sentConfig.StreamingEnabled);
                Assert.AreEqual("memory", sentConfig.Storage);
                Assert.AreEqual(configurations.FeaturesRefreshRate, (int)sentConfig.Rates.Splits);
                Assert.AreEqual(configurations.SegmentsRefreshRate, (int)sentConfig.Rates.Events);
                Assert.AreEqual(60, (int)sentConfig.Rates.Impressions);
                Assert.AreEqual(3600, (int)sentConfig.Rates.Telemetry);
                Assert.IsTrue(sentConfig.UrlOverrides.Telemetry);
                Assert.IsTrue(sentConfig.UrlOverrides.Sdk);
                Assert.IsTrue(sentConfig.UrlOverrides.Events);
                Assert.IsFalse(sentConfig.UrlOverrides.Stream);
                Assert.IsFalse(sentConfig.UrlOverrides.Auth);
                Assert.AreEqual(30000, (int)sentConfig.ImpressionsQueueSize);
                Assert.AreEqual(10000, (int)sentConfig.EventsQueueSize);
                Assert.AreEqual(ImpressionsMode.Optimized, sentConfig.ImpressionsMode);
                Assert.IsTrue(sentConfig.ImpressionListenerEnabled);
                Assert.IsTrue(1 <= sentConfig.ActiveFactories);
                Assert.AreEqual(1, sentConfig.BURTimeouts);

                var sentStats = GetMetricsStatsSentBackend(httpClientMock);
                Assert.AreEqual(0, sentStats.Count);

                client.Destroy();
            }
        }
Exemplo n.º 14
0
        private static ISplitClient CreateSplitClient(string apiKey)
        {
            var factory = new SplitFactory(apiKey);

            var client = factory.Client();

            client.BlockUntilReady(5000);

            return(client);
        }
Exemplo n.º 15
0
        public void GetTreatment_WithtInputValidation_ReturnsTreatments()
        {
            // Arrange.
            using (var httpClientMock = GetHttpClientMock())
            {
                var impressionListener = new IntegrationTestsImpressionListener(50);
                var configurations     = GetConfigurationOptions(httpClientMock?.GetUrl(), impressionListener: impressionListener);

                var apikey = "base-apikey2";

                var splitFactory = new SplitFactory(apikey, configurations);
                var client       = splitFactory.Client();

                client.BlockUntilReady(10000);

                // Act.
                var result1 = client.GetTreatment("nico_test", "FACUNDO_TEST");
                var result2 = client.GetTreatment(string.Empty, "FACUNDO_TEST");
                var result3 = client.GetTreatment("1", string.Empty);
                var result4 = client.GetTreatment("24", "Test_Save_1");

                // Assert.
                Assert.AreEqual("on", result1);
                Assert.AreEqual("control", result2);
                Assert.AreEqual("control", result3);
                Assert.AreEqual("off", result4);

                client.Destroy();

                // Validate impressions in listener.
                Thread.Sleep(2000);
                var impressionQueue = impressionListener.GetQueue();
                var keyImpressions  = impressionQueue.FetchAll();

                Assert.AreEqual(2, keyImpressions.Count);

                var impression1 = keyImpressions
                                  .Where(ki => ki.feature.Equals("FACUNDO_TEST"))
                                  .Where(ki => ki.keyName.Equals("nico_test"))
                                  .FirstOrDefault();

                var impression2 = keyImpressions
                                  .Where(ki => ki.feature.Equals("Test_Save_1"))
                                  .Where(ki => ki.keyName.Equals("24"))
                                  .FirstOrDefault();

                AssertImpression(impression1, 1506703262916, "FACUNDO_TEST", "nico_test", "whitelisted", "on");
                AssertImpression(impression2, 1503956389520, "Test_Save_1", "24", "in segment all", "off");

                //Validate impressions sent to the be.
                AssertSentImpressions(2, httpClientMock, impression1, impression2);

                client.Destroy();
            }
        }
Exemplo n.º 16
0
        public void BuildSplitClientShouldReturnClientDestroyed()
        {
            //Arrange
            var options = new ConfigurationOptions();
            var factory = new SplitFactory("any", options);

            //Act
            var client = factory.Client();

            client.BlockUntilReady(1000);
        }
Exemplo n.º 17
0
        public void BuildSplitClientWithApiKeyShouldReturnSelfRefreshingSplitClient()
        {
            //Arrange
            var factory = new SplitFactory("any", null);

            //Act
            var client = factory.Client();

            //Assert
            Assert.AreEqual(typeof(SelfRefreshingClient), client.GetType());
        }
Exemplo n.º 18
0
        public void BuildSplitClientShouldReturnExceptionIfSdkNotReady()
        {
            //Arrange
            var options = new ConfigurationOptions()
            {
                Ready = 1
            };
            var factory = new SplitFactory("any", options);

            //Act
            var client = factory.Client();
        }
Exemplo n.º 19
0
        public void Track_WithLowQueue_ReturnsTrue()
        {
            // Arrange.
            using (var httpClientMock = GetHttpClientMock())
            {
                var configurations = GetConfigurationOptions(httpClientMock?.GetUrl(), eventsPushRate: 60, eventsQueueSize: 3);

                var properties = new Dictionary <string, object>
                {
                    { "property_1", 1 },
                    { "property_2", 2 }
                };

                var events = new List <EventBackend>
                {
                    new EventBackend {
                        Key = "key_1", TrafficTypeName = "traffic_type_1", EventTypeId = "event_type_1", Value = 123, Properties = properties
                    },
                    new EventBackend {
                        Key = "key_2", TrafficTypeName = "traffic_type_2", EventTypeId = "event_type_2", Value = 222
                    },
                    new EventBackend {
                        Key = "key_3", TrafficTypeName = "traffic_type_3", EventTypeId = "event_type_3", Value = 333
                    },
                    new EventBackend {
                        Key = "key_4", TrafficTypeName = "traffic_type_4", EventTypeId = "event_type_4", Value = 444, Properties = properties
                    },
                    new EventBackend {
                        Key = "key_5", TrafficTypeName = "traffic_type_5", EventTypeId = "event_type_5"
                    }
                };

                var apikey = "base-apikey20";

                var splitFactory = new SplitFactory(apikey, configurations);
                var client       = splitFactory.Client();

                client.BlockUntilReady(10000);

                foreach (var _event in events)
                {
                    // Act.
                    var result = client.Track(_event.Key, _event.TrafficTypeName, _event.EventTypeId, _event.Value, _event.Properties);

                    // Assert.
                    Assert.IsTrue(result);
                }

                //Validate Events sent to the be.
                AssertSentEvents(events, httpClientMock, sleepTime: 1000, eventsCount: 3, validateEvents: false);
                client.Destroy();
            }
        }
Exemplo n.º 20
0
        public void BuildRedisSplitClientAsProducerShouldReturnException()
        {
            //Arrange
            var configurationOptions = new ConfigurationOptions();

            configurationOptions.Mode = Mode.Producer;

            var factory = new SplitFactory("any", configurationOptions);

            //Act
            var client = factory.Client();
        }
Exemplo n.º 21
0
        public void BuildRedisSplitClientAsConsumerWithNullRedisConfigShouldReturnException()
        {
            //Arrange
            var configurationOptions = new ConfigurationOptions
            {
                Mode = Mode.Consumer
            };

            var factory = new SplitFactory("any", configurationOptions);

            //Act
            var client = factory.Client();
        }
Exemplo n.º 22
0
        public void ControlMessage_StreamingDisabled()
        {
            using (var httpClientMock = new HttpClientMock())
            {
                httpClientMock.SplitChangesSequence("splits_push.json", "-1", "First_Time_2");
                httpClientMock.SplitChangesSequence("splits_push2.json", "1585948850109", "First_Time", "splits_push3.json", "1585948850109", "Second_Time");
                httpClientMock.SplitChangesSequence("splits_push4.json", "1585948850111", "First_Time_1");
                httpClientMock.SegmentChangesOk("-1", "segment4");
                httpClientMock.SegmentChangesOk("1470947453878", "segment4", "split_segment4_empty");
                httpClientMock.Post_Response("/api/testImpressions/bulk", 200, "ok");
                httpClientMock.Post_Response("/api/events/bulk", 200, "ok");

                var notification = "d4\r\nevent: message\ndata: {\"id\":\"123\",\"clientId\":\"emptyClientId\",\"timestamp\":1582056812285,\"encoding\":\"json\",\"channel\":\"[?occupancy=metrics.publishers]control_pri\",\"data\":\"{\\\"type\\\":\\\"CONTROL\\\",\\\"controlType\\\":\\\"STREAMING_DISABLED\\\"}\"}\n\n\r\n";
                httpClientMock.SSE_Channels_Response_WithPath(EventSourcePath, notification);

                var authResponse = new AuthenticationResponse
                {
                    PushEnabled = true,
                    Token       = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ4LWFibHktY2FwYWJpbGl0eSI6IntcInh4eHhfeHh4eF9zZWdtZW50c1wiOltcInN1YnNjcmliZVwiXSxcInh4eHhfeHh4eF9zcGxpdHNcIjpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sXCI6W1wic3Vic2NyaWJlXCJdfSJ9"
                };

                httpClientMock.AuthService_Response(JsonConvert.SerializeObject(authResponse));

                var url    = httpClientMock.GetUrl();
                var config = new ConfigurationOptions
                {
                    Endpoint            = url,
                    EventsEndpoint      = url,
                    FeaturesRefreshRate = 3000,
                    SegmentsRefreshRate = 3000,
                    AuthServiceURL      = $"{url}/api/auth",
                    StreamingServiceURL = $"{url}{EventSourcePath}",
                    StreamingEnabled    = true
                };

                var apikey = "apikey1";

                var splitFactory = new SplitFactory(apikey, config);
                var client       = splitFactory.Client();

                client.BlockUntilReady(10000);
                Thread.Sleep(500);

                var result = client.GetTreatment("admin", "push_test");

                Assert.AreEqual("on", result);

                client.Destroy();
            }
        }
Exemplo n.º 23
0
        public void BuildRedisSplitClientWithoutAllRequiredConfigsShouldReturnException()
        {
            //Arrange
            var configurationOptions = new ConfigurationOptions();

            configurationOptions.Mode = Mode.Consumer;
            configurationOptions.CacheAdapterConfig      = new CacheAdapterConfigurationOptions();
            configurationOptions.CacheAdapterConfig.Host = "local";

            var factory = new SplitFactory("any", configurationOptions);

            //Act
            var client = factory.Client();
        }
Exemplo n.º 24
0
        public void Split_WithLocalhostClient_WhenNameIsTestingSplitWithWl_ReturnsSplit()
        {
            // Arrange.
            var splitViewExpected = new SplitView
            {
                name       = "testing_split_with_wl",
                treatments = new List <string> {
                    "not_in_whitelist"
                },
                configs = new Dictionary <string, string>
                {
                    { "not_in_whitelist", "{\"color\": \"green\"}" },
                    { "multi_key_wl", "{\"color\": \"brown\"}" }
                }
            };

            var configurationOptions = new ConfigurationOptions
            {
                LocalhostFilePath = "split.yaml",
                Ready             = 500
            };

            _blockUntilReadyService
            .Setup(mock => mock.IsSdkReady())
            .Returns(true);

            var factory = new SplitFactory("localhost", configurationOptions);
            var manager = factory.Manager();

            manager.BlockUntilReady(1000);

            // Act.
            var splitViewResult = manager.Split("testing_split_with_wl");

            // Assert.
            Assert.AreEqual(splitViewExpected.name, splitViewResult.name);
            Assert.IsFalse(splitViewResult.killed);
            Assert.IsNull(splitViewResult.trafficType);
            Assert.AreEqual(splitViewExpected.configs.Count, splitViewResult.configs.Count);
            foreach (var config in splitViewExpected.configs)
            {
                Assert.AreEqual(config.Value, splitViewResult.configs[config.Key]);
            }

            Assert.AreEqual(splitViewExpected.treatments.Count, splitViewResult.treatments.Count);
            foreach (var treatment in splitViewExpected.treatments)
            {
                Assert.IsNotNull(splitViewResult.treatments.FirstOrDefault(t => t == treatment));
            }
        }
Exemplo n.º 25
0
        public void BuildSplitClientWithLocalhostApiKeyShouldReturnLocalhostClient()
        {
            //Arrange
            var options = new ConfigurationOptions {
                LocalhostFilePath = $"{rootFilePath}test.splits"
            };
            var factory = new SplitFactory("localhost", options);

            //Act
            var client = factory.Client();

            //Assert
            Assert.AreEqual(typeof(LocalhostClient), client.GetType());
        }
Exemplo n.º 26
0
        public void GetTreatment_SplitKill_ShouldFetch()
        {
            using (var httpClientMock = new HttpClientMock())
            {
                httpClientMock.SplitChangesSequence("splits_push.json", "-1", "First_Time_2");
                httpClientMock.SplitChangesSequence("splits_push2.json", "1585948850109", "First_Time", "splits_push3.json", "1585948850109", "Second_Time");
                httpClientMock.SplitChangesSequence("splits_push4.json", "1585948850111", "First_Time_1");
                httpClientMock.SegmentChangesOk("-1", "segment4");
                httpClientMock.SegmentChangesOk("1470947453878", "segment4", "split_segment4_empty");
                httpClientMock.Post_Response("/api/testImpressions/bulk", 200, "ok");
                httpClientMock.Post_Response("/api/events/bulk", 200, "ok");

                var notification = "fb\r\nid: 123\nevent: message\ndata: {\"id\":\"1\",\"clientId\":\"emptyClientId\",\"connectionId\":\"1\",\"timestamp\":1582045421733,\"channel\":\"mauroc\",\"data\":\"{\\\"type\\\" : \\\"SPLIT_KILL\\\",\\\"changeNumber\\\": 1585948850111, \\\"defaultTreatment\\\" : \\\"off_kill\\\", \\\"splitName\\\" : \\\"push_test\\\"}\",\"name\":\"asdasd\"}\n\n\r\n";
                httpClientMock.SSE_Channels_Response_WithPath(EventSourcePath, notification);

                var authResponse = new AuthenticationResponse
                {
                    PushEnabled = true,
                    Token       = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ4LWFibHktY2FwYWJpbGl0eSI6IntcInh4eHhfeHh4eF9zZWdtZW50c1wiOltcInN1YnNjcmliZVwiXSxcInh4eHhfeHh4eF9zcGxpdHNcIjpbXCJzdWJzY3JpYmVcIl0sXCJjb250cm9sXCI6W1wic3Vic2NyaWJlXCJdfSJ9"
                };

                httpClientMock.AuthService_Response(JsonConvert.SerializeObject(authResponse));

                var url    = httpClientMock.GetUrl();
                var config = new ConfigurationOptions
                {
                    Endpoint            = url,
                    EventsEndpoint      = url,
                    FeaturesRefreshRate = 3000,
                    SegmentsRefreshRate = 3000,
                    AuthServiceURL      = $"{url}/api/auth",
                    StreamingServiceURL = $"{url}{EventSourcePath}",
                    StreamingEnabled    = true
                };

                var apikey = "apikey1";

                var splitFactory = new SplitFactory(apikey, config);
                var client       = splitFactory.Client();

                client.BlockUntilReady(10000);
                Thread.Sleep(5000);

                var result = client.GetTreatment("admin", "push_test");

                Assert.AreEqual("after_fetch", result);

                client.Destroy();
            }
        }
Exemplo n.º 27
0
        public MyAppData()
        {
            var apikey         = "<your API KEY here>";
            var configurations = new ConfigurationOptions
            {
                FeaturesRefreshRate = 20,
                SegmentsRefreshRate = 20,
                ReadTimeout         = 20000,
                ConnectionTimeout   = 20000
            };

            var factory = new SplitFactory(apikey, configurations);

            _sdk = factory.Client();
        }
        public ActionResult UploadFile()
        {
            var config = new ConfigurationOptions();

            var factory     = new SplitFactory("v0gs87g1pd0frk07c62eqdr1kkhebo05bkne", config);
            var splitClient = factory.Client();

            try
            {
                splitClient.BlockUntilReady(10000);
            }
            catch (Exception)
            {
                // log & handle
            }

            var treatment = splitClient.GetTreatment("parth", "weather_feature");

            if (treatment == "on")
            {
                var    file        = Request.Form.Files[0];
                string folderName  = "Upload";
                string webRootPath = _hostingEnvironment.WebRootPath;
                string newPath     = Path.Combine(webRootPath, folderName);
                if (!Directory.Exists(newPath))
                {
                    Directory.CreateDirectory(newPath);
                }
                if (file.Length > 0)
                {
                    string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                    string fullPath = Path.Combine(newPath, fileName);
                    using (var stream = new FileStream(fullPath, FileMode.Create))
                    {
                        file.CopyTo(stream);
                    }
                }
                return(Json("Upload Successful."));
            }
            else if (treatment == "off")
            {
                return(Json("You do not have permission to upload."));
            }
            else
            {
                return(Json("There was error"));
            }
        }
Exemplo n.º 29
0
        public void GetTreatments_ValidateDedupeImpressions_Optimized()
        {
            // Arrange.
            var httpClientMock = GetHttpClientMock();
            var configurations = GetConfigurationOptions(httpClientMock);

            var apikey = "apikey3";

            var splitFactory = new SplitFactory(apikey, configurations);
            var client       = splitFactory.Client();

            client.BlockUntilReady(20000);

            // Act.
            client.GetTreatmentWithConfig("nico_test", "FACUNDO_TEST");
            client.GetTreatmentWithConfig("nico_test", "FACUNDO_TEST");
            client.GetTreatmentWithConfig("test", "MAURO_TEST");
            client.GetTreatmentWithConfig("mauro", "MAURO_TEST");
            client.GetTreatmentWithConfig("mauro", "MAURO_TEST");
            client.GetTreatments("admin", new List <string> {
                "FACUNDO_TEST", "Test_Save_1"
            });
            client.GetTreatment("admin", "FACUNDO_TEST");
            client.GetTreatment("admin", "Test_Save_1");
            client.GetTreatmentsWithConfig("admin", new List <string> {
                "FACUNDO_TEST", "MAURO_TEST"
            });

            client.Destroy();
            Thread.Sleep(3000);

            // Assert.
            var sentImpressions = GetImpressionsSentBackend(httpClientMock);

            Assert.AreEqual(3, sentImpressions.Count);
            Assert.AreEqual(2, sentImpressions.FirstOrDefault(i => i.F.Equals("FACUNDO_TEST")).I.Count);
            Assert.AreEqual(3, sentImpressions.FirstOrDefault(i => i.F.Equals("MAURO_TEST")).I.Count);
            Assert.AreEqual(1, sentImpressions.FirstOrDefault(i => i.F.Equals("Test_Save_1")).I.Count);

            var impressionCounts = GetImpressionsCountsSentBackend(httpClientMock);

            Assert.AreEqual(3, impressionCounts.FirstOrDefault().Pf.Count);
            Assert.AreEqual(5, impressionCounts.FirstOrDefault().Pf.FirstOrDefault(i => i.F.Equals("FACUNDO_TEST")).Rc);
            Assert.AreEqual(4, impressionCounts.FirstOrDefault().Pf.FirstOrDefault(i => i.F.Equals("MAURO_TEST")).Rc);
            Assert.AreEqual(2, impressionCounts.FirstOrDefault().Pf.FirstOrDefault(i => i.F.Equals("Test_Save_1")).Rc);

            ShutdownServer(httpClientMock);
        }
Exemplo n.º 30
0
        public void GetTreatments_ValidateDedupeImpressions_Optimized()
        {
            // Arrange.
            using (var httpClientMock = GetHttpClientMock())
            {
                var configurations = GetConfigurationOptions(httpClientMock.GetUrl());

                var apikey = "apikey9";

                var splitFactory = new SplitFactory(apikey, configurations);
                var client       = splitFactory.Client();

                client.BlockUntilReady(10000);

                // Act.
                client.GetTreatmentWithConfig("nico_test", "FACUNDO_TEST");
                client.GetTreatmentWithConfig("nico_test", "FACUNDO_TEST");
                client.GetTreatmentWithConfig("test", "MAURO_TEST");
                client.GetTreatmentWithConfig("mauro", "MAURO_TEST");
                client.GetTreatmentWithConfig("mauro", "MAURO_TEST");
                client.GetTreatments("admin", new List <string> {
                    "FACUNDO_TEST", "Test_Save_1"
                });
                client.GetTreatment("admin", "FACUNDO_TEST");
                client.GetTreatment("admin", "Test_Save_1");
                client.GetTreatmentsWithConfig("admin", new List <string> {
                    "FACUNDO_TEST", "MAURO_TEST"
                });

                client.Destroy();
                Thread.Sleep(3000);

                // Assert.
                var sentImpressions = GetImpressionsSentBackend(httpClientMock);
                Assert.AreEqual(3, sentImpressions.Select(x => x.F).Distinct().Count(), "1");
                Assert.AreEqual(2, sentImpressions.Where(x => x.F.Equals("FACUNDO_TEST")).Sum(x => x.I.Count), "2");
                Assert.AreEqual(3, sentImpressions.Where(x => x.F.Equals("MAURO_TEST")).Sum(x => x.I.Count), "3");
                Assert.AreEqual(1, sentImpressions.Where(x => x.F.Equals("Test_Save_1")).Sum(x => x.I.Count), "4");

                var impressionCounts = GetImpressionsCountsSentBackend(httpClientMock);
                var names            = new List <string>();
                impressionCounts.ForEach(item => names.AddRange(item.Pf.Select(x => x.F)));
                Assert.AreEqual(3, names.Distinct().Count(), "5");
                Assert.AreEqual(5, impressionCounts.Sum(x => x.Pf.Where(i => i.F.Equals("FACUNDO_TEST")).Sum(z => z.Rc)), "6");
                Assert.AreEqual(4, impressionCounts.Sum(x => x.Pf.Where(i => i.F.Equals("MAURO_TEST")).Sum(z => z.Rc)), "7");
                Assert.AreEqual(2, impressionCounts.Sum(x => x.Pf.Where(i => i.F.Equals("Test_Save_1")).Sum(z => z.Rc)), "8");
            }
        }