#!/usr/bin/env python3 """ Test script for background job functionality Run this to verify the background job system is working """ import json import time import requests from threading import Thread import sys import os # Add the project root to Python path sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) def test_flask_app(): """Test if Flask app can start and endpoints are registered""" print("๐Ÿงช Testing Flask App Setup...") try: from ai_med_extract.app import app from ai_med_extract.api.routes import register_routes from ai_med_extract.agents import agents # Register routes register_routes(app, agents) # Check URL rules rules = [str(rule) for rule in app.url_map.iter_rules()] job_rules = [r for r in rules if 'job' in r] generate_rules = [r for r in rules if 'generate_patient_summary' in r] print(f"โœ… Found {len(job_rules)} job endpoints:") for rule in job_rules: print(f" - {rule}") print(f"โœ… Found {len(generate_rules)} generate endpoints:") for rule in generate_rules: print(f" - {rule}") return True except Exception as e: print(f"โŒ Flask app test failed: {e}") import traceback traceback.print_exc() return False def test_background_job_creation(): """Test creating a background job""" print("\n๐Ÿงช Testing Background Job Creation...") try: from ai_med_extract.api.routes import create_job, JOB_STORAGE # Clear any existing jobs JOB_STORAGE.clear() # Create a job job_id = create_job() print(f"โœ… Created job with ID: {job_id}") # Check job storage if job_id in JOB_STORAGE: job_data = JOB_STORAGE[job_id] print(f"โœ… Job data: {job_data}") assert job_data['status'] == 'pending' assert 'created_at' in job_data print("โœ… Job creation test passed") return job_id else: print("โŒ Job not found in storage") return None except Exception as e: print(f"โŒ Job creation test failed: {e}") return None def test_job_status_updates(): """Test updating job status""" print("\n๐Ÿงช Testing Job Status Updates...") try: from ai_med_extract.api.routes import update_job_status, get_job_status job_id = test_background_job_creation() if not job_id: return False # Update to running update_job_status(job_id, 'running') job_data = get_job_status(job_id) assert job_data['status'] == 'running' print("โœ… Status update to 'running' successful") # Update to completed with result test_result = {"summary": "Test summary", "status": "completed"} update_job_status(job_id, 'completed', result=test_result) job_data = get_job_status(job_id) assert job_data['status'] == 'completed' assert job_data['result'] == test_result print("โœ… Status update to 'completed' with result successful") # Update to failed update_job_status(job_id, 'failed', error="Test error") job_data = get_job_status(job_id) assert job_data['status'] == 'failed' assert job_data['error'] == "Test error" print("โœ… Status update to 'failed' with error successful") print("โœ… Job status updates test passed") return True except Exception as e: print(f"โŒ Job status updates test failed: {e}") return False def test_job_cleanup(): """Test job cleanup functionality""" print("\n๐Ÿงช Testing Job Cleanup...") try: from ai_med_extract.api.routes import cleanup_old_jobs, JOB_STORAGE import time # Create some old jobs old_job_ids = [] for i in range(3): job_id = f"old_job_{i}" JOB_STORAGE[job_id] = { 'status': 'completed', 'created_at': time.time() - 7200, # 2 hours ago 'result': {"test": "data"} } old_job_ids.append(job_id) # Create a recent job recent_job_id = "recent_job" JOB_STORAGE[recent_job_id] = { 'status': 'completed', 'created_at': time.time() - 1800, # 30 minutes ago 'result': {"test": "recent"} } print(f"โœ… Created {len(old_job_ids)} old jobs and 1 recent job") # Run cleanup (should remove jobs older than 1 hour) cleanup_old_jobs() # Check that old jobs are gone removed_count = 0 for job_id in old_job_ids: if job_id not in JOB_STORAGE: removed_count += 1 print(f"โœ… Cleanup removed {removed_count} old jobs") # Check that recent job remains if recent_job_id in JOB_STORAGE: print("โœ… Recent job preserved") else: print("โŒ Recent job was incorrectly removed") return False print("โœ… Job cleanup test passed") return True except Exception as e: print(f"โŒ Job cleanup test failed: {e}") return False def test_background_processing(): """Test the background processing function""" print("\n๐Ÿงช Testing Background Processing Logic...") try: from ai_med_extract.api.routes import process_patient_summary_job, get_job_status # Create a test job with invalid data (should fail gracefully) job_id = test_background_job_creation() if not job_id: return False # Test data that should trigger fallback (missing required fields) test_data = { "patientid": None, # Invalid "token": "test_token", "key": "test_key" } # Run background processing process_patient_summary_job(job_id, test_data) # Check result job_data = get_job_status(job_id) if job_data['status'] == 'failed': print("โœ… Background processing correctly handled invalid data") print(f" Error: {job_data.get('error', 'No error message')}") else: print(f"โŒ Expected failed status, got: {job_data['status']}") print("โœ… Background processing test passed") return True except Exception as e: print(f"โŒ Background processing test failed: {e}") return False def run_all_tests(): """Run all tests""" print("๐Ÿš€ Starting Background Job System Tests\n") tests = [ ("Flask App Setup", test_flask_app), ("Job Creation", test_background_job_creation), ("Job Status Updates", test_job_status_updates), ("Job Cleanup", test_job_cleanup), ("Background Processing", test_background_processing), ] passed = 0 total = len(tests) for test_name, test_func in tests: try: if test_func(): passed += 1 print(f"โœ… {test_name}: PASSED") else: print(f"โŒ {test_name}: FAILED") except Exception as e: print(f"โŒ {test_name}: ERROR - {e}") print(f"\n๐Ÿ“Š Test Results: {passed}/{total} tests passed") if passed == total: print("๐ŸŽ‰ All tests passed! Background job system is working correctly.") return True else: print("โš ๏ธ Some tests failed. Please check the implementation.") return False if __name__ == "__main__": success = run_all_tests() sys.exit(0 if success else 1)