Coverage for user_preferences.py: 100.00%

20 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2026-11-30 18:53 +0000

1"""Per-account user preferences (SB-1286). 

2 

3Stored as one jsonb object on ``user_profiles.preferences``. This module owns 

4its shape: a new preference is a field on ``UserPreferences``, not a 

5migration. Absent key means "no preference" - readers fall through to their 

6own default, never to a zero value. 

7""" 

8 

9from collections.abc import Iterable 

10from typing import Any 

11 

12from pydantic import BaseModel, ConfigDict 

13 

14 

15class UserPreferences(BaseModel): 

16 """A partial preferences update. Only fields the client sends are applied; 

17 an explicit ``null`` clears that preference.""" 

18 

19 model_config = ConfigDict(extra="forbid") 

20 

21 default_age_group_id: int | None = None 

22 

23 

24class UnknownAgeGroupError(ValueError): 

25 """The requested default age group does not exist.""" 

26 

27 

28def read_preferences(raw: Any) -> dict: 

29 """Preferences as stored, or ``{}`` for a row that predates the column.""" 

30 return dict(raw) if isinstance(raw, dict) else {} 

31 

32 

33def merge_preferences(current: Any, update: UserPreferences, known_age_group_ids: Iterable[int]) -> dict: 

34 """Apply ``update`` on top of the stored preferences. 

35 

36 Keys the client did not send are kept; ``None`` removes the key. 

37 Raises UnknownAgeGroupError for an age group id that does not exist. 

38 """ 

39 changes = update.model_dump(exclude_unset=True) 

40 

41 age_group_id = changes.get("default_age_group_id") 

42 if age_group_id is not None and age_group_id not in set(known_age_group_ids): 

43 raise UnknownAgeGroupError(f"Unknown age group: {age_group_id}") 

44 

45 merged = read_preferences(current) 

46 for key, value in changes.items(): 

47 if value is None: 

48 merged.pop(key, None) 

49 else: 

50 merged[key] = value 

51 return merged