move test files to test folder to clean up repo

This commit is contained in:
Chuck
2025-07-22 20:01:39 -05:00
parent f50c457dc4
commit 3ab28e8201
10 changed files with 0 additions and 0 deletions

83
test/ChuckBuilds.py Normal file
View File

@@ -0,0 +1,83 @@
#!/usr/bin/env python3
import time
import sys
from rgbmatrix import RGBMatrix, RGBMatrixOptions
from PIL import Image, ImageDraw, ImageFont
def main():
# Matrix configuration
options = RGBMatrixOptions()
options.rows = 32
options.cols = 64
options.chain_length = 2
options.parallel = 1
options.hardware_mapping = 'adafruit-hat-pwm'
options.brightness = 90
options.pwm_bits = 10
options.pwm_lsb_nanoseconds = 150
options.led_rgb_sequence = 'RGB'
options.pixel_mapper_config = ''
options.row_address_type = 0
options.multiplexing = 0
options.disable_hardware_pulsing = False
options.show_refresh_rate = False
options.limit_refresh_rate_hz = 90
options.gpio_slowdown = 2
# Initialize the matrix
matrix = RGBMatrix(options=options)
canvas = matrix.CreateFrameCanvas()
# Load the PressStart2P font
font_path = "assets/fonts/PressStart2P-Regular.ttf"
font_size = 1
font = ImageFont.truetype(font_path, font_size)
# Create a PIL image and drawing context
image = Image.new('RGB', (matrix.width, matrix.height))
draw = ImageDraw.Draw(image)
# Text to display
text = " Chuck Builds"
# Find the largest font size that fits
min_font_size = 6
max_font_size = 36
font_size = min_font_size
while font_size <= max_font_size:
font = ImageFont.truetype(font_path, font_size)
bbox = draw.textbbox((0, 0), text, font=font)
text_width = bbox[2] - bbox[0]
text_height = bbox[3] - bbox[1]
if text_width <= matrix.width and text_height <= matrix.height:
font_size += 1
else:
font_size -= 1
font = ImageFont.truetype(font_path, font_size)
break
# Center the text
x = (matrix.width - text_width) // 2
y = (matrix.height - text_height) // 2
# Ensure text is fully visible
x = max(0, min(x, matrix.width - text_width))
y = max(0, min(y, matrix.height - text_height))
# Draw the text
draw.text((x, y), text, font=font, fill=(255, 255, 255))
# Display the image
canvas.SetImage(image)
matrix.SwapOnVSync(canvas)
# Keep the script running
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
matrix.Clear()
sys.exit(0)
if __name__ == "__main__":
main()

143
test/check_espn_api.py Normal file
View File

