Skip to content

Commit d775399

Browse files
authored
Fixing Targeting Context Groups (#81)
* Fix Groups * Update test_default_feature_flags.py * Delete CHANGELOG.md
1 parent 42871a2 commit d775399

4 files changed

Lines changed: 103 additions & 19 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 0 additions & 10 deletions
This file was deleted.

‎featuremanagement/_models/_targeting_context.py‎

Lines changed: 25 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,24 +5,40 @@
55
# --------------------------------------------------------------------------
66
"""Targeting context model for user and group targeting."""
77

8-
from typing import NamedTuple, Sequence
8+
from typing import NamedTuple
99

1010

11-
class TargetingContext(NamedTuple):
12-
"""
13-
Represents the context for targeting a feature flag.
14-
"""
11+
class _TargetingContextTuple(NamedTuple):
12+
"""Tuple fields shared by targeting contexts."""
1513

16-
user_id: str = ""
14+
user_id: str
1715
"""
1816
The user ID.
1917
2018
:type: str
2119
"""
2220

23-
groups: Sequence[str] = ()
21+
groups: list[str]
2422
"""
25-
The users groups.
23+
The user's groups.
2624
27-
:type: Sequence[str]
25+
:type: list[str]
26+
"""
27+
28+
29+
class TargetingContext(_TargetingContextTuple):
2830
"""
31+
Represents the context for targeting a feature flag.
32+
33+
:param str user_id: The user ID.
34+
:param groups: The user's groups. If omitted or None, a new empty list is created.
35+
:type groups: list[str] or None
36+
"""
37+
38+
__slots__ = ()
39+
40+
_field_defaults: dict[str, str | None] = {"user_id": "", "groups": None}
41+
42+
def __new__(cls, user_id: str = "", groups: list[str] | None = None) -> "TargetingContext":
43+
# Ensures that each instance gets its own list for groups, even if the default is used.
44+
return super().__new__(cls, user_id, groups if groups is not None else [])

‎tests/test_default_feature_flags.py‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,80 @@
55
# --------------------------------------------------------------------------
66
"""Tests for built-in feature filters."""
77

8+
import inspect
9+
import json
10+
import pickle
811
import unittest
912
import pytest
1013
from featuremanagement import FeatureManager, TargetingContext
1114

1215

1316
class TestDefaultFeatureFlags(unittest.TestCase):
17+
def test_targeting_context_field_defaults_match_construction(self) -> None:
18+
defaults = TargetingContext._field_defaults # pylint: disable=protected-access
19+
parameters = inspect.signature(TargetingContext).parameters
20+
assert defaults == {name: parameter.default for name, parameter in parameters.items()}
21+
22+
first = TargetingContext(**defaults)
23+
second = TargetingContext(**defaults)
24+
assert first == TargetingContext()
25+
first.groups.append("Admins")
26+
assert second.groups == []
27+
assert TargetingContext().groups == []
28+
29+
def test_targeting_context_fields_are_read_only(self) -> None:
30+
context = TargetingContext("Alice", ["Admins"])
31+
for field, value in (("user_id", "Bob"), ("groups", ["Users"]), ("extra", True)):
32+
with self.subTest(field=field), pytest.raises(AttributeError):
33+
setattr(context, field, value)
34+
assert context == TargetingContext("Alice", ["Admins"])
35+
36+
def test_targeting_context_serialization(self) -> None:
37+
context = TargetingContext("Alice", ["Admins"])
38+
assert json.dumps(context) == '["Alice", ["Admins"]]'
39+
for protocol in (0, pickle.HIGHEST_PROTOCOL):
40+
with self.subTest(protocol=protocol):
41+
restored = pickle.loads(pickle.dumps(context, protocol=protocol))
42+
self.assertIs(type(restored), TargetingContext)
43+
assert restored == context
44+
restored.groups.append("Users")
45+
assert context.groups == ["Admins"]
46+
47+
def test_targeting_context_helpers_preserve_subclass(self) -> None:
48+
groups = ["Admins"]
49+
context = TargetingContext._make(("Alice", groups))
50+
self.assertIs(type(context), TargetingContext)
51+
assert context == TargetingContext("Alice", groups)
52+
assert context.groups is groups
53+
54+
renamed = context._replace(user_id="Bob")
55+
self.assertIs(type(renamed), TargetingContext)
56+
assert renamed == TargetingContext("Bob", ["Admins"])
57+
assert renamed.groups is groups
58+
assert context == TargetingContext("Alice", ["Admins"])
59+
60+
def test_targeting_context_default_groups_are_independent(self) -> None:
61+
first = TargetingContext(user_id="Alice")
62+
second = TargetingContext(user_id="Bob")
63+
explicit_none = TargetingContext(groups=None)
64+
65+
first.groups.append("Admins")
66+
67+
assert first.groups == ["Admins"]
68+
assert second.groups == []
69+
assert explicit_none.groups == []
70+
assert TargetingContext().groups == []
71+
72+
def test_targeting_context_preserves_supplied_groups(self) -> None:
73+
groups: list[str] = []
74+
context = TargetingContext("Alice", groups)
75+
76+
context.groups.append("Admins")
77+
78+
assert context.user_id == "Alice"
79+
assert context.groups is groups
80+
assert groups == ["Admins"]
81+
1482
def test_invalid_feature_flags(self):
1583
with self.assertRaises(AttributeError):
1684
FeatureManager("")
@@ -53,6 +121,11 @@ def test_feature_manager_creation_with_targeting(self):
53121
# Brian is not enabled because he is not in Stage 2, group isn't looked at when user is targeted
54122
assert not feature_manager.is_enabled("Target", TargetingContext(user_id="Belle", groups=["Stage2"]))
55123

124+
first = TargetingContext("Belle")
125+
first.groups.append("Stage1")
126+
assert feature_manager.is_enabled("Target", first)
127+
assert not feature_manager.is_enabled("Target", TargetingContext("Belle"))
128+
56129
# method: feature_manager_creation
57130
def test_feature_manager_creation_with_time_window(self):
58131
feature_flags = {

‎tests/test_default_feature_flags_async.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,11 @@ async def test_feature_manager_creation_with_targeting(self):
5555
# Brian is not enabled because he is not in Stage 2, group isn't looked at when user is targeted
5656
assert not await feature_manager.is_enabled("Target", TargetingContext(user_id="Belle", groups=["Stage2"]))
5757

58+
first = TargetingContext("Belle")
59+
first.groups.append("Stage1")
60+
assert await feature_manager.is_enabled("Target", first)
61+
assert not await feature_manager.is_enabled("Target", TargetingContext("Belle"))
62+
5863
# method: feature_manager_creation
5964
@pytest.mark.asyncio
6065
async def test_feature_manager_creation_with_time_window(self):

0 commit comments

Comments
 (0)