PupaClic
feat(tests): Add validation and testing scripts for dashboard router error handling fix
5c22c89 | #!/usr/bin/env python3 | |
| """ | |
| Direct test of the dashboard router function to verify the variable scope fix | |
| """ | |
| import sys | |
| import os | |
| import asyncio | |
| from unittest.mock import MagicMock, AsyncMock | |
| # Add the app directory to the Python path | |
| sys.path.append('/Users/mukeshkapoor/projects/insightfy-bloom/backend/insightfy-bloom-ms-mpms') | |
| def test_variable_scope_fix(): | |
| """Test that the variable scope issue is fixed in the error handling""" | |
| print("π§ͺ Testing Variable Scope Fix") | |
| print("=" * 30) | |
| try: | |
| # Import the function | |
| from app.routers.dashboard_router import get_dashboard_layout | |
| print("β Successfully imported get_dashboard_layout function") | |
| # Create a mock current_user that will cause an exception | |
| # We'll test both scenarios: | |
| # 1. Exception before variables are set | |
| # 2. Exception after variables are set | |
| async def test_exception_before_variables(): | |
| """Test exception handling when variables aren't set yet""" | |
| print("\n1. Testing exception before variables are assigned...") | |
| # Create a mock that raises an exception immediately | |
| def failing_current_user(): | |
| raise Exception("Auth failed before variable assignment") | |
| try: | |
| # This should trigger the exception in the first few lines | |
| await get_dashboard_layout(current_user=failing_current_user()) | |
| except Exception as e: | |
| print(f" Exception caught (expected): {type(e).__name__}: {e}") | |
| return True | |
| return False | |
| async def test_exception_after_variables(): | |
| """Test exception handling when variables are set""" | |
| print("\n2. Testing exception after variables are assigned...") | |
| # Mock current_user that provides data but service fails | |
| mock_user = { | |
| "merchant_id": "test_merchant", | |
| "role_id": "test_role", | |
| "associate_id": "test_associate" | |
| } | |
| # Mock the DashboardService to raise an exception | |
| import app.routers.dashboard_router as router_module | |
| original_service = router_module.DashboardService | |
| class FailingDashboardService: | |
| async def get_dashboard_layout(*args, **kwargs): | |
| raise Exception("Service failed after variable assignment") | |
| # Replace the service temporarily | |
| router_module.DashboardService = FailingDashboardService | |
| try: | |
| result = await get_dashboard_layout(current_user=mock_user) | |
| print(f" Result type: {type(result)}") | |
| print(f" Result: {result}") | |
| # Check if it's an error response (not a 500 crash) | |
| if isinstance(result, dict) and "status" in result: | |
| if result.get("status") == "error": | |
| print("β Proper error response returned (no 500 crash)") | |
| return True | |
| except Exception as e: | |
| print(f" Exception: {type(e).__name__}: {e}") | |
| return False | |
| finally: | |
| # Restore original service | |
| router_module.DashboardService = original_service | |
| return False | |
| # Run the async tests | |
| print("\nRunning async tests...") | |
| # Test 1: Exception before variables | |
| try: | |
| result1 = asyncio.run(test_exception_before_variables()) | |
| except Exception as e: | |
| print(f"Test 1 failed with exception: {e}") | |
| result1 = False | |
| # Test 2: Exception after variables | |
| try: | |
| result2 = asyncio.run(test_exception_after_variables()) | |
| except Exception as e: | |
| print(f"Test 2 failed with exception: {e}") | |
| result2 = False | |
| print(f"\nπ Test Results:") | |
| print(f" Exception before variables: {'β Pass' if result1 else 'β Fail'}") | |
| print(f" Exception after variables: {'β Pass' if result2 else 'β Fail'}") | |
| if result1 and result2: | |
| print("β Variable scope fix appears to be working!") | |
| return True | |
| else: | |
| print("β οΈ Some tests failed - there may still be issues") | |
| return False | |
| except ImportError as e: | |
| print(f"β Import failed: {e}") | |
| print(" Make sure you're in the correct directory and dependencies are available") | |
| return False | |
| except Exception as e: | |
| print(f"β Test failed: {e}") | |
| return False | |
| def check_function_structure(): | |
| """Check the structure of the function to verify our fix""" | |
| print("\nπ Checking Function Structure") | |
| print("=" * 30) | |
| try: | |
| # Read the router file and check for our fix | |
| with open('/Users/mukeshkapoor/projects/insightfy-bloom/backend/insightfy-bloom-ms-mpms/app/routers/dashboard_router.py', 'r') as f: | |
| content = f.read() | |
| # Check for our fix patterns | |
| if "locals()" in content: | |
| print("β Found 'locals()' check in error handling") | |
| else: | |
| print("β 'locals()' check not found") | |
| if "extra_data = {}" in content: | |
| print("β Found 'extra_data' initialization") | |
| else: | |
| print("β 'extra_data' initialization not found") | |
| # Count the number of times variables are used in error handling | |
| error_section = content.split("except Exception as e:")[1] if "except Exception as e:" in content else "" | |
| if "merchant_id" in error_section and "locals()" in error_section: | |
| print("β Safe variable access pattern found") | |
| elif "merchant_id" in error_section: | |
| print("β οΈ Variable still used in error handling, but may not be safe") | |
| return True | |
| except Exception as e: | |
| print(f"β Error checking file: {e}") | |
| return False | |
| def main(): | |
| print("π Dashboard Router Variable Scope Fix Test") | |
| print("Testing if our fix prevents 500 errors from undefined variables") | |
| print() | |
| # Check the function structure first | |
| structure_ok = check_function_structure() | |
| # Test the actual functionality | |
| if structure_ok: | |
| test_ok = test_variable_scope_fix() | |
| if test_ok: | |
| print("\nπ All tests passed! The fix should prevent 500 errors.") | |
| else: | |
| print("\nβ οΈ Tests failed. There may still be issues.") | |
| else: | |
| print("\nβ Function structure check failed.") | |
| print("\nπ Summary:") | |
| print("The fix ensures that variables used in error logging are checked") | |
| print("for existence before use, preventing NameError exceptions that") | |
| print("cause 500 Internal Server Error responses.") | |
| if __name__ == "__main__": | |
| main() |