From c857b7ae0f1d5b75cffcd4f0cb97d86c28065d0f Mon Sep 17 00:00:00 2001 From: sighphyre Date: Mon, 3 Apr 2023 16:28:27 +0200 Subject: [PATCH] fix: patch random stickiness calculations for rollout strategies --- internal/strategies/flexible_rollout_test.go | 32 ++++++++++++++++++++ internal/strategies/helpers.go | 5 ++- internal/strategies/helpers_test.go | 2 +- 3 files changed, 37 insertions(+), 2 deletions(-) create mode 100644 internal/strategies/flexible_rollout_test.go diff --git a/internal/strategies/flexible_rollout_test.go b/internal/strategies/flexible_rollout_test.go new file mode 100644 index 0000000..566a96d --- /dev/null +++ b/internal/strategies/flexible_rollout_test.go @@ -0,0 +1,32 @@ +package strategies + +import ( + "testing" + + "github.com/Unleash/unleash-client-go/v3/context" + "github.com/Unleash/unleash-client-go/v3/strategy" + "github.com/stretchr/testify/assert" +) + +func TestFlexibleRolloutStrategy_IsWellDistributed(t *testing.T) { + s := NewFlexibleRolloutStrategy() + + enabledCount := 0 + rounds := 200000 + + for i := 0; i < rounds; i++ { + params := map[string]interface{}{ + strategy.ParamStickiness: "random", + strategy.ParamRollout: 50, + strategy.ParamGroupId: "test51", + } + enabled := s.IsEnabled(params, &context.Context{}) + if enabled { + enabledCount++ + } + } + + actualPercentage := round(100.0 * float64(enabledCount) / float64(rounds)) + + assert.InDelta(t, 50, actualPercentage, 1.0) +} diff --git a/internal/strategies/helpers.go b/internal/strategies/helpers.go index 1f3ed5c..236281c 100644 --- a/internal/strategies/helpers.go +++ b/internal/strategies/helpers.go @@ -84,7 +84,10 @@ func (r *rng) float() float64 { } func (r *rng) string() string { - return strconv.Itoa(r.int()) + r.Lock() + n := r.random.Intn(10000) + 1 + r.Unlock() + return strconv.Itoa(n) } // newRng creates a new random number generator for numbers between 1-100 diff --git a/internal/strategies/helpers_test.go b/internal/strategies/helpers_test.go index 652a6e6..da7e395 100644 --- a/internal/strategies/helpers_test.go +++ b/internal/strategies/helpers_test.go @@ -75,7 +75,7 @@ func TestNewRng(t *testing.T) { assert.True(t, randomInt >= 0 && randomInt <= 100) randomString := rng.string() - assert.True(t, len(randomString) <= 3) + assert.True(t, len(randomString) <= 5) randomFloat := rng.float() assert.True(t, randomFloat > 0.0 && randomFloat <= 100.0)