public void Should_not_override_static_fields()
        {
            // Arrange
            var context = new UnleashContext.Builder()
                          .UserId("*****@*****.**")
                          .SessionId("123")
                          .RemoteAddress("127.0.0.1")
                          .Environment("prod")
                          .AppName("myapp")
                          .AddProperty("test", "me")
                          .Build();

            // Act
            var enhancedContext = context.ApplyStaticFields(new UnleashSettings
            {
                Environment = "stage",
                AppName     = "someapp"
            });

            // Assert
            enhancedContext.UserId.Should().Be("*****@*****.**");
            enhancedContext.SessionId.Should().Be("123");
            enhancedContext.RemoteAddress.Should().Be("127.0.0.1");
            enhancedContext.Environment.Should().Be("prod");
            enhancedContext.AppName.Should().Be("myapp");
            enhancedContext.Properties["test"].Should().Be("me");
        }
        internal void IsEnabled_WhenPercentageIsSupplied_ShouldReturnRandomDataWithinConstraints(
            int percentage, double expectedTruePercentage, double expectedFalsePercentage,
            double expectationTolerance, int iterationsToTest)
        {
            var context    = new UnleashContext.Builder().Build();
            var parameters = new Dictionary <string, string>
            {
                ["percentage"] = percentage.ToString()
            };

            int trueCount  = 0;
            int falseCount = 0;

            for (var x = 0; x < iterationsToTest; x++)
            {
                var isEnabled = Strategy.IsEnabled(parameters, context);
                if (isEnabled)
                {
                    trueCount++;
                }
                else
                {
                    falseCount++;
                }
            }

            var truePercentage  = (double)trueCount / iterationsToTest;
            var falsePercentage = (double)falseCount / iterationsToTest;

            Assert.True(Math.Abs(truePercentage - expectedTruePercentage) <= expectationTolerance);
            Assert.True(Math.Abs(falsePercentage - expectedFalsePercentage) <= expectationTolerance);
        }
예제 #3
0
        public void IsEnabled_WhenRollingOutToSpecifiedPercentage_ShouldMissByAtMostOnePercent()
        {
            var groupId      = "group1";
            var percentage   = 25;
            var rounds       = 20000;
            var enabledCount = 0;

            var parameters = new Dictionary <string, string>
            {
                [GradualRolloutUserIdStrategy.PercentageConst] = percentage.ToString(),
                [GradualRolloutUserIdStrategy.GroupIdConst]    = groupId
            };

            for (var userId = 0; userId < rounds; userId++)
            {
                var context = new UnleashContext.Builder().UserId("user" + userId).Build();

                if (Strategy.IsEnabled(parameters, context))
                {
                    enabledCount++;
                }
            }

            var actualPercentage = (enabledCount / (double)rounds) * 100.0;

            Assert.True(percentage - 1 < actualPercentage);
            Assert.True(percentage + 1 > actualPercentage);
        }
        public void IsEnabled_WhenPercentageIsAboveMinimum_ShouldReturnTrue()
        {
            var groupId = string.Empty;

            var minimumPercentage = StrategyUtils.GetNormalizedNumber(SessionId, groupId);

            var context    = new UnleashContext.Builder().SessionId(SessionId).Build();
            var parameters = new Dictionary <string, string>();

            for (var percentage = 0; percentage <= 100; percentage++)
            {
                parameters[GradualRolloutSessionIdStrategy.Percentage] = percentage.ToString();
                parameters[GradualRolloutSessionIdStrategy.GroupId]    = groupId;

                var actual = Strategy.IsEnabled(parameters, context);

                if (percentage < minimumPercentage)
                {
                    Assert.False(actual);
                }
                else
                {
                    Assert.True(actual);
                }
            }
        }
        public void IsEnabled_WhenPassedEmptyParameters_ShouldReturnFalse()
        {
            var emptyParameters = new Dictionary <string, string>();
            var context         = new UnleashContext.Builder().Build();
            var result          = Strategy.IsEnabled(emptyParameters, context);

            Assert.False(result);
        }
        public void IsEnabled_WhenPercentageNotSet_ShouldReturnFalse()
        {
            var context    = new UnleashContext.Builder().Build();
            var parameters = new Dictionary <string, string>();

            var isEnabled = Strategy.IsEnabled(parameters, context);

            Assert.False(isEnabled);
        }
