Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .sampo/changesets/doughty-baron-lemminkainen.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
pypi/posthog: patch
---

Use device IDs during local feature flag evaluation
1 change: 1 addition & 0 deletions posthog/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3373,6 +3373,7 @@ def evaluate_flags(
person_properties=local_person_properties,
group_properties=group_properties,
flag_keys_to_evaluate=flag_keys,
device_id=device_id,
)

feature_flags_by_key: Dict[str, Any] = self.feature_flags_by_key or {}
Expand Down
49 changes: 49 additions & 0 deletions posthog/test/test_evaluate_flags.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,55 @@ def test_empty_distinct_id_returns_empty_snapshot_without_events(
self.assertEqual(len(feature_flag_called), 0)


class TestEvaluateFlagsLocalDeviceBucketing(unittest.TestCase):
def setUp(self):
self.client = Client(FAKE_TEST_API_KEY)
self.client.feature_flags = [
{
"id": 1,
"key": "device-bucketed-flag",
"active": True,
"filters": {
"bucketing_identifier": "device_id",
# user-1 hashes above 50%, while both test device IDs hash below
# 50%, so these assertions prove device bucketing is used.
"groups": [{"properties": [], "rollout_percentage": 50}],
},
}
]

def tearDown(self):
self.client.shutdown()

@mock.patch("posthog.client.flags")
@mock.patch.object(Client, "capture")
def test_explicit_device_id_is_used_for_local_evaluation(
self, _patch_capture, patch_flags
):
flags = self.client.evaluate_flags(
"user-1",
device_id="explicit-device",
only_evaluate_locally=True,
)

self.assertTrue(flags.get_flag("device-bucketed-flag"))
patch_flags.assert_not_called()

@mock.patch("posthog.client.flags")
@mock.patch.object(Client, "capture")
def test_context_device_id_is_used_for_local_evaluation(
self, _patch_capture, patch_flags
):
from posthog.contexts import new_context, set_context_device_id

with new_context():
set_context_device_id("context-device-0")
flags = self.client.evaluate_flags("user-1", only_evaluate_locally=True)

self.assertTrue(flags.get_flag("device-bucketed-flag"))
patch_flags.assert_not_called()


class TestEvaluateFlagsFiltering(unittest.TestCase):
def setUp(self):
self.client = Client(FAKE_TEST_API_KEY)
Expand Down