Skip to content

Commit bb0c7b4

Browse files
authored
test(flags): make wrong-key load_feature_flags deterministic (#432)
1 parent 499194e commit bb0c7b4

2 files changed

Lines changed: 14 additions & 9 deletions

File tree

posthog/client.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1928,10 +1928,12 @@ def _capture_feature_flag_called(
19281928
f"{key}_{'::null::' if response is None else str(response)}"
19291929
)
19301930

1931-
if (
1932-
feature_flag_reported_key
1933-
not in self.distinct_ids_feature_flags_reported[distinct_id]
1934-
):
1931+
reported_flags = self.distinct_ids_feature_flags_reported.get(distinct_id)
1932+
if reported_flags is None:
1933+
reported_flags = set()
1934+
self.distinct_ids_feature_flags_reported[distinct_id] = reported_flags
1935+
1936+
if feature_flag_reported_key not in reported_flags:
19351937
properties: dict[str, Any] = {
19361938
"$feature_flag": key,
19371939
"$feature_flag_response": response,
@@ -1967,9 +1969,7 @@ def _capture_feature_flag_called(
19671969
groups=groups,
19681970
disable_geoip=disable_geoip,
19691971
)
1970-
self.distinct_ids_feature_flags_reported[distinct_id].add(
1971-
feature_flag_reported_key
1972-
)
1972+
reported_flags.add(feature_flag_reported_key)
19731973

19741974
def get_remote_config_payload(self, key: str):
19751975
if self.disabled:

posthog/test/test_feature_flags.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2513,7 +2513,10 @@ def test_load_feature_flags_clears_etag_when_server_stops_sending(
25132513
self.assertIsNone(client._flags_etag)
25142514
self.assertEqual(client.feature_flags[0]["key"], "flag-v2")
25152515

2516-
def test_load_feature_flags_wrong_key(self):
2516+
@mock.patch("posthog.client.Poller")
2517+
@mock.patch("posthog.client.get")
2518+
def test_load_feature_flags_wrong_key(self, patch_get, _patch_poll):
2519+
patch_get.side_effect = APIError(401, "Unauthorized")
25172520
client = Client(FAKE_TEST_API_KEY, personal_api_key=FAKE_TEST_API_KEY)
25182521

25192522
with self.assertLogs("posthog", level="ERROR") as logs:
@@ -4266,13 +4269,15 @@ def test_disable_geoip_get_flag_capture_call(self, patch_flags, patch_capture):
42664269
disable_geoip=False,
42674270
)
42684271

4269-
@mock.patch("posthog.client.MAX_DICT_SIZE", 100)
42704272
@mock.patch.object(Client, "capture")
42714273
@mock.patch("posthog.client.flags")
42724274
def test_capture_multiple_users_doesnt_out_of_memory(
42734275
self, patch_flags, patch_capture
42744276
):
42754277
client = Client(FAKE_TEST_API_KEY, personal_api_key=FAKE_TEST_API_KEY)
4278+
# Set on the instance to avoid relying on module-constant patching behavior
4279+
# across Python/runtime implementations.
4280+
client.distinct_ids_feature_flags_reported.max_size = 100
42764281
client.feature_flags = [
42774282
{
42784283
"id": 1,

0 commit comments

Comments
 (0)