File size: 7,198 Bytes
5c22c89 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 | #!/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:
@staticmethod
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() |