Exemplo n.º 1
0
        public void GivenThereAreRequestsLeft_ThenTheCorrectFunctionShouldBeCalled()
        {
            var identityProvider = new PredictableClientIdentityProvider <LeakyBucketClientIdentity>(
                new LeakyBucketClientIdentity
            {
                UniqueIdentifier = "test"
            });

            var config = new LeakyBucketConfiguration
            {
                MaxRequests = 5,
                LeakRate    = TimeSpan.FromSeconds(5)
            };

            var rateLimiter = new LeakyBucketRateLimitStrategy();

            var successfulRequests = 0;
            var failedRequests     = 0;


            void RunRateLimiter()
            {
                var identity = identityProvider.GetCurrentIdentity();

                if (rateLimiter.HasRemainingAllowance(identity, config))
                {
                    rateLimiter.ReduceAllowanceBy(identity, config);
                    successfulRequests += 1;
                }
                else
                {
                    failedRequests += 1;
                }
            }

            RunRateLimiter();
            Assert.Equal(1, successfulRequests);

            for (var i = 0; i < 5; i++)
            {
                RunRateLimiter();
            }

            Thread.Sleep(TimeSpan.FromSeconds(6));
            Assert.Equal(5, successfulRequests);
            Assert.Equal(1, failedRequests);
        }
Exemplo n.º 2
0
        public void GivenAConfiguration_AfterALongInterval_TheCorrectNumberOfRequestsShouldBeAvailable(int maxRequests, int leakAmount, int requestCount, int waitSeconds, int expected)
        {
            var mockIdentity = new LeakyBucketClientIdentity
            {
                UniqueIdentifier = "test"
            };
            var identityProvider = new PredictableClientIdentityProvider <LeakyBucketClientIdentity>(
                mockIdentity);

            var config = new LeakyBucketConfiguration
            {
                MaxRequests = maxRequests,
                LeakRate    = TimeSpan.FromSeconds(1),
                LeakAmount  = leakAmount
            };

            var rateLimiter = new LeakyBucketRateLimitStrategy();

            void RunRateLimiter()
            {
                var identity = identityProvider.GetCurrentIdentity();

                if (rateLimiter.HasRemainingAllowance(identity, config))
                {
                    rateLimiter.ReduceAllowanceBy(identity, config);
                }
            }

            for (var i = 0; i < requestCount; i++)
            {
                RunRateLimiter();
            }

            if (waitSeconds > 0)
            {
                Thread.Sleep(TimeSpan.FromSeconds(waitSeconds));
            }

            RunRateLimiter();

            Assert.Equal(expected, rateLimiter.GetRemainingAllowance(mockIdentity, config));
        }