#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 事业部驾驶舱接口全面测试脚本 测试时间:202512 """ import requests import json from datetime import datetime from typing import Dict, Any, List # API基础配置 BASE_URL = "http://localhost:2011" TEST_MONTH = "202512" # 测试结果存储 test_results = [] def log_result(api_name: str, success: bool, request_data: Dict = None, response_data: Any = None, error: str = None, db_check: str = None): """记录测试结果""" result = { "api_name": api_name, "success": success, "timestamp": datetime.now().isoformat(), "request_data": request_data, "response_data": response_data, "error": error, "db_check": db_check } test_results.append(result) status = "✓ PASS" if success else "✗ FAIL" print(f"\n[{status}] {api_name}") if request_data: print(f" 请求参数: {json.dumps(request_data, ensure_ascii=False, indent=2)}") if error: print(f" 错误信息: {error}") elif response_data: print(f" 响应状态: {response_data.get('code', 'N/A')}") if response_data.get('code') == 200: print(f" 响应数据: {json.dumps(response_data.get('data', {}), ensure_ascii=False, indent=2)[:500]}") if db_check: print(f" 数据库验证: {db_check}") def get_token(): """获取登录token""" url = f"{BASE_URL}/api/oauth/Login" data = { "account": "admin", "password": "e10adc3949ba59abbe56e057f20f883e" } response = requests.post(url, data=data, headers={"Content-Type": "application/x-www-form-urlencoded"}) if response.status_code == 200: result = response.json() if result.get('code') == 200: token = result.get('data', {}).get('token', '') return token return None def test_api(api_name: str, endpoint: str, method: str = "POST", data: Dict = None, token: str = None, db_check_func=None): """测试API接口""" url = f"{BASE_URL}/api/Extend/LqBusinessUnitDashboard/{endpoint}" headers = { "Content-Type": "application/json" } if token: headers["Authorization"] = token try: if method == "POST": response = requests.post(url, json=data, headers=headers, timeout=30) else: response = requests.get(url, params=data, headers=headers, timeout=30) if response.status_code == 200: result = response.json() db_check = None if db_check_func: db_check = db_check_func(result.get('data', {})) log_result(api_name, True, data, result, db_check=db_check) return result else: error_msg = f"HTTP {response.status_code}: {response.text[:200]}" log_result(api_name, False, data, None, error=error_msg) return None except Exception as e: error_msg = f"请求异常: {str(e)}" log_result(api_name, False, data, None, error=error_msg) return None def main(): """主测试函数""" print("=" * 80) print("事业部驾驶舱接口全面测试") print(f"测试时间: {TEST_MONTH}") print("=" * 80) # 获取token print("\n[1] 获取登录token...") token = get_token() if not token: print("✗ 获取token失败,无法继续测试") return print(f"✓ Token获取成功: {token[:50]}...") # 测试数据(需要根据实际情况调整) business_unit_id = "734725299018663173" # 示例事业部ID,需要根据实际情况调整 store_ids = [] # 可选,如果不传则查询整个事业部 # 1. GetStatistics - 核心业务指标统计 print("\n" + "=" * 80) print("测试 1: GetStatistics - 核心业务指标统计") print("=" * 80) test_api( "GetStatistics", "GetStatistics", data={ "businessUnitId": business_unit_id, "statisticsMonth": TEST_MONTH }, token=token ) # 2. GetPerformanceTrend - 业绩趋势分析 print("\n" + "=" * 80) print("测试 2: GetPerformanceTrend - 业绩趋势分析") print("=" * 80) test_api( "GetPerformanceTrend", "GetPerformanceTrend", data={ "businessUnitId": business_unit_id, "statisticsMonth": TEST_MONTH, "monthCount": 6 }, token=token ) # 3. GetStoreRanking - 门店排行 print("\n" + "=" * 80) print("测试 3: GetStoreRanking - 门店排行") print("=" * 80) test_api( "GetStoreRanking", "GetStoreRanking", data={ "businessUnitId": business_unit_id, "statisticsMonth": TEST_MONTH, "topCount": 10, "rankingType": "NetPerformance" }, token=token ) # 4. GetOperationStatistics - 运营分析 print("\n" + "=" * 80) print("测试 4: GetOperationStatistics - 运营分析") print("=" * 80) test_api( "GetOperationStatistics", "GetOperationStatistics", data={ "businessUnitId": business_unit_id, "statisticsMonth": TEST_MONTH }, token=token ) # 5. GetStoreDetailList - 门店明细列表 print("\n" + "=" * 80) print("测试 5: GetStoreDetailList - 门店明细列表") print("=" * 80) test_api( "GetStoreDetailList", "GetStoreDetailList", data={ "businessUnitId": business_unit_id, "statisticsMonth": TEST_MONTH, "currentPage": 1, "pageSize": 10 }, token=token ) # 6. GetManagerRanking - 总经理/经理业绩排行 print("\n" + "=" * 80) print("测试 6: GetManagerRanking - 总经理/经理业绩排行") print("=" * 80) test_api( "GetManagerRanking", "GetManagerRanking", data={ "businessUnitId": business_unit_id, "statisticsMonth": TEST_MONTH, "managerType": 1, "topCount": 10 }, token=token ) # 7. GetComparisonAnalysis - 对比分析 print("\n" + "=" * 80) print("测试 7: GetComparisonAnalysis - 对比分析") print("=" * 80) test_api( "GetComparisonAnalysis", "GetComparisonAnalysis", data={ "businessUnitId": business_unit_id, "statisticsMonth": TEST_MONTH }, token=token ) # 8. GetStoreDistribution - 门店业绩分布 print("\n" + "=" * 80) print("测试 8: GetStoreDistribution - 门店业绩分布") print("=" * 80) test_api( "GetStoreDistribution", "GetStoreDistribution", data={ "businessUnitId": business_unit_id, "statisticsMonth": TEST_MONTH }, token=token ) # 9. GetManagerDistribution - 总经理/经理业绩分布 print("\n" + "=" * 80) print("测试 9: GetManagerDistribution - 总经理/经理业绩分布") print("=" * 80) test_api( "GetManagerDistribution", "GetManagerDistribution", data={ "businessUnitId": business_unit_id, "statisticsMonth": TEST_MONTH }, token=token ) # 10. GetManagerTrend - 总经理/经理业绩趋势 print("\n" + "=" * 80) print("测试 10: GetManagerTrend - 总经理/经理业绩趋势") print("=" * 80) # 需要先获取经理ID列表 manager_ranking_result = test_api( "GetManagerRanking", "GetManagerRanking", data={ "businessUnitId": business_unit_id, "statisticsMonth": TEST_MONTH, "managerType": 1, "topCount": 5 }, token=token ) if manager_ranking_result and manager_ranking_result.get('code') == 200: manager_ids = [item.get('managerId') for item in manager_ranking_result.get('data', {}).get('rankingData', [])[:2]] if manager_ids: test_api( "GetManagerTrend", "GetManagerTrend", data={ "businessUnitId": business_unit_id, "statisticsMonth": TEST_MONTH, "managerIds": manager_ids, "monthCount": 6 }, token=token ) # 11. GetStoreManagerRanking - 店长业绩排行 print("\n" + "=" * 80) print("测试 11: GetStoreManagerRanking - 店长业绩排行") print("=" * 80) test_api( "GetStoreManagerRanking", "GetStoreManagerRanking", data={ "businessUnitId": business_unit_id, "statisticsMonth": TEST_MONTH, "topCount": 10 }, token=token ) # 12. GetHealthCoachRanking - 健康师业绩排行 print("\n" + "=" * 80) print("测试 12: GetHealthCoachRanking - 健康师业绩排行") print("=" * 80) test_api( "GetHealthCoachRanking", "GetHealthCoachRanking", data={ "businessUnitId": business_unit_id, "statisticsMonth": TEST_MONTH, "topCount": 10 }, token=token ) # 13. GetManagerDetailList - 总经理/经理明细列表 print("\n" + "=" * 80) print("测试 13: GetManagerDetailList - 总经理/经理明细列表") print("=" * 80) test_api( "GetManagerDetailList", "GetManagerDetailList", data={ "businessUnitId": business_unit_id, "statisticsMonth": TEST_MONTH, "currentPage": 1, "pageSize": 10 }, token=token ) # 14. GetStoreManagerDetailList - 店长明细列表 print("\n" + "=" * 80) print("测试 14: GetStoreManagerDetailList - 店长明细列表") print("=" * 80) test_api( "GetStoreManagerDetailList", "GetStoreManagerDetailList", data={ "businessUnitId": business_unit_id, "statisticsMonth": TEST_MONTH, "currentPage": 1, "pageSize": 10 }, token=token ) # 15. GetHealthCoachDetailList - 健康师明细列表 print("\n" + "=" * 80) print("测试 15: GetHealthCoachDetailList - 健康师明细列表") print("=" * 80) test_api( "GetHealthCoachDetailList", "GetHealthCoachDetailList", data={ "businessUnitId": business_unit_id, "statisticsMonth": TEST_MONTH, "currentPage": 1, "pageSize": 10 }, token=token ) # 生成测试报告 print("\n" + "=" * 80) print("测试完成,生成测试报告...") print("=" * 80) total_tests = len(test_results) passed_tests = sum(1 for r in test_results if r['success']) failed_tests = total_tests - passed_tests report = f""" # 事业部驾驶舱接口测试报告 ## 测试概览 - 测试时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - 测试月份: {TEST_MONTH} - 总测试数: {total_tests} - 通过数: {passed_tests} - 失败数: {failed_tests} - 通过率: {(passed_tests/total_tests*100):.1f}% ## 测试详情 """ for i, result in enumerate(test_results, 1): status = "✓ 通过" if result['success'] else "✗ 失败" report += f"### {i}. {result['api_name']} - {status}\n\n" report += f"- **测试时间**: {result['timestamp']}\n" if result['request_data']: report += f"- **请求参数**: `{json.dumps(result['request_data'], ensure_ascii=False)}`\n" if result['error']: report += f"- **错误信息**: {result['error']}\n" elif result['response_data']: code = result['response_data'].get('code', 'N/A') report += f"- **响应状态码**: {code}\n" if result['db_check']: report += f"- **数据库验证**: {result['db_check']}\n" report += "\n" report += f""" ## 测试总结 - 总计: {total_tests} 个接口 - 通过: {passed_tests} 个 - 失败: {failed_tests} 个 - 通过率: {(passed_tests/total_tests*100):.1f}% """ if failed_tests > 0: report += "## 失败接口列表\n\n" for result in test_results: if not result['success']: report += f"- {result['api_name']}: {result.get('error', '未知错误')}\n" # 保存报告 with open("事业部驾驶舱接口测试报告.md", "w", encoding="utf-8") as f: f.write(report) print(f"\n测试报告已保存到: 事业部驾驶舱接口测试报告.md") print(f"\n测试统计:") print(f" 总测试数: {total_tests}") print(f" 通过数: {passed_tests}") print(f" 失败数: {failed_tests}") print(f" 通过率: {(passed_tests/total_tests*100):.1f}%") if __name__ == "__main__": main()