Exemple #1
0
        public async Task should_handle_errors()
        {
            var httpCodes = new[] { 400, 401, 403, 404, 500, 503 };

            foreach (var httpCode in httpCodes)
            {
                _server.Given(
                    Request
                    .Create()
                    .WithPath("/features")
                    .WithHeader("Accept", "application/json")
                    .UsingGet())
                .RespondWith(
                    Response
                    .Create()
                    .WithStatusCode(httpCode)
                    .WithHeader("Content-Type", "application/json")
                    );


                var uri               = new Uri("http://localhost:" + _server.Ports.First());
                var config            = UnleashConfig.TheBuilder().AppName("test").UnleashAPI(uri).Build();
                var httpToggleFetcher = new HttpToggleFetcher(config);
                var response          = await httpToggleFetcher.FetchToggles();

                Assert.False(response.IsChanged);
            }
        }
Exemple #2
0
        public async Task happy_path_test_version1()
        {
            _server.Given(
                Request
                .Create()
                .WithPath("/features")
                .WithHeader("Accept", "application/json")
                .UsingGet())
            .RespondWith(
                Response
                .Create()
                .WithStatusCode(200)
                .WithHeader("Content-Type", "application/json")
                .WithBodyFromFile("resources/features-v1.json")
                );

            var uri               = new Uri("http://localhost:" + _server.Ports.First());
            var config            = UnleashConfig.TheBuilder().AppName("test").UnleashAPI(uri).Build();
            var httpToggleFetcher = new HttpToggleFetcher(config);
            var response          = await httpToggleFetcher.FetchToggles();

            var featureX = response.ToggleCollection.GetToggle("featureX");

            Assert.True(featureX.IsEnabled);
        }
Exemple #3
0
        public async Task should_register_client()
        {
            long          interval = 10;
            UnleashConfig config   = UnleashConfig
                                     .TheBuilder()
                                     .AppName("test")
                                     .SendMetricsInterval(interval)
                                     .UnleashAPI("http://unleash.com")
                                     .Build();

            var executor = A.Fake <IUnleashScheduledExecutor>();
            var sender   = A.Fake <UnleashMetricsSender>();

            var argument = new Capture <ClientRegistration>();

            A.CallTo(() => sender.RegisterClient(argument)).Returns(Task.FromResult(0));

            var unleashMetricService = new UnleashMetricServiceImpl(config, sender, executor);
            var strategies           = new HashSet <string>();

            strategies.Add("default");
            strategies.Add("custom");
            await unleashMetricService.Register(strategies);

            Assert.Equal(config.AppName, argument.Value.AppName);
            Assert.Equal(config.InstanceId, argument.Value.InstanceId);
            Assert.True(argument.Value.Started > DateTime.MinValue);
            Assert.Equal(2, argument.Value.Strategies.Count);
            Assert.Contains("default", argument.Value.Strategies);
            Assert.Contains("custom", argument.Value.Strategies);
        }
Exemple #4
0
 public DefaultUnleash(UnleashConfig unleashConfig, IToggleRepository toggleRepository,
                       params AStrategy[] strategies)
 {
     _toggleRepository = toggleRepository;
     _strategyMap      = BuildStrategyMap(strategies);
     _metricService    = new UnleashMetricServiceImpl(unleashConfig, new UnleashScheduledExecutorImpl());
     _metricService.Register(new HashSet <string>(_strategyMap.Keys.ToList()));
 }
Exemple #5
0
 private static FeatureToggleRepository DefaultToggleRepository(UnleashConfig unleashConfig)
 {
     return(new FeatureToggleRepository(
                unleashConfig,
                new UnleashScheduledExecutorImpl(),
                new HttpToggleFetcher(unleashConfig),
                new ToggleBackupHandlerFile(unleashConfig)));
 }
Exemple #6
0
        internal UnleashMetricsSender(Util.UnleashConfig unleashConfig)
        {
            _unleashConfig = unleashConfig;
            var urls = unleashConfig.UnleashURLs;

            _baseURL = urls.BaseURL;
            HttpClient.BaseAddress = _baseURL;
        }
Exemple #7
0
 internal ClientRegistration(UnleashConfig config, DateTime started, HashSet <string> strategies)
 {
     AppName    = config.AppName;
     InstanceId = config.InstanceId;
     SdkVersion = config.SdkVersion;
     Started    = started;
     Strategies = strategies;
     Interval   = config.SendMetricsInterval;
 }
