Coverage for constants/positions.py: 31.03%
21 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 18:53 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 18:53 +0000
1"""Player position taxonomy — backend mirror.
3KEEP IN SYNC with frontend/src/constants/positions.js (the frontend file is
4the display source of truth; tests/test_position_constants.py asserts parity
5by parsing it).
7A player's positions are an ORDERED list of specific codes; the first entry
8is their primary position. Each code belongs to exactly one broad group.
9"""
11from typing import Annotated
13from pydantic import AfterValidator
15POSITION_GROUPS: dict[str, list[str]] = {
16 "GK": ["GK"],
17 "DEF": ["CB", "LB", "RB", "LWB", "RWB"],
18 "MID": ["CDM", "CM", "CAM", "LM", "RM"],
19 "FWD": ["LW", "RW", "ST", "CF"],
20}
22VALID_POSITIONS: frozenset[str] = frozenset(
23 code for codes in POSITION_GROUPS.values() for code in codes
24)
26# Old side-specific codes that may arrive from stale clients.
27LEGACY_POSITION_MAP: dict[str, str] = {
28 "LCB": "CB",
29 "RCB": "CB",
30 "LCM": "CM",
31 "RCM": "CM",
32}
34_POSITION_NAMES: dict[str, str] = {
35 "GK": "Goalkeeper",
36 "CB": "Center Back",
37 "LB": "Left Back",
38 "RB": "Right Back",
39 "LWB": "Left Wing Back",
40 "RWB": "Right Wing Back",
41 "CDM": "Defensive Midfielder",
42 "CM": "Central Midfielder",
43 "CAM": "Attacking Midfielder",
44 "LM": "Left Midfielder",
45 "RM": "Right Midfielder",
46 "LW": "Left Winger",
47 "RW": "Right Winger",
48 "ST": "Striker",
49 "CF": "Center Forward",
50}
52# API response shape for GET /api/positions (full_name/abbreviation keys kept
53# for compatibility with pre-taxonomy clients; group is new).
54PLAYER_POSITIONS: list[dict[str, str]] = [
55 {"full_name": _POSITION_NAMES[code], "abbreviation": code, "group": group}
56 for group, codes in POSITION_GROUPS.items()
57 for code in codes
58]
61def normalize_positions(positions: list[str] | None) -> list[str] | None:
62 """Validate and normalize an ordered positions list.
64 - Maps legacy codes to their canonical replacement.
65 - Deduplicates while preserving order (first occurrence wins).
66 - Raises ValueError on unknown codes.
67 Returns None for None, [] for [].
68 """
69 if positions is None:
70 return None
71 seen: set[str] = set()
72 normalized: list[str] = []
73 for raw in positions:
74 code = LEGACY_POSITION_MAP.get(raw, raw)
75 if code not in VALID_POSITIONS:
76 raise ValueError(
77 f"Invalid position code: {raw!r}. Valid codes: {sorted(VALID_POSITIONS)}"
78 )
79 if code not in seen:
80 seen.add(code)
81 normalized.append(code)
82 return normalized
85# Shared Pydantic field type: use `positions: Positions = None` on any model
86# with a positions field so validation can't be forgotten.
87Positions = Annotated[list[str] | None, AfterValidator(normalize_positions)]