#!/usr/bin/env python3 """ 测试登录 API 用途:直接测试后端的登录 API 是否能正常响应 使用方法:python3 test_login_api.py """ import sys import json import requests if len(sys.argv) != 3: print("Usage: python3 test_login_api.py ") print("Example: python3 test_login_api.py admin Hxit@54321") sys.exit(1) username = sys.argv[1] password = sys.argv[2] # 测试登录 API url = "http://localhost:5052/api/user/login" headers = {"Content-Type": "application/json"} data = {"username": username, "password": password} print(f"Testing login API for user '{username}'...") try: response = requests.post(url, headers=headers, data=json.dumps(data), timeout=5) print(f"Status code: {response.status_code}") print(f"Response: {response.json()}") if response.status_code == 200: print("✅ SUCCESS: Login API returned 200 OK") else: print("❌ FAILURE: Login API returned error") except requests.exceptions.ConnectionError: print("❌ FAILURE: Cannot connect to the server. Is the backend running?") except Exception as e: print(f"❌ FAILURE: Error testing login API: {e}") # 测试另一种方式:使用 Flask 应用上下文直接测试 print("\nTesting with Flask app context...") try: from app import create_app from app.models import User app = create_app() with app.app_context(): user = User.query.filter_by(username=username).first() if user: print(f"Found user: {user.username}, Role: {user.role}") if user.check_password(password): print(f"✅ SUCCESS: Password is correct for user '{username}'") else: print(f"❌ FAILURE: Password is incorrect for user '{username}'") else: print(f"❌ FAILURE: User '{username}' not found") except Exception as e: print(f"❌ FAILURE: Error testing with app context: {e}")