Coverage for match_minutes.py: 97.30%

25 statements  

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

1"""Minutes played, derived from a live-scored match's timeline (SB-1227). 

2 

3Pure: no database, no clock. The caller supplies who started (recorded at 

4kickoff, SB-671) and the match's events; this works out who was on the pitch 

5for how long. 

6 

7Minutes are counted on the nominal match clock — `2 * half_duration` — not 

8wall time. Stoppage is ignored: a sub at 45+3 came on at 45, and a starter who 

9plays the whole match played 90, however long the referee added. 

10""" 

11 

12from collections.abc import Iterable 

13 

14 

15def compute_minutes_played( 

16 starter_ids: Iterable[int], 

17 events: Iterable[dict], 

18 half_duration: int, 

19) -> dict[int, int]: 

20 """Return minutes played for every player who appeared. 

21 

22 Args: 

23 starter_ids: players on the pitch at kickoff 

24 events: match events; only `substitution` (player_id on, player_out_id 

25 off) and `red_card` (player_id off) are read, each needing a 

26 `match_minute`. Deleted events must already be filtered out. 

27 half_duration: minutes per half 

28 

29 Returns: 

30 {player_id: minutes} for each starter and each player brought on — 

31 including a player brought on at the final whistle, who appeared for 0. 

32 """ 

33 full_time = 2 * half_duration 

34 on_since: dict[int, int] = dict.fromkeys(starter_ids, 0) 

35 minutes: dict[int, int] = dict.fromkeys(on_since, 0) 

36 

37 def clamp(minute: int) -> int: 

38 return max(0, min(minute, full_time)) 

39 

40 def take_off(player_id: int | None, minute: int) -> None: 

41 if player_id in on_since: 

42 minutes[player_id] += minute - on_since.pop(player_id) 

43 

44 timed = [e for e in events if e.get("match_minute") is not None] 

45 # Ties within a minute keep their recorded order. 

46 timed.sort(key=lambda e: (e["match_minute"], e.get("created_at") or "")) 

47 

48 for event in timed: 

49 minute = clamp(event["match_minute"]) 

50 if event.get("event_type") == "substitution": 

51 take_off(event.get("player_out_id"), minute) 

52 player_in = event.get("player_id") 

53 if player_in is not None and player_in not in on_since: 53 ↛ 48line 53 didn't jump to line 48 because the condition on line 53 was always true

54 on_since[player_in] = minute 

55 minutes.setdefault(player_in, 0) 

56 elif event.get("event_type") == "red_card": 

57 take_off(event.get("player_id"), minute) 

58 

59 for player_id in list(on_since): 

60 take_off(player_id, full_time) 

61 

62 return minutes