Exemple #8
0
        public void should_set_sdk_version()
        {
            UnleashConfig config = UnleashConfig.TheBuilder()
                                   .AppName("my-app")
                                   .UnleashAPI("http://unleash.org")
                                   .Build();

            Assert.Equal("unleash-client-core:development", config.SdkVersion);
        }
Exemple #9
0
        public void should_generate_backupfile()
        {
            UnleashConfig config = UnleashConfig.TheBuilder()
                                   .AppName("my-app")
                                   .UnleashAPI("http://unleash.org")
                                   .Build();

            Assert.Equal("my-app", config.AppName);
            Assert.Equal(Path.GetTempPath() + Path.PathSeparator + "unleash-my-app-repo.json", config.BackupFile);
        }
Exemple #10
0
        public void should_use_provided_backupfile()
        {
            UnleashConfig config = UnleashConfig.TheBuilder()
                                   .AppName("my-app")
                                   .BackupFile("/test/unleash-backup.json")
                                   .UnleashAPI("http://unleash.org")
                                   .Build();

            Assert.Equal("my-app", config.AppName);
            Assert.Equal("/test/unleash-backup.json", config.BackupFile);
        }
Exemple #11
0
        public void no_backup_file_and_no_repository_available_should_give_empty_repo()
        {
            var config = UnleashConfig.TheBuilder()
                         .AppName("test")
                         .UnleashAPI("http://localhost:4242/api/")
                         .Build();
            var toggleFetcher       = new HttpToggleFetcher(config);
            var toggleBackupHandler = new ToggleBackupHandlerFile(config);
            var toggleRepository    = new FeatureToggleRepository(config, new MockExecutor(), toggleFetcher, toggleBackupHandler);

            Assert.Null(toggleRepository.GetToggle("unknownFeature"));
        }
Exemple #12
0
        public void test_read()
        {
            var config = UnleashConfig.TheBuilder()
                         .AppName("test")
                         .UnleashAPI("http://http://unleash.org")
                         .BackupFile("resources/unleash-repo-v0.json")
                         .Build();
            var toggleBackupHandlerFile = new ToggleBackupHandlerFile(config);
            var toggleCollection        = toggleBackupHandlerFile.Read();

            Assert.NotNull(toggleCollection.GetToggle("presentFeature"));
        }
Exemple #13
0
        public void should_build_config()
        {
            UnleashConfig config = UnleashConfig.TheBuilder()
                                   .AppName("my-app")
                                   .InstanceId("my-instance-1")
                                   .UnleashAPI("http://unleash.org")
                                   .Build();

            Assert.Equal("my-app", config.AppName);
            Assert.Equal("my-instance-1", config.InstanceId);
            Assert.Equal(new Uri("http://unleash.org"), config.UnleashAPI);
        }
Exemple #14
0
        public void test_read_file_with_invalid_data()
        {
            UnleashConfig config = UnleashConfig.TheBuilder()
                                   .AppName("test")
                                   .UnleashAPI("http://unleash.org")
                                   .BackupFile("resources/unleash-repo-without-feature-field.json")
                                   .Build();

            var fileGivingNullFeature = new ToggleBackupHandlerFile(config);

            Assert.NotNull(fileGivingNullFeature.Read());
        }
Exemple #15
0
        internal UnleashMetricServiceImpl(UnleashConfig unleashConfig,
                                          UnleashMetricsSender unleashMetricsSender,
                                          IUnleashScheduledExecutor executor)
        {
            _currentMetricsBucket = new MetricsBucket();
            _started              = DateTime.UtcNow;
            _unleashConfig        = unleashConfig;
            _metricsInterval      = unleashConfig.SendMetricsInterval;
            _unleashMetricsSender = unleashMetricsSender;
            _unleashExecutor      = executor;

            executor.SetInterval(async s => await SendMetrics(s), _metricsInterval, _metricsInterval);
        }
Exemple #16
0
        public void test_read_without_file()
        {
            UnleashConfig config = UnleashConfig.TheBuilder()
                                   .AppName("test")
                                   .UnleashAPI("http://unleash.org")
                                   .BackupFile("/does/not/exist.json")
                                   .Build();

            ToggleBackupHandlerFile toggleBackupHandlerFile = new ToggleBackupHandlerFile(config);
            ToggleCollection        toggleCollection        = toggleBackupHandlerFile.Read();

            Assert.Null(toggleCollection.GetToggle("presentFeature"));
        }
