Files
dababase-etl-python/test_url_encoding.py
2026-03-04 12:17:52 +08:00

181 lines
5.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
URL编码测试脚本
测试密码中包含特殊字符(如@符号的URL编码处理
"""
import sys
import os
from urllib.parse import quote_plus
# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from database_manager import DatabaseManager
from config import DatabaseConfig
def test_url_encoding():
"""
测试URL编码功能
"""
print("🔧 URL编码测试")
print("=" * 50)
# 测试密码编码
test_passwords = [
"sqlserver@7740",
"password@123",
"user#pass",
"test&password",
"simple123"
]
print("📋 密码编码测试:")
for password in test_passwords:
encoded = quote_plus(password)
print(f" 原始密码: {password}")
print(f" 编码后: {encoded}")
print()
# 测试SQL Server连接URL构建
print("🔗 SQL Server连接URL构建测试:")
db_manager = DatabaseManager()
# 获取配置
config = DatabaseConfig.get_config("sqlserver")
try:
# 构建连接URL
connection_url = db_manager._build_connection_url(
db_type="sqlserver",
host=config["host"],
port=config["port"],
username=config["username"],
password=config["password"],
database=config["database"]
)
print(f"✅ 连接URL构建成功:")
print(f" {connection_url}")
# 验证URL中不包含原始的@符号(除了用户名密码分隔符)
if "sqlserver@7740" in connection_url:
print("❌ 错误: URL中仍包含未编码的密码")
return False
elif "sqlserver%407740" in connection_url:
print("✅ 正确: 密码已正确编码")
return True
else:
print("⚠️ 警告: 无法确定编码状态")
return True
except Exception as e:
print(f"❌ 连接URL构建失败: {str(e)}")
return False
def test_direct_connection():
"""
测试直接数据库连接
"""
print("\n🔌 直接连接测试")
print("=" * 50)
try:
# 获取配置
config = DatabaseConfig.get_config("sqlserver")
print(f"📋 连接配置:")
print(f" 主机: {config['host']}")
print(f" 端口: {config['port']}")
print(f" 数据库: {config['database']}")
print(f" 用户名: {config['username']}")
print(f" 密码: {'*' * len(config['password'])}")
# 创建数据库管理器
db_manager = DatabaseManager()
# 尝试创建连接
print("\n正在尝试连接...")
connection_id = db_manager.create_connection(
db_type="sqlserver",
host=config["host"],
port=config["port"],
username=config["username"],
password=config["password"],
database=config["database"]
)
print(f"✅ SQL Server连接成功! 连接ID: {connection_id}")
# 测试查询
try:
result = db_manager.execute_query(connection_id, "SELECT 1 as test_value")
print(f"✅ 查询测试成功: {result}")
# 获取数据库版本
version_result = db_manager.execute_query(connection_id, "SELECT @@VERSION as version")
if version_result:
version_info = version_result[0]['version']
# 只显示版本信息的前100个字符
print(f"📋 数据库版本: {version_info[:100]}...")
except Exception as e:
print(f"⚠️ 查询测试失败: {str(e)}")
# 关闭连接
db_manager.close_connection(connection_id)
print("✅ 连接已关闭")
return True
except Exception as e:
print(f"❌ 连接测试失败: {str(e)}")
# 分析错误类型
error_str = str(e)
if "7740@192.168.11.200" in error_str:
print("\n🔍 错误分析: 密码中的@符号仍未正确处理")
print(" 建议检查URL编码逻辑")
elif "Unable to connect" in error_str:
print("\n🔍 错误分析: 无法连接到SQL Server")
print(" 可能原因:")
print(" 1. SQL Server服务未启动")
print(" 2. 网络连接问题")
print(" 3. 防火墙阻止连接")
print(" 4. 用户名或密码错误")
return False
def main():
"""
主函数
"""
print("🧪 数据库连接URL编码修复验证")
print("=" * 60)
# 1. URL编码测试
url_test_success = test_url_encoding()
# 2. 直接连接测试
connection_test_success = test_direct_connection()
# 总结
print("\n" + "=" * 60)
print("📊 测试结果总结:")
print(f" URL编码: {'✅ 通过' if url_test_success else '❌ 失败'}")
print(f" 连接测试: {'✅ 通过' if connection_test_success else '❌ 失败'}")
if url_test_success and connection_test_success:
print("\n🎉 所有测试通过! URL编码修复成功")
print(" 现在可以正常使用包含特殊字符的密码了")
elif url_test_success and not connection_test_success:
print("\n⚠️ URL编码修复成功但连接仍有问题")
print(" 请检查SQL Server配置和网络连接")
else:
print("\n❌ 测试失败,需要进一步检查代码")
if __name__ == "__main__":
main()