test_business_unit_dashboard_comprehensive.py 12.7 KB
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 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
#!/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()