Exemple #17
0
        public FeatureToggleRepository(
            UnleashConfig unleashConfig,
            IUnleashScheduledExecutor executor,
            IToggleFetcher toggleFetcher,
            IToggleBackupHandler toggleBackupHandler)
        {
            _toggleBackupHandler = toggleBackupHandler;
            _toggleFetcher       = toggleFetcher;

            _toggleCollection = toggleBackupHandler.Read();

            _executor = executor;
            _executor.SetInterval(s => UpdateToggles(s).Wait(), 0, unleashConfig.FetchTogglesInterval);
        }
Exemple #18
0
        public void test_read_old_format_with_strategies()
        {
            UnleashConfig config = UnleashConfig.TheBuilder()
                                   .AppName("test")
                                   .UnleashAPI("http://unleash.org")
                                   .BackupFile("resources/unleash-repo-v0.json")
                                   .Build();

            var toggleBackupHandlerFile = new ToggleBackupHandlerFile(config);
            var toggleCollection        = toggleBackupHandlerFile.Read();

            Assert.NotNull(toggleCollection.GetToggle("featureCustomStrategy"));
            Assert.Single(toggleCollection.GetToggle("featureCustomStrategy").Strategies);
            Assert.Equal("customValue", toggleCollection.GetToggle("featureCustomStrategy").Strategies.First().Parameters["customParameter"]);
        }
Exemple #19
0
        public void backup_toggles_should_be_loaded_at_startup()
        {
            UnleashConfig config = UnleashConfig.TheBuilder()
                                   .AppName("test")
                                   .UnleashAPI("http://localhost:4242/api/")
                                   .FetchTogglesInterval(long.MaxValue)
                                   .Build();

            var toggleBackupHandler = A.Fake <IToggleBackupHandler>();
            var toggleFetcher       = A.Fake <IToggleFetcher>();
            var executor            = A.Fake <IUnleashScheduledExecutor>();

            new FeatureToggleRepository(config, executor, toggleFetcher, toggleBackupHandler);

            A.CallTo(() => toggleBackupHandler.Read()).MustHaveHappened(Repeated.Exactly.Once);
        }
Exemple #20
0
        private async Task <HttpStatusCode> Post(string url, Object o, string operation)
        {
            var request = new HttpRequestMessage(HttpMethod.Post, UnleashURLs.FetchTogglesUri);

            UnleashConfig.SetRequestProperties(request.Headers, _unleashConfig);
            request.Headers.Add("Cache-Control", "no-cache"); //  CacheControl.NoCache = true;
            request.Content = new StringContent(JsonConvert.SerializeObject(o), Encoding.UTF8, "application/json");

            var result = await HttpClient.SendAsync(request);

            if (!result.IsSuccessStatusCode)
            {
                Logger.WarnFormat("failed to {Operation}: statuscode {StatusCode}", operation, result.StatusCode);
            }
            return(result.StatusCode);
        }
Exemple #21
0
        public void should_record_and_send_metrics()
        {
            UnleashConfig config = UnleashConfig
                                   .TheBuilder()
                                   .AppName("test")
                                   .SendMetricsInterval(10)
                                   .UnleashAPI("http://unleash.com")
                                   .Build();

            var executor = A.Fake <IUnleashScheduledExecutor>();
            var sender   = A.Fake <UnleashMetricsSender>();

            var sendMetricsCallback = new Capture <TimerCallback>();

            A.CallTo(() => executor.SetInterval(sendMetricsCallback, A <long> .Ignored, A <long> .Ignored)).Returns(new AutoResetEvent(false));

            var clientMetricsArgumentCaptor = new Capture <ClientMetrics>();

            A.CallTo(() => sender.SendMetrics(clientMetricsArgumentCaptor)).Returns(Task.FromResult(0));

            var unleashMetricService = new UnleashMetricServiceImpl(config, sender, executor);

            unleashMetricService.Count("someToggle", true);
            unleashMetricService.Count("someToggle", false);
            unleashMetricService.Count("someToggle", true);
            unleashMetricService.Count("otherToggle", true);

            //Call the sendMetricsCallback
            // var sendMetricsCallback = ArgumentCaptor.forClass(Runnable.class);
            // verify(executor).setInterval(sendMetricsCallback.capture(), anyLong(), anyLong());
            // sendMetricsCallback.getValue().run();

            //verify(sender).sendMetrics(clientMetricsArgumentCaptor.capture());
            sendMetricsCallback.Value.Invoke(null);


            var clientMetrics = clientMetricsArgumentCaptor.Value;
            var bucket        = clientMetricsArgumentCaptor.Value.Bucket;

            Assert.Equal(config.AppName, clientMetrics.AppName);
            Assert.Equal(config.InstanceId, clientMetrics.InstanceId);
            Assert.True(bucket.Start > DateTime.MinValue);
            Assert.True(bucket.Stop > DateTime.MinValue);
            Assert.Equal(2, bucket.Toggles.Count);
            Assert.Equal(2, bucket.Toggles["someToggle"].Yes);
            Assert.Equal(1, bucket.Toggles["someToggle"].No);
        }