@@ -0,0 +1,143 @@
#!/usr/bin/env python3
"""
Script to check ESPN API responses for broadcast information
"""
import requests
import json
from datetime import datetime, timedelta
import sys
def check_espn_api():
"""Check ESPN API responses for broadcast information"""
# Test different sports and leagues
test_urls = [
# MLB
"https://site.api.espn.com/apis/site/v2/sports/baseball/mlb/scoreboard",
# NFL
"https://site.api.espn.com/apis/site/v2/sports/football/nfl/scoreboard",
# NBA
"https://site.api.espn.com/apis/site/v2/sports/basketball/nba/scoreboard",
# College Football
"https://site.api.espn.com/apis/site/v2/sports/football/college-football/scoreboard",
]
today = datetime.now().strftime("%Y%m%d")
for url in test_urls:
print(f"\n{'='*60}")
print(f"Checking: {url}")
print(f"{'='*60}")
try:
# Add date parameter
params = {'dates': today}
response = requests.get(url, params=params, timeout=10)
response.raise_for_status()
data = response.json()
events = data.get('events', [])
print(f"Found {len(events)} events")
# Check first few events for broadcast info
for i, event in enumerate(events[:3]): # Check first 3 events
print(f"\n--- Event {i+1} ---")
print(f"Event ID: {event.get('id')}")
print(f"Name: {event.get('name', 'N/A')}")
print(f"Status: {event.get('status', {}).get('type', {}).get('name', 'N/A')}")
# Check competitions for broadcast info
competitions = event.get('competitions', [])
if competitions:
competition = competitions[0]
broadcasts = competition.get('broadcasts', [])
print(f"Broadcasts found: {len(broadcasts)}")
for j, broadcast in enumerate(broadcasts):
print(f" Broadcast {j+1}:")
print(f" Raw broadcast data: {broadcast}")
# Check media info
media = broadcast.get('media', {})
print(f" Media data: {media}")
# Check for shortName
short_name = media.get('shortName')
if short_name:
print(f" ✓ shortName: '{short_name}'")
else:
print(f" ✗ No shortName found")
# Check for other possible broadcast fields
for key in ['name', 'type', 'callLetters', 'id']:
value = media.get(key)
if value:
print(f" {key}: '{value}'")
else:
print("No competitions found")
except Exception as e:
print(f"Error fetching {url}: {e}")
def check_specific_game():
"""Check a specific game that should have broadcast info"""
print(f"\n{'='*60}")
print("Checking for games with known broadcast info")
print(f"{'='*60}")
# Check NFL games (more likely to have broadcast info)
url = "https://site.api.espn.com/apis/site/v2/sports/football/nfl/scoreboard"
today = datetime.now().strftime("%Y%m%d")
try:
params = {'dates': today}
response = requests.get(url, params=params, timeout=10)
response.raise_for_status()
data = response.json()
events = data.get('events', [])
print(f"Found {len(events)} NFL events")
# Look for events with broadcast info
events_with_broadcasts = []
for event in events:
competitions = event.get('competitions', [])
if competitions:
broadcasts = competitions[0].get('broadcasts', [])
if broadcasts:
events_with_broadcasts.append(event)
print(f"Events with broadcast info: {len(events_with_broadcasts)}")
for i, event in enumerate(events_with_broadcasts[:2]): # Show first 2
print(f"\n--- Event with Broadcast {i+1} ---")
print(f"Event ID: {event.get('id')}")
print(f"Name: {event.get('name', 'N/A')}")
competitions = event.get('competitions', [])
if competitions:
broadcasts = competitions[0].get('broadcasts', [])
for j, broadcast in enumerate(broadcasts):
print(f" Broadcast {j+1}:")
media = broadcast.get('media', {})
print(f" Media: {media}")
# Show all possible broadcast-related fields
for key, value in media.items():
print(f" {key}: {value}")
except Exception as e:
print(f"Error checking specific games: {e}")
if __name__ == "__main__":
print("ESPN API Broadcast Information Check")
print("This script will check what broadcast information is available in ESPN API responses")
check_espn_api()
check_specific_game()
print(f"\n{'='*60}")
print("Check complete. Look for 'shortName' fields in the broadcast data.")
print("This is what the odds ticker uses to map to broadcast logos.")

51
test/run_font_test.py Normal file
View File

