Skip to content
Merged
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
10 changes: 0 additions & 10 deletions CHANGELOG.md

This file was deleted.

34 changes: 25 additions & 9 deletions featuremanagement/_models/_targeting_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,40 @@
# --------------------------------------------------------------------------
"""Targeting context model for user and group targeting."""

from typing import NamedTuple, Sequence
from typing import NamedTuple


class TargetingContext(NamedTuple):
"""
Represents the context for targeting a feature flag.
"""
class _TargetingContextTuple(NamedTuple):
"""Tuple fields shared by targeting contexts."""

user_id: str = ""
user_id: str
"""
The user ID.
:type: str
"""

groups: Sequence[str] = ()
groups: list[str]
"""
The users groups.
The user's groups.
:type: Sequence[str]
:type: list[str]
"""


class TargetingContext(_TargetingContextTuple):
"""
Represents the context for targeting a feature flag.
:param str user_id: The user ID.
:param groups: The user's groups. If omitted or None, a new empty list is created.
:type groups: list[str] or None
"""

__slots__ = ()
Comment thread
avanigupta marked this conversation as resolved.
Resolved

_field_defaults: dict[str, str | None] = {"user_id": "", "groups": None}

def __new__(cls, user_id: str = "", groups: list[str] | None = None) -> "TargetingContext":
Comment thread
mrm9084 marked this conversation as resolved.
Resolved
# Ensures that each instance gets its own list for groups, even if the default is used.
return super().__new__(cls, user_id, groups if groups is not None else [])
73 changes: 73 additions & 0 deletions tests/test_default_feature_flags.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,80 @@
# --------------------------------------------------------------------------
"""Tests for built-in feature filters."""

import inspect
import json
import pickle
import unittest
import pytest
from featuremanagement import FeatureManager, TargetingContext


class TestDefaultFeatureFlags(unittest.TestCase):
def test_targeting_context_field_defaults_match_construction(self) -> None:
defaults = TargetingContext._field_defaults # pylint: disable=protected-access
parameters = inspect.signature(TargetingContext).parameters
assert defaults == {name: parameter.default for name, parameter in parameters.items()}

first = TargetingContext(**defaults)
second = TargetingContext(**defaults)
assert first == TargetingContext()
first.groups.append("Admins")
assert second.groups == []
assert TargetingContext().groups == []

def test_targeting_context_fields_are_read_only(self) -> None:
context = TargetingContext("Alice", ["Admins"])
for field, value in (("user_id", "Bob"), ("groups", ["Users"]), ("extra", True)):
with self.subTest(field=field), pytest.raises(AttributeError):
setattr(context, field, value)
assert context == TargetingContext("Alice", ["Admins"])

def test_targeting_context_serialization(self) -> None:
context = TargetingContext("Alice", ["Admins"])
assert json.dumps(context) == '["Alice", ["Admins"]]'
for protocol in (0, pickle.HIGHEST_PROTOCOL):
with self.subTest(protocol=protocol):
restored = pickle.loads(pickle.dumps(context, protocol=protocol))
self.assertIs(type(restored), TargetingContext)
assert restored == context
restored.groups.append("Users")
assert context.groups == ["Admins"]

def test_targeting_context_helpers_preserve_subclass(self) -> None:
groups = ["Admins"]
context = TargetingContext._make(("Alice", groups))
self.assertIs(type(context), TargetingContext)
assert context == TargetingContext("Alice", groups)
assert context.groups is groups

renamed = context._replace(user_id="Bob")
self.assertIs(type(renamed), TargetingContext)
assert renamed == TargetingContext("Bob", ["Admins"])
assert renamed.groups is groups
assert context == TargetingContext("Alice", ["Admins"])

def test_targeting_context_default_groups_are_independent(self) -> None:
first = TargetingContext(user_id="Alice")
second = TargetingContext(user_id="Bob")
explicit_none = TargetingContext(groups=None)

first.groups.append("Admins")

assert first.groups == ["Admins"]
assert second.groups == []
assert explicit_none.groups == []
assert TargetingContext().groups == []

def test_targeting_context_preserves_supplied_groups(self) -> None:
groups: list[str] = []
context = TargetingContext("Alice", groups)

context.groups.append("Admins")

assert context.user_id == "Alice"
assert context.groups is groups
assert groups == ["Admins"]

def test_invalid_feature_flags(self):
with self.assertRaises(AttributeError):
FeatureManager("")
Expand Down Expand Up @@ -53,6 +121,11 @@ def test_feature_manager_creation_with_targeting(self):
# Brian is not enabled because he is not in Stage 2, group isn't looked at when user is targeted
assert not feature_manager.is_enabled("Target", TargetingContext(user_id="Belle", groups=["Stage2"]))

first = TargetingContext("Belle")
first.groups.append("Stage1")
assert feature_manager.is_enabled("Target", first)
assert not feature_manager.is_enabled("Target", TargetingContext("Belle"))

# method: feature_manager_creation
def test_feature_manager_creation_with_time_window(self):
feature_flags = {
Expand Down
5 changes: 5 additions & 0 deletions tests/test_default_feature_flags_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ async def test_feature_manager_creation_with_targeting(self):
# Brian is not enabled because he is not in Stage 2, group isn't looked at when user is targeted
assert not await feature_manager.is_enabled("Target", TargetingContext(user_id="Belle", groups=["Stage2"]))

first = TargetingContext("Belle")
first.groups.append("Stage1")
assert await feature_manager.is_enabled("Target", first)
assert not await feature_manager.is_enabled("Target", TargetingContext("Belle"))

# method: feature_manager_creation
@pytest.mark.asyncio
async def test_feature_manager_creation_with_time_window(self):
Expand Down
Loading