Files
OSIT-AE-API-FastAPI/tests/unit/test_unit_errors.py
Scott Idem 9adf5659bc test(errors): add unit test for 1364 schema mismatch error
Covers the fix from 308a7f2 — verifies that MariaDB error 1364
is classified as database_schema and the field name is extracted
into a readable message.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-17 19:09:53 -04:00

63 lines
2.1 KiB
Python

import sys
import os
import asyncio
from unittest.mock import MagicMock, AsyncMock
# --- Environment Setup ---
sys.modules['redis'] = MagicMock()
sys.modules['sqlalchemy'] = MagicMock()
sys.modules['sqlalchemy.text'] = MagicMock()
sys.modules['app.config'] = MagicMock()
sys.modules['app.log'] = MagicMock()
sys.modules['app.lib_general'] = MagicMock()
# Mock app.db_sql
mock_db_sql = MagicMock()
mock_db_sql.get_last_sql_error.return_value = '(pymysql.err.IntegrityError) (1062, "Duplicate entry \'test-id\' for key \'id_random\'" )'
sys.modules['app.db_sql'] = mock_db_sql
# Add project root to path
sys.path.append(os.getcwd())
from app.lib_api_crud_v3 import format_db_error
def test_error_formatting():
print("\n--- Testing Error Formatting ---")
raw = '(pymysql.err.IntegrityError) (1062, "Duplicate entry \'abc\' for key \'id_random\'" )'
formatted = format_db_error(raw)
print(f"Raw: {raw}")
print(f"Formatted: {formatted}")
if formatted.category == "database_duplicate" and formatted.code == 1062:
print("✅ Error formatting works.")
else:
print("❌ Error formatting FAILED.")
def test_null_error_handling():
print("\n--- Testing Null Error Handling ---")
formatted = format_db_error(None)
if formatted.category == "unknown":
print("✅ Null error handled correctly.")
else:
print("❌ Null error check FAILED.")
def test_1364_schema_mismatch():
print("\n--- Testing 1364 Schema Mismatch ---")
raw = "(MySQLdb.OperationalError) (1364, \"Field 'account' doesn't have a default value\")"
formatted = format_db_error(raw)
print(f"Raw: {raw}")
print(f"Formatted: {formatted}")
if (formatted.category == "database_schema"
and formatted.code == 1364
and "account" in formatted.message
and "NOT NULL" in formatted.message):
print("✅ 1364 schema mismatch handled correctly.")
else:
print("❌ 1364 schema mismatch check FAILED.")
if __name__ == "__main__":
test_error_formatting()
test_null_error_handling()
test_1364_schema_mismatch()