test_products.py 22.3 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 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
import os
import sys
import json
import time
from typing import Dict, List, Optional

from client import ApiClient


BASE_URL = os.environ.get('API_BASE_URL', 'http://localhost:8083')


class ProductApiTester:
    """产品信息管理API测试类"""
    
    def __init__(self):
        self.client = ApiClient(BASE_URL)
        self.test_product_id: Optional[int] = None
        self.test_product_ids: List[int] = []
        
    def print_result(self, test_name: str, success: bool, message: str = ""):
        """打印测试结果"""
        status = "✅ PASS" if success else "❌ FAIL"
        print(f"{status} {test_name}")
        if message:
            print(f"    {message}")
        print()
    
    def test_list_products(self) -> bool:
        """测试分页查询产品列表接口"""
        print("🔍 测试分页查询产品列表接口...")
        
        try:
            # 测试基本查询
            resp = self.client.get('/api/product/list', {
                'pageNum': 1,
                'pageSize': 10
            })
            
            if resp.status_code != 200:
                self.print_result("分页查询产品列表", False, f"HTTP状态码错误: {resp.status_code}")
                return False
                
            data = resp.json()
            if data.get('code') != 200:
                self.print_result("分页查询产品列表", False, f"业务状态码错误: {data.get('message', '未知错误')}")
                return False
            
            # 检查响应结构
            if 'data' not in data:
                self.print_result("分页查询产品列表", False, "响应缺少data字段")
                return False
                
            product_data = data['data']
            required_fields = ['records', 'total', 'current', 'size', 'pages']
            for field in required_fields:
                if field not in product_data:
                    self.print_result("分页查询产品列表", False, f"响应缺少{field}字段")
                    return False
            
            # 保存测试产品ID用于后续测试
            if product_data['records']:
                self.test_product_id = product_data['records'][0].get('productId')
                self.test_product_ids = [item.get('productId') for item in product_data['records'][:3] if item.get('productId')]
            
            self.print_result("分页查询产品列表", True, f"查询到{product_data['total']}条记录")
            
            # 测试条件查询
            resp2 = self.client.get('/api/product/list', {
                'productCode': 'APL',
                'productName': 'iPhone',
                'saleStatus': 1,
                'pageNum': 1,
                'pageSize': 5
            })
            
            if resp2.status_code == 200:
                data2 = resp2.json()
                if data2.get('code') == 200:
                    self.print_result("条件查询产品列表", True, "条件查询成功")
                else:
                    self.print_result("条件查询产品列表", False, f"条件查询失败: {data2.get('message')}")
            else:
                self.print_result("条件查询产品列表", False, f"条件查询HTTP错误: {resp2.status_code}")
            
            return True
            
        except Exception as e:
            self.print_result("分页查询产品列表", False, f"异常: {str(e)}")
            return False
    
    def test_get_product_detail(self) -> bool:
        """测试获取产品详情接口"""
        print("🔍 测试获取产品详情接口...")
        
        if not self.test_product_id:
            self.print_result("获取产品详情", False, "没有可用的产品ID进行测试")
            return False
        
        try:
            resp = self.client.get(f'/api/product/{self.test_product_id}')
            
            if resp.status_code != 200:
                self.print_result("获取产品详情", False, f"HTTP状态码错误: {resp.status_code}")
                return False
                
            data = resp.json()
            if data.get('code') != 200:
                self.print_result("获取产品详情", False, f"业务状态码错误: {data.get('message', '未知错误')}")
                return False
            
            # 检查产品详情字段
            product_detail = data.get('data', {})
            required_fields = ['productId', 'productCode', 'productName', 'productModel', 'productType']
            for field in required_fields:
                if field not in product_detail:
                    self.print_result("获取产品详情", False, f"产品详情缺少{field}字段")
                    return False
            
            self.print_result("获取产品详情", True, f"成功获取产品: {product_detail.get('productName', '未知')}")
            return True
            
        except Exception as e:
            self.print_result("获取产品详情", False, f"异常: {str(e)}")
            return False
    
    def test_add_product(self) -> bool:
        """测试新增产品接口"""
        print("🔍 测试新增产品接口...")
        
        try:
            # 生成唯一的测试产品编码
            timestamp = int(time.time())
            test_product_code = f"TEST-{timestamp}"
            
            product_data = {
                "productCode": test_product_code,
                "productName": f"测试产品_{timestamp}",
                "productModel": "TEST-MODEL",
                "productType": "测试类型",
                "storageCapacity": "128GB",
                "color": "测试色",
                "productImgUrl": "https://example.com/test.jpg",
                "officialPrice": 5999.00,
                "saleStatus": 1,
                "rebateFlag": 1,
                "saleStartDate": "2024-01-01",
                "saleEndDate": "2024-12-31",
                "remark": "API测试产品"
            }
            
            resp = self.client.post('/api/product', product_data)
            
            if resp.status_code != 200:
                self.print_result("新增产品", False, f"HTTP状态码错误: {resp.status_code}")
                return False
                
            data = resp.json()
            if data.get('code') != 200:
                self.print_result("新增产品", False, f"业务状态码错误: {data.get('message', '未知错误')}")
                return False
            
            self.print_result("新增产品", True, f"成功新增产品: {test_product_code}")
            
            # 保存新增的产品ID用于后续测试
            # 通过查询接口获取新增的产品ID
            list_resp = self.client.get('/api/product/list', {
                'productCode': test_product_code,
                'pageNum': 1,
                'pageSize': 1
            })
            
            if list_resp.status_code == 200:
                list_data = list_resp.json()
                if list_data.get('code') == 200 and list_data.get('data', {}).get('records'):
                    new_product_id = list_data['data']['records'][0].get('productId')
                    if new_product_id:
                        self.test_product_ids.append(new_product_id)
                        self.print_result("获取新增产品ID", True, f"新增产品ID: {new_product_id}")
            
            return True
            
        except Exception as e:
            self.print_result("新增产品", False, f"异常: {str(e)}")
            return False
    
    def test_update_product(self) -> bool:
        """测试修改产品接口"""
        print("🔍 测试修改产品接口...")
        
        if not self.test_product_id:
            self.print_result("修改产品", False, "没有可用的产品ID进行测试")
            return False
        
        try:
            # 先获取产品详情
            detail_resp = self.client.get(f'/api/product/{self.test_product_id}')
            if detail_resp.status_code != 200:
                self.print_result("修改产品", False, "无法获取产品详情")
                return False
            
            detail_data = detail_resp.json()
            if detail_data.get('code') != 200:
                self.print_result("修改产品", False, "无法获取产品详情")
                return False
            
            product_detail = detail_data.get('data', {})
            
            # 修改产品信息
            update_data = {
                "productId": self.test_product_id,
                "productCode": product_detail.get('productCode', ''),
                "productName": f"{product_detail.get('productName', '')}_修改",
                "productModel": product_detail.get('productModel', ''),
                "productType": product_detail.get('productType', ''),
                "storageCapacity": product_detail.get('storageCapacity', ''),
                "color": product_detail.get('color', ''),
                "productImgUrl": product_detail.get('productImgUrl', ''),
                "officialPrice": product_detail.get('officialPrice', 0),
                "saleStatus": product_detail.get('saleStatus', 1),
                "rebateFlag": product_detail.get('rebateFlag', 1),
                "saleStartDate": product_detail.get('saleStartDate', ''),
                "saleEndDate": product_detail.get('saleEndDate', ''),
                "remark": f"{product_detail.get('remark', '')}_API修改测试"
            }
            
            resp = self.client.post('/api/product/update', update_data)
            
            if resp.status_code != 200:
                self.print_result("修改产品", False, f"HTTP状态码错误: {resp.status_code}")
                return False
                
            data = resp.json()
            if data.get('code') != 200:
                self.print_result("修改产品", False, f"业务状态码错误: {data.get('message', '未知错误')}")
                return False
            
            self.print_result("修改产品", True, f"成功修改产品ID: {self.test_product_id}")
            return True
            
        except Exception as e:
            self.print_result("修改产品", False, f"异常: {str(e)}")
            return False
    
    def test_change_rebate_flag(self) -> bool:
        """测试修改返利标识接口"""
        print("🔍 测试修改返利标识接口...")
        
        if not self.test_product_id:
            self.print_result("修改返利标识", False, "没有可用的产品ID进行测试")
            return False
        
        try:
            # 测试修改返利标识 - 使用路径参数和查询参数,发送空请求体
            resp = self.client.post(f'/api/product/{self.test_product_id}/rebate?rebateFlag=0', {})
            
            if resp.status_code != 200:
                self.print_result("修改返利标识", False, f"HTTP状态码错误: {resp.status_code}")
                return False
                
            data = resp.json()
            if data.get('code') != 200:
                self.print_result("修改返利标识", False, f"业务状态码错误: {data.get('message', '未知错误')}")
                return False
            
            self.print_result("修改返利标识", True, f"成功修改返利标识: {self.test_product_id}")
            
            # 恢复返利标识
            resp2 = self.client.post(f'/api/product/{self.test_product_id}/rebate?rebateFlag=1', {})
            
            if resp2.status_code == 200:
                data2 = resp2.json()
                if data2.get('code') == 200:
                    self.print_result("恢复返利标识", True, "成功恢复返利标识")
                else:
                    self.print_result("恢复返利标识", False, f"恢复返利标识失败: {data2.get('message')}")
            else:
                self.print_result("恢复返利标识", False, f"恢复返利标识HTTP错误: {resp2.status_code}")
            
            return True
            
        except Exception as e:
            self.print_result("修改返利标识", False, f"异常: {str(e)}")
            return False
    
    def test_get_all_products(self) -> bool:
        """测试获取所有产品接口"""
        print("🔍 测试获取所有产品接口...")
        
        try:
            resp = self.client.get('/api/product/all')
            
            if resp.status_code != 200:
                self.print_result("获取所有产品", False, f"HTTP状态码错误: {resp.status_code}")
                return False
                
            data = resp.json()
            if data.get('code') != 200:
                self.print_result("获取所有产品", False, f"业务状态码错误: {data.get('message', '未知错误')}")
                return False
            
            # 检查响应结构
            products = data.get('data', [])
            if not isinstance(products, list):
                self.print_result("获取所有产品", False, "响应数据不是数组格式")
                return False
            
            # 检查产品字段
            if products:
                product = products[0]
                required_fields = ['productId', 'productCode', 'productName']
                for field in required_fields:
                    if field not in product:
                        self.print_result("获取所有产品", False, f"产品数据缺少{field}字段")
                        return False
            
            self.print_result("获取所有产品", True, f"成功获取{len(products)}个产品")
            return True
            
        except Exception as e:
            self.print_result("获取所有产品", False, f"异常: {str(e)}")
            return False
    
    def test_batch_delete_products(self) -> bool:
        """测试批量删除产品接口"""
        print("🔍 测试批量删除产品接口...")
        
        if not self.test_product_ids:
            self.print_result("批量删除产品", False, "没有可用的产品ID进行测试")
            return False
        
        try:
            # 只删除测试创建的产品(通过产品编码识别)
            test_ids = []
            for product_id in self.test_product_ids:
                # 获取产品详情检查是否为测试产品
                detail_resp = self.client.get(f'/api/product/{product_id}')
                if detail_resp.status_code == 200:
                    detail_data = detail_resp.json()
                    if detail_data.get('code') == 200:
                        product_detail = detail_data.get('data', {})
                        if product_detail.get('productCode', '').startswith('TEST-'):
                            test_ids.append(product_id)
            
            if not test_ids:
                self.print_result("批量删除产品", False, "没有找到测试产品进行删除")
                return False
            
            resp = self.client.post('/api/product/batchDelete', test_ids)
            
            if resp.status_code != 200:
                self.print_result("批量删除产品", False, f"HTTP状态码错误: {resp.status_code}")
                return False
                
            data = resp.json()
            if data.get('code') != 200:
                self.print_result("批量删除产品", False, f"业务状态码错误: {data.get('message', '未知错误')}")
                return False
            
            self.print_result("批量删除产品", True, f"成功删除{len(test_ids)}个测试产品")
            return True
            
        except Exception as e:
            self.print_result("批量删除产品", False, f"异常: {str(e)}")
            return False
    
    def test_delete_product(self) -> bool:
        """测试删除产品接口"""
        print("🔍 测试删除产品接口...")
        
        # 先创建一个测试产品用于删除
        timestamp = int(time.time())
        test_product_code = f"DELETE-TEST-{timestamp}"
        
        try:
            # 创建测试产品
            product_data = {
                "productCode": test_product_code,
                "productName": f"删除测试产品_{timestamp}",
                "productModel": "DELETE-TEST-MODEL",
                "productType": "删除测试类型",
                "saleStatus": 1,
                "rebateFlag": 1
            }
            
            create_resp = self.client.post('/api/product', product_data)
            if create_resp.status_code != 200:
                self.print_result("删除产品", False, "无法创建测试产品")
                return False
            
            create_data = create_resp.json()
            if create_data.get('code') != 200:
                self.print_result("删除产品", False, "无法创建测试产品")
                return False
            
            # 获取创建的产品ID
            list_resp = self.client.get('/api/product/list', {
                'productCode': test_product_code,
                'pageNum': 1,
                'pageSize': 1
            })
            
            if list_resp.status_code != 200:
                self.print_result("删除产品", False, "无法获取测试产品ID")
                return False
            
            list_data = list_resp.json()
            if list_data.get('code') != 200 or not list_data.get('data', {}).get('records'):
                self.print_result("删除产品", False, "无法获取测试产品ID")
                return False
            
            delete_product_id = list_data['data']['records'][0].get('productId')
            if not delete_product_id:
                self.print_result("删除产品", False, "无法获取测试产品ID")
                return False
            
            # 删除产品
            resp = self.client.delete(f'/api/product/{delete_product_id}')
            
            if resp.status_code != 200:
                self.print_result("删除产品", False, f"HTTP状态码错误: {resp.status_code}")
                return False
                
            data = resp.json()
            if data.get('code') != 200:
                self.print_result("删除产品", False, f"业务状态码错误: {data.get('message', '未知错误')}")
                return False
            
            self.print_result("删除产品", True, f"成功删除产品ID: {delete_product_id}")
            return True
            
        except Exception as e:
            self.print_result("删除产品", False, f"异常: {str(e)}")
            return False
    
    def test_parameter_validation(self) -> bool:
        """测试参数验证"""
        print("🔍 测试参数验证...")
        
        try:
            # 测试必填字段验证
            invalid_data = {
                "productName": "测试产品",
                # 缺少必填字段 productCode, productModel, productType, saleStatus, rebateFlag
            }
            
            resp = self.client.post('/api/product', invalid_data)
            
            if resp.status_code == 200:
                data = resp.json()
                if data.get('code') != 200:
                    self.print_result("参数验证", True, "正确返回参数验证错误")
                else:
                    self.print_result("参数验证", False, "应该返回参数验证错误")
                    return False
            else:
                self.print_result("参数验证", True, f"HTTP状态码正确: {resp.status_code}")
            
            # 测试无效的产品ID
            resp2 = self.client.get('/api/product/999999')
            
            if resp2.status_code == 200:
                data2 = resp2.json()
                if data2.get('code') != 200:
                    self.print_result("无效ID验证", True, "正确返回产品不存在错误")
                else:
                    self.print_result("无效ID验证", False, "应该返回产品不存在错误")
                    return False
            else:
                self.print_result("无效ID验证", True, f"HTTP状态码正确: {resp2.status_code}")
            
            return True
            
        except Exception as e:
            self.print_result("参数验证", False, f"异常: {str(e)}")
            return False
    
    def run_all_tests(self) -> bool:
        """运行所有测试"""
        print("🚀 开始产品信息管理API测试")
        print("=" * 50)
        
        tests = [
            ("分页查询产品列表", self.test_list_products),
            ("获取产品详情", self.test_get_product_detail),
            ("新增产品", self.test_add_product),
            ("修改产品", self.test_update_product),
            ("修改返利标识", self.test_change_rebate_flag),
            ("获取所有产品", self.test_get_all_products),
            ("参数验证", self.test_parameter_validation),
            ("删除产品", self.test_delete_product),
            ("批量删除产品", self.test_batch_delete_products),
        ]
        
        passed = 0
        total = len(tests)
        
        for test_name, test_func in tests:
            try:
                if test_func():
                    passed += 1
            except Exception as e:
                self.print_result(test_name, False, f"测试异常: {str(e)}")
        
        print("=" * 50)
        print(f"📊 测试结果: {passed}/{total} 通过")
        
        if passed == total:
            print("🎉 所有测试通过!")
            return True
        else:
            print("⚠️  部分测试失败,请检查API实现")
            return False


def main():
    """主函数"""
    if len(sys.argv) > 1 and sys.argv[1] == '--help':
        print("产品信息管理API测试工具")
        print("用法: python test_products.py")
        print("环境变量: API_BASE_URL (默认: http://localhost:8083)")
        return
    
    print("🚀 开始产品信息管理API测试")
    print("=" * 50)
    
    # 检查环境变量
    base_url = os.environ.get('API_BASE_URL', 'http://localhost:8083')
    print(f"API基础URL: {base_url}")
    print()
    
    # 创建测试器并运行测试
    tester = ProductApiTester()
    success = tester.run_all_tests()
    
    if success:
        print("🎉 所有产品API测试通过!")
        return 0
    else:
        print("⚠️  部分产品API测试失败,请检查API实现")
        return 1


if __name__ == '__main__':
    main()