Exemple #22
0
        public async Task <FeatureToggleResponse> FetchToggles()
        {
            var request = new HttpRequestMessage(HttpMethod.Get, UnleashURLs.FetchTogglesUri);

            if (!string.IsNullOrEmpty(_etag))
            {
                request.Headers.IfNoneMatch.Add(new EntityTagHeaderValue(_etag));
            }
            //useCache(true)
            UnleashConfig.SetRequestProperties(request.Headers, _unleashConfig);

            var result = await HttpClient.SendAsync(request);

            return(await(result.IsSuccessStatusCode ?
                         GetToggleResponse(result) :
                         Task.FromResult(FeatureToggleResponse.NotChanged())));
        }
Exemple #23
0
        public void should_register_future_for_sending_interval_regualry()
        {
            long          interval = 10;
            UnleashConfig config   = UnleashConfig
                                     .TheBuilder()
                                     .AppName("test")
                                     .SendMetricsInterval(interval)
                                     .UnleashAPI("http://unleash.com")
                                     .Build();
            var executor             = A.Fake <IUnleashScheduledExecutor>();
            var unleashMetricService = new UnleashMetricServiceImpl(config, executor);

            A.CallTo(() => executor.SetInterval(
                         A <TimerCallback> .Ignored,
                         A <long> .That.IsEqualTo(interval),
                         A <long> .That.IsEqualTo(interval)))
            .MustHaveHappened(Repeated.Exactly.Once);
        }
Exemple #24
0
        public void test_write_strategies()
        {
            var backupFile = Path.GetTempPath() + Path.PathSeparator + "unleash-repo-test-write.json";
            var config     = UnleashConfig.TheBuilder()
                             .AppName("test")
                             .UnleashAPI("http://unleash.org")
                             .BackupFile(backupFile)
                             .Build();

            var staticData = "{\"features\": [{\"name\": \"writableFeature\",\"enabled\": true,\"strategy\": \"default\"}]}";

            var toggleCollection = JsonToggleParser.FromJson(staticData);

            var toggleBackupHandlerFile = new ToggleBackupHandlerFile(config);

            toggleBackupHandlerFile.Write(toggleCollection);
            toggleBackupHandlerFile = new ToggleBackupHandlerFile(config);
            toggleCollection        = toggleBackupHandlerFile.Read();
            Assert.NotNull(toggleCollection.GetToggle("writableFeature"));
        }
Exemple #25
0
        public async Task should_send_client_registration()
        {
            _server.Given(
                Request
                .Create()
                .WithPath("/client/register")
                .WithHeader("UNLEASH-APPNAME", "test-app")
                .UsingGet())
            .RespondWith(
                Response
                .Create()
                .WithStatusCode(200)
                );

            var uri    = new Uri("http://localhost:" + _server.Ports.First());
            var config = UnleashConfig.TheBuilder().AppName("test-app").UnleashAPI(uri).Build();

            var sender = new UnleashMetricsSender(config);
            await sender.RegisterClient(new ClientRegistration(config, DateTime.Now, new HashSet <string>()));
        }
