From 8a0b36b27edcd6bd03b00a02a89ad136f9cbab23 Mon Sep 17 00:00:00 2001 From: Kim Gustyr Date: Tue, 20 Jun 2023 03:56:25 +0100 Subject: [PATCH] fix!: consistent split evaluations (#88) * fix!: consistent split evaluations * fix: reset mocked `GetHashedPercentageForObjectIds` correctly * fix: better identityHashKey inferring --- flagengine/segments/evaluator.go | 6 ++++- flagengine/segments/evaluator_test.go | 37 ++++++++++++++++++++++++++- flagengine/utils/hashing.go | 4 +++ 3 files changed, 45 insertions(+), 2 deletions(-) diff --git a/flagengine/segments/evaluator.go b/flagengine/segments/evaluator.go index 8873d75..a53e89f 100644 --- a/flagengine/segments/evaluator.go +++ b/flagengine/segments/evaluator.go @@ -24,8 +24,12 @@ func EvaluateIdentityInSegment( traits = overrideTraits } + identityHashKey := identity.CompositeKey() + if identity.DjangoID != 0 { + identityHashKey = strconv.Itoa(identity.DjangoID) + } for _, rule := range segment.Rules { - if !traitsMatchSegmentRule(traits, rule, segment.ID, identity.CompositeKey()) { + if !traitsMatchSegmentRule(traits, rule, segment.ID, identityHashKey) { return false } } diff --git a/flagengine/segments/evaluator_test.go b/flagengine/segments/evaluator_test.go index c8cca97..39bad4e 100644 --- a/flagengine/segments/evaluator_test.go +++ b/flagengine/segments/evaluator_test.go @@ -297,7 +297,42 @@ func TestIdentityInSegmentPercentageSplit(t *testing.T) { assert.Equal(t, c.expectedResult, result) }) } - utils.MockSetHashedPercentageForObjectIds(utils.GetHashedPercentageForObjectIds) + utils.ResetMocks() +} + +func TestIdentityInSegmentPercentageSplitUsesDjangoID(t *testing.T) { + cases := []struct { + identity *identities.IdentityModel + expectedResult bool + }{ + {&identities.IdentityModel{ + DjangoID: 1, + Identifier: "Test", + EnvironmentAPIKey: "key", + }, false}, + {&identities.IdentityModel{ + Identifier: "Test", + EnvironmentAPIKey: "key", + }, true}, + } + + for i, c := range cases { + t.Run(strconv.Itoa(i), func(t *testing.T) { + cond := &segments.SegmentConditionModel{ + Operator: segments.PercentageSplit, + Value: "50", + } + rule := &segments.SegmentRuleModel{ + Type: segments.All, + Conditions: []*segments.SegmentConditionModel{cond}, + } + segment := &segments.SegmentModel{ID: 1, Name: "% split", Rules: []*segments.SegmentRuleModel{rule}} + + result := segments.EvaluateIdentityInSegment(c.identity, segment) + + assert.Equal(t, result, c.expectedResult) + }) + } } func TestIdentityInSegmentIsSetAndIsNotSet(t *testing.T) { diff --git a/flagengine/utils/hashing.go b/flagengine/utils/hashing.go index 4216fc2..74efd6f 100644 --- a/flagengine/utils/hashing.go +++ b/flagengine/utils/hashing.go @@ -35,3 +35,7 @@ var hashedPercentageForObjectIdsFunc = getHashedPercentageForObjectIds func MockSetHashedPercentageForObjectIds(fn func([]string, int) float64) { hashedPercentageForObjectIdsFunc = fn } + +func ResetMocks() { + hashedPercentageForObjectIdsFunc = getHashedPercentageForObjectIds +}