예제 #7
0
        public static IUnleash CreateUnleash(TestDefinition testDefinition, UnleashContextDefinition contextDefinition)
        {
            var fakeHttpClientFactory  = A.Fake <IHttpClientFactory>();
            var fakeHttpMessageHandler = new TestHttpMessageHandler();
            var httpClient             = new HttpClient(fakeHttpMessageHandler)
            {
                BaseAddress = new Uri("http://localhost")
            };
            var fakeScheduler  = A.Fake <IUnleashScheduledTaskManager>();
            var fakeFileSystem = new MockFileSystem();

            A.CallTo(() => fakeHttpClientFactory.Create(A <Uri> ._)).Returns(httpClient);
            A.CallTo(() => fakeScheduler.Configure(A <IEnumerable <IUnleashScheduledTask> > ._, A <CancellationToken> ._)).Invokes(action =>
            {
                var task = ((IEnumerable <IUnleashScheduledTask>)action.Arguments[0]).First();
                task.ExecuteAsync((CancellationToken)action.Arguments[1]).Wait();
            });

            fakeHttpMessageHandler.Response = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(testDefinition.State.ToString(), Encoding.UTF8, "application/json"),
                Headers    =
                {
                    ETag = new EntityTagHeaderValue("\"123\"")
                }
            };

            var contextBuilder = new UnleashContext.Builder()
                                 .UserId(contextDefinition.UserId)
                                 .SessionId(contextDefinition.SessionId)
                                 .RemoteAddress(contextDefinition.RemoteAddress)
                                 .Environment(contextDefinition.Environment)
                                 .AppName(contextDefinition.AppName);

            if (contextDefinition.Properties != null)
            {
                foreach (var property in contextDefinition.Properties)
                {
                    contextBuilder.AddProperty(property.Key, property.Value);
                }
            }

            var settings = new UnleashSettings
            {
                AppName = testDefinition.Name,
                UnleashContextProvider = new DefaultUnleashContextProvider(contextBuilder.Build()),
                HttpClientFactory      = fakeHttpClientFactory,
                ScheduledTaskManager   = fakeScheduler,
                FileSystem             = fakeFileSystem
            };

            var unleash = new DefaultUnleash(settings);

            return(unleash);
        }
        public void IsEnabled_WhenUsing0Or100PercentRollout_ShouldReturnFalseOrTrue(int percentage, bool expectedResult)
        {
            var context    = new UnleashContext.Builder().SessionId(SessionId).Build();
            var parameters = new Dictionary <string, string> {
                [GradualRolloutSessionIdStrategy.Percentage] = percentage.ToString(),
                [GradualRolloutSessionIdStrategy.GroupId]    = "innfinn"
            };

            var result = Strategy.IsEnabled(parameters, context);

            Assert.Equal(expectedResult, result);
        }
        public void IsEnabled_WhenPercentageIs0Or100_ShouldAlwaysReturnFalseOrTrue(int percentage, bool expectedResult, int iterationsToTest)
        {
            var context    = new UnleashContext.Builder().Build();
            var parameters = new Dictionary <string, string>
            {
                ["percentage"] = percentage.ToString()
            };

            for (var x = 0; x < iterationsToTest; x++)
            {
                var isEnabled = Strategy.IsEnabled(parameters, context);
                Assert.Equal(expectedResult, isEnabled);
            }
        }
예제 #10
0
        public void IsEnabled_WhenHostNameIsIpv4Address_ShouldReturnTrue()
        {
            var hostName = UnleashExtensions.GetLocalIpAddress();

            Environment.SetEnvironmentVariable("hostname", hostName);

            var context    = new UnleashContext.Builder().Build();
            var parameters = new Dictionary <string, string>
            {
                ["hostNames"] = $"MegaHost,{hostName},MiniHost, happyHost"
            };

            var isEnabled = Strategy.IsEnabled(parameters, context);

            Assert.True(isEnabled);
        }
        public void IsEnabled_WhenInvokedRepeatedly_ShouldReturnFalse(int iterations)
        {
            var context    = new UnleashContext.Builder().SessionId(SessionId).Build();
            var parameters = new Dictionary <string, string> {
                [GradualRolloutSessionIdStrategy.Percentage] = "1",
                [GradualRolloutSessionIdStrategy.GroupId]    = "innfinn"
            };

            bool firstRunResult = Strategy.IsEnabled(parameters, context);

            for (int i = 0; i < iterations; i++)
            {
                var subsequentRunResult = Strategy.IsEnabled(parameters, context);

                // loginId will return same result when unchanged parameters
                Assert.Equal(firstRunResult, subsequentRunResult);
            }
        }
예제 #12
0
        public void IsEnabed_WhenExecutedRepeatedlyForTheSameUser_ShouldReturnTheSameResult()
        {
            var context = new UnleashContext.Builder().UserId(UserId).Build();;
            var gradualRolloutStrategy = new GradualRolloutUserIdStrategy();

            var parameters = new Dictionary <string, string>
            {
                [GradualRolloutUserIdStrategy.PercentageConst] = "1",
                [GradualRolloutUserIdStrategy.GroupIdConst]    = "innfin"
            };

            var firstRunResult = gradualRolloutStrategy.IsEnabled(parameters, context);

            for (var i = 0; i < 10; i++)
            {
                var subsequentRunResult = gradualRolloutStrategy.IsEnabled(parameters, context);
                Assert.Equal(firstRunResult, subsequentRunResult);
            }
        }
        public void Should_build_context_with_fields_set()
        {
            // Act
            var context = new UnleashContext.Builder()
                          .UserId("*****@*****.**")
                          .SessionId("123")
                          .RemoteAddress("127.0.0.1")
                          .Environment("prod")
                          .AppName("myapp")
                          .AddProperty("test", "me")
                          .Build();

            // Assert
            context.UserId.Should().Be("*****@*****.**");
            context.SessionId.Should().Be("123");
            context.RemoteAddress.Should().Be("127.0.0.1");
            context.Environment.Should().Be("prod");
            context.AppName.Should().Be("myapp");
            context.Properties["test"].Should().Be("me");
        }
예제 #14
0
        public void IsEnabled_WhenContextIsComparedToParameters_ShouldReturnExpectedResult(
            string hostName,
            string hostNamesParameterValueFormat,
            bool expectedResult)
        {
            if (hostName != null)
            {
                Environment.SetEnvironmentVariable("hostname", hostName);
            }

            var context    = new UnleashContext.Builder().Build();
            var parameters = new Dictionary <string, string>
            {
                ["hostNames"] = string.Format(hostNamesParameterValueFormat, hostName)
            };

            var actualResult = Strategy.IsEnabled(parameters, context);

            Assert.Equal(expectedResult, actualResult);
        }