Exemple #26
0
        public void should_add_custom_headers_to_connection_if_present()
        {
            string unleashAPI  = "http://unleash.org";
            string headerName  = "UNLEASH-CUSTOM-TEST-HEADER";
            string headerValue = "Some value";

            UnleashConfig unleashConfig = UnleashConfig.TheBuilder()
                                          .AppName("my-app")
                                          .InstanceId("my-instance-1")
                                          .UnleashAPI(unleashAPI)
                                          .CustomHttpHeader(headerName, headerValue)
                                          .Build();

            var someUrl = new Uri(unleashAPI + "/some/arbitrary/path");
            var request = new HttpRequestMessage(HttpMethod.Get, someUrl);

            UnleashConfig.SetRequestProperties(request.Headers, unleashConfig);

            Assert.Single(request.Headers.GetValues(headerName));
            Assert.Equal(headerValue, request.Headers.GetValues(headerName).First());
        }
Exemple #27
0
        public void given_empty_body()
        {
            _server.Given(
                Request
                .Create()
                .WithPath("/features")
                .WithHeader("Accept", "application/json")
                .UsingGet())
            .RespondWith(
                Response
                .Create()
                .WithStatusCode(200)
                .WithHeader("Content-Type", "application/json")
                );


            var uri               = new Uri("http://localhost:" + _server.Ports.First());
            var config            = UnleashConfig.TheBuilder().AppName("test").UnleashAPI(uri).Build();
            var httpToggleFetcher = new HttpToggleFetcher(config);

            Assert.ThrowsAnyAsync <Exception>(async() => await httpToggleFetcher.FetchToggles());
        }
Exemple #28
0
        public async Task should_send_client_metrics()
        {
            _server.Given(
                Request
                .Create()
                .WithPath("/client/metrics")
                .WithHeader("UNLEASH-APPNAME", "test-app")
                .UsingGet())
            .RespondWith(
                Response
                .Create()
                .WithStatusCode(200)
                );

            var uri    = new Uri("http://localhost:" + _server.Ports.First());
            var config = UnleashConfig.TheBuilder().AppName("test-app").UnleashAPI(uri).Build();

            var sender  = new UnleashMetricsSender(config);
            var bucket  = new MetricsBucket();
            var metrics = new ClientMetrics(config, bucket);
            await sender.SendMetrics(metrics);
        }
Exemple #29
0
        public void should_add_app_name_and_instance_id_and_user_agent_to_connection() //throws IOException
        {
            string appName    = "my-app";
            string instanceId = "my-instance-1";
            string unleashAPI = "http://unleash.org";

            var unleashConfig = UnleashConfig.TheBuilder()
                                .AppName(appName)
                                .InstanceId(instanceId)
                                .UnleashAPI(unleashAPI)
                                .Build();

            var someUrl = new Uri(unleashAPI + "/some/arbitrary/path");
            var request = new HttpRequestMessage(HttpMethod.Get, someUrl);

            UnleashConfig.SetRequestProperties(request.Headers, unleashConfig);

            Assert.Single(request.Headers.GetValues(UnleashConfig.UNLEASH_APP_NAME_HEADER));
            Assert.Equal(appName, request.Headers.GetValues(UnleashConfig.UNLEASH_APP_NAME_HEADER).First());
            Assert.Single(request.Headers.GetValues(UnleashConfig.UNLEASH_INSTANCE_ID_HEADER));
            Assert.Equal(instanceId, request.Headers.GetValues(UnleashConfig.UNLEASH_INSTANCE_ID_HEADER).First());
            Assert.Equal(appName, request.Headers.GetValues("User-Agent").First());
        }
Exemple #30
0
        public async Task should_send_metrics()
        {
            UnleashConfig config = UnleashConfig
                                   .TheBuilder()
                                   .AppName("test")
                                   .SendMetricsInterval(10)
                                   .UnleashAPI("http://unleash.com")
                                   .Build();

            var executor = A.Fake <IUnleashScheduledExecutor>();
            var sender   = A.Fake <UnleashMetricsSender>();

            var sendMetricsCallback = new Capture <TimerCallback>();

            A.CallTo(() => executor.SetInterval(sendMetricsCallback, A <long> .Ignored, A <long> .Ignored)).Returns(new AutoResetEvent(false));

            var unleashMetricService = new UnleashMetricServiceImpl(config, sender, executor);

            sendMetricsCallback.Value.Invoke(null);

            A.CallTo(() => sender.SendMetrics(
                         A <ClientMetrics> .Ignored))
            .MustHaveHappened(Repeated.Exactly.Once);
        }