Skip to content

Commit 44b145e

Browse files
update: Refactor cache decision logic and enhance test cases for DefaultCmabService
1 parent a2a10d9 commit 44b145e

File tree

2 files changed

+19
-5
lines changed

2 files changed

+19
-5
lines changed

optimizely/cmab/cmab_service.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ def get_decision(self, project_config: ProjectConfig, user_context: OptimizelyUs
6464
if cached_value:
6565
if cached_value['attributes_hash'] == attributes_hash:
6666
return CmabDecision(variation_id=cached_value['variation_id'], cmab_uuid=cached_value['cmab_uuid'])
67-
elif OptimizelyDecideOption.INVALIDATE_USER_CMAB_CACHE not in options:
67+
else:
6868
self.cmab_cache.remove(cache_key)
6969

7070
cmab_decision = self._fetch_decision(rule_id, user_context.user_id, filtered_attributes)

tests/test_cmab_service.py

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -50,18 +50,27 @@ def setUp(self):
5050
}
5151

5252
def test_returns_decision_from_cache_when_valid(self):
53+
expected_key = self.cmab_service._get_cache_key("user123", "exp1")
54+
expected_attributes = {"age": 25, "location": "USA"}
55+
expected_hash = self.cmab_service._hash_attributes(expected_attributes)
56+
5357
self.mock_cmab_cache.lookup.return_value = {
54-
"attributes_hash": self.cmab_service._hash_attributes({"age": 25, "location": "USA"}),
58+
"attributes_hash": expected_hash,
5559
"variation_id": "varA",
5660
"cmab_uuid": "uuid-123"
5761
}
5862

59-
decision = self.cmab_service.get_decision(self.mock_project_config, self.mock_user_context, "exp1", [])
63+
decision = self.cmab_service.get_decision(
64+
self.mock_project_config, self.mock_user_context, "exp1", []
65+
)
66+
67+
self.mock_cmab_cache.lookup.assert_called_once_with(expected_key)
6068
self.assertEqual(decision["variation_id"], "varA")
6169
self.assertEqual(decision["cmab_uuid"], "uuid-123")
6270

6371
def test_ignores_cache_when_option_given(self):
6472
self.mock_cmab_client.fetch_decision.return_value = "varB"
73+
expected_attributes = {"age": 25, "location": "USA"}
6574

6675
decision = self.cmab_service.get_decision(
6776
self.mock_project_config,
@@ -72,11 +81,16 @@ def test_ignores_cache_when_option_given(self):
7281

7382
self.assertEqual(decision["variation_id"], "varB")
7483
self.assertIn('cmab_uuid', decision)
75-
self.mock_cmab_client.fetch_decision.assert_called_once()
84+
self.mock_cmab_client.fetch_decision.assert_called_once_with(
85+
"exp1",
86+
self.mock_user_context.user_id,
87+
expected_attributes,
88+
decision["cmab_uuid"]
89+
)
7690

7791
def test_invalidates_user_cache_when_option_given(self):
7892
self.mock_cmab_client.fetch_decision.return_value = "varC"
79-
93+
self.mock_cmab_cache.lookup.return_value = None
8094
self.cmab_service.get_decision(
8195
self.mock_project_config,
8296
self.mock_user_context,

0 commit comments

Comments
 (0)