@@ -0,0 +1,51 @@
#!/usr/bin/env python3
import time
import json
import logging
from src.display_manager import DisplayManager
from src.font_test_manager import FontTestManager
from src.config_manager import ConfigManager
# Configure logging to match main application
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s.%(msecs)03d - %(levelname)s:%(name)s:%(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)
def main():
"""Run the font test display."""
try:
# Load configuration
config_manager = ConfigManager()
config = config_manager.load_config()
# Initialize display manager
display_manager = DisplayManager(config)
# Initialize font test manager
font_test_manager = FontTestManager(config, display_manager)
logger.info("Starting static font test display. Press Ctrl+C to exit.")
# Display all font sizes at once
font_test_manager.display()
# Keep the display running until user interrupts
try:
while True:
time.sleep(1) # Sleep to prevent CPU hogging
except KeyboardInterrupt:
logger.info("Font test display stopped by user.")
finally:
# Clean up
display_manager.clear()
display_manager.cleanup()
except Exception as e:
logger.error(f"Error running font test display: {e}", exc_info=True)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,196 @@
#!/usr/bin/env python3
"""
Simple broadcast logo test script
Tests the core broadcast logo functionality without complex dependencies
"""
import os
import sys
import logging
from PIL import Image
# Set up logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
def test_broadcast_logo_files():
"""Test if broadcast logo files exist and can be loaded"""
print("=== Testing Broadcast Logo Files ===")
broadcast_logos_dir = "assets/broadcast_logos"
if not os.path.exists(broadcast_logos_dir):
print(f"ERROR: Broadcast logos directory not found: {broadcast_logos_dir}")
return False
print(f"Found broadcast logos directory: {broadcast_logos_dir}")
# List all files in the directory
files = os.listdir(broadcast_logos_dir)
print(f"Files in directory: {files}")
# Test a few key logos
test_logos = ["espn", "fox", "cbs", "nbc", "tbs", "tnt"]
for logo_name in test_logos:
logo_path = os.path.join(broadcast_logos_dir, f"{logo_name}.png")
if os.path.exists(logo_path):
try:
logo = Image.open(logo_path)
print(f"{logo_name}.png - Size: {logo.size}")
except Exception as e:
print(f"{logo_name}.png - Error loading: {e}")
else:
print(f"{logo_name}.png - File not found")
return True
def test_broadcast_logo_mapping():
"""Test the broadcast logo mapping logic"""
print("\n=== Testing Broadcast Logo Mapping ===")
# Define the broadcast logo mapping (copied from odds_ticker_manager.py)
BROADCAST_LOGO_MAP = {
"ACC Network": "accn",
"ACCN": "accn",
"ABC": "abc",
"BTN": "btn",
"CBS": "cbs",
"CBSSN": "cbssn",
"CBS Sports Network": "cbssn",
"ESPN": "espn",
"ESPN2": "espn2",
"ESPN3": "espn3",
"ESPNU": "espnu",
"ESPNEWS": "espn",
"ESPN+": "espn",
"ESPN Plus": "espn",
"FOX": "fox",
"FS1": "fs1",
"FS2": "fs2",
"MLBN": "mlbn",
"MLB Network": "mlbn",
"NBC": "nbc",
"NFLN": "nfln",
"NFL Network": "nfln",
"PAC12": "pac12n",
"Pac-12 Network": "pac12n",
"SECN": "espn-sec-us",
"TBS": "tbs",
"TNT": "tnt",
"truTV": "tru",
"Peacock": "nbc",
"Paramount+": "cbs",
"Hulu": "espn",
"Disney+": "espn",
"Apple TV+": "nbc"
}
# Test various broadcast names that might appear in the API
test_cases = [
["ESPN"],
["FOX"],
["CBS"],
["NBC"],
["ESPN2"],
["FS1"],
["ESPNEWS"],
["ESPN+"],
["ESPN Plus"],
["Peacock"],
["Paramount+"],
["ABC"],
["TBS"],
["TNT"],
["Unknown Channel"],
[]
]
for broadcast_names in test_cases:
print(f"\nTesting broadcast names: {broadcast_names}")
# Simulate the logo mapping logic
logo_name = None
sorted_keys = sorted(BROADCAST_LOGO_MAP.keys(), key=len, reverse=True)
for b_name in broadcast_names:
for key in sorted_keys:
if key in b_name:
logo_name = BROADCAST_LOGO_MAP[key]
print(f" Matched '{key}' to '{logo_name}' for '{b_name}'")
break
if logo_name:
break
print(f" Final mapped logo name: '{logo_name}'")
if logo_name:
# Test loading the actual logo
logo_path = os.path.join('assets', 'broadcast_logos', f"{logo_name}.png")
print(f" Logo path: {logo_path}")
print(f" File exists: {os.path.exists(logo_path)}")
if os.path.exists(logo_path):
try:
logo = Image.open(logo_path)
print(f" ✓ Successfully loaded logo: {logo.size} pixels")
except Exception as e:
print(f" ✗ Error loading logo: {e}")
else:
print(" ✗ Logo file not found!")
def test_simple_image_creation():
"""Test creating a simple image with a broadcast logo"""
print("\n=== Testing Simple Image Creation ===")
try:
# Create a simple test image
width, height = 64, 32
image = Image.new('RGB', (width, height), color=(0, 0, 0))
# Try to load and paste a broadcast logo
logo_path = os.path.join('assets', 'broadcast_logos', 'espn.png')
if os.path.exists(logo_path):
logo = Image.open(logo_path)
print(f"Loaded ESPN logo: {logo.size}")
# Resize logo to fit
logo_height = height - 4
ratio = logo_height / logo.height
logo_width = int(logo.width * ratio)
logo = logo.resize((logo_width, logo_height), Image.Resampling.LANCZOS)
# Paste logo in the center
x = (width - logo_width) // 2
y = (height - logo_height) // 2
image.paste(logo, (x, y), logo if logo.mode == 'RGBA' else None)
# Save the test image
output_path = 'test_simple_broadcast_logo.png'
image.save(output_path)
print(f"✓ Created test image: {output_path}")
else:
print("✗ ESPN logo not found")
except Exception as e:
print(f"✗ Error creating test image: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
print("=== Simple Broadcast Logo Test ===\n")
# Test 1: Check if broadcast logo files exist
test_broadcast_logo_files()
# Test 2: Test broadcast logo mapping
test_broadcast_logo_mapping()
# Test 3: Test simple image creation
test_simple_image_creation()
print("\n=== Test Complete ===")
print("Check the generated PNG files to see if broadcast logos are working.")

View File

@@ -0,0 +1,155 @@
#!/usr/bin/env python3
"""
Test script to debug broadcast logo display in odds ticker
"""
import os
import sys
import logging
from PIL import Image
# Add the src directory to the path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
from odds_ticker_manager import OddsTickerManager
from display_manager import DisplayManager
from config_manager import ConfigManager
# Set up logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
def test_broadcast_logo_loading():
"""Test broadcast logo loading functionality"""
# Load config
config_manager = ConfigManager()
config = config_manager.get_config()
# Create a mock display manager
class MockDisplayManager:
def __init__(self):
self.matrix = type('Matrix', (), {'width': 64, 'height': 32})()
self.image = None
self.draw = None
def update_display(self):
pass
display_manager = MockDisplayManager()
# Create odds ticker manager
odds_ticker = OddsTickerManager(config, display_manager)
# Test broadcast logo mapping
print("Testing broadcast logo mapping...")
test_broadcast_names = [
["ESPN"],
["FOX"],
["CBS"],
["NBC"],
["ESPN2"],
["FS1"],
["ESPNEWS"],
["ABC"],
["TBS"],
["TNT"],
["Unknown Channel"],
[]
]
for broadcast_names in test_broadcast_names:
print(f"\nTesting broadcast names: {broadcast_names}")
# Simulate the logo mapping logic
logo_name = None
sorted_keys = sorted(odds_ticker.BROADCAST_LOGO_MAP.keys(), key=len, reverse=True)
for b_name in broadcast_names:
for key in sorted_keys:
if key in b_name:
logo_name = odds_ticker.BROADCAST_LOGO_MAP[key]
break
if logo_name:
break
print(f"Mapped logo name: '{logo_name}'")
if logo_name:
# Test loading the actual logo
logo_path = os.path.join('assets', 'broadcast_logos', f"{logo_name}.png")
print(f"Logo path: {logo_path}")
print(f"File exists: {os.path.exists(logo_path)}")
if os.path.exists(logo_path):
try:
logo = Image.open(logo_path)
print(f"Successfully loaded logo: {logo.size} pixels")
except Exception as e:
print(f"Error loading logo: {e}")
else:
print("Logo file not found!")
def test_game_with_broadcast_info():
"""Test creating a game display with broadcast info"""
# Load config
config_manager = ConfigManager()
config = config_manager.get_config()
# Create a mock display manager
class MockDisplayManager:
def __init__(self):
self.matrix = type('Matrix', (), {'width': 64, 'height': 32})()
self.image = None
self.draw = None
def update_display(self):
pass
display_manager = MockDisplayManager()
# Create odds ticker manager
odds_ticker = OddsTickerManager(config, display_manager)
# Create a test game with broadcast info
test_game = {
'id': 'test_game_1',
'home_team': 'TB',
'away_team': 'BOS',
'home_team_name': 'Tampa Bay Rays',
'away_team_name': 'Boston Red Sox',
'start_time': '2024-01-15T19:00:00Z',
'home_record': '95-67',
'away_record': '78-84',
'broadcast_info': ['ESPN'],
'logo_dir': 'assets/sports/mlb_logos'
}
print(f"\nTesting game display with broadcast info: {test_game['broadcast_info']}")
try:
# Create the game display
game_image = odds_ticker._create_game_display(test_game)
print(f"Successfully created game image: {game_image.size} pixels")
# Save the image for inspection
output_path = 'test_broadcast_logo_output.png'
game_image.save(output_path)
print(f"Saved test image to: {output_path}")
except Exception as e:
print(f"Error creating game display: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
print("=== Testing Broadcast Logo Functionality ===\n")
# Test 1: Logo loading
test_broadcast_logo_loading()
# Test 2: Game display with broadcast info
test_game_with_broadcast_info()
print("\n=== Test Complete ===")

View File

@@ -0,0 +1,218 @@
#!/usr/bin/env python3
"""
Diagnostic script for broadcast logo display on Raspberry Pi
Run this on the Pi to test broadcast logo functionality
"""
import os
import sys
import logging
from PIL import Image
from datetime import datetime
# Add the src directory to the path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
# Import with proper error handling
try:
from odds_ticker_manager import OddsTickerManager
from config_manager import ConfigManager
# Create a mock display manager to avoid hardware dependencies
class MockDisplayManager:
def __init__(self):
self.matrix = type('Matrix', (), {'width': 64, 'height': 32})()
self.image = None
self.draw = None
def update_display(self):
pass
display_manager = MockDisplayManager()
except ImportError as e:
print(f"Import error: {e}")
print("This script needs to be run from the LEDMatrix directory")
sys.exit(1)
# Set up logging to see what's happening
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
def test_broadcast_logo_files():
"""Test if broadcast logo files exist and can be loaded"""
print("=== Testing Broadcast Logo Files ===")
broadcast_logos_dir = "assets/broadcast_logos"
if not os.path.exists(broadcast_logos_dir):
print(f"ERROR: Broadcast logos directory not found: {broadcast_logos_dir}")
return False
print(f"Found broadcast logos directory: {broadcast_logos_dir}")
# Test a few key logos
test_logos = ["espn", "fox", "cbs", "nbc", "tbs", "tnt"]
for logo_name in test_logos:
logo_path = os.path.join(broadcast_logos_dir, f"{logo_name}.png")
if os.path.exists(logo_path):
try:
logo = Image.open(logo_path)
print(f"{logo_name}.png - Size: {logo.size}")
except Exception as e:
print(f"{logo_name}.png - Error loading: {e}")
else:
print(f"{logo_name}.png - File not found")
return True
def test_broadcast_logo_mapping():
"""Test the broadcast logo mapping logic"""
print("\n=== Testing Broadcast Logo Mapping ===")
# Load config
config_manager = ConfigManager()
config = config_manager.load_config()
# Create odds ticker manager
odds_ticker = OddsTickerManager(config, display_manager)
# Test various broadcast names that might appear in the API
test_cases = [
["ESPN"],
["FOX"],
["CBS"],
["NBC"],
["ESPN2"],
["FS1"],
["ESPNEWS"],
["ESPN+"],
["ESPN Plus"],
["Peacock"],
["Paramount+"],
["ABC"],
["TBS"],
["TNT"],
["Unknown Channel"],
[]
]
for broadcast_names in test_cases:
print(f"\nTesting broadcast names: {broadcast_names}")
# Simulate the logo mapping logic
logo_name = None
sorted_keys = sorted(odds_ticker.BROADCAST_LOGO_MAP.keys(), key=len, reverse=True)
for b_name in broadcast_names:
for key in sorted_keys:
if key in b_name:
logo_name = odds_ticker.BROADCAST_LOGO_MAP[key]
break
if logo_name:
break
print(f" Mapped logo name: '{logo_name}'")
if logo_name:
# Test loading the actual logo
logo_path = os.path.join('assets', 'broadcast_logos', f"{logo_name}.png")
print(f" Logo path: {logo_path}")
print(f" File exists: {os.path.exists(logo_path)}")
if os.path.exists(logo_path):
try:
logo = Image.open(logo_path)
print(f" ✓ Successfully loaded logo: {logo.size} pixels")
except Exception as e:
print(f" ✗ Error loading logo: {e}")
else:
print(" ✗ Logo file not found!")
def test_game_display_with_broadcast():
"""Test creating a game display with broadcast info"""
print("\n=== Testing Game Display with Broadcast Info ===")
# Load config
config_manager = ConfigManager()
config = config_manager.load_config()
# Create odds ticker manager
odds_ticker = OddsTickerManager(config, display_manager)
# Test cases with different broadcast info
test_games = [
{
'id': 'test_game_1',
'home_team': 'TB',
'away_team': 'BOS',
'home_team_name': 'Tampa Bay Rays',
'away_team_name': 'Boston Red Sox',
'start_time': datetime.fromisoformat('2024-01-15T19:00:00+00:00'),
'home_record': '95-67',
'away_record': '78-84',
'broadcast_info': ['ESPN'],
'logo_dir': 'assets/sports/mlb_logos'
},
{
'id': 'test_game_2',
'home_team': 'NYY', # Changed from NY to NYY for better logo matching
'away_team': 'LAD', # Changed from LA to LAD for better logo matching
'home_team_name': 'New York Yankees',
'away_team_name': 'Los Angeles Dodgers',
'start_time': datetime.fromisoformat('2024-01-15T20:00:00+00:00'),
'home_record': '82-80',
'away_record': '100-62',
'broadcast_info': ['FOX'],
'logo_dir': 'assets/sports/mlb_logos'
},
{
'id': 'test_game_3',
'home_team': 'CHC', # Changed from CHI to CHC for better logo matching
'away_team': 'MIA',
'home_team_name': 'Chicago Cubs',
'away_team_name': 'Miami Marlins',
'start_time': datetime.fromisoformat('2024-01-15T21:00:00+00:00'),
'home_record': '83-79',
'away_record': '84-78',
'broadcast_info': [], # No broadcast info
'logo_dir': 'assets/sports/mlb_logos'
}
]
for i, test_game in enumerate(test_games):
print(f"\n--- Test Game {i+1}: {test_game['away_team']} @ {test_game['home_team']} ---")
print(f"Broadcast info: {test_game['broadcast_info']}")
try:
# Create the game display
game_image = odds_ticker._create_game_display(test_game)
print(f"✓ Successfully created game image: {game_image.size} pixels")
# Save the image for inspection
output_path = f'test_broadcast_logo_output_{i+1}.png'
game_image.save(output_path)
print(f"✓ Saved test image to: {output_path}")
except Exception as e:
print(f"✗ Error creating game display: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
print("=== Broadcast Logo Diagnostic Script ===\n")
# Test 1: Check if broadcast logo files exist
test_broadcast_logo_files()
# Test 2: Test broadcast logo mapping
test_broadcast_logo_mapping()
# Test 3: Test game display with broadcast info
test_game_display_with_broadcast()
print("\n=== Diagnostic Complete ===")
print("Check the generated PNG files to see if broadcast logos are being included.")

69
test/test_mlb_api.py Normal file
View File

@@ -0,0 +1,69 @@
#!/usr/bin/env python3
"""
Test script to check MLB API directly
"""
import requests
import json
from datetime import datetime, timedelta, timezone
def test_mlb_api():
"""Test the MLB API directly to see what games are available."""
print("Testing MLB API directly...")
# Get dates for the next 7 days
now = datetime.now(timezone.utc)
dates = []
for i in range(8): # Today + 7 days
date = now + timedelta(days=i)
dates.append(date.strftime("%Y%m%d"))
print(f"Checking dates: {dates}")
for date in dates:
try:
url = f"https://site.api.espn.com/apis/site/v2/sports/baseball/mlb/scoreboard?dates={date}"
print(f"\nFetching MLB games for date: {date}")
print(f"URL: {url}")
response = requests.get(url, timeout=10)
response.raise_for_status()
data = response.json()
events = data.get('events', [])
print(f"Found {len(events)} events for MLB on {date}")
for event in events:
game_id = event['id']
status = event['status']['type']['name'].lower()
game_time = datetime.fromisoformat(event['date'].replace('Z', '+00:00'))
print(f" Game {game_id}:")
print(f" Status: {status}")
print(f" Time: {game_time}")
if status in ['scheduled', 'pre-game']:
# Get team information
competitors = event['competitions'][0]['competitors']
home_team = next(c for c in competitors if c['homeAway'] == 'home')
away_team = next(c for c in competitors if c['homeAway'] == 'away')
home_abbr = home_team['team']['abbreviation']
away_abbr = away_team['team']['abbreviation']
print(f" Teams: {away_abbr} @ {home_abbr}")
# Check if it's in the next 7 days
if now <= game_time <= now + timedelta(days=7):
print(f" ✅ IN RANGE (next 7 days)")
else:
print(f" ❌ OUT OF RANGE")
else:
print(f" ❌ Status '{status}' - not upcoming")
except Exception as e:
print(f"Error fetching MLB games for date {date}: {e}")
if __name__ == "__main__":
test_mlb_api()

View File

@@ -0,0 +1,110 @@
#!/usr/bin/env python3
"""
Test script for the new broadcast extraction logic
"""
import sys
import os
# Add the src directory to the path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
from odds_ticker_manager import OddsTickerManager
from config_manager import ConfigManager
def test_broadcast_extraction():
"""Test the new broadcast extraction logic"""
# Load config
config_manager = ConfigManager()
config = config_manager.load_config()
# Create a mock display manager
class MockDisplayManager:
def __init__(self):
self.matrix = type('Matrix', (), {'width': 64, 'height': 32})()
self.image = None
self.draw = None
def update_display(self):
pass
display_manager = MockDisplayManager()
# Create odds ticker manager
odds_ticker = OddsTickerManager(config, display_manager)
# Test the broadcast extraction logic with sample data from the API
test_broadcasts = [
# Sample from the API response
[
{'market': 'away', 'names': ['MLB.TV', 'MAS+', 'MASN2']},
{'market': 'home', 'names': ['CLEGuardians.TV']}
],
[
{'market': 'away', 'names': ['MLB.TV', 'FanDuel SN DET']},
{'market': 'home', 'names': ['SportsNet PIT']}
],
[
{'market': 'away', 'names': ['MLB.TV', 'Padres.TV']},
{'market': 'home', 'names': ['FanDuel SN FL']}
],
# Test with old format too
[
{'media': {'shortName': 'ESPN'}},
{'media': {'shortName': 'FOX'}}
]
]
for i, broadcasts in enumerate(test_broadcasts):
print(f"\n--- Test Case {i+1} ---")
print(f"Input broadcasts: {broadcasts}")
# Simulate the extraction logic
broadcast_info = []
for broadcast in broadcasts:
if 'names' in broadcast:
# New format: broadcast names are in 'names' array
broadcast_names = broadcast.get('names', [])
broadcast_info.extend(broadcast_names)
elif 'media' in broadcast and 'shortName' in broadcast['media']:
# Old format: broadcast name is in media.shortName
short_name = broadcast['media']['shortName']
if short_name:
broadcast_info.append(short_name)
# Remove duplicates and filter out empty strings
broadcast_info = list(set([name for name in broadcast_info if name]))
print(f"Extracted broadcast info: {broadcast_info}")
# Test logo mapping
if broadcast_info:
logo_name = None
sorted_keys = sorted(odds_ticker.BROADCAST_LOGO_MAP.keys(), key=len, reverse=True)
for b_name in broadcast_info:
for key in sorted_keys:
if key in b_name:
logo_name = odds_ticker.BROADCAST_LOGO_MAP[key]
print(f" Matched '{key}' to '{logo_name}' for '{b_name}'")
break
if logo_name:
break
print(f" Final mapped logo: '{logo_name}'")
if logo_name:
logo_path = os.path.join('assets', 'broadcast_logos', f"{logo_name}.png")
print(f" Logo file exists: {os.path.exists(logo_path)}")
else:
print(" No broadcast info extracted")
if __name__ == "__main__":
print("Testing New Broadcast Extraction Logic")
print("=" * 50)
test_broadcast_extraction()
print("\n" + "=" * 50)
print("Test complete. Check if the broadcast extraction and mapping works correctly.")

103
test/test_odds_ticker.py Normal file
View File

@@ -0,0 +1,103 @@
#!/usr/bin/env python3
"""
Test script for the OddsTickerManager
"""
import sys
import os
import time
import logging
# Add the src directory to the path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
from src.display_manager import DisplayManager
from src.config_manager import ConfigManager
from src.odds_ticker_manager import OddsTickerManager
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s.%(msecs)03d - %(levelname)s:%(name)s:%(message)s',
datefmt='%H:%M:%S'
)
def test_odds_ticker():
"""Test the odds ticker functionality."""
print("Testing OddsTickerManager...")
try:
# Load configuration
config_manager = ConfigManager()
config = config_manager.load_config()
# Initialize display manager
display_manager = DisplayManager(config)
# Initialize odds ticker
odds_ticker = OddsTickerManager(config, display_manager)
print(f"Odds ticker enabled: {odds_ticker.is_enabled}")
print(f"Enabled leagues: {odds_ticker.enabled_leagues}")
print(f"Show favorite teams only: {odds_ticker.show_favorite_teams_only}")
if not odds_ticker.is_enabled:
print("Odds ticker is disabled in config. Enabling for test...")
odds_ticker.is_enabled = True
# Temporarily disable favorite teams filter for testing
print("Temporarily disabling favorite teams filter to test display...")
original_show_favorite = odds_ticker.show_favorite_teams_only
odds_ticker.show_favorite_teams_only = False
# Update odds ticker data
print("Updating odds ticker data...")
odds_ticker.update()
print(f"Found {len(odds_ticker.games_data)} games")
if odds_ticker.games_data:
print("Sample game data:")
for i, game in enumerate(odds_ticker.games_data[:3]): # Show first 3 games
print(f" Game {i+1}: {game['away_team']} @ {game['home_team']}")
print(f" Time: {game['start_time']}")
print(f" League: {game['league']}")
if game.get('odds'):
print(f" Has odds: Yes")
else:
print(f" Has odds: No")
print()
# Test display
print("Testing display...")
for i in range(5): # Display for 5 iterations
print(f" Display iteration {i+1} starting...")
odds_ticker.display()
print(f" Display iteration {i+1} complete")
time.sleep(2)
else:
print("No games found even with favorite teams filter disabled. This suggests:")
print("- No upcoming MLB games in the next 3 days")
print("- API is not returning data")
print("- MLB league is disabled")
# Test fallback message display
print("Testing fallback message display...")
odds_ticker._display_fallback_message()
time.sleep(3)
# Restore original setting
odds_ticker.show_favorite_teams_only = original_show_favorite
# Cleanup
display_manager.cleanup()
print("Test completed successfully!")
except Exception as e:
print(f"Error during test: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
test_odds_ticker()

View File

@@ -0,0 +1,105 @@
#!/usr/bin/env python3
"""
Test script to run the odds ticker and check for broadcast logos
"""
import sys
import os
import time
import logging
# Add the src directory to the path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
from odds_ticker_manager import OddsTickerManager
from config_manager import ConfigManager
# Set up logging to see what's happening
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
def test_odds_ticker_broadcast():
"""Test the odds ticker with broadcast logo functionality"""
# Load config
config_manager = ConfigManager()
config = config_manager.load_config()
# Create a mock display manager
class MockDisplayManager:
def __init__(self):
self.matrix = type('Matrix', (), {'width': 64, 'height': 32})()
self.image = None
self.draw = None
def update_display(self):
pass
display_manager = MockDisplayManager()
# Create odds ticker manager
odds_ticker = OddsTickerManager(config, display_manager)
print("=== Testing Odds Ticker with Broadcast Logos ===")
print(f"Show channel logos enabled: {odds_ticker.show_channel_logos}")
print(f"Enabled leagues: {odds_ticker.enabled_leagues}")
print(f"Show favorite teams only: {odds_ticker.show_favorite_teams_only}")
# Force an update to fetch fresh data
print("\n--- Fetching games data ---")
odds_ticker.update()
if odds_ticker.games_data:
print(f"\nFound {len(odds_ticker.games_data)} games")
# Check each game for broadcast info
for i, game in enumerate(odds_ticker.games_data[:5]): # Check first 5 games
print(f"\n--- Game {i+1}: {game.get('away_team')} @ {game.get('home_team')} ---")
print(f"Game ID: {game.get('id')}")
print(f"Broadcast info: {game.get('broadcast_info', [])}")
# Test creating a display for this game
try:
game_image = odds_ticker._create_game_display(game)
print(f"✓ Created game display: {game_image.size} pixels")
# Save the image for inspection
output_path = f'odds_ticker_game_{i+1}.png'
game_image.save(output_path)
print(f"✓ Saved to: {output_path}")
except Exception as e:
print(f"✗ Error creating game display: {e}")
import traceback
traceback.print_exc()
else:
print("No games data found")
# Try to fetch some sample data
print("\n--- Trying to fetch sample data ---")
try:
# Force a fresh update
odds_ticker.last_update = 0
odds_ticker.update()
if odds_ticker.games_data:
print(f"Found {len(odds_ticker.games_data)} games after fresh update")
else:
print("Still no games data found")
except Exception as e:
print(f"Error during update: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
print("Testing Odds Ticker Broadcast Logo Display")
print("=" * 60)
test_odds_ticker_broadcast()
print("\n" + "=" * 60)
print("Test complete. Check the generated PNG files to see if broadcast logos appear.")
print("If broadcast logos are visible in the images, the fix is working!")