Coverage for celery_tasks/validation_tasks.py: 8.42%
61 statements
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 18:21 +0000
« prev ^ index » next coverage.py v7.10.6, created at 2026-11-30 18:21 +0000
1"""
2Validation Tasks
4Tasks for validating match data before processing.
5These ensure data quality and prevent invalid data from entering the database.
6"""
8import logging
9from datetime import datetime
10from typing import Any
12from celery_app import app
13from celery_tasks.tournament_filing import tournament_filing_errors
15logger = logging.getLogger(__name__)
18@app.task(name="celery_tasks.validation_tasks.validate_match_data")
19def validate_match_data(match_data: dict[str, Any]) -> dict[str, Any]:
20 """
21 Validate match data structure and contents.
23 Checks:
24 - Required fields are present
25 - Data types are correct
26 - Values are within acceptable ranges
27 - Dates are valid
28 - Team names are not empty
29 - Tournament fields, when present, can be filed
31 Args:
32 match_data: Dictionary containing match information
34 Returns:
35 Dict containing:
36 - valid: bool - Whether the data is valid
37 - errors: List[str] - List of validation errors (empty if valid)
38 - warnings: List[str] - List of warnings (data is still valid)
39 """
40 errors: list[str] = []
41 warnings: list[str] = []
43 # Required fields
44 required_fields = ["home_team", "away_team", "match_date", "season"]
45 for field in required_fields:
46 if field not in match_data or not match_data[field]:
47 errors.append(f"Missing required field: {field}")
49 # If required fields are missing, return early
50 if errors:
51 return {"valid": False, "errors": errors, "warnings": warnings}
53 # Validate team names
54 home_team = match_data["home_team"]
55 away_team = match_data["away_team"]
57 if not isinstance(home_team, str) or len(home_team.strip()) == 0:
58 errors.append("home_team must be a non-empty string")
60 if not isinstance(away_team, str) or len(away_team.strip()) == 0:
61 errors.append("away_team must be a non-empty string")
63 if home_team == away_team:
64 errors.append("home_team and away_team cannot be the same")
66 # Validate date
67 try:
68 match_date = match_data["match_date"]
69 if isinstance(match_date, str):
70 # Try to parse ISO format date
71 datetime.fromisoformat(match_date.replace("Z", "+00:00"))
72 elif not isinstance(match_date, datetime):
73 errors.append("match_date must be a string in ISO format or datetime object")
74 except (ValueError, AttributeError) as e:
75 errors.append(f"Invalid match_date format: {e}")
77 # Validate scores (if provided)
78 if "home_score" in match_data and match_data["home_score"] is not None:
79 try:
80 score = int(match_data["home_score"])
81 if score < 0:
82 errors.append("home_score cannot be negative")
83 except (ValueError, TypeError):
84 errors.append("home_score must be an integer")
86 if "away_score" in match_data and match_data["away_score"] is not None:
87 try:
88 score = int(match_data["away_score"])
89 if score < 0:
90 errors.append("away_score cannot be negative")
91 except (ValueError, TypeError):
92 errors.append("away_score must be an integer")
94 # Validate match status
95 valid_statuses = ["scheduled", "tbd", "live", "completed", "cancelled", "postponed"]
96 if "match_status" in match_data:
97 status = match_data["match_status"]
98 if status and status not in valid_statuses:
99 warnings.append(f"Unusual match_status: {status}. Expected one of: {valid_statuses}")
101 # Validate season format
102 season = match_data["season"]
103 if not isinstance(season, str):
104 errors.append("season must be a string")
105 elif len(season) < 4:
106 warnings.append(f"Unusual season format: {season}")
108 # Validate tournament fields (SB-1747). All optional; a message with none
109 # is a league message. Any of them without tournament_id is an error.
110 errors.extend(tournament_filing_errors(match_data))
112 # Log validation result
113 if errors:
114 logger.warning(f"Validation failed for match {home_team} vs {away_team}: {errors}")
115 elif warnings:
116 logger.info(f"Validation passed with warnings for {home_team} vs {away_team}: {warnings}")
117 else:
118 logger.debug(f"Validation passed for {home_team} vs {away_team}")
120 return {"valid": len(errors) == 0, "errors": errors, "warnings": warnings}